@easbot/gateway 0.1.14 → 0.1.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- 'use strict';var s={name:"@easbot/gateway",version:"0.1.14",description:"EASBot Gateway - AI Agent Server and Multi-channel Integration Platform - \u652F\u6301 WebSocket\u3001HTTP\u3001Discord\u3001Telegram\u3001Slack \u7B49\u591A\u6E20\u9053\u96C6\u6210",type:"module",main:"dist/index.cjs",module:"dist/index.mjs",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.cjs"},"./package.json":"./package.json"},scripts:{dev:"cross-env NODE_ENV=development tsx src/cli.ts -- start",start:"cross-env NODE_ENV=production node dist/cli.mjs start",build:"tsup --env.NODE_ENV production",test:"vitest","test:run":"vitest run",lint:"biome check .","lint:fix":"biome check --write .","lint:report":"biome check --reporter=summary .",format:"biome format .","format:fix":"biome format --write .","type-check":"tsc --noEmit",clean:"npx rimraf dist node_modules",prepare:"echo norun",prepublishOnly:"pnpm build","publish:npm":"bash scripts/publish.sh","publish:npm:win":"powershell -ExecutionPolicy Bypass -File scripts/publish.ps1"},keywords:["easbot","gateway","server","websocket","http","agent","multi-channel","discord","telegram","slack","feishu","wechat","chat","integration"],author:"houjallen",license:"MIT",repository:{type:"git",url:"https://github.com/houjallen/easbot.git",directory:"packages/gateway"},homepage:"https://github.com/houjallen/easbot/tree/main/packages/gateway#readme",bugs:{url:"https://github.com/houjallen/easbot/issues"},files:["dist","README.md","README.en.md","LICENSE"],dependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/provider-utils":"^4.0.21","@ai-sdk/openai-compatible":"2.0.37","@ai-sdk/anthropic":"3.0.63","@easbot/plugin":"workspace:*","@easbot/sdk":"workspace:*","@easbot/types":"workspace:*","@easbot/utils":"workspace:*",zod:"^4.3.6",ws:"^8.20.0",ai:"^6.0.136","better-sqlite3":"^12.9.0","jieba-wasm":"^2.4.0","xdg-basedir":"^5.1.0"},devDependencies:{"@biomejs/biome":"^2.4.8","@types/better-sqlite3":"^7.6.13","@types/ws":"^8.18.1","@types/node":"^22.17.0","@vitest/coverage-v8":"^4.1.1",dotenv:"^17.3.1",tsup:"^8.5.1",typescript:"^6.0.2",vitest:"^4.1.1"},engines:{node:">=22.17.0"},publishConfig:{access:"public"}};
1
+ 'use strict';var s={name:"@easbot/gateway",version:"0.1.15",description:"EASBot Gateway - AI Agent Server and Multi-channel Integration Platform - \u652F\u6301 WebSocket\u3001HTTP\u3001Discord\u3001Telegram\u3001Slack \u7B49\u591A\u6E20\u9053\u96C6\u6210",type:"module",main:"dist/index.cjs",module:"dist/index.mjs",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.cjs"},"./package.json":"./package.json"},scripts:{dev:"cross-env NODE_ENV=development tsx src/cli.ts -- start",start:"cross-env NODE_ENV=production node dist/cli.mjs start",build:"tsup --env.NODE_ENV production",test:"vitest","test:run":"vitest run",lint:"biome check .","lint:fix":"biome check --write .","lint:report":"biome check --reporter=summary .",format:"biome format .","format:fix":"biome format --write .","type-check":"tsc --noEmit",clean:"npx rimraf dist node_modules",prepare:"echo norun",prepublishOnly:"pnpm build","publish:npm":"bash scripts/publish.sh","publish:npm:win":"powershell -ExecutionPolicy Bypass -File scripts/publish.ps1"},keywords:["easbot","gateway","server","websocket","http","agent","multi-channel","discord","telegram","slack","feishu","wechat","chat","integration"],author:"houjallen",license:"MIT",repository:{type:"git",url:"https://github.com/houjallen/easbot.git",directory:"packages/gateway"},homepage:"https://github.com/houjallen/easbot/tree/main/packages/gateway#readme",bugs:{url:"https://github.com/houjallen/easbot/issues"},files:["dist","README.md","README.en.md","LICENSE"],dependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/provider-utils":"^4.0.21","@ai-sdk/openai-compatible":"2.0.37","@ai-sdk/anthropic":"3.0.63","@easbot/plugin":"workspace:*","@easbot/sdk":"workspace:*","@easbot/types":"workspace:*","@easbot/utils":"workspace:*",zod:"^4.3.6",ws:"^8.20.0",ai:"^6.0.136","better-sqlite3":"^12.9.0","jieba-wasm":"^2.4.0","xdg-basedir":"^5.1.0"},devDependencies:{"@biomejs/biome":"^2.4.8","@types/better-sqlite3":"^7.6.13","@types/ws":"^8.18.1","@types/node":"^22.17.0","@vitest/coverage-v8":"^4.1.1",dotenv:"^17.3.1",tsup:"^8.5.1",typescript:"^6.0.2",vitest:"^4.1.1"},engines:{node:">=22.17.0"},publishConfig:{access:"public"}};
2
2
  exports.a=s;
@@ -1 +1 @@
1
- 'use strict';var chunkEKLLH53Y_cjs=require('./chunk-EKLLH53Y.cjs'),chunkSIOB4FC7_cjs=require('./chunk-SIOB4FC7.cjs'),chunkXQVVSJRM_cjs=require('./chunk-XQVVSJRM.cjs');chunkSIOB4FC7_cjs.a();var a=chunkEKLLH53Y_cjs.a.create({service:"gateway"}),c=class t extends Error{constructor(e,w,m){super(e);chunkXQVVSJRM_cjs.e(this,"type");chunkXQVVSJRM_cjs.e(this,"stage");chunkXQVVSJRM_cjs.e(this,"cause");this.type="GatewayInitializationError",this.stage=w,this.cause=m,Error.captureStackTrace&&Error.captureStackTrace(this,t);}};function S(t){let s=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],e=t.code;return s.includes(e??"")}function z(){process.on("unhandledRejection",t=>{let s=t instanceof Error?t:new Error(String(t));if(a.error("unhandled promise rejection",{error:s.message,stack:s.stack}),S(s)){a.warn("recoverable network error, continuing...",{code:s.code});return}}),process.on("uncaughtException",t=>{if(a.error("uncaught exception",{error:t.message,stack:t.stack}),S(t)){a.warn("recoverable network error, continuing...",{code:t.code});return}process.exit(1);});}exports.a=void 0;(F=>{let t={initialized:false,initPromise:null,directory:".easbot",config:null},s,e={server:null,config:null,initialized:false,status:"stopped"};async function w(o={}){if(t.initialized)return;if(t.initPromise)return t.initPromise;let i={directory:o.directory??".easbot",printLogs:o.printLogs??false,logLevel:o.logLevel??"INFO"};return t.directory=i.directory,t.initPromise=(async()=>{let{Global:n}=await import('./global-Q2ANDP2N.cjs');try{await n.init();}catch(r){throw new c("Failed to initialize global directories","global",r instanceof Error?r:void 0)}try{await chunkEKLLH53Y_cjs.a.init({logDir:n.Path.log,print:i.printLogs,level:i.logLevel});}catch(r){throw new c("Failed to initialize log infrastructure","log",r instanceof Error?r:void 0)}try{z();}catch(r){throw new c("Failed to install unhandled exception handlers","server",r instanceof Error?r:void 0)}try{let r=chunkEKLLH53Y_cjs.Q();t.config=await r.load(i.directory);}catch(r){throw new c("Failed to load gateway configuration","config",r instanceof Error?r:void 0)}t.initialized=true,a.info("gateway runtime initialized",{directory:i.directory,logLevel:i.logLevel});})(),t.initPromise}F.init=w;function m(){return t.initialized}F.isInitialized=m;function b(){return s||(s=async()=>{if(!t.initialized)throw new c("Gateway not initialized. Call init() first.","server");let o=chunkEKLLH53Y_cjs.Q(),i=chunkEKLLH53Y_cjs.S(),n=await o.load(i.directory);return n.server?.enabled?(e={server:null,config:n,initialized:true,status:"stopped"},a.info("gateway initialized",{port:n.server?.port,hostname:n.server?.hostname}),e):(a.debug("gateway server disabled or not configured"),{server:null,config:n,initialized:true,status:"stopped"})}),s}function u(){return b()()}F.state=u;async function R(){return (await u()).server}F.get=R;async function N(){return (await u()).config?.server?.enabled??false}F.isEnabled=N;async function L(){return (await u()).config}F.config=L;function T(){return e.status}F.getStatus=T;async function P(o){t.initialized||await w();let i=await u();if(!(i.config?.server?.enabled??true))throw a.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(e.status==="running"){a.info("gateway server is already running");return}if(e.status==="starting"){a.info("gateway server is starting");return}e.status="starting";try{let r={...i.config?.server,...o},g=await x(r);e.server=g,e.status="running",e.error=void 0,a.info("gateway server started",{port:r.port,hostname:r.hostname});}catch(r){throw e.status="error",e.error=r instanceof Error?r.message:String(r),a.error("failed to start gateway server",{error:e.error}),r}}F.start=P;async function G(){if(e.status==="stopped"){a.info("gateway server is already stopped");return}if(e.status==="stopping"){a.info("gateway server is stopping");return}e.status="stopping";try{e.server&&await e.server.stop(),e.server=null,e.status="stopped",e.error=void 0,a.info("gateway server stopped");}catch(o){throw e.status="error",e.error=o instanceof Error?o.message:String(o),a.error("failed to stop gateway server",{error:e.error}),o}}F.stop=G;async function I(o){a.info("restarting gateway server"),(e.status==="running"||e.status==="starting")&&await G(),await P(o);}F.restart=I;async function k(){let o=chunkEKLLH53Y_cjs.Q(),i=chunkEKLLH53Y_cjs.S(),n=await o.load(i.directory);return e.config=n,t.config=n,a.info("gateway config reloaded"),n}F.reloadConfig=k;async function x(o,i){let{GatewayServer:n}=await import('./server-3CBE5XNJ.cjs'),r=new n(o),g=i?.startupTimeout??3e4;if(await(async()=>{let l=new Promise((d,C)=>{setTimeout(()=>{C(new Error(`Gateway server startup timeout after ${g}ms`));},g);});try{await Promise.race([r.start(),l]);}catch(d){a.error("gateway server start failed, attempting cleanup",{error:d instanceof Error?d.message:String(d)});try{await r.stop();}catch{}throw d}})(),i?.onStarted)try{await i.onStarted(r);}catch(l){a.warn("server started but onStarted callback failed",{error:l instanceof Error?l.message:String(l)});}return a.info("gateway server created and started",{port:o.port,hostname:o.hostname}),r}F.createGatewayServer=x;})(exports.a||(exports.a={}));
1
+ 'use strict';var chunkEKLLH53Y_cjs=require('./chunk-EKLLH53Y.cjs'),chunkSIOB4FC7_cjs=require('./chunk-SIOB4FC7.cjs'),chunkXQVVSJRM_cjs=require('./chunk-XQVVSJRM.cjs');chunkSIOB4FC7_cjs.a();var a=chunkEKLLH53Y_cjs.a.create({service:"gateway"}),c=class t extends Error{constructor(e,w,m){super(e);chunkXQVVSJRM_cjs.e(this,"type");chunkXQVVSJRM_cjs.e(this,"stage");chunkXQVVSJRM_cjs.e(this,"cause");this.type="GatewayInitializationError",this.stage=w,this.cause=m,Error.captureStackTrace&&Error.captureStackTrace(this,t);}};function S(t){let s=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],e=t.code;return s.includes(e??"")}function z(){process.on("unhandledRejection",t=>{let s=t instanceof Error?t:new Error(String(t));if(a.error("unhandled promise rejection",{error:s.message,stack:s.stack}),S(s)){a.warn("recoverable network error, continuing...",{code:s.code});return}}),process.on("uncaughtException",t=>{if(a.error("uncaught exception",{error:t.message,stack:t.stack}),S(t)){a.warn("recoverable network error, continuing...",{code:t.code});return}process.exit(1);});}exports.a=void 0;(F=>{let t={initialized:false,initPromise:null,directory:".easbot",config:null},s,e={server:null,config:null,initialized:false,status:"stopped"};async function w(o={}){if(t.initialized)return;if(t.initPromise)return t.initPromise;let i={directory:o.directory??".easbot",printLogs:o.printLogs??false,logLevel:o.logLevel??"INFO"};return t.directory=i.directory,t.initPromise=(async()=>{let{Global:n}=await import('./global-K4U25JQK.cjs');try{await n.init();}catch(r){throw new c("Failed to initialize global directories","global",r instanceof Error?r:void 0)}try{await chunkEKLLH53Y_cjs.a.init({logDir:n.Path.log,print:i.printLogs,level:i.logLevel});}catch(r){throw new c("Failed to initialize log infrastructure","log",r instanceof Error?r:void 0)}try{z();}catch(r){throw new c("Failed to install unhandled exception handlers","server",r instanceof Error?r:void 0)}try{let r=chunkEKLLH53Y_cjs.Q();t.config=await r.load(i.directory);}catch(r){throw new c("Failed to load gateway configuration","config",r instanceof Error?r:void 0)}t.initialized=true,a.info("gateway runtime initialized",{directory:i.directory,logLevel:i.logLevel});})(),t.initPromise}F.init=w;function m(){return t.initialized}F.isInitialized=m;function b(){return s||(s=async()=>{if(!t.initialized)throw new c("Gateway not initialized. Call init() first.","server");let o=chunkEKLLH53Y_cjs.Q(),i=chunkEKLLH53Y_cjs.S(),n=await o.load(i.directory);return n.server?.enabled?(e={server:null,config:n,initialized:true,status:"stopped"},a.info("gateway initialized",{port:n.server?.port,hostname:n.server?.hostname}),e):(a.debug("gateway server disabled or not configured"),{server:null,config:n,initialized:true,status:"stopped"})}),s}function u(){return b()()}F.state=u;async function R(){return (await u()).server}F.get=R;async function N(){return (await u()).config?.server?.enabled??false}F.isEnabled=N;async function L(){return (await u()).config}F.config=L;function T(){return e.status}F.getStatus=T;async function P(o){t.initialized||await w();let i=await u();if(!(i.config?.server?.enabled??true))throw a.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(e.status==="running"){a.info("gateway server is already running");return}if(e.status==="starting"){a.info("gateway server is starting");return}e.status="starting";try{let r={...i.config?.server,...o},g=await x(r);e.server=g,e.status="running",e.error=void 0,a.info("gateway server started",{port:r.port,hostname:r.hostname});}catch(r){throw e.status="error",e.error=r instanceof Error?r.message:String(r),a.error("failed to start gateway server",{error:e.error}),r}}F.start=P;async function G(){if(e.status==="stopped"){a.info("gateway server is already stopped");return}if(e.status==="stopping"){a.info("gateway server is stopping");return}e.status="stopping";try{e.server&&await e.server.stop(),e.server=null,e.status="stopped",e.error=void 0,a.info("gateway server stopped");}catch(o){throw e.status="error",e.error=o instanceof Error?o.message:String(o),a.error("failed to stop gateway server",{error:e.error}),o}}F.stop=G;async function I(o){a.info("restarting gateway server"),(e.status==="running"||e.status==="starting")&&await G(),await P(o);}F.restart=I;async function k(){let o=chunkEKLLH53Y_cjs.Q(),i=chunkEKLLH53Y_cjs.S(),n=await o.load(i.directory);return e.config=n,t.config=n,a.info("gateway config reloaded"),n}F.reloadConfig=k;async function x(o,i){let{GatewayServer:n}=await import('./server-3CBE5XNJ.cjs'),r=new n(o),g=i?.startupTimeout??3e4;if(await(async()=>{let l=new Promise((d,C)=>{setTimeout(()=>{C(new Error(`Gateway server startup timeout after ${g}ms`));},g);});try{await Promise.race([r.start(),l]);}catch(d){a.error("gateway server start failed, attempting cleanup",{error:d instanceof Error?d.message:String(d)});try{await r.stop();}catch{}throw d}})(),i?.onStarted)try{await i.onStarted(r);}catch(l){a.warn("server started but onStarted callback failed",{error:l instanceof Error?l.message:String(l)});}return a.info("gateway server created and started",{port:o.port,hostname:o.hostname}),r}F.createGatewayServer=x;})(exports.a||(exports.a={}));
@@ -1 +1 @@
1
- import {a as a$2,Q,S as S$1}from'./chunk-ETYFY7SI.mjs';import {a as a$1}from'./chunk-SJNPXLNN.mjs';import {e}from'./chunk-TY6W6O7O.mjs';a$1();var a=a$2.create({service:"gateway"}),c=class t extends Error{constructor(e$1,w,m){super(e$1);e(this,"type");e(this,"stage");e(this,"cause");this.type="GatewayInitializationError",this.stage=w,this.cause=m,Error.captureStackTrace&&Error.captureStackTrace(this,t);}};function S(t){let s=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],e=t.code;return s.includes(e??"")}function z(){process.on("unhandledRejection",t=>{let s=t instanceof Error?t:new Error(String(t));if(a.error("unhandled promise rejection",{error:s.message,stack:s.stack}),S(s)){a.warn("recoverable network error, continuing...",{code:s.code});return}}),process.on("uncaughtException",t=>{if(a.error("uncaught exception",{error:t.message,stack:t.stack}),S(t)){a.warn("recoverable network error, continuing...",{code:t.code});return}process.exit(1);});}var h;(F=>{let t={initialized:false,initPromise:null,directory:".easbot",config:null},s,e={server:null,config:null,initialized:false,status:"stopped"};async function w(o={}){if(t.initialized)return;if(t.initPromise)return t.initPromise;let i={directory:o.directory??".easbot",printLogs:o.printLogs??false,logLevel:o.logLevel??"INFO"};return t.directory=i.directory,t.initPromise=(async()=>{let{Global:n}=await import('./global-P3VKF3YI.mjs');try{await n.init();}catch(r){throw new c("Failed to initialize global directories","global",r instanceof Error?r:void 0)}try{await a$2.init({logDir:n.Path.log,print:i.printLogs,level:i.logLevel});}catch(r){throw new c("Failed to initialize log infrastructure","log",r instanceof Error?r:void 0)}try{z();}catch(r){throw new c("Failed to install unhandled exception handlers","server",r instanceof Error?r:void 0)}try{let r=Q();t.config=await r.load(i.directory);}catch(r){throw new c("Failed to load gateway configuration","config",r instanceof Error?r:void 0)}t.initialized=true,a.info("gateway runtime initialized",{directory:i.directory,logLevel:i.logLevel});})(),t.initPromise}F.init=w;function m(){return t.initialized}F.isInitialized=m;function b(){return s||(s=async()=>{if(!t.initialized)throw new c("Gateway not initialized. Call init() first.","server");let o=Q(),i=S$1(),n=await o.load(i.directory);return n.server?.enabled?(e={server:null,config:n,initialized:true,status:"stopped"},a.info("gateway initialized",{port:n.server?.port,hostname:n.server?.hostname}),e):(a.debug("gateway server disabled or not configured"),{server:null,config:n,initialized:true,status:"stopped"})}),s}function u(){return b()()}F.state=u;async function R(){return (await u()).server}F.get=R;async function N(){return (await u()).config?.server?.enabled??false}F.isEnabled=N;async function L(){return (await u()).config}F.config=L;function T(){return e.status}F.getStatus=T;async function P(o){t.initialized||await w();let i=await u();if(!(i.config?.server?.enabled??true))throw a.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(e.status==="running"){a.info("gateway server is already running");return}if(e.status==="starting"){a.info("gateway server is starting");return}e.status="starting";try{let r={...i.config?.server,...o},g=await x(r);e.server=g,e.status="running",e.error=void 0,a.info("gateway server started",{port:r.port,hostname:r.hostname});}catch(r){throw e.status="error",e.error=r instanceof Error?r.message:String(r),a.error("failed to start gateway server",{error:e.error}),r}}F.start=P;async function G(){if(e.status==="stopped"){a.info("gateway server is already stopped");return}if(e.status==="stopping"){a.info("gateway server is stopping");return}e.status="stopping";try{e.server&&await e.server.stop(),e.server=null,e.status="stopped",e.error=void 0,a.info("gateway server stopped");}catch(o){throw e.status="error",e.error=o instanceof Error?o.message:String(o),a.error("failed to stop gateway server",{error:e.error}),o}}F.stop=G;async function I(o){a.info("restarting gateway server"),(e.status==="running"||e.status==="starting")&&await G(),await P(o);}F.restart=I;async function k(){let o=Q(),i=S$1(),n=await o.load(i.directory);return e.config=n,t.config=n,a.info("gateway config reloaded"),n}F.reloadConfig=k;async function x(o,i){let{GatewayServer:n}=await import('./server-GVEVKN4C.mjs'),r=new n(o),g=i?.startupTimeout??3e4;if(await(async()=>{let l=new Promise((d,C)=>{setTimeout(()=>{C(new Error(`Gateway server startup timeout after ${g}ms`));},g);});try{await Promise.race([r.start(),l]);}catch(d){a.error("gateway server start failed, attempting cleanup",{error:d instanceof Error?d.message:String(d)});try{await r.stop();}catch{}throw d}})(),i?.onStarted)try{await i.onStarted(r);}catch(l){a.warn("server started but onStarted callback failed",{error:l instanceof Error?l.message:String(l)});}return a.info("gateway server created and started",{port:o.port,hostname:o.hostname}),r}F.createGatewayServer=x;})(h||(h={}));export{h as a};
1
+ import {a as a$2,Q,S as S$1}from'./chunk-ETYFY7SI.mjs';import {a as a$1}from'./chunk-SJNPXLNN.mjs';import {e}from'./chunk-TY6W6O7O.mjs';a$1();var a=a$2.create({service:"gateway"}),c=class t extends Error{constructor(e$1,w,m){super(e$1);e(this,"type");e(this,"stage");e(this,"cause");this.type="GatewayInitializationError",this.stage=w,this.cause=m,Error.captureStackTrace&&Error.captureStackTrace(this,t);}};function S(t){let s=["ECONNRESET","EPIPE","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","ENETUNREACH"],e=t.code;return s.includes(e??"")}function z(){process.on("unhandledRejection",t=>{let s=t instanceof Error?t:new Error(String(t));if(a.error("unhandled promise rejection",{error:s.message,stack:s.stack}),S(s)){a.warn("recoverable network error, continuing...",{code:s.code});return}}),process.on("uncaughtException",t=>{if(a.error("uncaught exception",{error:t.message,stack:t.stack}),S(t)){a.warn("recoverable network error, continuing...",{code:t.code});return}process.exit(1);});}var h;(F=>{let t={initialized:false,initPromise:null,directory:".easbot",config:null},s,e={server:null,config:null,initialized:false,status:"stopped"};async function w(o={}){if(t.initialized)return;if(t.initPromise)return t.initPromise;let i={directory:o.directory??".easbot",printLogs:o.printLogs??false,logLevel:o.logLevel??"INFO"};return t.directory=i.directory,t.initPromise=(async()=>{let{Global:n}=await import('./global-KXPT44QD.mjs');try{await n.init();}catch(r){throw new c("Failed to initialize global directories","global",r instanceof Error?r:void 0)}try{await a$2.init({logDir:n.Path.log,print:i.printLogs,level:i.logLevel});}catch(r){throw new c("Failed to initialize log infrastructure","log",r instanceof Error?r:void 0)}try{z();}catch(r){throw new c("Failed to install unhandled exception handlers","server",r instanceof Error?r:void 0)}try{let r=Q();t.config=await r.load(i.directory);}catch(r){throw new c("Failed to load gateway configuration","config",r instanceof Error?r:void 0)}t.initialized=true,a.info("gateway runtime initialized",{directory:i.directory,logLevel:i.logLevel});})(),t.initPromise}F.init=w;function m(){return t.initialized}F.isInitialized=m;function b(){return s||(s=async()=>{if(!t.initialized)throw new c("Gateway not initialized. Call init() first.","server");let o=Q(),i=S$1(),n=await o.load(i.directory);return n.server?.enabled?(e={server:null,config:n,initialized:true,status:"stopped"},a.info("gateway initialized",{port:n.server?.port,hostname:n.server?.hostname}),e):(a.debug("gateway server disabled or not configured"),{server:null,config:n,initialized:true,status:"stopped"})}),s}function u(){return b()()}F.state=u;async function R(){return (await u()).server}F.get=R;async function N(){return (await u()).config?.server?.enabled??false}F.isEnabled=N;async function L(){return (await u()).config}F.config=L;function T(){return e.status}F.getStatus=T;async function P(o){t.initialized||await w();let i=await u();if(!(i.config?.server?.enabled??true))throw a.warn("gateway server is disabled"),new Error("Gateway server is disabled");if(e.status==="running"){a.info("gateway server is already running");return}if(e.status==="starting"){a.info("gateway server is starting");return}e.status="starting";try{let r={...i.config?.server,...o},g=await x(r);e.server=g,e.status="running",e.error=void 0,a.info("gateway server started",{port:r.port,hostname:r.hostname});}catch(r){throw e.status="error",e.error=r instanceof Error?r.message:String(r),a.error("failed to start gateway server",{error:e.error}),r}}F.start=P;async function G(){if(e.status==="stopped"){a.info("gateway server is already stopped");return}if(e.status==="stopping"){a.info("gateway server is stopping");return}e.status="stopping";try{e.server&&await e.server.stop(),e.server=null,e.status="stopped",e.error=void 0,a.info("gateway server stopped");}catch(o){throw e.status="error",e.error=o instanceof Error?o.message:String(o),a.error("failed to stop gateway server",{error:e.error}),o}}F.stop=G;async function I(o){a.info("restarting gateway server"),(e.status==="running"||e.status==="starting")&&await G(),await P(o);}F.restart=I;async function k(){let o=Q(),i=S$1(),n=await o.load(i.directory);return e.config=n,t.config=n,a.info("gateway config reloaded"),n}F.reloadConfig=k;async function x(o,i){let{GatewayServer:n}=await import('./server-GVEVKN4C.mjs'),r=new n(o),g=i?.startupTimeout??3e4;if(await(async()=>{let l=new Promise((d,C)=>{setTimeout(()=>{C(new Error(`Gateway server startup timeout after ${g}ms`));},g);});try{await Promise.race([r.start(),l]);}catch(d){a.error("gateway server start failed, attempting cleanup",{error:d instanceof Error?d.message:String(d)});try{await r.stop();}catch{}throw d}})(),i?.onStarted)try{await i.onStarted(r);}catch(l){a.warn("server started but onStarted callback failed",{error:l instanceof Error?l.message:String(l)});}return a.info("gateway server created and started",{port:o.port,hostname:o.hostname}),r}F.createGatewayServer=x;})(h||(h={}));export{h as a};
@@ -1,2 +1,2 @@
1
- var s={name:"@easbot/gateway",version:"0.1.14",description:"EASBot Gateway - AI Agent Server and Multi-channel Integration Platform - \u652F\u6301 WebSocket\u3001HTTP\u3001Discord\u3001Telegram\u3001Slack \u7B49\u591A\u6E20\u9053\u96C6\u6210",type:"module",main:"dist/index.cjs",module:"dist/index.mjs",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.cjs"},"./package.json":"./package.json"},scripts:{dev:"cross-env NODE_ENV=development tsx src/cli.ts -- start",start:"cross-env NODE_ENV=production node dist/cli.mjs start",build:"tsup --env.NODE_ENV production",test:"vitest","test:run":"vitest run",lint:"biome check .","lint:fix":"biome check --write .","lint:report":"biome check --reporter=summary .",format:"biome format .","format:fix":"biome format --write .","type-check":"tsc --noEmit",clean:"npx rimraf dist node_modules",prepare:"echo norun",prepublishOnly:"pnpm build","publish:npm":"bash scripts/publish.sh","publish:npm:win":"powershell -ExecutionPolicy Bypass -File scripts/publish.ps1"},keywords:["easbot","gateway","server","websocket","http","agent","multi-channel","discord","telegram","slack","feishu","wechat","chat","integration"],author:"houjallen",license:"MIT",repository:{type:"git",url:"https://github.com/houjallen/easbot.git",directory:"packages/gateway"},homepage:"https://github.com/houjallen/easbot/tree/main/packages/gateway#readme",bugs:{url:"https://github.com/houjallen/easbot/issues"},files:["dist","README.md","README.en.md","LICENSE"],dependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/provider-utils":"^4.0.21","@ai-sdk/openai-compatible":"2.0.37","@ai-sdk/anthropic":"3.0.63","@easbot/plugin":"workspace:*","@easbot/sdk":"workspace:*","@easbot/types":"workspace:*","@easbot/utils":"workspace:*",zod:"^4.3.6",ws:"^8.20.0",ai:"^6.0.136","better-sqlite3":"^12.9.0","jieba-wasm":"^2.4.0","xdg-basedir":"^5.1.0"},devDependencies:{"@biomejs/biome":"^2.4.8","@types/better-sqlite3":"^7.6.13","@types/ws":"^8.18.1","@types/node":"^22.17.0","@vitest/coverage-v8":"^4.1.1",dotenv:"^17.3.1",tsup:"^8.5.1",typescript:"^6.0.2",vitest:"^4.1.1"},engines:{node:">=22.17.0"},publishConfig:{access:"public"}};
1
+ var s={name:"@easbot/gateway",version:"0.1.15",description:"EASBot Gateway - AI Agent Server and Multi-channel Integration Platform - \u652F\u6301 WebSocket\u3001HTTP\u3001Discord\u3001Telegram\u3001Slack \u7B49\u591A\u6E20\u9053\u96C6\u6210",type:"module",main:"dist/index.cjs",module:"dist/index.mjs",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.cjs"},"./package.json":"./package.json"},scripts:{dev:"cross-env NODE_ENV=development tsx src/cli.ts -- start",start:"cross-env NODE_ENV=production node dist/cli.mjs start",build:"tsup --env.NODE_ENV production",test:"vitest","test:run":"vitest run",lint:"biome check .","lint:fix":"biome check --write .","lint:report":"biome check --reporter=summary .",format:"biome format .","format:fix":"biome format --write .","type-check":"tsc --noEmit",clean:"npx rimraf dist node_modules",prepare:"echo norun",prepublishOnly:"pnpm build","publish:npm":"bash scripts/publish.sh","publish:npm:win":"powershell -ExecutionPolicy Bypass -File scripts/publish.ps1"},keywords:["easbot","gateway","server","websocket","http","agent","multi-channel","discord","telegram","slack","feishu","wechat","chat","integration"],author:"houjallen",license:"MIT",repository:{type:"git",url:"https://github.com/houjallen/easbot.git",directory:"packages/gateway"},homepage:"https://github.com/houjallen/easbot/tree/main/packages/gateway#readme",bugs:{url:"https://github.com/houjallen/easbot/issues"},files:["dist","README.md","README.en.md","LICENSE"],dependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/provider-utils":"^4.0.21","@ai-sdk/openai-compatible":"2.0.37","@ai-sdk/anthropic":"3.0.63","@easbot/plugin":"workspace:*","@easbot/sdk":"workspace:*","@easbot/types":"workspace:*","@easbot/utils":"workspace:*",zod:"^4.3.6",ws:"^8.20.0",ai:"^6.0.136","better-sqlite3":"^12.9.0","jieba-wasm":"^2.4.0","xdg-basedir":"^5.1.0"},devDependencies:{"@biomejs/biome":"^2.4.8","@types/better-sqlite3":"^7.6.13","@types/ws":"^8.18.1","@types/node":"^22.17.0","@vitest/coverage-v8":"^4.1.1",dotenv:"^17.3.1",tsup:"^8.5.1",typescript:"^6.0.2",vitest:"^4.1.1"},engines:{node:">=22.17.0"},publishConfig:{access:"public"}};
2
2
  export{s as a};
@@ -1 +1 @@
1
- 'use strict';var chunkOLIHERIJ_cjs=require('./chunk-OLIHERIJ.cjs'),chunkSIOB4FC7_cjs=require('./chunk-SIOB4FC7.cjs');require('./chunk-XQVVSJRM.cjs');var promises=require('fs/promises'),o=require('path'),xdgBasedir=require('xdg-basedir'),x=require('os');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var o__default=/*#__PURE__*/_interopDefault(o);var x__default=/*#__PURE__*/_interopDefault(x);chunkSIOB4FC7_cjs.a();var s="easbot",c=o__default.default.join(xdgBasedir.xdgData,s),H=o__default.default.join(xdgBasedir.xdgCache,s),N=o__default.default.join(xdgBasedir.xdgConfig,s),j=o__default.default.join(xdgBasedir.xdgState,s);exports.Global=void 0;(e=>{e.Path={get home(){return process.env.EASBOT_TEST_HOME||x__default.default.homedir()},data:c,bin:o__default.default.join(c,"bin"),log:o__default.default.join(c,"log"),cache:H,config:N,state:j};let t=null,n=null;async function A(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{let r=await import('./package-WJU2NXN3.cjs');t=r.default?.version||r.version||"local";}catch{t="local";}return t||"local"}function E(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{t=chunkOLIHERIJ_cjs.a.version||"local";}catch{t="local";}return t||"local"}e.getVersion=E;function l(){if(n)return n;if(process.env.EASBOT_CHANNEL)return n=process.env.EASBOT_CHANNEL,n;let r=E();return r==="local"||r.includes("dev")?n="local":r.includes("beta")||r.includes("alpha")?n="preview":n="latest",n||"local"}e.getChannel=l;function C(){return l()==="local"}e.isLocal=C;function V(){return l()==="preview"}e.isPreview=V;let u=false,a=null;async function I(){if(!u)return a||(a=(async()=>{await A(),await Promise.all([promises.mkdir(e.Path.data,{recursive:true}),promises.mkdir(e.Path.config,{recursive:true}),promises.mkdir(e.Path.state,{recursive:true}),promises.mkdir(e.Path.log,{recursive:true}),promises.mkdir(e.Path.bin,{recursive:true}),promises.mkdir(e.Path.cache,{recursive:true})]).then(()=>{process.env.EASBOT_DATA_PATH=e.Path.data,process.env.EASBOT_CONFIG_PATH=e.Path.config,process.env.EASBOT_STATE_PATH=e.Path.state,process.env.EASBOT_LOG_PATH=e.Path.log,process.env.EASBOT_BIN_PATH=e.Path.bin,process.env.EASBOT_CACHE_PATH=e.Path.cache;});let r="1",h=o__default.default.join(e.Path.cache,"version");if(await promises.readFile(h,"utf-8").catch(()=>"0")!==r){try{let p=await promises.readdir(e.Path.cache);await Promise.all(p.map(g=>promises.rm(o__default.default.join(e.Path.cache,g),{recursive:!0,force:!0})));}catch{}await promises.writeFile(h,r);}u=true;})(),a)}e.init=I;})(exports.Global||(exports.Global={}));
1
+ 'use strict';var chunkBOHNPDOJ_cjs=require('./chunk-BOHNPDOJ.cjs'),chunkSIOB4FC7_cjs=require('./chunk-SIOB4FC7.cjs');require('./chunk-XQVVSJRM.cjs');var promises=require('fs/promises'),o=require('path'),xdgBasedir=require('xdg-basedir'),x=require('os');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var o__default=/*#__PURE__*/_interopDefault(o);var x__default=/*#__PURE__*/_interopDefault(x);chunkSIOB4FC7_cjs.a();var s="easbot",c=o__default.default.join(xdgBasedir.xdgData,s),H=o__default.default.join(xdgBasedir.xdgCache,s),N=o__default.default.join(xdgBasedir.xdgConfig,s),j=o__default.default.join(xdgBasedir.xdgState,s);exports.Global=void 0;(e=>{e.Path={get home(){return process.env.EASBOT_TEST_HOME||x__default.default.homedir()},data:c,bin:o__default.default.join(c,"bin"),log:o__default.default.join(c,"log"),cache:H,config:N,state:j};let t=null,n=null;async function A(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{let r=await import('./package-2UGUDLKV.cjs');t=r.default?.version||r.version||"local";}catch{t="local";}return t||"local"}function E(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{t=chunkBOHNPDOJ_cjs.a.version||"local";}catch{t="local";}return t||"local"}e.getVersion=E;function l(){if(n)return n;if(process.env.EASBOT_CHANNEL)return n=process.env.EASBOT_CHANNEL,n;let r=E();return r==="local"||r.includes("dev")?n="local":r.includes("beta")||r.includes("alpha")?n="preview":n="latest",n||"local"}e.getChannel=l;function C(){return l()==="local"}e.isLocal=C;function V(){return l()==="preview"}e.isPreview=V;let u=false,a=null;async function I(){if(!u)return a||(a=(async()=>{await A(),await Promise.all([promises.mkdir(e.Path.data,{recursive:true}),promises.mkdir(e.Path.config,{recursive:true}),promises.mkdir(e.Path.state,{recursive:true}),promises.mkdir(e.Path.log,{recursive:true}),promises.mkdir(e.Path.bin,{recursive:true}),promises.mkdir(e.Path.cache,{recursive:true})]).then(()=>{process.env.EASBOT_DATA_PATH=e.Path.data,process.env.EASBOT_CONFIG_PATH=e.Path.config,process.env.EASBOT_STATE_PATH=e.Path.state,process.env.EASBOT_LOG_PATH=e.Path.log,process.env.EASBOT_BIN_PATH=e.Path.bin,process.env.EASBOT_CACHE_PATH=e.Path.cache;});let r="1",h=o__default.default.join(e.Path.cache,"version");if(await promises.readFile(h,"utf-8").catch(()=>"0")!==r){try{let p=await promises.readdir(e.Path.cache);await Promise.all(p.map(g=>promises.rm(o__default.default.join(e.Path.cache,g),{recursive:!0,force:!0})));}catch{}await promises.writeFile(h,r);}u=true;})(),a)}e.init=I;})(exports.Global||(exports.Global={}));
@@ -1 +1 @@
1
- import {a as a$1}from'./chunk-5B5ZM3Q7.mjs';import {a}from'./chunk-SJNPXLNN.mjs';import'./chunk-TY6W6O7O.mjs';import {mkdir,readFile,readdir,rm,writeFile}from'fs/promises';import o from'path';import {xdgData,xdgCache,xdgConfig,xdgState}from'xdg-basedir';import x from'os';a();var s="easbot",c=o.join(xdgData,s),H=o.join(xdgCache,s),N=o.join(xdgConfig,s),j=o.join(xdgState,s),P;(e=>{e.Path={get home(){return process.env.EASBOT_TEST_HOME||x.homedir()},data:c,bin:o.join(c,"bin"),log:o.join(c,"log"),cache:H,config:N,state:j};let t=null,n=null;async function A(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{let r=await import('./package-ZGPC2F6B.mjs');t=r.default?.version||r.version||"local";}catch{t="local";}return t||"local"}function E(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{t=a$1.version||"local";}catch{t="local";}return t||"local"}e.getVersion=E;function l(){if(n)return n;if(process.env.EASBOT_CHANNEL)return n=process.env.EASBOT_CHANNEL,n;let r=E();return r==="local"||r.includes("dev")?n="local":r.includes("beta")||r.includes("alpha")?n="preview":n="latest",n||"local"}e.getChannel=l;function C(){return l()==="local"}e.isLocal=C;function V(){return l()==="preview"}e.isPreview=V;let u=false,a=null;async function I(){if(!u)return a||(a=(async()=>{await A(),await Promise.all([mkdir(e.Path.data,{recursive:true}),mkdir(e.Path.config,{recursive:true}),mkdir(e.Path.state,{recursive:true}),mkdir(e.Path.log,{recursive:true}),mkdir(e.Path.bin,{recursive:true}),mkdir(e.Path.cache,{recursive:true})]).then(()=>{process.env.EASBOT_DATA_PATH=e.Path.data,process.env.EASBOT_CONFIG_PATH=e.Path.config,process.env.EASBOT_STATE_PATH=e.Path.state,process.env.EASBOT_LOG_PATH=e.Path.log,process.env.EASBOT_BIN_PATH=e.Path.bin,process.env.EASBOT_CACHE_PATH=e.Path.cache;});let r="1",h=o.join(e.Path.cache,"version");if(await readFile(h,"utf-8").catch(()=>"0")!==r){try{let p=await readdir(e.Path.cache);await Promise.all(p.map(g=>rm(o.join(e.Path.cache,g),{recursive:!0,force:!0})));}catch{}await writeFile(h,r);}u=true;})(),a)}e.init=I;})(P||(P={}));export{P as Global};
1
+ import {a as a$1}from'./chunk-VVZG6LF6.mjs';import {a}from'./chunk-SJNPXLNN.mjs';import'./chunk-TY6W6O7O.mjs';import {mkdir,readFile,readdir,rm,writeFile}from'fs/promises';import o from'path';import {xdgData,xdgCache,xdgConfig,xdgState}from'xdg-basedir';import x from'os';a();var s="easbot",c=o.join(xdgData,s),H=o.join(xdgCache,s),N=o.join(xdgConfig,s),j=o.join(xdgState,s),P;(e=>{e.Path={get home(){return process.env.EASBOT_TEST_HOME||x.homedir()},data:c,bin:o.join(c,"bin"),log:o.join(c,"log"),cache:H,config:N,state:j};let t=null,n=null;async function A(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{let r=await import('./package-UZJDAOIA.mjs');t=r.default?.version||r.version||"local";}catch{t="local";}return t||"local"}function E(){if(t)return t;if(process.env.EASBOT_VERSION)return t=process.env.EASBOT_VERSION,t;try{t=a$1.version||"local";}catch{t="local";}return t||"local"}e.getVersion=E;function l(){if(n)return n;if(process.env.EASBOT_CHANNEL)return n=process.env.EASBOT_CHANNEL,n;let r=E();return r==="local"||r.includes("dev")?n="local":r.includes("beta")||r.includes("alpha")?n="preview":n="latest",n||"local"}e.getChannel=l;function C(){return l()==="local"}e.isLocal=C;function V(){return l()==="preview"}e.isPreview=V;let u=false,a=null;async function I(){if(!u)return a||(a=(async()=>{await A(),await Promise.all([mkdir(e.Path.data,{recursive:true}),mkdir(e.Path.config,{recursive:true}),mkdir(e.Path.state,{recursive:true}),mkdir(e.Path.log,{recursive:true}),mkdir(e.Path.bin,{recursive:true}),mkdir(e.Path.cache,{recursive:true})]).then(()=>{process.env.EASBOT_DATA_PATH=e.Path.data,process.env.EASBOT_CONFIG_PATH=e.Path.config,process.env.EASBOT_STATE_PATH=e.Path.state,process.env.EASBOT_LOG_PATH=e.Path.log,process.env.EASBOT_BIN_PATH=e.Path.bin,process.env.EASBOT_CACHE_PATH=e.Path.cache;});let r="1",h=o.join(e.Path.cache,"version");if(await readFile(h,"utf-8").catch(()=>"0")!==r){try{let p=await readdir(e.Path.cache);await Promise.all(p.map(g=>rm(o.join(e.Path.cache,g),{recursive:!0,force:!0})));}catch{}await writeFile(h,r);}u=true;})(),a)}e.init=I;})(P||(P={}));export{P as Global};
@@ -0,0 +1 @@
1
+ 'use strict';var chunkBOHNPDOJ_cjs=require('./chunk-BOHNPDOJ.cjs');require('./chunk-XQVVSJRM.cjs');module.exports=chunkBOHNPDOJ_cjs.a;
@@ -0,0 +1 @@
1
+ export{a as default}from'./chunk-VVZG6LF6.mjs';import'./chunk-TY6W6O7O.mjs';
package/dist/cli.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkLV4EDVUL_cjs=require('./chunks/chunk-LV4EDVUL.cjs'),chunkEKLLH53Y_cjs=require('./chunks/chunk-EKLLH53Y.cjs'),chunkSIOB4FC7_cjs=require('./chunks/chunk-SIOB4FC7.cjs'),chunkXQVVSJRM_cjs=require('./chunks/chunk-XQVVSJRM.cjs'),utils=require('@easbot/utils');var v=chunkXQVVSJRM_cjs.c(F=>{chunkSIOB4FC7_cjs.a();var T=class extends Error{constructor(t,e,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0;}},P=class extends T{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name;}};F.CommanderError=T;F.InvalidArgumentError=P;});var H=chunkXQVVSJRM_cjs.c(D=>{chunkSIOB4FC7_cjs.a();var{InvalidArgumentError:Vt}=v(),R=class{constructor(t,e){switch(this.description=e||"",this.variadic=false,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case "<":this.required=true,this._name=t.slice(1,-1);break;case "[":this.required=false,this._name=t.slice(1,-1);break;default:this.required=true,this._name=t;break}this._name.endsWith("...")&&(this.variadic=true,this._name=this._name.slice(0,-3));}name(){return this._name}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new Vt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}argRequired(){return this.required=true,this}argOptional(){return this.required=false,this}};function Lt(r){let t=r.name()+(r.variadic===true?"...":"");return r.required?"<"+t+">":"["+t+"]"}D.Argument=R;D.humanReadableArgName=Lt;});var q=chunkXQVVSJRM_cjs.c(M=>{chunkSIOB4FC7_cjs.a();var{humanReadableArgName:It}=H(),N=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=false,this.sortOptions=false,this.showGlobalOptions=false;}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80;}visibleCommands(t){let e=t.commands.filter(n=>!n._hidden),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort((n,s)=>n.name().localeCompare(s.name())),e}compareOptions(t,e){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter(n=>!n.hidden),i=t._getHelpOption();if(i&&!i.hidden){let n=i.short&&t._findOption(i.short),s=i.long&&t._findOption(i.long);!n&&!s?e.push(i):i.long&&!s?e.push(t.createOption(i.long,i.description)):i.short&&!n&&e.push(t.createOption(i.short,i.description));}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return [];let e=[];for(let i=t.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);e.push(...n);}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||"";}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(i=>It(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(n)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(n)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let n=t.parent;n;n=n.parent)i=n.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatItemList(t,e,i){return e.length===0?[]:[i.styleTitle(t),...e,""]}groupItems(t,e,i){let n=new Map;return t.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]);}),e.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]),n.get(o).push(s);}),n}formatHelp(t,e){let i=e.padWidth(t,e),n=e.helpWidth??80;function s(c,d){return e.formatItem(c,i,d,e)}let o=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],a=e.commandDescription(t);a.length>0&&(o=o.concat([e.boxWrap(e.styleCommandDescription(a),n),""]));let h=e.visibleArguments(t).map(c=>s(e.styleArgumentTerm(e.argumentTerm(c)),e.styleArgumentDescription(e.argumentDescription(c))));if(o=o.concat(this.formatItemList("Arguments:",h,e)),this.groupItems(t.options,e.visibleOptions(t),c=>c.helpGroupHeading??"Options:").forEach((c,d)=>{let E=c.map(b=>s(e.styleOptionTerm(e.optionTerm(b)),e.styleOptionDescription(e.optionDescription(b))));o=o.concat(this.formatItemList(d,E,e));}),e.showGlobalOptions){let c=e.visibleGlobalOptions(t).map(d=>s(e.styleOptionTerm(e.optionTerm(d)),e.styleOptionDescription(e.optionDescription(d))));o=o.concat(this.formatItemList("Global Options:",c,e));}return this.groupItems(t.commands,e.visibleCommands(t),c=>c.helpGroup()||"Commands:").forEach((c,d)=>{let E=c.map(b=>s(e.styleSubcommandTerm(e.subcommandTerm(b)),e.styleSubcommandDescription(e.subcommandDescription(b))));o=o.concat(this.formatItemList(d,E,e));}),o.join(`
1
+ 'use strict';var chunkEOLBEWUW_cjs=require('./chunks/chunk-EOLBEWUW.cjs'),chunkEKLLH53Y_cjs=require('./chunks/chunk-EKLLH53Y.cjs'),chunkSIOB4FC7_cjs=require('./chunks/chunk-SIOB4FC7.cjs'),chunkXQVVSJRM_cjs=require('./chunks/chunk-XQVVSJRM.cjs'),utils=require('@easbot/utils');var v=chunkXQVVSJRM_cjs.c(F=>{chunkSIOB4FC7_cjs.a();var T=class extends Error{constructor(t,e,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0;}},P=class extends T{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name;}};F.CommanderError=T;F.InvalidArgumentError=P;});var H=chunkXQVVSJRM_cjs.c(D=>{chunkSIOB4FC7_cjs.a();var{InvalidArgumentError:Vt}=v(),R=class{constructor(t,e){switch(this.description=e||"",this.variadic=false,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case "<":this.required=true,this._name=t.slice(1,-1);break;case "[":this.required=false,this._name=t.slice(1,-1);break;default:this.required=true,this._name=t;break}this._name.endsWith("...")&&(this.variadic=true,this._name=this._name.slice(0,-3));}name(){return this._name}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new Vt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}argRequired(){return this.required=true,this}argOptional(){return this.required=false,this}};function Lt(r){let t=r.name()+(r.variadic===true?"...":"");return r.required?"<"+t+">":"["+t+"]"}D.Argument=R;D.humanReadableArgName=Lt;});var q=chunkXQVVSJRM_cjs.c(M=>{chunkSIOB4FC7_cjs.a();var{humanReadableArgName:It}=H(),N=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=false,this.sortOptions=false,this.showGlobalOptions=false;}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80;}visibleCommands(t){let e=t.commands.filter(n=>!n._hidden),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort((n,s)=>n.name().localeCompare(s.name())),e}compareOptions(t,e){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter(n=>!n.hidden),i=t._getHelpOption();if(i&&!i.hidden){let n=i.short&&t._findOption(i.short),s=i.long&&t._findOption(i.long);!n&&!s?e.push(i):i.long&&!s?e.push(t.createOption(i.long,i.description)):i.short&&!n&&e.push(t.createOption(i.short,i.description));}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return [];let e=[];for(let i=t.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);e.push(...n);}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||"";}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(i=>It(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(n)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(n)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let n=t.parent;n;n=n.parent)i=n.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatItemList(t,e,i){return e.length===0?[]:[i.styleTitle(t),...e,""]}groupItems(t,e,i){let n=new Map;return t.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]);}),e.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]),n.get(o).push(s);}),n}formatHelp(t,e){let i=e.padWidth(t,e),n=e.helpWidth??80;function s(c,d){return e.formatItem(c,i,d,e)}let o=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],a=e.commandDescription(t);a.length>0&&(o=o.concat([e.boxWrap(e.styleCommandDescription(a),n),""]));let h=e.visibleArguments(t).map(c=>s(e.styleArgumentTerm(e.argumentTerm(c)),e.styleArgumentDescription(e.argumentDescription(c))));if(o=o.concat(this.formatItemList("Arguments:",h,e)),this.groupItems(t.options,e.visibleOptions(t),c=>c.helpGroupHeading??"Options:").forEach((c,d)=>{let E=c.map(b=>s(e.styleOptionTerm(e.optionTerm(b)),e.styleOptionDescription(e.optionDescription(b))));o=o.concat(this.formatItemList(d,E,e));}),e.showGlobalOptions){let c=e.visibleGlobalOptions(t).map(d=>s(e.styleOptionTerm(e.optionTerm(d)),e.styleOptionDescription(e.optionDescription(d))));o=o.concat(this.formatItemList("Global Options:",c,e));}return this.groupItems(t.commands,e.visibleCommands(t),c=>c.helpGroup()||"Commands:").forEach((c,d)=>{let E=c.map(b=>s(e.styleSubcommandTerm(e.subcommandTerm(b)),e.styleSubcommandDescription(e.subcommandDescription(b))));o=o.concat(this.formatItemList(d,E,e));}),o.join(`
2
2
  `)}displayWidth(t){return ot(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e==="[command]"?this.styleSubcommandText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleCommandText(e)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleSubcommandText(e)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}preformatted(t){return /\n[^\S\r\n]/.test(t)}formatItem(t,e,i,n){let o=" ".repeat(2);if(!i)return o+t;let a=t.padEnd(e+t.length-n.displayWidth(t)),h=2,l=(this.helpWidth??80)-e-h-2,c;return l<this.minWidthToWrap||n.preformatted(i)?c=i:c=n.boxWrap(i,l).replace(/\n/g,`
3
3
  `+" ".repeat(e+h)),o+a+" ".repeat(h)+c.replace(/\n/g,`
4
4
  ${o}`)}boxWrap(t,e){if(e<this.minWidthToWrap)return t;let i=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,s=[];return i.forEach(o=>{let a=o.match(n);if(a===null){s.push("");return}let h=[a.shift()],p=this.displayWidth(h[0]);a.forEach(l=>{let c=this.displayWidth(l);if(p+c<=e){h.push(l),p+=c;return}s.push(h.join(""));let d=l.trimStart();h=[d],p=this.displayWidth(d);}),s.push(h.join(""));}),s.join(`
@@ -23,8 +23,8 @@ Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._life
23
23
  `),this.outputHelp({error:true}));let i=e||{},n=i.exitCode||1,s=i.code||"commander.error";this._exit(n,s,t);}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in m.env){let e=t.attributeName();(this.getOptionValue(e)===void 0||["default","config","env"].includes(this.getOptionValueSource(e)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,m.env[t.envVar]):this.emit(`optionEnv:${t.name()}`));}});}_parseOptionsImplied(){let t=new Bt(this.options),e=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&e(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!e(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"implied");});});}missingArgument(t){let e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"});}optionMissingArgument(t){let e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"});}missingMandatoryOptionValue(t){let e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"});}_conflictingOption(t,e){let i=o=>{let a=o.attributeName(),h=this.getOptionValue(a),p=this.options.find(c=>c.negate&&a===c.attributeName()),l=this.options.find(c=>!c.negate&&a===c.attributeName());return p&&(p.presetArg===void 0&&h===false||p.presetArg!==void 0&&h===p.presetArg)?p:l||o},n=o=>{let a=i(o),h=a.attributeName();return this.getOptionValueSource(h)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${n(t)} cannot be used with ${n(e)}`;this.error(s,{code:"commander.conflictingOption"});}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{let o=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);n=n.concat(o),s=s.parent;}while(s&&!s._enablePositionalOptions);e=ht(t,n);}let i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"});}_excessArguments(t){if(this._allowExcessArguments)return;let e=this.registeredArguments.length,i=e===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${e} argument${i} but got ${t.length}.`;this.error(s,{code:"commander.excessArguments"});}unknownCommand(){let t=this.args[0],e="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(s=>{n.push(s.name()),s.alias()&&n.push(s.alias());}),e=ht(t,n);}let i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"});}version(t,e,i){if(t===void 0)return this._version;this._version=t,e=e||"-V, --version",i=i||"output the version number";let n=this.createOption(e,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${t}
24
24
  `),this._exit(0,"commander.version",t);}),this}description(t,e){return t===void 0&&e===void 0?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(e=this.commands[this.commands.length-1]),t===e._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${n}'`)}return e._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(e=>this.alias(e)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(i=>Mt(i));return [].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}helpGroup(t){return t===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=t,this)}commandsGroup(t){return t===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=t,this)}optionsGroup(t){return t===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=t,this)}_initOptionGroup(t){this._defaultOptionGroup&&!t.helpGroupHeading&&t.helpGroup(this._defaultOptionGroup);}_initCommandGroup(t){this._defaultCommandGroup&&!t.helpGroup()&&t.helpGroup(this._defaultCommandGroup);}nameFromFilename(t){return this._name=w.basename(t,w.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let e=this.createHelp(),i=this._getOutputContext(t);e.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=e.formatHelp(this,e);return i.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(t){t=t||{};let e=!!t.error,i,n,s;return e?(i=a=>this._outputConfiguration.writeErr(a),n=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),n=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:e,write:a=>(n||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:n,helpWidth:s}}outputHelp(t){let e;typeof t=="function"&&(e=t,t=void 0);let i=this._getOutputContext(t),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation({error:i.error});if(e&&(s=e(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",n));}helpOption(t,e){return typeof t=="boolean"?(t?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(t??"-h, --help",e??"display help for command"),(t||e)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let e=Number(m.exitCode??0);e===0&&t&&typeof t!="function"&&t.error&&(e=1),this._exit(e,"commander.help","(outputHelp)");}addHelpText(t,e){let i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw new Error(`Unexpected value for position to addHelpText.
25
25
  Expecting one of '${i.join("', '")}'`);let n=`${t}Help`;return this.on(n,s=>{let o;typeof e=="function"?o=e({error:s.error,command:s.command}):o=e,o&&s.write(`${o}
26
- `);}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(n=>e.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"));}};function pt(r){return r.map(t=>{if(!t.startsWith("--inspect"))return t;let e,i="127.0.0.1",n="9229",s;return (s=t.match(/^(--inspect(-brk)?)$/))!==null?e=s[1]:(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(e=s[1],/^\d+$/.test(s[3])?n=s[3]:i=s[3]):(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(e=s[1],i=s[3],n=s[4]),e&&n!=="0"?`${e}=${i}:${parseInt(n)+1}`:t})}function Y(){if(m.env.NO_COLOR||m.env.FORCE_COLOR==="0"||m.env.FORCE_COLOR==="false")return false;if(m.env.FORCE_COLOR||m.env.CLICOLOR_FORCE!==void 0)return true}Z.Command=J;Z.useColor=Y;});var _t=chunkXQVVSJRM_cjs.c(C=>{chunkSIOB4FC7_cjs.a();var{Argument:mt}=H(),{Command:Q}=dt(),{CommanderError:Ut,InvalidArgumentError:ft}=v(),{Help:zt}=q(),{Option:gt}=z();C.program=new Q;C.createCommand=r=>new Q(r);C.createOption=(r,t)=>new gt(r,t);C.createArgument=(r,t)=>new mt(r,t);C.Command=Q;C.Option=gt;C.Argument=mt;C.Help=zt;C.CommanderError=Ut;C.InvalidArgumentError=ft;C.InvalidOptionArgumentError=ft;});chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var Ot=chunkXQVVSJRM_cjs.d(_t(),1),{program:Se,createCommand:ve,createArgument:$e,createOption:Te,CommanderError:He,InvalidArgumentError:ke,InvalidOptionArgumentError:Ge,Command:yt,Argument:Ve,Option:Le,Help:Ie}=Ot.default;chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var Ct={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 Xt=Ct.languages,Jt=Xt.filter(r=>r.supported).map(r=>r.value),A={defaultLocale:"zh-CN",locales:Jt},$={},G=(r,t)=>{let e=$[r]||{translation:{}};return $[r]={translation:{...e.translation,...t.translation}},$[r]},V=(r=A.defaultLocale)=>($[r]||G(r,{translation:{}}),{locale:r,resources:$[r]||{translation:{}}});chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var Yt={translation:{"cli.startup.title":"Gateway WebSocket \u670D\u52A1\u5DF2\u542F\u52A8","cli.startup.status":"\u72B6\u6001","cli.startup.port":"\u7AEF\u53E3","cli.startup.hostname":"\u4E3B\u673A\u5730\u5740","cli.startup.protocol":"\u534F\u8BAE","cli.startup.connections":"\u8FDE\u63A5\u6570","cli.startup.running":"\u8FD0\u884C\u4E2D","cli.startup.stopped":"\u5DF2\u505C\u6B62","cli.startup.mode":"\u6A21\u5F0F","cli.startup.mode_standalone":"\u72EC\u7ACB\u6A21\u5F0F","cli.startup.mode_integrated":"\u96C6\u6210\u6A21\u5F0F","cli.status.title":"Gateway WebSocket \u670D\u52A1\u72B6\u6001","cli.stop.title":"Gateway WebSocket \u670D\u52A1\u5DF2\u505C\u6B62","cli.already_running":"Gateway \u670D\u52A1\u5DF2\u5728\u8FD0\u884C\u4E2D","cli.already_stopped":"Gateway \u670D\u52A1\u5DF2\u505C\u6B62","cli.shutdown_signal":"\u6536\u5230 {{signal}}\uFF0C\u6B63\u5728\u4F18\u96C5\u5173\u95ED...","cli.shutdown_success":"Gateway \u670D\u52A1\u5DF2\u6210\u529F\u505C\u6B62","cli.unknown_command":"\u672A\u77E5\u547D\u4EE4: {{command}}","cli.error.start_failed":"\u542F\u52A8 Gateway \u5931\u8D25","cli.error.stop_failed":"\u505C\u6B62 Gateway \u5931\u8D25","cli.error.restart_failed":"\u91CD\u542F Gateway \u5931\u8D25","cli.error.status_failed":"\u83B7\u53D6 Gateway \u72B6\u6001\u5931\u8D25","cli.error.shutdown":"\u5173\u95ED\u65F6\u53D1\u751F\u9519\u8BEF","cli.error.execution_failed":"CLI \u6267\u884C\u5931\u8D25","cli.error.detail":"\u9519\u8BEF\u8BE6\u60C5:","cli.command.start.desc":"\u542F\u52A8 Gateway WebSocket \u670D\u52A1","cli.command.stop.desc":"\u505C\u6B62 Gateway \u670D\u52A1","cli.command.restart.desc":"\u91CD\u542F Gateway \u670D\u52A1","cli.command.status.desc":"\u67E5\u770B Gateway \u670D\u52A1\u72B6\u6001","cli.option.directory":"\u5DE5\u4F5C\u76EE\u5F55","cli.option.port":"\u670D\u52A1\u7AEF\u53E3","cli.option.hostname":"\u4E3B\u673A\u5730\u5740","cli.option.debug":"\u542F\u7528\u8C03\u8BD5\u6A21\u5F0F","cli.help.command":"\u663E\u793A\u5E2E\u52A9\u4FE1\u606F","cli.program.description":"Gateway WebSocket \u670D\u52A1\u7BA1\u7406 CLI","cli.examples.title":"\u793A\u4F8B","cli.example.start":"\u542F\u52A8\u670D\u52A1","cli.example.stop":"\u505C\u6B62\u670D\u52A1","cli.example.restart":"\u91CD\u542F\u670D\u52A1","cli.example.hostname":"\u6307\u5B9A\u76D1\u542C\u5730\u5740"}},wt=Yt;chunkSIOB4FC7_cjs.a();var Zt={translation:{"cli.startup.title":"Gateway WebSocket Server Started","cli.startup.status":"Status","cli.startup.port":"Port","cli.startup.hostname":"Hostname","cli.startup.protocol":"Protocol","cli.startup.connections":"Connections","cli.startup.running":"Running","cli.startup.stopped":"Stopped","cli.startup.mode":"Mode","cli.startup.mode_standalone":"Standalone","cli.startup.mode_integrated":"Integrated","cli.status.title":"Gateway WebSocket Server Status","cli.stop.title":"Gateway WebSocket Server Stopped","cli.already_running":"Gateway server is already running.","cli.already_stopped":"Gateway server is already stopped.","cli.shutdown_signal":"Received {{signal}}, shutting down gracefully...","cli.shutdown_success":"Gateway stopped successfully.","cli.unknown_command":"Unknown command: {{command}}","cli.error.start_failed":"Failed to start gateway","cli.error.stop_failed":"Failed to stop gateway","cli.error.restart_failed":"Failed to restart gateway","cli.error.status_failed":"Failed to get gateway status","cli.error.shutdown":"Error during shutdown","cli.error.execution_failed":"CLI failed to execute","cli.error.detail":"Error detail:","cli.command.start.desc":"Start Gateway WebSocket service","cli.command.stop.desc":"Stop Gateway service","cli.command.restart.desc":"Restart Gateway service","cli.command.status.desc":"Check Gateway service status","cli.option.directory":"Working directory","cli.option.port":"Service port","cli.option.hostname":"Host address","cli.option.debug":"Enable debug mode","cli.help.command":"Display help information","cli.program.description":"Gateway WebSocket service management CLI","cli.examples.title":"Examples","cli.example.start":"Start service","cli.example.stop":"Stop service","cli.example.restart":"Restart service","cli.example.hostname":"Specify listening address"}},bt=Zt;var Qt=()=>{V("zh-CN"),V("en-US"),G("zh-CN",wt),G("en-US",bt);};Qt();var tt=new Map;var et=new Map;var te=r=>{if(et.has(r))return et.get(r);let t=/{{\s*(\w+)\s*}}/g,e=[],i;for(;(i=t.exec(r))!==null;){let o=i[1];o&&!e.includes(o)&&e.push(o);}let n=new RegExp("{{\\s*("+e.join("|")+")\\s*}}","g"),s={keys:e,regex:n};return et.set(r,s),s},xt=(r,t)=>{if(!r||typeof r!="string")return "";if(!t||Object.keys(t).length===0)return r;let{regex:e,keys:i}=te(r);return i.length===0||!i.some(s=>s in t)?r:r.replace(e,(s,o)=>{let a=t[o];return a==null?"":String(a)})},ee=r=>r&&A.locales.includes(r)?r:A.defaultLocale,At=r=>{if(!tt.has(r)){let{resources:t}=V(r);tt.set(r,t);}return tt.get(r)},ie=(r,t={})=>{let e=ee(t.locale),n=At(e)?.translation[r];if(n&&typeof n=="string"){let s=xt(n,t.vars);return s!=null?String(s):String(r)}if(e!==A.defaultLocale){let o=At(A.defaultLocale)?.translation[r];if(o&&typeof o=="string"){let a=xt(o,t.vars);return a!=null?String(a):String(r)}}return String(t.fallback??r)},u=ie;chunkSIOB4FC7_cjs.a();var O=chunkEKLLH53Y_cjs.a.create({service:"cli-gateway"}),I=58,Et="\u2551",St="\u2554",vt="\u255A",$t="\u2560",it="\u2550";function se(r,t=I){let e=t-r.length;return e<=0?r:r+" ".repeat(e)}function _(r){console.log(`${Et} ${se(r)} ${Et}`);}function nt(){console.log(`${St}${it.repeat(I)}${St.replace("\u2554","\u2557")}`);}function Tt(){console.log(`${$t}${it.repeat(I)}${$t.replace("\u2560","\u2563")}`);}function st(){console.log(`${vt}${it.repeat(I)}${vt.replace("\u255A","\u255D")}`);}function Ht(r){console.log(""),nt(),_(u("cli.startup.title")),Tt(),_(`${u("cli.startup.status")}: ${u("cli.startup.running").padEnd(37-u("cli.startup.status").length)}`),_(`${u("cli.startup.port")}: ${String(r.port).padEnd(37-u("cli.startup.port").length)}`),_(`${u("cli.startup.hostname")}: ${r.hostname.padEnd(37-u("cli.startup.hostname").length)}`),_(`${u("cli.startup.protocol")}: ws${" ".repeat(32)}`),r.connections!==void 0&&_(`${u("cli.startup.connections")}:${String(r.connections).padEnd(37-u("cli.startup.connections").length)}`),_(`${u("cli.startup.mode")}: ${(r.mode==="standalone"?u("cli.startup.mode_standalone"):u("cli.startup.mode_integrated")).padEnd(37-u("cli.startup.mode").length)}`),st(),console.log("");}function re(){console.log(""),nt(),_(u("cli.stop.title")),st(),console.log("");}async function oe(){try{let r=chunkLV4EDVUL_cjs.a.getStatus(),e=(await chunkLV4EDVUL_cjs.a.get())?.getStatus();console.log(""),nt(),_(u("cli.status.title")),Tt(),_(`${u("cli.startup.status")}: ${r.toUpperCase().padEnd(37-u("cli.startup.status").length)}`),e&&(_(`${u("cli.startup.port")}: ${String(e.port).padEnd(37-u("cli.startup.port").length)}`),_(`${u("cli.startup.hostname")}: ${(e.hostname||"localhost").padEnd(37-u("cli.startup.hostname").length)}`),_(`${u("cli.startup.connections")}:${String(e.connections||0).padEnd(37-u("cli.startup.connections").length)}`)),st(),console.log("");}catch(r){O.error("Failed to get gateway status",{error:r instanceof Error?r.message:String(r)}),console.error(`${u("cli.error.status_failed")}: ${r instanceof Error?r.message:String(r)}`),process.exit(1);}}async function ae(r){let t=r.directory||process.cwd();O.info("Starting gateway service",{port:r.port,hostname:r.hostname,directory:t});try{if(await chunkLV4EDVUL_cjs.a.init({directory:t,printLogs:r.debug,logLevel:r.debug?"DEBUG":"INFO"}),chunkLV4EDVUL_cjs.a.getStatus()==="running"){console.log(u("cli.already_running"));return}let i={};r.port&&(i.port=r.port),r.hostname&&(i.hostname=r.hostname),await chunkLV4EDVUL_cjs.a.start(i);let s=(await chunkLV4EDVUL_cjs.a.get())?.getStatus();Ht({port:s?.port||r.port||8080,hostname:s?.hostname||r.hostname||"localhost",connections:s?.connections||0,mode:chunkEKLLH53Y_cjs.O()?"integrated":"standalone"}),kt();}catch(e){O.error("Failed to start gateway",{error:e instanceof Error?e.message:String(e)}),console.error(`${u("cli.error.start_failed")}: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}}async function le(){O.info("Stopping gateway service");try{if(chunkLV4EDVUL_cjs.a.getStatus()==="stopped"){console.log(u("cli.already_stopped"));return}await chunkLV4EDVUL_cjs.a.stop(),re(),O.info("Gateway stopped successfully");}catch(r){O.error("Failed to stop gateway",{error:r instanceof Error?r.message:String(r)}),console.error(`${u("cli.error.stop_failed")}: ${r instanceof Error?r.message:String(r)}`),process.exit(1);}}async function ce(r){O.info("Restarting gateway service");try{let t={};r.port&&(t.port=r.port),r.hostname&&(t.hostname=r.hostname),await chunkLV4EDVUL_cjs.a.restart(t);let i=(await chunkLV4EDVUL_cjs.a.get())?.getStatus();Ht({port:i?.port||r.port||8080,hostname:i?.hostname||r.hostname||"localhost",connections:i?.connections||0,mode:chunkEKLLH53Y_cjs.O()?"integrated":"standalone"}),kt(),O.info("Gateway restarted successfully");}catch(t){O.error("Failed to restart gateway",{error:t instanceof Error?t.message:String(t)}),console.error(`${u("cli.error.restart_failed")}: ${t instanceof Error?t.message:String(t)}`),process.exit(1);}}function kt(){let r=async t=>{O.debug(`Received ${t}, shutting down gracefully...`),console.log(`
27
- ${u("cli.shutdown_signal",{vars:{signal:t}})}`);try{await chunkLV4EDVUL_cjs.a.stop(),O.debug("Gateway stopped"),console.log(u("cli.shutdown_success"));}catch(e){O.error("Error during shutdown",{error:e instanceof Error?e.message:String(e)});}process.exit(0);};process.on("SIGINT",()=>{r("SIGINT").catch(console.error);}),process.on("SIGTERM",()=>{r("SIGTERM").catch(console.error);});}async function L(r,t){switch(r){case "start":await ae(t);break;case "stop":await le();break;case "restart":await ce(t);break;case "status":await oe();break;default:console.error(u("cli.unknown_command",{vars:{command:r}})),process.exit(1);}}function ue(r){r.command("start").description(u("cli.command.start.desc")).option("-D, --directory <path>",u("cli.option.directory")).option("-p, --port <number>",u("cli.option.port"),t=>parseInt(t,10)).option("-H, --hostname <address>",u("cli.option.hostname")).option("-d, --debug",u("cli.option.debug"),false).action(async t=>{await L("start",{directory:t.directory,port:t.port,hostname:t.hostname,debug:t.debug});}),r.command("stop").description(u("cli.command.stop.desc")).action(async()=>{await L("stop",{});}),r.command("restart").description(u("cli.command.restart.desc")).option("-D, --directory <path>",u("cli.option.directory")).option("-p, --port <number>",u("cli.option.port"),t=>parseInt(t,10)).option("-H, --hostname <address>",u("cli.option.hostname")).option("-d, --debug",u("cli.option.debug"),false).action(async t=>{await L("restart",{directory:t.directory,port:t.port,hostname:t.hostname,debug:t.debug});}),r.command("status").description(u("cli.command.status.desc")).action(async()=>{await L("status",{});}),r.addHelpCommand("help",u("cli.help.command")).addHelpText("after",`
26
+ `);}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(n=>e.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"));}};function pt(r){return r.map(t=>{if(!t.startsWith("--inspect"))return t;let e,i="127.0.0.1",n="9229",s;return (s=t.match(/^(--inspect(-brk)?)$/))!==null?e=s[1]:(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(e=s[1],/^\d+$/.test(s[3])?n=s[3]:i=s[3]):(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(e=s[1],i=s[3],n=s[4]),e&&n!=="0"?`${e}=${i}:${parseInt(n)+1}`:t})}function Y(){if(m.env.NO_COLOR||m.env.FORCE_COLOR==="0"||m.env.FORCE_COLOR==="false")return false;if(m.env.FORCE_COLOR||m.env.CLICOLOR_FORCE!==void 0)return true}Z.Command=J;Z.useColor=Y;});var _t=chunkXQVVSJRM_cjs.c(C=>{chunkSIOB4FC7_cjs.a();var{Argument:mt}=H(),{Command:Q}=dt(),{CommanderError:Ut,InvalidArgumentError:ft}=v(),{Help:zt}=q(),{Option:gt}=z();C.program=new Q;C.createCommand=r=>new Q(r);C.createOption=(r,t)=>new gt(r,t);C.createArgument=(r,t)=>new mt(r,t);C.Command=Q;C.Option=gt;C.Argument=mt;C.Help=zt;C.CommanderError=Ut;C.InvalidArgumentError=ft;C.InvalidOptionArgumentError=ft;});chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var Ot=chunkXQVVSJRM_cjs.d(_t(),1),{program:Se,createCommand:ve,createArgument:$e,createOption:Te,CommanderError:He,InvalidArgumentError:ke,InvalidOptionArgumentError:Ge,Command:yt,Argument:Ve,Option:Le,Help:Ie}=Ot.default;chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var Ct={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 Xt=Ct.languages,Jt=Xt.filter(r=>r.supported).map(r=>r.value),A={defaultLocale:"zh-CN",locales:Jt},$={},G=(r,t)=>{let e=$[r]||{translation:{}};return $[r]={translation:{...e.translation,...t.translation}},$[r]},V=(r=A.defaultLocale)=>($[r]||G(r,{translation:{}}),{locale:r,resources:$[r]||{translation:{}}});chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var Yt={translation:{"cli.startup.title":"Gateway WebSocket \u670D\u52A1\u5DF2\u542F\u52A8","cli.startup.status":"\u72B6\u6001","cli.startup.port":"\u7AEF\u53E3","cli.startup.hostname":"\u4E3B\u673A\u5730\u5740","cli.startup.protocol":"\u534F\u8BAE","cli.startup.connections":"\u8FDE\u63A5\u6570","cli.startup.running":"\u8FD0\u884C\u4E2D","cli.startup.stopped":"\u5DF2\u505C\u6B62","cli.startup.mode":"\u6A21\u5F0F","cli.startup.mode_standalone":"\u72EC\u7ACB\u6A21\u5F0F","cli.startup.mode_integrated":"\u96C6\u6210\u6A21\u5F0F","cli.status.title":"Gateway WebSocket \u670D\u52A1\u72B6\u6001","cli.stop.title":"Gateway WebSocket \u670D\u52A1\u5DF2\u505C\u6B62","cli.already_running":"Gateway \u670D\u52A1\u5DF2\u5728\u8FD0\u884C\u4E2D","cli.already_stopped":"Gateway \u670D\u52A1\u5DF2\u505C\u6B62","cli.shutdown_signal":"\u6536\u5230 {{signal}}\uFF0C\u6B63\u5728\u4F18\u96C5\u5173\u95ED...","cli.shutdown_success":"Gateway \u670D\u52A1\u5DF2\u6210\u529F\u505C\u6B62","cli.unknown_command":"\u672A\u77E5\u547D\u4EE4: {{command}}","cli.error.start_failed":"\u542F\u52A8 Gateway \u5931\u8D25","cli.error.stop_failed":"\u505C\u6B62 Gateway \u5931\u8D25","cli.error.restart_failed":"\u91CD\u542F Gateway \u5931\u8D25","cli.error.status_failed":"\u83B7\u53D6 Gateway \u72B6\u6001\u5931\u8D25","cli.error.shutdown":"\u5173\u95ED\u65F6\u53D1\u751F\u9519\u8BEF","cli.error.execution_failed":"CLI \u6267\u884C\u5931\u8D25","cli.error.detail":"\u9519\u8BEF\u8BE6\u60C5:","cli.command.start.desc":"\u542F\u52A8 Gateway WebSocket \u670D\u52A1","cli.command.stop.desc":"\u505C\u6B62 Gateway \u670D\u52A1","cli.command.restart.desc":"\u91CD\u542F Gateway \u670D\u52A1","cli.command.status.desc":"\u67E5\u770B Gateway \u670D\u52A1\u72B6\u6001","cli.option.directory":"\u5DE5\u4F5C\u76EE\u5F55","cli.option.port":"\u670D\u52A1\u7AEF\u53E3","cli.option.hostname":"\u4E3B\u673A\u5730\u5740","cli.option.debug":"\u542F\u7528\u8C03\u8BD5\u6A21\u5F0F","cli.help.command":"\u663E\u793A\u5E2E\u52A9\u4FE1\u606F","cli.program.description":"Gateway WebSocket \u670D\u52A1\u7BA1\u7406 CLI","cli.examples.title":"\u793A\u4F8B","cli.example.start":"\u542F\u52A8\u670D\u52A1","cli.example.stop":"\u505C\u6B62\u670D\u52A1","cli.example.restart":"\u91CD\u542F\u670D\u52A1","cli.example.hostname":"\u6307\u5B9A\u76D1\u542C\u5730\u5740"}},wt=Yt;chunkSIOB4FC7_cjs.a();var Zt={translation:{"cli.startup.title":"Gateway WebSocket Server Started","cli.startup.status":"Status","cli.startup.port":"Port","cli.startup.hostname":"Hostname","cli.startup.protocol":"Protocol","cli.startup.connections":"Connections","cli.startup.running":"Running","cli.startup.stopped":"Stopped","cli.startup.mode":"Mode","cli.startup.mode_standalone":"Standalone","cli.startup.mode_integrated":"Integrated","cli.status.title":"Gateway WebSocket Server Status","cli.stop.title":"Gateway WebSocket Server Stopped","cli.already_running":"Gateway server is already running.","cli.already_stopped":"Gateway server is already stopped.","cli.shutdown_signal":"Received {{signal}}, shutting down gracefully...","cli.shutdown_success":"Gateway stopped successfully.","cli.unknown_command":"Unknown command: {{command}}","cli.error.start_failed":"Failed to start gateway","cli.error.stop_failed":"Failed to stop gateway","cli.error.restart_failed":"Failed to restart gateway","cli.error.status_failed":"Failed to get gateway status","cli.error.shutdown":"Error during shutdown","cli.error.execution_failed":"CLI failed to execute","cli.error.detail":"Error detail:","cli.command.start.desc":"Start Gateway WebSocket service","cli.command.stop.desc":"Stop Gateway service","cli.command.restart.desc":"Restart Gateway service","cli.command.status.desc":"Check Gateway service status","cli.option.directory":"Working directory","cli.option.port":"Service port","cli.option.hostname":"Host address","cli.option.debug":"Enable debug mode","cli.help.command":"Display help information","cli.program.description":"Gateway WebSocket service management CLI","cli.examples.title":"Examples","cli.example.start":"Start service","cli.example.stop":"Stop service","cli.example.restart":"Restart service","cli.example.hostname":"Specify listening address"}},bt=Zt;var Qt=()=>{V("zh-CN"),V("en-US"),G("zh-CN",wt),G("en-US",bt);};Qt();var tt=new Map;var et=new Map;var te=r=>{if(et.has(r))return et.get(r);let t=/{{\s*(\w+)\s*}}/g,e=[],i;for(;(i=t.exec(r))!==null;){let o=i[1];o&&!e.includes(o)&&e.push(o);}let n=new RegExp("{{\\s*("+e.join("|")+")\\s*}}","g"),s={keys:e,regex:n};return et.set(r,s),s},xt=(r,t)=>{if(!r||typeof r!="string")return "";if(!t||Object.keys(t).length===0)return r;let{regex:e,keys:i}=te(r);return i.length===0||!i.some(s=>s in t)?r:r.replace(e,(s,o)=>{let a=t[o];return a==null?"":String(a)})},ee=r=>r&&A.locales.includes(r)?r:A.defaultLocale,At=r=>{if(!tt.has(r)){let{resources:t}=V(r);tt.set(r,t);}return tt.get(r)},ie=(r,t={})=>{let e=ee(t.locale),n=At(e)?.translation[r];if(n&&typeof n=="string"){let s=xt(n,t.vars);return s!=null?String(s):String(r)}if(e!==A.defaultLocale){let o=At(A.defaultLocale)?.translation[r];if(o&&typeof o=="string"){let a=xt(o,t.vars);return a!=null?String(a):String(r)}}return String(t.fallback??r)},u=ie;chunkSIOB4FC7_cjs.a();var O=chunkEKLLH53Y_cjs.a.create({service:"cli-gateway"}),I=58,Et="\u2551",St="\u2554",vt="\u255A",$t="\u2560",it="\u2550";function se(r,t=I){let e=t-r.length;return e<=0?r:r+" ".repeat(e)}function _(r){console.log(`${Et} ${se(r)} ${Et}`);}function nt(){console.log(`${St}${it.repeat(I)}${St.replace("\u2554","\u2557")}`);}function Tt(){console.log(`${$t}${it.repeat(I)}${$t.replace("\u2560","\u2563")}`);}function st(){console.log(`${vt}${it.repeat(I)}${vt.replace("\u255A","\u255D")}`);}function Ht(r){console.log(""),nt(),_(u("cli.startup.title")),Tt(),_(`${u("cli.startup.status")}: ${u("cli.startup.running").padEnd(37-u("cli.startup.status").length)}`),_(`${u("cli.startup.port")}: ${String(r.port).padEnd(37-u("cli.startup.port").length)}`),_(`${u("cli.startup.hostname")}: ${r.hostname.padEnd(37-u("cli.startup.hostname").length)}`),_(`${u("cli.startup.protocol")}: ws${" ".repeat(32)}`),r.connections!==void 0&&_(`${u("cli.startup.connections")}:${String(r.connections).padEnd(37-u("cli.startup.connections").length)}`),_(`${u("cli.startup.mode")}: ${(r.mode==="standalone"?u("cli.startup.mode_standalone"):u("cli.startup.mode_integrated")).padEnd(37-u("cli.startup.mode").length)}`),st(),console.log("");}function re(){console.log(""),nt(),_(u("cli.stop.title")),st(),console.log("");}async function oe(){try{let r=chunkEOLBEWUW_cjs.a.getStatus(),e=(await chunkEOLBEWUW_cjs.a.get())?.getStatus();console.log(""),nt(),_(u("cli.status.title")),Tt(),_(`${u("cli.startup.status")}: ${r.toUpperCase().padEnd(37-u("cli.startup.status").length)}`),e&&(_(`${u("cli.startup.port")}: ${String(e.port).padEnd(37-u("cli.startup.port").length)}`),_(`${u("cli.startup.hostname")}: ${(e.hostname||"localhost").padEnd(37-u("cli.startup.hostname").length)}`),_(`${u("cli.startup.connections")}:${String(e.connections||0).padEnd(37-u("cli.startup.connections").length)}`)),st(),console.log("");}catch(r){O.error("Failed to get gateway status",{error:r instanceof Error?r.message:String(r)}),console.error(`${u("cli.error.status_failed")}: ${r instanceof Error?r.message:String(r)}`),process.exit(1);}}async function ae(r){let t=r.directory||process.cwd();O.info("Starting gateway service",{port:r.port,hostname:r.hostname,directory:t});try{if(await chunkEOLBEWUW_cjs.a.init({directory:t,printLogs:r.debug,logLevel:r.debug?"DEBUG":"INFO"}),chunkEOLBEWUW_cjs.a.getStatus()==="running"){console.log(u("cli.already_running"));return}let i={};r.port&&(i.port=r.port),r.hostname&&(i.hostname=r.hostname),await chunkEOLBEWUW_cjs.a.start(i);let s=(await chunkEOLBEWUW_cjs.a.get())?.getStatus();Ht({port:s?.port||r.port||8080,hostname:s?.hostname||r.hostname||"localhost",connections:s?.connections||0,mode:chunkEKLLH53Y_cjs.O()?"integrated":"standalone"}),kt();}catch(e){O.error("Failed to start gateway",{error:e instanceof Error?e.message:String(e)}),console.error(`${u("cli.error.start_failed")}: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}}async function le(){O.info("Stopping gateway service");try{if(chunkEOLBEWUW_cjs.a.getStatus()==="stopped"){console.log(u("cli.already_stopped"));return}await chunkEOLBEWUW_cjs.a.stop(),re(),O.info("Gateway stopped successfully");}catch(r){O.error("Failed to stop gateway",{error:r instanceof Error?r.message:String(r)}),console.error(`${u("cli.error.stop_failed")}: ${r instanceof Error?r.message:String(r)}`),process.exit(1);}}async function ce(r){O.info("Restarting gateway service");try{let t={};r.port&&(t.port=r.port),r.hostname&&(t.hostname=r.hostname),await chunkEOLBEWUW_cjs.a.restart(t);let i=(await chunkEOLBEWUW_cjs.a.get())?.getStatus();Ht({port:i?.port||r.port||8080,hostname:i?.hostname||r.hostname||"localhost",connections:i?.connections||0,mode:chunkEKLLH53Y_cjs.O()?"integrated":"standalone"}),kt(),O.info("Gateway restarted successfully");}catch(t){O.error("Failed to restart gateway",{error:t instanceof Error?t.message:String(t)}),console.error(`${u("cli.error.restart_failed")}: ${t instanceof Error?t.message:String(t)}`),process.exit(1);}}function kt(){let r=async t=>{O.debug(`Received ${t}, shutting down gracefully...`),console.log(`
27
+ ${u("cli.shutdown_signal",{vars:{signal:t}})}`);try{await chunkEOLBEWUW_cjs.a.stop(),O.debug("Gateway stopped"),console.log(u("cli.shutdown_success"));}catch(e){O.error("Error during shutdown",{error:e instanceof Error?e.message:String(e)});}process.exit(0);};process.on("SIGINT",()=>{r("SIGINT").catch(console.error);}),process.on("SIGTERM",()=>{r("SIGTERM").catch(console.error);});}async function L(r,t){switch(r){case "start":await ae(t);break;case "stop":await le();break;case "restart":await ce(t);break;case "status":await oe();break;default:console.error(u("cli.unknown_command",{vars:{command:r}})),process.exit(1);}}function ue(r){r.command("start").description(u("cli.command.start.desc")).option("-D, --directory <path>",u("cli.option.directory")).option("-p, --port <number>",u("cli.option.port"),t=>parseInt(t,10)).option("-H, --hostname <address>",u("cli.option.hostname")).option("-d, --debug",u("cli.option.debug"),false).action(async t=>{await L("start",{directory:t.directory,port:t.port,hostname:t.hostname,debug:t.debug});}),r.command("stop").description(u("cli.command.stop.desc")).action(async()=>{await L("stop",{});}),r.command("restart").description(u("cli.command.restart.desc")).option("-D, --directory <path>",u("cli.option.directory")).option("-p, --port <number>",u("cli.option.port"),t=>parseInt(t,10)).option("-H, --hostname <address>",u("cli.option.hostname")).option("-d, --debug",u("cli.option.debug"),false).action(async t=>{await L("restart",{directory:t.directory,port:t.port,hostname:t.hostname,debug:t.debug});}),r.command("status").description(u("cli.command.status.desc")).action(async()=>{await L("status",{});}),r.addHelpCommand("help",u("cli.help.command")).addHelpText("after",`
28
28
 
29
29
  ${u("cli.examples.title")}:
30
30
  $ gateway start --port 8080 # ${u("cli.example.start")}
package/dist/cli.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import {a as a$3}from'./chunks/chunk-UHALF3PM.mjs';import {a as a$2,O as O$1}from'./chunks/chunk-ETYFY7SI.mjs';import {a}from'./chunks/chunk-SJNPXLNN.mjs';import {c,a as a$1,d}from'./chunks/chunk-TY6W6O7O.mjs';import {loadEnv}from'@easbot/utils';var $=c(R=>{a();var H=class extends Error{constructor(t,e,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0;}},F=class extends H{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name;}};R.CommanderError=H;R.InvalidArgumentError=F;});var k=c(N=>{a();var{InvalidArgumentError:Lt}=$(),D=class{constructor(t,e){switch(this.description=e||"",this.variadic=false,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case "<":this.required=true,this._name=t.slice(1,-1);break;case "[":this.required=false,this._name=t.slice(1,-1);break;default:this.required=true,this._name=t;break}this._name.endsWith("...")&&(this.variadic=true,this._name=this._name.slice(0,-3));}name(){return this._name}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new Lt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}argRequired(){return this.required=true,this}argOptional(){return this.required=false,this}};function It(r){let t=r.name()+(r.variadic===true?"...":"");return r.required?"<"+t+">":"["+t+"]"}N.Argument=D;N.humanReadableArgName=It;});var j=c(q=>{a();var{humanReadableArgName:Wt}=k(),M=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=false,this.sortOptions=false,this.showGlobalOptions=false;}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80;}visibleCommands(t){let e=t.commands.filter(n=>!n._hidden),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort((n,s)=>n.name().localeCompare(s.name())),e}compareOptions(t,e){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter(n=>!n.hidden),i=t._getHelpOption();if(i&&!i.hidden){let n=i.short&&t._findOption(i.short),s=i.long&&t._findOption(i.long);!n&&!s?e.push(i):i.long&&!s?e.push(t.createOption(i.long,i.description)):i.short&&!n&&e.push(t.createOption(i.short,i.description));}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return [];let e=[];for(let i=t.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);e.push(...n);}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||"";}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(i=>Wt(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(n)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(n)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let n=t.parent;n;n=n.parent)i=n.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatItemList(t,e,i){return e.length===0?[]:[i.styleTitle(t),...e,""]}groupItems(t,e,i){let n=new Map;return t.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]);}),e.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]),n.get(o).push(s);}),n}formatHelp(t,e){let i=e.padWidth(t,e),n=e.helpWidth??80;function s(c,d){return e.formatItem(c,i,d,e)}let o=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],a=e.commandDescription(t);a.length>0&&(o=o.concat([e.boxWrap(e.styleCommandDescription(a),n),""]));let h=e.visibleArguments(t).map(c=>s(e.styleArgumentTerm(e.argumentTerm(c)),e.styleArgumentDescription(e.argumentDescription(c))));if(o=o.concat(this.formatItemList("Arguments:",h,e)),this.groupItems(t.options,e.visibleOptions(t),c=>c.helpGroupHeading??"Options:").forEach((c,d)=>{let S=c.map(x=>s(e.styleOptionTerm(e.optionTerm(x)),e.styleOptionDescription(e.optionDescription(x))));o=o.concat(this.formatItemList(d,S,e));}),e.showGlobalOptions){let c=e.visibleGlobalOptions(t).map(d=>s(e.styleOptionTerm(e.optionTerm(d)),e.styleOptionDescription(e.optionDescription(d))));o=o.concat(this.formatItemList("Global Options:",c,e));}return this.groupItems(t.commands,e.visibleCommands(t),c=>c.helpGroup()||"Commands:").forEach((c,d)=>{let S=c.map(x=>s(e.styleSubcommandTerm(e.subcommandTerm(x)),e.styleSubcommandDescription(e.subcommandDescription(x))));o=o.concat(this.formatItemList(d,S,e));}),o.join(`
1
+ import {a as a$3}from'./chunks/chunk-J2DSTELL.mjs';import {a as a$2,O as O$1}from'./chunks/chunk-ETYFY7SI.mjs';import {a}from'./chunks/chunk-SJNPXLNN.mjs';import {c,a as a$1,d}from'./chunks/chunk-TY6W6O7O.mjs';import {loadEnv}from'@easbot/utils';var $=c(R=>{a();var H=class extends Error{constructor(t,e,i){super(i),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=e,this.exitCode=t,this.nestedError=void 0;}},F=class extends H{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name;}};R.CommanderError=H;R.InvalidArgumentError=F;});var k=c(N=>{a();var{InvalidArgumentError:Lt}=$(),D=class{constructor(t,e){switch(this.description=e||"",this.variadic=false,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case "<":this.required=true,this._name=t.slice(1,-1);break;case "[":this.required=false,this._name=t.slice(1,-1);break;default:this.required=true,this._name=t;break}this._name.endsWith("...")&&(this.variadic=true,this._name=this._name.slice(0,-3));}name(){return this._name}_collectValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:(e.push(t),e)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new Lt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(e,i):e},this}argRequired(){return this.required=true,this}argOptional(){return this.required=false,this}};function It(r){let t=r.name()+(r.variadic===true?"...":"");return r.required?"<"+t+">":"["+t+"]"}N.Argument=D;N.humanReadableArgName=It;});var j=c(q=>{a();var{humanReadableArgName:Wt}=k(),M=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=false,this.sortOptions=false,this.showGlobalOptions=false;}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80;}visibleCommands(t){let e=t.commands.filter(n=>!n._hidden),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort((n,s)=>n.name().localeCompare(s.name())),e}compareOptions(t,e){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter(n=>!n.hidden),i=t._getHelpOption();if(i&&!i.hidden){let n=i.short&&t._findOption(i.short),s=i.long&&t._findOption(i.long);!n&&!s?e.push(i):i.long&&!s?e.push(t.createOption(i.long,i.description)):i.short&&!n&&e.push(t.createOption(i.short,i.description));}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return [];let e=[];for(let i=t.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);e.push(...n);}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||"";}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(i=>Wt(i)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(n)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(n)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let n=t.parent;n;n=n.parent)i=n.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatItemList(t,e,i){return e.length===0?[]:[i.styleTitle(t),...e,""]}groupItems(t,e,i){let n=new Map;return t.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]);}),e.forEach(s=>{let o=i(s);n.has(o)||n.set(o,[]),n.get(o).push(s);}),n}formatHelp(t,e){let i=e.padWidth(t,e),n=e.helpWidth??80;function s(c,d){return e.formatItem(c,i,d,e)}let o=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],a=e.commandDescription(t);a.length>0&&(o=o.concat([e.boxWrap(e.styleCommandDescription(a),n),""]));let h=e.visibleArguments(t).map(c=>s(e.styleArgumentTerm(e.argumentTerm(c)),e.styleArgumentDescription(e.argumentDescription(c))));if(o=o.concat(this.formatItemList("Arguments:",h,e)),this.groupItems(t.options,e.visibleOptions(t),c=>c.helpGroupHeading??"Options:").forEach((c,d)=>{let S=c.map(x=>s(e.styleOptionTerm(e.optionTerm(x)),e.styleOptionDescription(e.optionDescription(x))));o=o.concat(this.formatItemList(d,S,e));}),e.showGlobalOptions){let c=e.visibleGlobalOptions(t).map(d=>s(e.styleOptionTerm(e.optionTerm(d)),e.styleOptionDescription(e.optionDescription(d))));o=o.concat(this.formatItemList("Global Options:",c,e));}return this.groupItems(t.commands,e.visibleCommands(t),c=>c.helpGroup()||"Commands:").forEach((c,d)=>{let S=c.map(x=>s(e.styleSubcommandTerm(e.subcommandTerm(x)),e.styleSubcommandDescription(e.subcommandDescription(x))));o=o.concat(this.formatItemList(d,S,e));}),o.join(`
2
2
  `)}displayWidth(t){return at(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e==="[command]"?this.styleSubcommandText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleCommandText(e)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleSubcommandText(e)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}preformatted(t){return /\n[^\S\r\n]/.test(t)}formatItem(t,e,i,n){let o=" ".repeat(2);if(!i)return o+t;let a=t.padEnd(e+t.length-n.displayWidth(t)),h=2,l=(this.helpWidth??80)-e-h-2,c;return l<this.minWidthToWrap||n.preformatted(i)?c=i:c=n.boxWrap(i,l).replace(/\n/g,`
3
3
  `+" ".repeat(e+h)),o+a+" ".repeat(h)+c.replace(/\n/g,`
4
4
  ${o}`)}boxWrap(t,e){if(e<this.minWidthToWrap)return t;let i=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,s=[];return i.forEach(o=>{let a=o.match(n);if(a===null){s.push("");return}let h=[a.shift()],p=this.displayWidth(h[0]);a.forEach(l=>{let c=this.displayWidth(l);if(p+c<=e){h.push(l),p+=c;return}s.push(h.join(""));let d=l.trimStart();h=[d],p=this.displayWidth(d);}),s.push(h.join(""));}),s.join(`
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var chunkLV4EDVUL_cjs=require('./chunks/chunk-LV4EDVUL.cjs'),chunkCTTZF7B6_cjs=require('./chunks/chunk-CTTZF7B6.cjs'),chunkEKLLH53Y_cjs=require('./chunks/chunk-EKLLH53Y.cjs'),chunkSIOB4FC7_cjs=require('./chunks/chunk-SIOB4FC7.cjs'),chunkXQVVSJRM_cjs=require('./chunks/chunk-XQVVSJRM.cjs');chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var u=chunkEKLLH53Y_cjs.a.create({service:"gateway:agent-registry"}),k=class{constructor(n={}){chunkXQVVSJRM_cjs.e(this,"config");chunkXQVVSJRM_cjs.e(this,"agents",new Map);chunkXQVVSJRM_cjs.e(this,"heartbeatTimer",null);chunkXQVVSJRM_cjs.e(this,"roundRobinIndex",0);this.config={...chunkCTTZF7B6_cjs.j,...n};}async register(n){if(this.agents.has(n.id))throw new Error(`Agent with ID "${n.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let e=Date.now(),t={...n,status:"healthy",lastHeartbeat:e,registeredAt:e,connectionCount:0};this.agents.set(n.id,t),u.info("Agent registered",{agentId:n.id,name:n.name,capabilities:n.capabilities,address:n.address,totalAgents:this.agents.size});}async deregister(n){let e=this.agents.get(n);if(!e){u.warn("Attempted to deregister unknown agent",{agentId:n});return}this.agents.delete(n),u.info("Agent deregistered",{agentId:n,name:e.name,totalAgents:this.agents.size});}async heartbeat(n,e){let t=this.agents.get(n);if(!t)throw u.warn("Heartbeat received from unknown agent",{agentId:n}),new Error(`Agent "${n}" is not registered`);t.lastHeartbeat=Date.now(),t.status="healthy",e&&(t.metadata={...t.metadata,...e}),u.debug("Agent heartbeat received",{agentId:n,lastHeartbeat:t.lastHeartbeat});}getAgent(n){return this.agents.get(n)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(n=>n.status==="healthy")}selectAgent(n){let{strategy:e,capabilities:t,healthyOnly:s=true}=n,i=s?this.getHealthyAgents():this.getAllAgents();if(t&&t.length>0&&(i=i.filter(o=>t.every(p=>o.capabilities.includes(p)))),i.length===0){u.warn("No agents available for selection",{strategy:e,capabilities:t,healthyOnly:s,totalAgents:this.agents.size});return}let a;switch(e){case "random":a=this.selectRandom(i);break;case "round-robin":a=this.selectRoundRobin(i);break;case "least-connections":a=this.selectLeastConnections(i);break;default:a=this.selectRandom(i);}return u.debug("Agent selected",{agentId:a.id,strategy:e,connectionCount:a.connectionCount}),a}incrementConnection(n){let e=this.agents.get(n);e&&(e.connectionCount++,u.debug("Agent connection incremented",{agentId:n,connectionCount:e.connectionCount}));}decrementConnection(n){let e=this.agents.get(n);e&&e.connectionCount>0&&(e.connectionCount--,u.debug("Agent connection decremented",{agentId:n,connectionCount:e.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){u.warn("Heartbeat check is already running");return}u.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,u.info("Heartbeat check stopped"));}checkHeartbeats(){let n=Date.now(),{heartbeatTimeout:e,autoDeregisterTimeout:t}=this.config,s=[],i=0;for(let[a,o]of this.agents.entries()){let p=n-o.lastHeartbeat;if(p>t){s.push(a);continue}p>e&&o.status==="healthy"&&(o.status="unhealthy",i++,u.warn("Agent marked as unhealthy due to heartbeat timeout",{agentId:a,lastHeartbeat:o.lastHeartbeat,timeSinceLastHeartbeat:p,timeout:e}));}for(let a of s){let o=this.agents.get(a);o&&(u.info("Auto-deregistering agent due to timeout",{agentId:a,name:o.name,lastHeartbeat:o.lastHeartbeat,timeout:t}),this.agents.delete(a));}(i>0||s.length>0)&&u.info("Heartbeat check completed",{unhealthyCount:i,deregisteredCount:s.length,totalAgents:this.agents.size});}selectRandom(n){let e=Math.floor(Math.random()*n.length);return n[e]}selectRoundRobin(n){this.roundRobinIndex=this.roundRobinIndex%n.length;let e=n[this.roundRobinIndex];return this.roundRobinIndex++,e}selectLeastConnections(n){return n.reduce((e,t)=>t.connectionCount<e.connectionCount?t:e)}getStats(){let n=this.getAllAgents();return {totalAgents:n.length,healthyAgents:n.filter(e=>e.status==="healthy").length,unhealthyAgents:n.filter(e=>e.status==="unhealthy").length,offlineAgents:n.filter(e=>e.status==="offline").length,totalConnections:n.reduce((e,t)=>e+t.connectionCount,0)}}setAgentStatus(n,e){let t=this.agents.get(n);t&&(t.status=e);}setLastHeartbeat(n,e){let t=this.agents.get(n);t&&(t.lastHeartbeat=e);}};chunkSIOB4FC7_cjs.a();var c=chunkEKLLH53Y_cjs.a.create({service:"gateway:agent-sync-manager"}),T=class{constructor(n){chunkXQVVSJRM_cjs.e(this,"config");chunkXQVVSJRM_cjs.e(this,"registry");chunkXQVVSJRM_cjs.e(this,"localNodeId");chunkXQVVSJRM_cjs.e(this,"localNodeName");chunkXQVVSJRM_cjs.e(this,"remoteNodes",new Map);chunkXQVVSJRM_cjs.e(this,"remoteAgents",new Map);chunkXQVVSJRM_cjs.e(this,"syncTimer",null);chunkXQVVSJRM_cjs.e(this,"running",false);chunkXQVVSJRM_cjs.e(this,"httpClient");this.registry=n.registry,this.localNodeId=n.localNodeId,this.localNodeName=n.localNodeName,this.config={...chunkCTTZF7B6_cjs.k,...n.config},this.httpClient=n.httpClient||{fetch:globalThis.fetch.bind(globalThis)};}async start(){if(this.running){c.warn("Agent sync manager is already running");return}c.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let n of this.config.remoteNodes)this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.running=true,c.info("Agent sync manager started");}async stop(){if(!this.running){c.warn("Agent sync manager is not running");return}c.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,c.info("Agent sync manager stopped");}async pullFromAllNodes(){for(let[n]of this.remoteNodes.entries())try{await this.pullFromNode(n);}catch(e){c.error("Failed to pull from node",{nodeId:n,error:e.message});}}async pullFromNode(n){let e=this.remoteNodes.get(n);if(!e)throw new Error(`Unknown remote node: ${n}`);e.status="syncing";let t=this.config.remoteNodes.find(s=>s.id===n);if(!t)throw new Error(`Remote node not found in config: ${n}`);c.debug("Pulling agent list from node",{nodeId:n,address:t.address});try{let s=`http://${t.address}:${t.port}/sync/agents`,i=await this.httpClient.fetch(s,{method:"GET",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);let o=(await i.json()).agents||[];for(let p of o)p.sourceGatewayId=n,this.remoteAgents.set(p.id,p);return e.lastSyncAt=Date.now(),e.status="synced",e.info.lastSyncAt=e.lastSyncAt,e.info.status="online",delete e.error,c.info("Pulled agent list from node",{nodeId:n,agentCount:o.length,lastSyncAt:e.lastSyncAt}),o}catch(s){throw e.status="error",e.error=s.message,e.info.status="offline",c.error("Failed to pull from node",{nodeId:n,error:s.message}),s}}async pushEvent(n){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let e=[];for(let[t]of this.remoteNodes.entries())e.push(this.pushToNode(t,n));await Promise.allSettled(e);}async pushToNode(n,e){let t=this.config.remoteNodes.find(s=>s.id===n);if(!t){c.warn("Unknown remote node for push",{nodeId:n});return}try{let s=`http://${t.address}:${t.port}/sync/events`,i=await this.httpClient.fetch(s,{method:"POST",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId},body:JSON.stringify(e)});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);c.debug("Pushed event to node",{nodeId:n,eventType:e.type});}catch(s){c.error("Failed to push to node",{nodeId:n,eventType:e.type,error:s.message});}}async handleSyncMessage(n){switch(c.debug("Received sync message",{type:n.type,sourceNodeId:n.sourceNodeId}),n.type){case "agent_list_request":await this.handleAgentListRequest(n);break;case "agent_list_response":await this.handleAgentListResponse(n);break;case "agent_register":await this.handleAgentRegister(n);break;case "agent_deregister":await this.handleAgentDeregister(n);break;case "agent_heartbeat":await this.handleAgentHeartbeat(n);break;case "agent_status_change":await this.handleAgentStatusChange(n);break;default:c.warn("Unknown sync message type",{type:n.type});}}async handleAgentListRequest(n){let e=this.getLocalAgentsForSync(),t={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:n.requestId,agents:e,fullList:true,syncAt:Date.now()};await this.pushToNode(n.sourceNodeId,t);}async handleAgentListResponse(n){for(let e of n.agents)this.remoteAgents.set(e.id,e);c.info("Received agent list response",{sourceNodeId:n.sourceNodeId,agentCount:n.agents.length});}async handleAgentRegister(n){let{agent:e}=n,t=this.remoteAgents.get(e.id);if(t){let s=this.resolveConflict(t,e);this.remoteAgents.set(e.id,s);}else this.remoteAgents.set(e.id,e);c.info("Remote agent registered",{agentId:e.id,name:e.name,sourceNodeId:n.sourceNodeId});}async handleAgentDeregister(n){let{agentId:e}=n;this.remoteAgents.delete(e),c.info("Remote agent deregistered",{agentId:e,sourceNodeId:n.sourceNodeId});}async handleAgentHeartbeat(n){let{agentId:e,heartbeatAt:t,status:s}=n,i=this.remoteAgents.get(e);i&&(i.updatedAt=t,i.status=s),c.debug("Remote agent heartbeat received",{agentId:e,status:s,sourceNodeId:n.sourceNodeId});}async handleAgentStatusChange(n){let{agentId:e,newStatus:t,changedAt:s}=n,i=this.remoteAgents.get(e);i&&(i.status=t,i.updatedAt=s),c.info("Remote agent status changed",{agentId:e,newStatus:t,sourceNodeId:n.sourceNodeId});}resolveConflict(n,e){switch(this.config.conflictResolution){case "latest":return e.updatedAt>n.updatedAt?e:n;case "local":return n;case "remote":return e;default:return e.updatedAt>n.updatedAt?e:n}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(e=>({id:e.id,name:e.name,sourceGatewayId:this.localNodeId,address:e.address,capabilities:e.capabilities,status:e.status,updatedAt:e.lastHeartbeat,metadata:e.metadata}))}getMergedAgentList(){let n=new Map;for(let e of this.getLocalAgentsForSync())n.set(e.id,e);for(let[e,t]of this.remoteAgents.entries())n.has(e)||n.set(e,t);return Array.from(n.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values())}getStats(){let n=this.registry.getAllAgents(),e=0,t=0;for(let i of this.remoteNodes.values())i.info.status==="online"?e++:t++;let s=null;for(let i of this.remoteNodes.values())i.lastSyncAt>(s||0)&&(s=i.lastSyncAt);return {localAgentCount:n.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:n.length+this.remoteAgents.size,onlineNodeCount:e,offlineNodeCount:t,lastSyncAt:s}}isRunning(){return this.running}addRemoteNode(n){this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"}),c.info("Remote node added",{nodeId:n.id,address:n.address});}removeRemoteNode(n){this.remoteNodes.delete(n);for(let[e,t]of this.remoteAgents.entries())t.sourceGatewayId===n&&this.remoteAgents.delete(e);c.info("Remote node removed",{nodeId:n});}};chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var l=class{constructor(){chunkXQVVSJRM_cjs.e(this,"version","1.0.0");chunkXQVVSJRM_cjs.e(this,"log");chunkXQVVSJRM_cjs.e(this,"config",null);chunkXQVVSJRM_cjs.e(this,"messageHandler",null);chunkXQVVSJRM_cjs.e(this,"_status","stopped");chunkXQVVSJRM_cjs.e(this,"lastActivity",0);}initLog(){this.log=chunkEKLLH53Y_cjs.a.create({service:`channel:${this.platform}`});}async start(n,e){if(this._status==="running"){this.log.warn("plugin is already running");return}this.log.info("starting channel plugin",{id:this.id,platform:this.platform}),this._status="starting",this.config=n,this.messageHandler=e;try{await this.doStart(),this._status="running",this.lastActivity=Date.now(),this.log.info("channel plugin started",{id:this.id});}catch(t){throw this._status="error",this.log.error("failed to start channel plugin",{error:String(t)}),t}}async stop(){if(this._status==="stopped"){this.log.warn("plugin is already stopped");return}this.log.info("stopping channel plugin",{id:this.id}),this._status="stopping";try{await this.doStop(),this._status="stopped",this.log.info("channel plugin stopped",{id:this.id});}catch(n){throw this._status="error",this.log.error("failed to stop channel plugin",{error:String(n)}),n}}async healthCheck(){try{return {healthy:await this.doHealthCheck(),lastCheck:Date.now()}}catch(n){return {healthy:false,lastCheck:Date.now(),error:n instanceof Error?n.message:String(n)}}}getStatus(){return {status:this._status,lastActivity:this.lastActivity}}async doHealthCheck(){return this._status==="running"}updateActivity(){this.lastActivity=Date.now();}async handleMessage(n){if(!this.messageHandler){this.log.warn("no message handler set, dropping message",{id:n.id});return}this.updateActivity(),await this.messageHandler.onMessage(n);}async handleEvent(n,e){if(!this.messageHandler){this.log.warn("no message handler set, dropping event",{type:n});return}await this.messageHandler.onEvent({type:n,channelId:this.id,data:e,timestamp:Date.now()});}};chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var x=class{constructor(n){chunkXQVVSJRM_cjs.e(this,"log");chunkXQVVSJRM_cjs.e(this,"config");chunkXQVVSJRM_cjs.e(this,"ws",null);chunkXQVVSJRM_cjs.e(this,"state","disconnected");chunkXQVVSJRM_cjs.e(this,"subscriptions",new Map);chunkXQVVSJRM_cjs.e(this,"messageCallbacks",new Set);chunkXQVVSJRM_cjs.e(this,"agentListCallbacks",new Set);chunkXQVVSJRM_cjs.e(this,"cachedAgentList",[]);chunkXQVVSJRM_cjs.e(this,"localAgentList",[]);chunkXQVVSJRM_cjs.e(this,"reconnectAttempts",0);chunkXQVVSJRM_cjs.e(this,"reconnectTimer",null);chunkXQVVSJRM_cjs.e(this,"heartbeatTimer",null);chunkXQVVSJRM_cjs.e(this,"agentListRequestId",null);chunkXQVVSJRM_cjs.e(this,"agentListRequestResolve",null);this.config={url:n.url,type:n.type,id:n.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,reconnect:{enabled:n.reconnect?.enabled??true,maxAttempts:n.reconnect?.maxAttempts??5,delay:n.reconnect?.delay??3e3},heartbeat:{enabled:n.heartbeat?.enabled??true,interval:n.heartbeat?.interval??3e4}},this.log=chunkEKLLH53Y_cjs.a.create({service:`gateway:client:${this.config.id}`});}async connect(){if(this.state==="connected"||this.state==="connecting"){this.log.warn("already connected or connecting");return}return this.state="connecting",this.log.info("connecting to gateway",{url:this.config.url}),new Promise((n,e)=>{try{this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{this.state="connected",this.reconnectAttempts=0,this.log.info("connected to gateway"),this.config.heartbeat.enabled&&this.startHeartbeat(),this.resubscribeAll(),n();},this.ws.onmessage=t=>{this.handleMessage(t.data);},this.ws.onclose=t=>{this.handleClose(t.code,t.reason);},this.ws.onerror=t=>{this.log.error("WebSocket error",{error:String(t)}),this.state==="connecting"&&e(new Error("Connection failed"));};}catch(t){this.state="disconnected",e(t);}})}async disconnect(){this.state!=="disconnected"&&(this.log.info("disconnecting from gateway"),this.stopHeartbeat(),this.stopReconnect(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.state="disconnected",this.log.info("disconnected from gateway"));}async subscribe(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"subscribe",sessionId:n,clientId:this.config.id}),this.log.info("subscribed to session",{sessionId:n});}async unsubscribe(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:n,clientId:this.config.id}),this.subscriptions.delete(n),this.log.info("unsubscribed from session",{sessionId:n});}async send(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:n});}onMessage(n){this.messageCallbacks.add(n);}offMessage(n){this.messageCallbacks.delete(n);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(n){this.localAgentList=n,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((n,e)=>{let t=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=t,this.agentListRequestResolve=n,this.sendData({type:"agent_list_request",requestId:t}),setTimeout(()=>{this.agentListRequestId===t&&(this.agentListRequestId=null,this.agentListRequestResolve=null,e(new Error("Agent list request timeout")));},1e4);})}getConnectableAgents(n={}){let{localAgents:e,preferLocal:t=true,filterOffline:s=true}=n,i=e||this.localAgentList,a=this.cachedAgentList,o=this.mergeAgentLists(i,a,t);return s?o.filter(p=>p.status!=="offline"):o}onAgentListChange(n){this.agentListCallbacks.add(n);}offAgentListChange(n){this.agentListCallbacks.delete(n);}mergeAgentLists(n,e,t){let s=new Map,i=t?e:n,a=t?n:e;for(let o of i)s.set(o.id,o);for(let o of a)s.set(o.id,o);return Array.from(s.values())}updateMergedAgentList(){let n=this.getConnectableAgents({filterOffline:false});for(let e of this.agentListCallbacks)try{e(n);}catch(t){this.log.error("agent list callback error",{error:String(t)});}}handleAgentListResponse(n,e){e&&this.agentListRequestId===e&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(n),this.agentListRequestResolve=null),this.cachedAgentList=n,this.updateMergedAgentList(),this.log.debug("received agent list",{count:n.length});}sendData(n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(n));}handleMessage(n){try{let e=JSON.parse(n);switch(e.type){case "message":this.handleGatewayMessage(e.message);break;case "subscribed":this.subscriptions.set(e.sessionId,e.subscription);break;case "unsubscribed":this.subscriptions.delete(e.sessionId);break;case "pong":break;case "agent_list_response":this.handleAgentListResponse(e.agents||[],e.requestId);break;case "agent_update":this.handleAgentUpdate(e.agent,e.action);break;default:this.log.debug("unknown message type",{type:e.type});}}catch(e){this.log.error("failed to parse message",{error:String(e)});}}handleAgentUpdate(n,e){switch(e){case "add":case "update":{let t=this.cachedAgentList.findIndex(s=>s.id===n.id);t>=0?this.cachedAgentList[t]=n:this.cachedAgentList.push(n);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(t=>t.id!==n.id);break}this.updateMergedAgentList();}handleGatewayMessage(n){for(let e of this.messageCallbacks)try{e(n);}catch(t){this.log.error("message callback error",{error:String(t)});}}handleClose(n,e){this.log.info("connection closed",{code:n,reason:e}),this.state="disconnected",this.ws=null,this.stopHeartbeat(),this.config.reconnect.enabled&&this.scheduleReconnect();}scheduleReconnect(){if(this.reconnectAttempts>=this.config.reconnect.maxAttempts){this.log.error("max reconnect attempts reached");return}this.reconnectAttempts++,this.state="reconnecting";let n=this.config.reconnect.delay*this.reconnectAttempts;this.log.info("scheduling reconnect",{attempt:this.reconnectAttempts,delay:n}),this.reconnectTimer=setTimeout(async()=>{try{await this.connect();}catch(e){this.log.error("reconnect failed",{error:String(e)});}},n);}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.state==="connected"&&this.sendData({type:"ping"});},this.config.heartbeat.interval);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);}async resubscribeAll(){for(let n of this.subscriptions.keys())try{await this.subscribe(n);}catch(e){this.log.error("failed to resubscribe",{sessionId:n,error:String(e)});}}};chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var y=class extends l{constructor(e="telegram-main"){super();chunkXQVVSJRM_cjs.e(this,"id");chunkXQVVSJRM_cjs.e(this,"platform","telegram");chunkXQVVSJRM_cjs.e(this,"name","Telegram Bot");chunkXQVVSJRM_cjs.e(this,"botConfig",null);chunkXQVVSJRM_cjs.e(this,"pollingInterval",null);chunkXQVVSJRM_cjs.e(this,"lastUpdateId",0);chunkXQVVSJRM_cjs.e(this,"baseUrl","");this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");this.baseUrl=`https://api.telegram.org/bot${this.botConfig.botToken}`;let e=await this.getMe();this.log.info("Telegram bot connected",{id:e.id,username:e.username,first_name:e.first_name}),this.botConfig.polling?.enabled!==false&&this.startPolling();}async doStop(){this.stopPolling(),this.botConfig=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Chat ID is required");let s=this.extractText(e);return (await this.sendMessage(t,s)).message_id.toString()}startPolling(){if(this.pollingInterval)return;let e=this.botConfig?.polling?.interval??1e3;this.pollingInterval=setInterval(async()=>{try{await this.poll();}catch(t){this.log.error("Polling error",{error:String(t)});}},e),this.log.info("Polling started",{interval:e});}stopPolling(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null,this.log.info("Polling stopped"));}async poll(){let e=await this.getUpdates(this.lastUpdateId+1,100,0);for(let t of e)this.lastUpdateId=t.update_id,t.message&&await this.handleTelegramMessage(t.message);}async handleTelegramMessage(e){if(this.updateActivity(),e.from?.is_bot)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return chunkCTTZF7B6_cjs.c(t,"input",this.parseContent(e),{channel:{platform:"telegram",channelId:this.id,userId:e.from?.id.toString(),chatId:e.chat.id.toString(),username:e.from?.username,firstName:e.from?.first_name,lastName:e.from?.last_name,chatType:e.chat.type,chatTitle:e.chat.title},context:{replyTo:e.reply_to_message?.message_id.toString()}})}parseContent(e){let t=[];if(e.text&&t.push({type:"text",text:e.text}),e.photo&&e.photo.length>0){let s=e.photo[e.photo.length-1];s&&t.push({type:"image",image:s.file_id,mime:"image/jpeg"});}if(e.document&&t.push({type:"file",data:e.document.file_id,mime:e.document.mime_type}),e.caption&&t.length>0){let s=t[0];s&&s.type==="text"?t[0]={type:"text",text:`${s.text}
1
+ 'use strict';var chunkEOLBEWUW_cjs=require('./chunks/chunk-EOLBEWUW.cjs'),chunkCTTZF7B6_cjs=require('./chunks/chunk-CTTZF7B6.cjs'),chunkEKLLH53Y_cjs=require('./chunks/chunk-EKLLH53Y.cjs'),chunkSIOB4FC7_cjs=require('./chunks/chunk-SIOB4FC7.cjs'),chunkXQVVSJRM_cjs=require('./chunks/chunk-XQVVSJRM.cjs');chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var u=chunkEKLLH53Y_cjs.a.create({service:"gateway:agent-registry"}),k=class{constructor(n={}){chunkXQVVSJRM_cjs.e(this,"config");chunkXQVVSJRM_cjs.e(this,"agents",new Map);chunkXQVVSJRM_cjs.e(this,"heartbeatTimer",null);chunkXQVVSJRM_cjs.e(this,"roundRobinIndex",0);this.config={...chunkCTTZF7B6_cjs.j,...n};}async register(n){if(this.agents.has(n.id))throw new Error(`Agent with ID "${n.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let e=Date.now(),t={...n,status:"healthy",lastHeartbeat:e,registeredAt:e,connectionCount:0};this.agents.set(n.id,t),u.info("Agent registered",{agentId:n.id,name:n.name,capabilities:n.capabilities,address:n.address,totalAgents:this.agents.size});}async deregister(n){let e=this.agents.get(n);if(!e){u.warn("Attempted to deregister unknown agent",{agentId:n});return}this.agents.delete(n),u.info("Agent deregistered",{agentId:n,name:e.name,totalAgents:this.agents.size});}async heartbeat(n,e){let t=this.agents.get(n);if(!t)throw u.warn("Heartbeat received from unknown agent",{agentId:n}),new Error(`Agent "${n}" is not registered`);t.lastHeartbeat=Date.now(),t.status="healthy",e&&(t.metadata={...t.metadata,...e}),u.debug("Agent heartbeat received",{agentId:n,lastHeartbeat:t.lastHeartbeat});}getAgent(n){return this.agents.get(n)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(n=>n.status==="healthy")}selectAgent(n){let{strategy:e,capabilities:t,healthyOnly:s=true}=n,i=s?this.getHealthyAgents():this.getAllAgents();if(t&&t.length>0&&(i=i.filter(o=>t.every(p=>o.capabilities.includes(p)))),i.length===0){u.warn("No agents available for selection",{strategy:e,capabilities:t,healthyOnly:s,totalAgents:this.agents.size});return}let a;switch(e){case "random":a=this.selectRandom(i);break;case "round-robin":a=this.selectRoundRobin(i);break;case "least-connections":a=this.selectLeastConnections(i);break;default:a=this.selectRandom(i);}return u.debug("Agent selected",{agentId:a.id,strategy:e,connectionCount:a.connectionCount}),a}incrementConnection(n){let e=this.agents.get(n);e&&(e.connectionCount++,u.debug("Agent connection incremented",{agentId:n,connectionCount:e.connectionCount}));}decrementConnection(n){let e=this.agents.get(n);e&&e.connectionCount>0&&(e.connectionCount--,u.debug("Agent connection decremented",{agentId:n,connectionCount:e.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){u.warn("Heartbeat check is already running");return}u.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,u.info("Heartbeat check stopped"));}checkHeartbeats(){let n=Date.now(),{heartbeatTimeout:e,autoDeregisterTimeout:t}=this.config,s=[],i=0;for(let[a,o]of this.agents.entries()){let p=n-o.lastHeartbeat;if(p>t){s.push(a);continue}p>e&&o.status==="healthy"&&(o.status="unhealthy",i++,u.warn("Agent marked as unhealthy due to heartbeat timeout",{agentId:a,lastHeartbeat:o.lastHeartbeat,timeSinceLastHeartbeat:p,timeout:e}));}for(let a of s){let o=this.agents.get(a);o&&(u.info("Auto-deregistering agent due to timeout",{agentId:a,name:o.name,lastHeartbeat:o.lastHeartbeat,timeout:t}),this.agents.delete(a));}(i>0||s.length>0)&&u.info("Heartbeat check completed",{unhealthyCount:i,deregisteredCount:s.length,totalAgents:this.agents.size});}selectRandom(n){let e=Math.floor(Math.random()*n.length);return n[e]}selectRoundRobin(n){this.roundRobinIndex=this.roundRobinIndex%n.length;let e=n[this.roundRobinIndex];return this.roundRobinIndex++,e}selectLeastConnections(n){return n.reduce((e,t)=>t.connectionCount<e.connectionCount?t:e)}getStats(){let n=this.getAllAgents();return {totalAgents:n.length,healthyAgents:n.filter(e=>e.status==="healthy").length,unhealthyAgents:n.filter(e=>e.status==="unhealthy").length,offlineAgents:n.filter(e=>e.status==="offline").length,totalConnections:n.reduce((e,t)=>e+t.connectionCount,0)}}setAgentStatus(n,e){let t=this.agents.get(n);t&&(t.status=e);}setLastHeartbeat(n,e){let t=this.agents.get(n);t&&(t.lastHeartbeat=e);}};chunkSIOB4FC7_cjs.a();var c=chunkEKLLH53Y_cjs.a.create({service:"gateway:agent-sync-manager"}),T=class{constructor(n){chunkXQVVSJRM_cjs.e(this,"config");chunkXQVVSJRM_cjs.e(this,"registry");chunkXQVVSJRM_cjs.e(this,"localNodeId");chunkXQVVSJRM_cjs.e(this,"localNodeName");chunkXQVVSJRM_cjs.e(this,"remoteNodes",new Map);chunkXQVVSJRM_cjs.e(this,"remoteAgents",new Map);chunkXQVVSJRM_cjs.e(this,"syncTimer",null);chunkXQVVSJRM_cjs.e(this,"running",false);chunkXQVVSJRM_cjs.e(this,"httpClient");this.registry=n.registry,this.localNodeId=n.localNodeId,this.localNodeName=n.localNodeName,this.config={...chunkCTTZF7B6_cjs.k,...n.config},this.httpClient=n.httpClient||{fetch:globalThis.fetch.bind(globalThis)};}async start(){if(this.running){c.warn("Agent sync manager is already running");return}c.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let n of this.config.remoteNodes)this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.running=true,c.info("Agent sync manager started");}async stop(){if(!this.running){c.warn("Agent sync manager is not running");return}c.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,c.info("Agent sync manager stopped");}async pullFromAllNodes(){for(let[n]of this.remoteNodes.entries())try{await this.pullFromNode(n);}catch(e){c.error("Failed to pull from node",{nodeId:n,error:e.message});}}async pullFromNode(n){let e=this.remoteNodes.get(n);if(!e)throw new Error(`Unknown remote node: ${n}`);e.status="syncing";let t=this.config.remoteNodes.find(s=>s.id===n);if(!t)throw new Error(`Remote node not found in config: ${n}`);c.debug("Pulling agent list from node",{nodeId:n,address:t.address});try{let s=`http://${t.address}:${t.port}/sync/agents`,i=await this.httpClient.fetch(s,{method:"GET",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);let o=(await i.json()).agents||[];for(let p of o)p.sourceGatewayId=n,this.remoteAgents.set(p.id,p);return e.lastSyncAt=Date.now(),e.status="synced",e.info.lastSyncAt=e.lastSyncAt,e.info.status="online",delete e.error,c.info("Pulled agent list from node",{nodeId:n,agentCount:o.length,lastSyncAt:e.lastSyncAt}),o}catch(s){throw e.status="error",e.error=s.message,e.info.status="offline",c.error("Failed to pull from node",{nodeId:n,error:s.message}),s}}async pushEvent(n){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let e=[];for(let[t]of this.remoteNodes.entries())e.push(this.pushToNode(t,n));await Promise.allSettled(e);}async pushToNode(n,e){let t=this.config.remoteNodes.find(s=>s.id===n);if(!t){c.warn("Unknown remote node for push",{nodeId:n});return}try{let s=`http://${t.address}:${t.port}/sync/events`,i=await this.httpClient.fetch(s,{method:"POST",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId},body:JSON.stringify(e)});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);c.debug("Pushed event to node",{nodeId:n,eventType:e.type});}catch(s){c.error("Failed to push to node",{nodeId:n,eventType:e.type,error:s.message});}}async handleSyncMessage(n){switch(c.debug("Received sync message",{type:n.type,sourceNodeId:n.sourceNodeId}),n.type){case "agent_list_request":await this.handleAgentListRequest(n);break;case "agent_list_response":await this.handleAgentListResponse(n);break;case "agent_register":await this.handleAgentRegister(n);break;case "agent_deregister":await this.handleAgentDeregister(n);break;case "agent_heartbeat":await this.handleAgentHeartbeat(n);break;case "agent_status_change":await this.handleAgentStatusChange(n);break;default:c.warn("Unknown sync message type",{type:n.type});}}async handleAgentListRequest(n){let e=this.getLocalAgentsForSync(),t={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:n.requestId,agents:e,fullList:true,syncAt:Date.now()};await this.pushToNode(n.sourceNodeId,t);}async handleAgentListResponse(n){for(let e of n.agents)this.remoteAgents.set(e.id,e);c.info("Received agent list response",{sourceNodeId:n.sourceNodeId,agentCount:n.agents.length});}async handleAgentRegister(n){let{agent:e}=n,t=this.remoteAgents.get(e.id);if(t){let s=this.resolveConflict(t,e);this.remoteAgents.set(e.id,s);}else this.remoteAgents.set(e.id,e);c.info("Remote agent registered",{agentId:e.id,name:e.name,sourceNodeId:n.sourceNodeId});}async handleAgentDeregister(n){let{agentId:e}=n;this.remoteAgents.delete(e),c.info("Remote agent deregistered",{agentId:e,sourceNodeId:n.sourceNodeId});}async handleAgentHeartbeat(n){let{agentId:e,heartbeatAt:t,status:s}=n,i=this.remoteAgents.get(e);i&&(i.updatedAt=t,i.status=s),c.debug("Remote agent heartbeat received",{agentId:e,status:s,sourceNodeId:n.sourceNodeId});}async handleAgentStatusChange(n){let{agentId:e,newStatus:t,changedAt:s}=n,i=this.remoteAgents.get(e);i&&(i.status=t,i.updatedAt=s),c.info("Remote agent status changed",{agentId:e,newStatus:t,sourceNodeId:n.sourceNodeId});}resolveConflict(n,e){switch(this.config.conflictResolution){case "latest":return e.updatedAt>n.updatedAt?e:n;case "local":return n;case "remote":return e;default:return e.updatedAt>n.updatedAt?e:n}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(e=>({id:e.id,name:e.name,sourceGatewayId:this.localNodeId,address:e.address,capabilities:e.capabilities,status:e.status,updatedAt:e.lastHeartbeat,metadata:e.metadata}))}getMergedAgentList(){let n=new Map;for(let e of this.getLocalAgentsForSync())n.set(e.id,e);for(let[e,t]of this.remoteAgents.entries())n.has(e)||n.set(e,t);return Array.from(n.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values())}getStats(){let n=this.registry.getAllAgents(),e=0,t=0;for(let i of this.remoteNodes.values())i.info.status==="online"?e++:t++;let s=null;for(let i of this.remoteNodes.values())i.lastSyncAt>(s||0)&&(s=i.lastSyncAt);return {localAgentCount:n.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:n.length+this.remoteAgents.size,onlineNodeCount:e,offlineNodeCount:t,lastSyncAt:s}}isRunning(){return this.running}addRemoteNode(n){this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"}),c.info("Remote node added",{nodeId:n.id,address:n.address});}removeRemoteNode(n){this.remoteNodes.delete(n);for(let[e,t]of this.remoteAgents.entries())t.sourceGatewayId===n&&this.remoteAgents.delete(e);c.info("Remote node removed",{nodeId:n});}};chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var l=class{constructor(){chunkXQVVSJRM_cjs.e(this,"version","1.0.0");chunkXQVVSJRM_cjs.e(this,"log");chunkXQVVSJRM_cjs.e(this,"config",null);chunkXQVVSJRM_cjs.e(this,"messageHandler",null);chunkXQVVSJRM_cjs.e(this,"_status","stopped");chunkXQVVSJRM_cjs.e(this,"lastActivity",0);}initLog(){this.log=chunkEKLLH53Y_cjs.a.create({service:`channel:${this.platform}`});}async start(n,e){if(this._status==="running"){this.log.warn("plugin is already running");return}this.log.info("starting channel plugin",{id:this.id,platform:this.platform}),this._status="starting",this.config=n,this.messageHandler=e;try{await this.doStart(),this._status="running",this.lastActivity=Date.now(),this.log.info("channel plugin started",{id:this.id});}catch(t){throw this._status="error",this.log.error("failed to start channel plugin",{error:String(t)}),t}}async stop(){if(this._status==="stopped"){this.log.warn("plugin is already stopped");return}this.log.info("stopping channel plugin",{id:this.id}),this._status="stopping";try{await this.doStop(),this._status="stopped",this.log.info("channel plugin stopped",{id:this.id});}catch(n){throw this._status="error",this.log.error("failed to stop channel plugin",{error:String(n)}),n}}async healthCheck(){try{return {healthy:await this.doHealthCheck(),lastCheck:Date.now()}}catch(n){return {healthy:false,lastCheck:Date.now(),error:n instanceof Error?n.message:String(n)}}}getStatus(){return {status:this._status,lastActivity:this.lastActivity}}async doHealthCheck(){return this._status==="running"}updateActivity(){this.lastActivity=Date.now();}async handleMessage(n){if(!this.messageHandler){this.log.warn("no message handler set, dropping message",{id:n.id});return}this.updateActivity(),await this.messageHandler.onMessage(n);}async handleEvent(n,e){if(!this.messageHandler){this.log.warn("no message handler set, dropping event",{type:n});return}await this.messageHandler.onEvent({type:n,channelId:this.id,data:e,timestamp:Date.now()});}};chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var x=class{constructor(n){chunkXQVVSJRM_cjs.e(this,"log");chunkXQVVSJRM_cjs.e(this,"config");chunkXQVVSJRM_cjs.e(this,"ws",null);chunkXQVVSJRM_cjs.e(this,"state","disconnected");chunkXQVVSJRM_cjs.e(this,"subscriptions",new Map);chunkXQVVSJRM_cjs.e(this,"messageCallbacks",new Set);chunkXQVVSJRM_cjs.e(this,"agentListCallbacks",new Set);chunkXQVVSJRM_cjs.e(this,"cachedAgentList",[]);chunkXQVVSJRM_cjs.e(this,"localAgentList",[]);chunkXQVVSJRM_cjs.e(this,"reconnectAttempts",0);chunkXQVVSJRM_cjs.e(this,"reconnectTimer",null);chunkXQVVSJRM_cjs.e(this,"heartbeatTimer",null);chunkXQVVSJRM_cjs.e(this,"agentListRequestId",null);chunkXQVVSJRM_cjs.e(this,"agentListRequestResolve",null);this.config={url:n.url,type:n.type,id:n.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,reconnect:{enabled:n.reconnect?.enabled??true,maxAttempts:n.reconnect?.maxAttempts??5,delay:n.reconnect?.delay??3e3},heartbeat:{enabled:n.heartbeat?.enabled??true,interval:n.heartbeat?.interval??3e4}},this.log=chunkEKLLH53Y_cjs.a.create({service:`gateway:client:${this.config.id}`});}async connect(){if(this.state==="connected"||this.state==="connecting"){this.log.warn("already connected or connecting");return}return this.state="connecting",this.log.info("connecting to gateway",{url:this.config.url}),new Promise((n,e)=>{try{this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{this.state="connected",this.reconnectAttempts=0,this.log.info("connected to gateway"),this.config.heartbeat.enabled&&this.startHeartbeat(),this.resubscribeAll(),n();},this.ws.onmessage=t=>{this.handleMessage(t.data);},this.ws.onclose=t=>{this.handleClose(t.code,t.reason);},this.ws.onerror=t=>{this.log.error("WebSocket error",{error:String(t)}),this.state==="connecting"&&e(new Error("Connection failed"));};}catch(t){this.state="disconnected",e(t);}})}async disconnect(){this.state!=="disconnected"&&(this.log.info("disconnecting from gateway"),this.stopHeartbeat(),this.stopReconnect(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.state="disconnected",this.log.info("disconnected from gateway"));}async subscribe(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"subscribe",sessionId:n,clientId:this.config.id}),this.log.info("subscribed to session",{sessionId:n});}async unsubscribe(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:n,clientId:this.config.id}),this.subscriptions.delete(n),this.log.info("unsubscribed from session",{sessionId:n});}async send(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:n});}onMessage(n){this.messageCallbacks.add(n);}offMessage(n){this.messageCallbacks.delete(n);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(n){this.localAgentList=n,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((n,e)=>{let t=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=t,this.agentListRequestResolve=n,this.sendData({type:"agent_list_request",requestId:t}),setTimeout(()=>{this.agentListRequestId===t&&(this.agentListRequestId=null,this.agentListRequestResolve=null,e(new Error("Agent list request timeout")));},1e4);})}getConnectableAgents(n={}){let{localAgents:e,preferLocal:t=true,filterOffline:s=true}=n,i=e||this.localAgentList,a=this.cachedAgentList,o=this.mergeAgentLists(i,a,t);return s?o.filter(p=>p.status!=="offline"):o}onAgentListChange(n){this.agentListCallbacks.add(n);}offAgentListChange(n){this.agentListCallbacks.delete(n);}mergeAgentLists(n,e,t){let s=new Map,i=t?e:n,a=t?n:e;for(let o of i)s.set(o.id,o);for(let o of a)s.set(o.id,o);return Array.from(s.values())}updateMergedAgentList(){let n=this.getConnectableAgents({filterOffline:false});for(let e of this.agentListCallbacks)try{e(n);}catch(t){this.log.error("agent list callback error",{error:String(t)});}}handleAgentListResponse(n,e){e&&this.agentListRequestId===e&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(n),this.agentListRequestResolve=null),this.cachedAgentList=n,this.updateMergedAgentList(),this.log.debug("received agent list",{count:n.length});}sendData(n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(n));}handleMessage(n){try{let e=JSON.parse(n);switch(e.type){case "message":this.handleGatewayMessage(e.message);break;case "subscribed":this.subscriptions.set(e.sessionId,e.subscription);break;case "unsubscribed":this.subscriptions.delete(e.sessionId);break;case "pong":break;case "agent_list_response":this.handleAgentListResponse(e.agents||[],e.requestId);break;case "agent_update":this.handleAgentUpdate(e.agent,e.action);break;default:this.log.debug("unknown message type",{type:e.type});}}catch(e){this.log.error("failed to parse message",{error:String(e)});}}handleAgentUpdate(n,e){switch(e){case "add":case "update":{let t=this.cachedAgentList.findIndex(s=>s.id===n.id);t>=0?this.cachedAgentList[t]=n:this.cachedAgentList.push(n);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(t=>t.id!==n.id);break}this.updateMergedAgentList();}handleGatewayMessage(n){for(let e of this.messageCallbacks)try{e(n);}catch(t){this.log.error("message callback error",{error:String(t)});}}handleClose(n,e){this.log.info("connection closed",{code:n,reason:e}),this.state="disconnected",this.ws=null,this.stopHeartbeat(),this.config.reconnect.enabled&&this.scheduleReconnect();}scheduleReconnect(){if(this.reconnectAttempts>=this.config.reconnect.maxAttempts){this.log.error("max reconnect attempts reached");return}this.reconnectAttempts++,this.state="reconnecting";let n=this.config.reconnect.delay*this.reconnectAttempts;this.log.info("scheduling reconnect",{attempt:this.reconnectAttempts,delay:n}),this.reconnectTimer=setTimeout(async()=>{try{await this.connect();}catch(e){this.log.error("reconnect failed",{error:String(e)});}},n);}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.state==="connected"&&this.sendData({type:"ping"});},this.config.heartbeat.interval);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);}async resubscribeAll(){for(let n of this.subscriptions.keys())try{await this.subscribe(n);}catch(e){this.log.error("failed to resubscribe",{sessionId:n,error:String(e)});}}};chunkSIOB4FC7_cjs.a();chunkSIOB4FC7_cjs.a();var y=class extends l{constructor(e="telegram-main"){super();chunkXQVVSJRM_cjs.e(this,"id");chunkXQVVSJRM_cjs.e(this,"platform","telegram");chunkXQVVSJRM_cjs.e(this,"name","Telegram Bot");chunkXQVVSJRM_cjs.e(this,"botConfig",null);chunkXQVVSJRM_cjs.e(this,"pollingInterval",null);chunkXQVVSJRM_cjs.e(this,"lastUpdateId",0);chunkXQVVSJRM_cjs.e(this,"baseUrl","");this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");this.baseUrl=`https://api.telegram.org/bot${this.botConfig.botToken}`;let e=await this.getMe();this.log.info("Telegram bot connected",{id:e.id,username:e.username,first_name:e.first_name}),this.botConfig.polling?.enabled!==false&&this.startPolling();}async doStop(){this.stopPolling(),this.botConfig=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Chat ID is required");let s=this.extractText(e);return (await this.sendMessage(t,s)).message_id.toString()}startPolling(){if(this.pollingInterval)return;let e=this.botConfig?.polling?.interval??1e3;this.pollingInterval=setInterval(async()=>{try{await this.poll();}catch(t){this.log.error("Polling error",{error:String(t)});}},e),this.log.info("Polling started",{interval:e});}stopPolling(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null,this.log.info("Polling stopped"));}async poll(){let e=await this.getUpdates(this.lastUpdateId+1,100,0);for(let t of e)this.lastUpdateId=t.update_id,t.message&&await this.handleTelegramMessage(t.message);}async handleTelegramMessage(e){if(this.updateActivity(),e.from?.is_bot)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return chunkCTTZF7B6_cjs.c(t,"input",this.parseContent(e),{channel:{platform:"telegram",channelId:this.id,userId:e.from?.id.toString(),chatId:e.chat.id.toString(),username:e.from?.username,firstName:e.from?.first_name,lastName:e.from?.last_name,chatType:e.chat.type,chatTitle:e.chat.title},context:{replyTo:e.reply_to_message?.message_id.toString()}})}parseContent(e){let t=[];if(e.text&&t.push({type:"text",text:e.text}),e.photo&&e.photo.length>0){let s=e.photo[e.photo.length-1];s&&t.push({type:"image",image:s.file_id,mime:"image/jpeg"});}if(e.document&&t.push({type:"file",data:e.document.file_id,mime:e.document.mime_type}),e.caption&&t.length>0){let s=t[0];s&&s.type==="text"?t[0]={type:"text",text:`${s.text}
2
2
 
3
3
  ${e.caption}`}:t.unshift({type:"text",text:e.caption});}return t}getSessionId(e){let t=e.chat.id.toString(),s=e.from?.id.toString();return e.chat.type==="private"?`telegram_${this.id}_${t}`:`telegram_${this.id}_${t}_${s}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
4
4
  `)}async getMe(){return (await this.request("getMe")).result}async getUpdates(e,t,s){return (await this.request("getUpdates",{offset:e,limit:t,timeout:s})).result||[]}async sendMessage(e,t){return (await this.request("sendMessage",{chat_id:e,text:t,parse_mode:"Markdown"})).result}async request(e,t={}){let s=`${this.baseUrl}/${e}`,a=await(await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(!a.ok)throw new Error(`Telegram API error: ${a.description}`);return a}};chunkSIOB4FC7_cjs.a();var b=class extends l{constructor(e="discord-main"){super();chunkXQVVSJRM_cjs.e(this,"id");chunkXQVVSJRM_cjs.e(this,"platform","discord");chunkXQVVSJRM_cjs.e(this,"name","Discord Bot");chunkXQVVSJRM_cjs.e(this,"botConfig",null);chunkXQVVSJRM_cjs.e(this,"baseUrl","https://discord.com/api/v10");chunkXQVVSJRM_cjs.e(this,"gatewayWs",null);chunkXQVVSJRM_cjs.e(this,"heartbeatInterval",null);chunkXQVVSJRM_cjs.e(this,"sessionId",null);chunkXQVVSJRM_cjs.e(this,"sequenceNumber",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");let e=await this.getCurrentUser();this.log.info("Discord bot connected",{id:e.id,username:e.username}),this.botConfig.gateway?.enabled!==false&&await this.startGateway();}async doStop(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.gatewayWs&&(this.gatewayWs.close(),this.gatewayWs=null),this.botConfig=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Channel ID is required");let s=this.extractText(e);return (await this.createMessage(t,s,e.metadata.context?.replyTo)).id}async startGateway(){let t=`${(await this.getGatewayBot()).url}/?v=10&encoding=json`;this.gatewayWs=new WebSocket(t),this.gatewayWs.onmessage=s=>{this.handleGatewayMessage(JSON.parse(s.data.toString()));},this.gatewayWs.onclose=()=>{this.log.info("Gateway disconnected"),setTimeout(()=>this.startGateway(),5e3);},this.gatewayWs.onerror=s=>{this.log.error("Gateway error",{error:String(s)});};}handleGatewayMessage(e){switch(this.updateActivity(),e.op){case 10:this.handleHello(e.d);break;case 11:this.log.debug("Heartbeat ACK");break;case 0:e.s&&(this.sequenceNumber=e.s),this.handleDispatch(e.t,e.d);break;case 9:this.log.warn("Invalid session, reconnecting"),this.gatewayWs?.close();break}return Promise.resolve()}handleHello(e){this.heartbeatInterval=setInterval(()=>{this.gatewayWs?.send(JSON.stringify({op:1,d:this.sequenceNumber}));},e.heartbeat_interval),this.gatewayWs?.send(JSON.stringify({op:2,d:{token:this.botConfig?.botToken,intents:this.botConfig?.gateway?.intents??513,properties:{os:"linux",browser:"easbot",device:"easbot"}}}));}handleDispatch(e,t){e==="MESSAGE_CREATE"&&this.handleDiscordMessage(t);}async handleDiscordMessage(e){if(e.author.bot)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return chunkCTTZF7B6_cjs.c(t,"input",this.parseContent(e),{channel:{platform:"discord",channelId:this.id,userId:e.author.id,chatId:e.channel_id,messageId:e.id,guildId:e.guild_id,username:e.author.username,discriminator:e.author.discriminator},context:{threadId:e.message_reference?.message_id,conversationId:e.channel_id}})}parseContent(e){let t=[];e.content&&t.push({type:"text",text:e.content});for(let s of e.attachments)s.content_type?.startsWith("image/")?t.push({type:"image",image:s.url,mime:s.content_type}):t.push({type:"file",data:s.url,mime:s.content_type});return t}getSessionId(e){let t=e.channel_id,s=e.author.id;return `discord_${this.id}_${t}_${s}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
@@ -8,4 +8,4 @@ ${e.caption}`}:t.unshift({type:"text",text:e.caption});}return t}getSessionId(e)
8
8
  `)}async refreshTenantAccessToken(){let t=await(await fetch(`${this.baseUrl}/auth/v3/tenant_access_token/internal`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({app_id:this.botConfig?.appId,app_secret:this.botConfig?.appSecret})})).json();if(t.code!==0)throw new Error(`Feishu API error: ${t.msg}`);this.tenantAccessToken=t.tenant_access_token,this.tokenExpireTime=Date.now()+t.expire*1e3-6e4;}async ensureTokenValid(){(!this.tenantAccessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshTenantAccessToken();}async sendMessage(e,t){let i=await(await fetch(`${this.baseUrl}/im/v1/messages?receive_id_type=chat_id`,{method:"POST",headers:{Authorization:`Bearer ${this.tenantAccessToken}`,"Content-Type":"application/json"},body:JSON.stringify({receive_id:e,msg_type:"text",content:JSON.stringify({text:t})})})).json();if(i.code!==0)throw new Error(`Feishu API error: ${i.msg}`);return i.data}};chunkSIOB4FC7_cjs.a();var w=class extends l{constructor(e="wechat-main"){super();chunkXQVVSJRM_cjs.e(this,"id");chunkXQVVSJRM_cjs.e(this,"platform","wechat");chunkXQVVSJRM_cjs.e(this,"name","WeChat Bot");chunkXQVVSJRM_cjs.e(this,"botConfig",null);chunkXQVVSJRM_cjs.e(this,"accessToken",null);chunkXQVVSJRM_cjs.e(this,"tokenExpireTime",0);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.appId||!this.botConfig.appSecret)throw new Error("App ID and App Secret are required");await this.refreshAccessToken(),this.log.info("WeChat bot connected",{app_id:this.botConfig.appId,mode:this.botConfig.mode});}async doStop(){this.botConfig=null,this.accessToken=null;}async send(e){let t=e.metadata.channel.userId;if(!t)throw new Error("User ID is required");await this.ensureTokenValid();let s=this.extractText(e);return this.botConfig?.mode==="wecom"?await this.sendWeComMessage(t,s):await this.sendOfficialMessage(t,s)}async handleWebhookMessage(e){this.updateActivity();let t=this.parseXmlMessage(e);if(t){let s=this.toGatewayMessage(t);await this.handleMessage(s);}}parseXmlMessage(e){let t=a=>e.match(new RegExp(`<${a}><!\\[CDATA\\[(.*?)\\]\\]></${a}>`))?.[1],s=a=>{let o=e.match(new RegExp(`<${a}>(\\d+)</${a}>`));return o?.[1]?parseInt(o[1],10):void 0},i=t("MsgType");return i?{ToUserName:t("ToUserName")??"",FromUserName:t("FromUserName")??"",CreateTime:s("CreateTime")??0,MsgType:i,Content:t("Content"),MsgId:s("MsgId"),PicUrl:t("PicUrl"),MediaId:t("MediaId")}:null}toGatewayMessage(e){let t=this.getSessionId(e);return chunkCTTZF7B6_cjs.c(t,"input",this.parseContent(e),{channel:{platform:"wechat",channelId:this.id,userId:e.FromUserName,chatId:e.FromUserName,toUser:e.ToUserName,msgId:e.MsgId?.toString(),mode:this.botConfig?.mode},context:{conversationId:e.FromUserName}})}parseContent(e){let t=[];switch(e.MsgType){case "text":e.Content&&t.push({type:"text",text:e.Content});break;case "image":(e.PicUrl||e.MediaId)&&t.push({type:"image",image:e.PicUrl??e.MediaId??"",mime:"image/jpeg"});break;case "voice":e.MediaId&&t.push({type:"file",data:e.MediaId,mime:"audio/amr"}),"Recognition"in e&&e.Recognition&&t.push({type:"text",text:e.Recognition});break;case "video":case "shortvideo":e.MediaId&&t.push({type:"file",data:e.MediaId,mime:"video/mp4"});break;default:e.Content&&t.push({type:"text",text:e.Content});}return t}getSessionId(e){let t=e.FromUserName;return `wechat_${this.id}_${t}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
9
9
  `)}async refreshAccessToken(){let e;this.botConfig?.mode==="wecom"?e=`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${this.botConfig.appId}&corpsecret=${this.botConfig.appSecret}`:e=`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${this.botConfig?.appId}&secret=${this.botConfig?.appSecret}`;let s=await(await fetch(e)).json();if(s.errcode&&s.errcode!==0)throw new Error(`WeChat API error: ${s.errmsg}`);this.accessToken=s.access_token,this.tokenExpireTime=Date.now()+s.expires_in*1e3-6e4;}async ensureTokenValid(){(!this.accessToken||Date.now()>=this.tokenExpireTime)&&await this.refreshAccessToken();}async sendOfficialMessage(e,t){let i=await(await fetch(`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${this.accessToken}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({touser:e,msgtype:"text",text:{content:t}})})).json();if(i.errcode!==0)throw new Error(`WeChat API error: ${i.errmsg}`);return i.msg_id?.toString()??Date.now().toString()}async sendWeComMessage(e,t){let i=await(await fetch(`https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${this.accessToken}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({touser:e,msgtype:"text",agentid:this.botConfig?.agentId,text:{content:t}})})).json();if(i.errcode!==0)throw new Error(`WeCom API error: ${i.errmsg}`);return i.msgid??Date.now().toString()}};chunkSIOB4FC7_cjs.a();var S=class extends l{constructor(e="webchat-main"){super();chunkXQVVSJRM_cjs.e(this,"id");chunkXQVVSJRM_cjs.e(this,"platform","webchat");chunkXQVVSJRM_cjs.e(this,"name","WebChat");chunkXQVVSJRM_cjs.e(this,"webChatConfig",null);chunkXQVVSJRM_cjs.e(this,"connections",new Map);chunkXQVVSJRM_cjs.e(this,"heartbeatInterval",null);chunkXQVVSJRM_cjs.e(this,"wsServer",null);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");this.webChatConfig=this.config.platform,await this.startWebSocketServer(),this.startHeartbeat(),this.log.info("WebChat plugin started",{port:this.webChatConfig.port,hostname:this.webChatConfig.hostname,path:this.webChatConfig.path,maxConnections:this.webChatConfig.maxConnections});}async startWebSocketServer(){if(!this.webChatConfig)return;let e={port:this.webChatConfig.port,hostname:this.webChatConfig.hostname,path:this.webChatConfig.path,maxConnections:this.webChatConfig.maxConnections,connectionTimeout:this.webChatConfig.connectionTimeout,heartbeatInterval:this.webChatConfig.heartbeatInterval,sessionExpireMs:this.webChatConfig.sessionExpireMs,https:this.webChatConfig.https};this.wsServer=new chunkCTTZF7B6_cjs.r(e),await this.wsServer.start(),this.log.info("WebSocket server started",{url:`${this.webChatConfig.https?.enabled?"wss":"ws"}://${this.webChatConfig.hostname}:${this.webChatConfig.port}${this.webChatConfig.path}`});}async doStop(){this.wsServer&&(await this.wsServer.stop(),this.wsServer=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null);for(let e of this.connections.values())e.ws.close();this.connections.clear(),this.webChatConfig=null;}async send(e){let t=e.sessionId,s=e.metadata.channel.userId;if(this.wsServer&&t){let o={type:"message",sessionId:t,properties:{sessionID:t,content:e.content,timestamp:e.timestamp||Date.now()}};return this.wsServer.broadcastToSession(t,o),e.id}if(!s)throw new Error("User ID is required");let i=this.findConnectionByUser(s);if(!i)throw new Error("User not connected");let a={type:"message",sessionId:t,content:e.content,metadata:e.metadata};return i.ws.send(JSON.stringify(a)),i.lastActivity=Date.now(),e.id}pushEvent(e,t){this.wsServer&&this.wsServer.broadcastToSession(e,t);}getWebSocketServer(){return this.wsServer}async handleConnection(e,t){let s=this.generateConnectionId();if(this.connections.size>=(this.webChatConfig?.maxConnections??1e3)){e.close(1013,"Maximum connections reached");return}let i={id:s,ws:e,userId:t,lastActivity:Date.now()};this.connections.set(s,i),e.onmessage=a=>{this.handleWebSocketMessage(i,a.data.toString());},e.onclose=()=>{this.connections.delete(s),this.log.debug("WebSocket closed",{connId:s,userId:t});},e.onerror=a=>{this.log.error("WebSocket error",{connId:s,userId:t,error:String(a)});},this.log.info("WebSocket connected",{connId:s,userId:t});}async handleWebSocketMessage(e,t){this.updateActivity(),e.lastActivity=Date.now();try{let s=JSON.parse(t);switch(s.type){case "message":await this.handleChatMessage(e,s);break;case "ping":e.ws.send(JSON.stringify({type:"pong"}));break;case "subscribe":s.sessionId&&(e.sessionId=s.sessionId);break;case "unsubscribe":e.sessionId=void 0;break}}catch(s){this.log.error("Failed to handle WebSocket message",{error:String(s)});}}async handleChatMessage(e,t){if(!t.content||!t.sessionId)return;let s=chunkCTTZF7B6_cjs.c(t.sessionId,"input",t.content,{channel:{platform:"webchat",channelId:this.id,userId:e.userId,chatId:t.sessionId,connectionId:e.id},context:{conversationId:t.sessionId},...t.metadata});await this.handleMessage(s);}startHeartbeat(){let e=this.webChatConfig?.heartbeatInterval??3e4;this.heartbeatInterval=setInterval(()=>{let t=Date.now(),s=this.webChatConfig?.connectionTimeout??6e4;for(let[i,a]of this.connections)t-a.lastActivity>s&&(this.log.info("Closing inactive connection",{connId:i}),a.ws.close(1001,"Connection timeout"),this.connections.delete(i));},e);}findConnectionByUser(e){for(let t of this.connections.values())if(t.userId===e)return t}generateConnectionId(){return `conn_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}getConnectionCount(){return this.connections.size}getWsServerConnectionCount(){return this.wsServer?.getConnectionCount()??0}};chunkSIOB4FC7_cjs.a();var A=class extends l{constructor(e="signal-main"){super();chunkXQVVSJRM_cjs.e(this,"id");chunkXQVVSJRM_cjs.e(this,"platform","signal");chunkXQVVSJRM_cjs.e(this,"name","Signal Bot");chunkXQVVSJRM_cjs.e(this,"botConfig",null);chunkXQVVSJRM_cjs.e(this,"pollingInterval",null);chunkXQVVSJRM_cjs.e(this,"lastTimestamp",0);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.phoneNumber)throw new Error("Phone number is required");let e=await this.getAccountInfo();this.log.info("Signal bot connected",{number:this.botConfig.phoneNumber,address:e.address}),this.startPolling();}async doStop(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.botConfig=null;}async send(e){let t=e.metadata.channel.userId;if(!t)throw new Error("Recipient is required");let s=this.extractText(e);return (await this.sendMessage(t,s)).timestamp.toString()}startPolling(){this.pollingInterval=setInterval(async()=>{try{await this.poll();}catch(t){this.log.error("Polling error",{error:String(t)});}},5e3),this.log.info("Polling started",{interval:5e3});}async poll(){let e=await this.receiveMessages(this.lastTimestamp);for(let t of e)this.lastTimestamp=t.envelope.timestamp,t.envelope.dataMessage&&await this.handleSignalMessage(t);}async handleSignalMessage(e){this.updateActivity();let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e),s=e.envelope.dataMessage;return chunkCTTZF7B6_cjs.c(t,"input",this.parseContent(s),{channel:{platform:"signal",channelId:this.id,userId:e.envelope.sourceNumber,chatId:e.envelope.sourceNumber,sourceUuid:e.envelope.sourceUuid,timestamp:e.envelope.timestamp},context:{conversationId:e.envelope.sourceNumber}})}parseContent(e){let t=[];if(!e)return t;if(e.message&&t.push({type:"text",text:e.message}),e.attachments)for(let s of e.attachments)s.contentType.startsWith("image/")?t.push({type:"image",image:s.id,mime:s.contentType}):t.push({type:"file",data:s.id,mime:s.contentType});return t}getSessionId(e){let t=e.envelope.sourceNumber;return `signal_${this.id}_${t}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
10
10
  `)}async getAccountInfo(){return await this.request("GET",`/v1/accounts/${this.botConfig?.phoneNumber}`)}async receiveMessages(e){let t=e>0?`?since=${e}`:"";return await this.request("GET",`/v1/receive/${this.botConfig?.phoneNumber}${t}`)||[]}async sendMessage(e,t){return await this.request("POST","/v2/send",{number:this.botConfig?.phoneNumber,recipients:[e],message:t})}async request(e,t,s){let i=`${this.botConfig?.serviceUrl}${t}`,a={"Content-Type":"application/json"};this.botConfig?.password&&(a.Authorization=`Basic ${Buffer.from(`${this.botConfig.phoneNumber}:${this.botConfig.password}`).toString("base64")}`);let o=await fetch(i,{method:e,headers:a,body:s?JSON.stringify(s):void 0});if(!o.ok){let p=await o.text();throw new Error(`Signal API error: ${p}`)}return o.json()}};chunkSIOB4FC7_cjs.a();var M=class extends l{constructor(e="nostr-main"){super();chunkXQVVSJRM_cjs.e(this,"id");chunkXQVVSJRM_cjs.e(this,"platform","nostr");chunkXQVVSJRM_cjs.e(this,"name","Nostr Bot");chunkXQVVSJRM_cjs.e(this,"botConfig",null);chunkXQVVSJRM_cjs.e(this,"relayConnections",new Map);chunkXQVVSJRM_cjs.e(this,"subscriptions",new Map);chunkXQVVSJRM_cjs.e(this,"eventHandlers",new Map);this.id=e,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.relays||this.botConfig.relays.length===0)throw new Error("At least one relay is required");for(let e of this.botConfig.relays)await this.connectToRelay(e);this.log.info("Nostr bot connected",{relays:this.botConfig.relays,pubkey:this.botConfig.publicKey?.substring(0,16)+"..."});}async doStop(){for(let[e,t]of this.relayConnections)t.close();this.relayConnections.clear(),this.subscriptions.clear(),this.eventHandlers.clear(),this.botConfig=null;}async send(e){if(!this.botConfig?.privateKey)throw new Error("Private key is required for sending messages");let t=this.extractText(e),s=await this.createEvent(t,e.metadata.context?.replyTo);return await this.publishEvent(s),s.id}async connectToRelay(e){let t=new WebSocket(e);t.onopen=()=>{this.log.info("Connected to relay",{relay:e});for(let[s,i]of this.subscriptions)this.subscribeToRelay(t,s,i);},t.onmessage=s=>{this.handleRelayMessage(e,s.data.toString());},t.onclose=()=>{this.log.info("Disconnected from relay",{relay:e}),this.relayConnections.delete(e),setTimeout(()=>this.connectToRelay(e),5e3);},t.onerror=s=>{this.log.error("Relay error",{relay:e,error:String(s)});},this.relayConnections.set(e,t);}handleRelayMessage(e,t){this.updateActivity();try{let s=JSON.parse(t);if(s[0]==="EVENT"&&s[2]){let i=s[2];this.handleNostrEvent(i);}if(s[0]==="OK"){let i=s[1],a=s[2];this.log.debug("Event published",{eventId:i,success:a});}}catch(s){this.log.error("Failed to handle relay message",{error:String(s)});}return Promise.resolve()}async handleNostrEvent(e){if(e.kind!==1||e.pubkey===this.botConfig?.publicKey)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return chunkCTTZF7B6_cjs.c(t,"input",this.parseContent(e),{channel:{platform:"nostr",channelId:this.id,userId:e.pubkey,chatId:e.pubkey,eventId:e.id,createdAt:e.created_at,tags:e.tags},context:{replyTo:this.findReplyTo(e.tags),conversationId:e.pubkey}})}parseContent(e){let t=[];e.content&&t.push({type:"text",text:e.content});for(let s of e.tags)if(s[0]==="url"&&s[1]){let i=s[1];i.match(/\.(jpg|jpeg|png|gif|webp)$/i)&&t.push({type:"image",image:i});}return t}findReplyTo(e){for(let t of e)if(t[0]==="e"&&t[1])return t[1]}getSessionId(e){return `nostr_${this.id}_${e.pubkey}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
11
- `)}subscribeToRelay(e,t,s){let i=["REQ",t,s];e.send(JSON.stringify(i));}async createEvent(e,t){let s=[];t&&s.push(["e",t]);let i={id:"",pubkey:this.botConfig?.publicKey??"",created_at:Math.floor(Date.now()/1e3),kind:1,tags:s,content:e,sig:""};return i.id=await this.computeEventId(i),i.sig=await this.signEvent(i),i}async computeEventId(e){let t=JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]),i=new TextEncoder().encode(t),a=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(a)).map(p=>p.toString(16).padStart(2,"0")).join("")}async signEvent(e){if(!this.botConfig?.privateKey)throw new Error("Private key is required");return "signature_placeholder"}async publishEvent(e){let t=["EVENT",e];for(let s of this.relayConnections.values())s.readyState===WebSocket.OPEN&&s.send(JSON.stringify(t));}};chunkSIOB4FC7_cjs.a();var _=class extends l{constructor(e){super();chunkXQVVSJRM_cjs.e(this,"id");chunkXQVVSJRM_cjs.e(this,"platform");chunkXQVVSJRM_cjs.e(this,"name");chunkXQVVSJRM_cjs.e(this,"version");chunkXQVVSJRM_cjs.e(this,"options");this.id=e.id,this.platform=e.platform||"custom",this.name=e.name,this.version=e.version||"1.0.0",this.options=e,this.initLog();}async doStart(){this.options.setup?.initialize&&await this.options.setup.initialize(),this.log.info("Channel plugin started",{id:this.id,platform:this.platform});}async doStop(){this.options.setup?.destroy&&await this.options.setup.destroy(),this.log.info("Channel plugin stopped",{id:this.id});}async send(e){let t=e;this.options.actions?.beforeSend&&(t=await this.options.actions.beforeSend(e));let s=await this.options.messaging.send(t);return this.options.actions?.afterSend&&await this.options.actions.afterSend(t,s),s}async healthCheck(){return this.options.status?.healthCheck?{healthy:await this.options.status.healthCheck(),lastCheck:Date.now()}:{healthy:true,lastCheck:Date.now()}}};function N(f){return new _(f)}var E={telegram:y,discord:b,slack:C,feishu:v,wechat:w,webchat:S,signal:A,nostr:M};function Ge(){return Object.keys(E)}Object.defineProperty(exports,"Gateway",{enumerable:true,get:function(){return chunkLV4EDVUL_cjs.a}});Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.q}});Object.defineProperty(exports,"DEFAULT_AGENT_REGISTRY_CONFIG",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.j}});Object.defineProperty(exports,"DEFAULT_CONNECTION_POOL_CONFIG",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.l}});Object.defineProperty(exports,"DEFAULT_SYNC_CONFIG",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.k}});Object.defineProperty(exports,"DEFAULT_TOKEN_AUTH_CONFIG",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.i}});Object.defineProperty(exports,"DEFAULT_WEBSOCKET_SERVER_CONFIG",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.h}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.s}});Object.defineProperty(exports,"GatewaySessionManager",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.p}});Object.defineProperty(exports,"MessageLockManager",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.a}});Object.defineProperty(exports,"MessageRetryManager",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.b}});Object.defineProperty(exports,"MessageRouter",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.m}});Object.defineProperty(exports,"MessageStore",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.n}});Object.defineProperty(exports,"SessionStore",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.o}});Object.defineProperty(exports,"createDefaultSessionState",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.f}});Object.defineProperty(exports,"createGatewayMessage",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.c}});Object.defineProperty(exports,"createTextMessage",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.d}});Object.defineProperty(exports,"generateSessionId",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.e}});Object.defineProperty(exports,"generateSubscriptionId",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.g}});Object.defineProperty(exports,"AgentRegistryConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.q}});Object.defineProperty(exports,"AgentSyncConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.l}});Object.defineProperty(exports,"AuthConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.k}});Object.defineProperty(exports,"ChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.i}});Object.defineProperty(exports,"CircuitBreakerConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.p}});Object.defineProperty(exports,"ConnectionPoolConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.n}});Object.defineProperty(exports,"FeishuChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.d}});Object.defineProperty(exports,"GatewayClusterConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.m}});Object.defineProperty(exports,"GatewayConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.t}});Object.defineProperty(exports,"GatewayServerConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.s}});Object.defineProperty(exports,"HTTPSConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.j}});Object.defineProperty(exports,"MessageQueueConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.o}});Object.defineProperty(exports,"NostrChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.h}});Object.defineProperty(exports,"SessionConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.r}});Object.defineProperty(exports,"SignalChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.g}});Object.defineProperty(exports,"SlackChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.c}});Object.defineProperty(exports,"TelegramChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.b}});Object.defineProperty(exports,"WeChatChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.e}});Object.defineProperty(exports,"WebChatChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.f}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.A}});Object.defineProperty(exports,"getAgentRegistryConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.H}});Object.defineProperty(exports,"getAuthConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.K}});Object.defineProperty(exports,"getChannelConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.D}});Object.defineProperty(exports,"getCircuitBreakerConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.G}});Object.defineProperty(exports,"getClusterConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.L}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.y}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.B}});Object.defineProperty(exports,"getConnectionPoolConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.E}});Object.defineProperty(exports,"getDefaultAgent",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.M}});Object.defineProperty(exports,"getHTTPSConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.J}});Object.defineProperty(exports,"getLogLevel",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.N}});Object.defineProperty(exports,"getMessageQueueConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.F}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.C}});Object.defineProperty(exports,"getSessionConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.I}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.z}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.x}});Object.defineProperty(exports,"parsePartialConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.v}});Object.defineProperty(exports,"validateConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.u}});exports.AgentRegistry=k;exports.AgentSyncManager=T;exports.BaseChannelPlugin=l;exports.ChannelPluginRegistry=E;exports.DiscordPlugin=b;exports.FeishuPlugin=v;exports.GatewayClient=x;exports.NostrPlugin=M;exports.SignalPlugin=A;exports.SlackPlugin=C;exports.TelegramPlugin=y;exports.WeChatPlugin=w;exports.WebChatPlugin=S;exports.createChannelPlugin=N;exports.getSupportedPlatforms=Ge;
11
+ `)}subscribeToRelay(e,t,s){let i=["REQ",t,s];e.send(JSON.stringify(i));}async createEvent(e,t){let s=[];t&&s.push(["e",t]);let i={id:"",pubkey:this.botConfig?.publicKey??"",created_at:Math.floor(Date.now()/1e3),kind:1,tags:s,content:e,sig:""};return i.id=await this.computeEventId(i),i.sig=await this.signEvent(i),i}async computeEventId(e){let t=JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content]),i=new TextEncoder().encode(t),a=await crypto.subtle.digest("SHA-256",i);return Array.from(new Uint8Array(a)).map(p=>p.toString(16).padStart(2,"0")).join("")}async signEvent(e){if(!this.botConfig?.privateKey)throw new Error("Private key is required");return "signature_placeholder"}async publishEvent(e){let t=["EVENT",e];for(let s of this.relayConnections.values())s.readyState===WebSocket.OPEN&&s.send(JSON.stringify(t));}};chunkSIOB4FC7_cjs.a();var _=class extends l{constructor(e){super();chunkXQVVSJRM_cjs.e(this,"id");chunkXQVVSJRM_cjs.e(this,"platform");chunkXQVVSJRM_cjs.e(this,"name");chunkXQVVSJRM_cjs.e(this,"version");chunkXQVVSJRM_cjs.e(this,"options");this.id=e.id,this.platform=e.platform||"custom",this.name=e.name,this.version=e.version||"1.0.0",this.options=e,this.initLog();}async doStart(){this.options.setup?.initialize&&await this.options.setup.initialize(),this.log.info("Channel plugin started",{id:this.id,platform:this.platform});}async doStop(){this.options.setup?.destroy&&await this.options.setup.destroy(),this.log.info("Channel plugin stopped",{id:this.id});}async send(e){let t=e;this.options.actions?.beforeSend&&(t=await this.options.actions.beforeSend(e));let s=await this.options.messaging.send(t);return this.options.actions?.afterSend&&await this.options.actions.afterSend(t,s),s}async healthCheck(){return this.options.status?.healthCheck?{healthy:await this.options.status.healthCheck(),lastCheck:Date.now()}:{healthy:true,lastCheck:Date.now()}}};function N(f){return new _(f)}var E={telegram:y,discord:b,slack:C,feishu:v,wechat:w,webchat:S,signal:A,nostr:M};function Ge(){return Object.keys(E)}Object.defineProperty(exports,"Gateway",{enumerable:true,get:function(){return chunkEOLBEWUW_cjs.a}});Object.defineProperty(exports,"ChannelPluginLoader",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.q}});Object.defineProperty(exports,"DEFAULT_AGENT_REGISTRY_CONFIG",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.j}});Object.defineProperty(exports,"DEFAULT_CONNECTION_POOL_CONFIG",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.l}});Object.defineProperty(exports,"DEFAULT_SYNC_CONFIG",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.k}});Object.defineProperty(exports,"DEFAULT_TOKEN_AUTH_CONFIG",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.i}});Object.defineProperty(exports,"DEFAULT_WEBSOCKET_SERVER_CONFIG",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.h}});Object.defineProperty(exports,"GatewayServer",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.s}});Object.defineProperty(exports,"GatewaySessionManager",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.p}});Object.defineProperty(exports,"MessageLockManager",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.a}});Object.defineProperty(exports,"MessageRetryManager",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.b}});Object.defineProperty(exports,"MessageRouter",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.m}});Object.defineProperty(exports,"MessageStore",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.n}});Object.defineProperty(exports,"SessionStore",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.o}});Object.defineProperty(exports,"createDefaultSessionState",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.f}});Object.defineProperty(exports,"createGatewayMessage",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.c}});Object.defineProperty(exports,"createTextMessage",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.d}});Object.defineProperty(exports,"generateSessionId",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.e}});Object.defineProperty(exports,"generateSubscriptionId",{enumerable:true,get:function(){return chunkCTTZF7B6_cjs.g}});Object.defineProperty(exports,"AgentRegistryConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.q}});Object.defineProperty(exports,"AgentSyncConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.l}});Object.defineProperty(exports,"AuthConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.k}});Object.defineProperty(exports,"ChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.i}});Object.defineProperty(exports,"CircuitBreakerConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.p}});Object.defineProperty(exports,"ConnectionPoolConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.n}});Object.defineProperty(exports,"FeishuChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.d}});Object.defineProperty(exports,"GatewayClusterConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.m}});Object.defineProperty(exports,"GatewayConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.t}});Object.defineProperty(exports,"GatewayServerConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.s}});Object.defineProperty(exports,"HTTPSConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.j}});Object.defineProperty(exports,"MessageQueueConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.o}});Object.defineProperty(exports,"NostrChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.h}});Object.defineProperty(exports,"SessionConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.r}});Object.defineProperty(exports,"SignalChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.g}});Object.defineProperty(exports,"SlackChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.c}});Object.defineProperty(exports,"TelegramChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.b}});Object.defineProperty(exports,"WeChatChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.e}});Object.defineProperty(exports,"WebChatChannelConfigSchema",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.f}});Object.defineProperty(exports,"clearConfigCache",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.A}});Object.defineProperty(exports,"getAgentRegistryConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.H}});Object.defineProperty(exports,"getAuthConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.K}});Object.defineProperty(exports,"getChannelConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.D}});Object.defineProperty(exports,"getCircuitBreakerConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.G}});Object.defineProperty(exports,"getClusterConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.L}});Object.defineProperty(exports,"getConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.y}});Object.defineProperty(exports,"getConfigDirectory",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.B}});Object.defineProperty(exports,"getConnectionPoolConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.E}});Object.defineProperty(exports,"getDefaultAgent",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.M}});Object.defineProperty(exports,"getHTTPSConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.J}});Object.defineProperty(exports,"getLogLevel",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.N}});Object.defineProperty(exports,"getMessageQueueConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.F}});Object.defineProperty(exports,"getServerConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.C}});Object.defineProperty(exports,"getSessionConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.I}});Object.defineProperty(exports,"isConfigLoaded",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.z}});Object.defineProperty(exports,"loadConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.x}});Object.defineProperty(exports,"parsePartialConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.v}});Object.defineProperty(exports,"validateConfig",{enumerable:true,get:function(){return chunkEKLLH53Y_cjs.u}});exports.AgentRegistry=k;exports.AgentSyncManager=T;exports.BaseChannelPlugin=l;exports.ChannelPluginRegistry=E;exports.DiscordPlugin=b;exports.FeishuPlugin=v;exports.GatewayClient=x;exports.NostrPlugin=M;exports.SignalPlugin=A;exports.SlackPlugin=C;exports.TelegramPlugin=y;exports.WeChatPlugin=w;exports.WebChatPlugin=S;exports.createChannelPlugin=N;exports.getSupportedPlatforms=Ge;
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- export{a as Gateway}from'./chunks/chunk-UHALF3PM.mjs';import {j,k,c as c$1,r}from'./chunks/chunk-YAKKDECJ.mjs';export{q as ChannelPluginLoader,j as DEFAULT_AGENT_REGISTRY_CONFIG,l as DEFAULT_CONNECTION_POOL_CONFIG,k as DEFAULT_SYNC_CONFIG,i as DEFAULT_TOKEN_AUTH_CONFIG,h as DEFAULT_WEBSOCKET_SERVER_CONFIG,s as GatewayServer,p as GatewaySessionManager,a as MessageLockManager,b as MessageRetryManager,m as MessageRouter,n as MessageStore,o as SessionStore,f as createDefaultSessionState,c as createGatewayMessage,d as createTextMessage,e as generateSessionId,g as generateSubscriptionId}from'./chunks/chunk-YAKKDECJ.mjs';import {a as a$1}from'./chunks/chunk-ETYFY7SI.mjs';export{q as AgentRegistryConfigSchema,l as AgentSyncConfigSchema,k as AuthConfigSchema,i as ChannelConfigSchema,p as CircuitBreakerConfigSchema,n as ConnectionPoolConfigSchema,d as FeishuChannelConfigSchema,m as GatewayClusterConfigSchema,t as GatewayConfigSchema,s as GatewayServerConfigSchema,j as HTTPSConfigSchema,o as MessageQueueConfigSchema,h as NostrChannelConfigSchema,r as SessionConfigSchema,g as SignalChannelConfigSchema,c as SlackChannelConfigSchema,b as TelegramChannelConfigSchema,e as WeChatChannelConfigSchema,f as WebChatChannelConfigSchema,A as clearConfigCache,H as getAgentRegistryConfig,K as getAuthConfig,D as getChannelConfig,G as getCircuitBreakerConfig,L as getClusterConfig,y as getConfig,B as getConfigDirectory,E as getConnectionPoolConfig,M as getDefaultAgent,J as getHTTPSConfig,N as getLogLevel,F as getMessageQueueConfig,C as getServerConfig,I as getSessionConfig,z as isConfigLoaded,x as loadConfig,v as parsePartialConfig,u as validateConfig}from'./chunks/chunk-ETYFY7SI.mjs';import {a}from'./chunks/chunk-SJNPXLNN.mjs';import {e}from'./chunks/chunk-TY6W6O7O.mjs';a();a();a();var f=a$1.create({service:"gateway:agent-registry"}),T=class{constructor(n={}){e(this,"config");e(this,"agents",new Map);e(this,"heartbeatTimer",null);e(this,"roundRobinIndex",0);this.config={...j,...n};}async register(n){if(this.agents.has(n.id))throw new Error(`Agent with ID "${n.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let e=Date.now(),t={...n,status:"healthy",lastHeartbeat:e,registeredAt:e,connectionCount:0};this.agents.set(n.id,t),f.info("Agent registered",{agentId:n.id,name:n.name,capabilities:n.capabilities,address:n.address,totalAgents:this.agents.size});}async deregister(n){let e=this.agents.get(n);if(!e){f.warn("Attempted to deregister unknown agent",{agentId:n});return}this.agents.delete(n),f.info("Agent deregistered",{agentId:n,name:e.name,totalAgents:this.agents.size});}async heartbeat(n,e){let t=this.agents.get(n);if(!t)throw f.warn("Heartbeat received from unknown agent",{agentId:n}),new Error(`Agent "${n}" is not registered`);t.lastHeartbeat=Date.now(),t.status="healthy",e&&(t.metadata={...t.metadata,...e}),f.debug("Agent heartbeat received",{agentId:n,lastHeartbeat:t.lastHeartbeat});}getAgent(n){return this.agents.get(n)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(n=>n.status==="healthy")}selectAgent(n){let{strategy:e,capabilities:t,healthyOnly:s=true}=n,i=s?this.getHealthyAgents():this.getAllAgents();if(t&&t.length>0&&(i=i.filter(o=>t.every(u=>o.capabilities.includes(u)))),i.length===0){f.warn("No agents available for selection",{strategy:e,capabilities:t,healthyOnly:s,totalAgents:this.agents.size});return}let a;switch(e){case "random":a=this.selectRandom(i);break;case "round-robin":a=this.selectRoundRobin(i);break;case "least-connections":a=this.selectLeastConnections(i);break;default:a=this.selectRandom(i);}return f.debug("Agent selected",{agentId:a.id,strategy:e,connectionCount:a.connectionCount}),a}incrementConnection(n){let e=this.agents.get(n);e&&(e.connectionCount++,f.debug("Agent connection incremented",{agentId:n,connectionCount:e.connectionCount}));}decrementConnection(n){let e=this.agents.get(n);e&&e.connectionCount>0&&(e.connectionCount--,f.debug("Agent connection decremented",{agentId:n,connectionCount:e.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){f.warn("Heartbeat check is already running");return}f.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,f.info("Heartbeat check stopped"));}checkHeartbeats(){let n=Date.now(),{heartbeatTimeout:e,autoDeregisterTimeout:t}=this.config,s=[],i=0;for(let[a,o]of this.agents.entries()){let u=n-o.lastHeartbeat;if(u>t){s.push(a);continue}u>e&&o.status==="healthy"&&(o.status="unhealthy",i++,f.warn("Agent marked as unhealthy due to heartbeat timeout",{agentId:a,lastHeartbeat:o.lastHeartbeat,timeSinceLastHeartbeat:u,timeout:e}));}for(let a of s){let o=this.agents.get(a);o&&(f.info("Auto-deregistering agent due to timeout",{agentId:a,name:o.name,lastHeartbeat:o.lastHeartbeat,timeout:t}),this.agents.delete(a));}(i>0||s.length>0)&&f.info("Heartbeat check completed",{unhealthyCount:i,deregisteredCount:s.length,totalAgents:this.agents.size});}selectRandom(n){let e=Math.floor(Math.random()*n.length);return n[e]}selectRoundRobin(n){this.roundRobinIndex=this.roundRobinIndex%n.length;let e=n[this.roundRobinIndex];return this.roundRobinIndex++,e}selectLeastConnections(n){return n.reduce((e,t)=>t.connectionCount<e.connectionCount?t:e)}getStats(){let n=this.getAllAgents();return {totalAgents:n.length,healthyAgents:n.filter(e=>e.status==="healthy").length,unhealthyAgents:n.filter(e=>e.status==="unhealthy").length,offlineAgents:n.filter(e=>e.status==="offline").length,totalConnections:n.reduce((e,t)=>e+t.connectionCount,0)}}setAgentStatus(n,e){let t=this.agents.get(n);t&&(t.status=e);}setLastHeartbeat(n,e){let t=this.agents.get(n);t&&(t.lastHeartbeat=e);}};a();var c=a$1.create({service:"gateway:agent-sync-manager"}),x=class{constructor(n){e(this,"config");e(this,"registry");e(this,"localNodeId");e(this,"localNodeName");e(this,"remoteNodes",new Map);e(this,"remoteAgents",new Map);e(this,"syncTimer",null);e(this,"running",false);e(this,"httpClient");this.registry=n.registry,this.localNodeId=n.localNodeId,this.localNodeName=n.localNodeName,this.config={...k,...n.config},this.httpClient=n.httpClient||{fetch:globalThis.fetch.bind(globalThis)};}async start(){if(this.running){c.warn("Agent sync manager is already running");return}c.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let n of this.config.remoteNodes)this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.running=true,c.info("Agent sync manager started");}async stop(){if(!this.running){c.warn("Agent sync manager is not running");return}c.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,c.info("Agent sync manager stopped");}async pullFromAllNodes(){for(let[n]of this.remoteNodes.entries())try{await this.pullFromNode(n);}catch(e){c.error("Failed to pull from node",{nodeId:n,error:e.message});}}async pullFromNode(n){let e=this.remoteNodes.get(n);if(!e)throw new Error(`Unknown remote node: ${n}`);e.status="syncing";let t=this.config.remoteNodes.find(s=>s.id===n);if(!t)throw new Error(`Remote node not found in config: ${n}`);c.debug("Pulling agent list from node",{nodeId:n,address:t.address});try{let s=`http://${t.address}:${t.port}/sync/agents`,i=await this.httpClient.fetch(s,{method:"GET",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);let o=(await i.json()).agents||[];for(let u of o)u.sourceGatewayId=n,this.remoteAgents.set(u.id,u);return e.lastSyncAt=Date.now(),e.status="synced",e.info.lastSyncAt=e.lastSyncAt,e.info.status="online",delete e.error,c.info("Pulled agent list from node",{nodeId:n,agentCount:o.length,lastSyncAt:e.lastSyncAt}),o}catch(s){throw e.status="error",e.error=s.message,e.info.status="offline",c.error("Failed to pull from node",{nodeId:n,error:s.message}),s}}async pushEvent(n){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let e=[];for(let[t]of this.remoteNodes.entries())e.push(this.pushToNode(t,n));await Promise.allSettled(e);}async pushToNode(n,e){let t=this.config.remoteNodes.find(s=>s.id===n);if(!t){c.warn("Unknown remote node for push",{nodeId:n});return}try{let s=`http://${t.address}:${t.port}/sync/events`,i=await this.httpClient.fetch(s,{method:"POST",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId},body:JSON.stringify(e)});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);c.debug("Pushed event to node",{nodeId:n,eventType:e.type});}catch(s){c.error("Failed to push to node",{nodeId:n,eventType:e.type,error:s.message});}}async handleSyncMessage(n){switch(c.debug("Received sync message",{type:n.type,sourceNodeId:n.sourceNodeId}),n.type){case "agent_list_request":await this.handleAgentListRequest(n);break;case "agent_list_response":await this.handleAgentListResponse(n);break;case "agent_register":await this.handleAgentRegister(n);break;case "agent_deregister":await this.handleAgentDeregister(n);break;case "agent_heartbeat":await this.handleAgentHeartbeat(n);break;case "agent_status_change":await this.handleAgentStatusChange(n);break;default:c.warn("Unknown sync message type",{type:n.type});}}async handleAgentListRequest(n){let e=this.getLocalAgentsForSync(),t={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:n.requestId,agents:e,fullList:true,syncAt:Date.now()};await this.pushToNode(n.sourceNodeId,t);}async handleAgentListResponse(n){for(let e of n.agents)this.remoteAgents.set(e.id,e);c.info("Received agent list response",{sourceNodeId:n.sourceNodeId,agentCount:n.agents.length});}async handleAgentRegister(n){let{agent:e}=n,t=this.remoteAgents.get(e.id);if(t){let s=this.resolveConflict(t,e);this.remoteAgents.set(e.id,s);}else this.remoteAgents.set(e.id,e);c.info("Remote agent registered",{agentId:e.id,name:e.name,sourceNodeId:n.sourceNodeId});}async handleAgentDeregister(n){let{agentId:e}=n;this.remoteAgents.delete(e),c.info("Remote agent deregistered",{agentId:e,sourceNodeId:n.sourceNodeId});}async handleAgentHeartbeat(n){let{agentId:e,heartbeatAt:t,status:s}=n,i=this.remoteAgents.get(e);i&&(i.updatedAt=t,i.status=s),c.debug("Remote agent heartbeat received",{agentId:e,status:s,sourceNodeId:n.sourceNodeId});}async handleAgentStatusChange(n){let{agentId:e,newStatus:t,changedAt:s}=n,i=this.remoteAgents.get(e);i&&(i.status=t,i.updatedAt=s),c.info("Remote agent status changed",{agentId:e,newStatus:t,sourceNodeId:n.sourceNodeId});}resolveConflict(n,e){switch(this.config.conflictResolution){case "latest":return e.updatedAt>n.updatedAt?e:n;case "local":return n;case "remote":return e;default:return e.updatedAt>n.updatedAt?e:n}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(e=>({id:e.id,name:e.name,sourceGatewayId:this.localNodeId,address:e.address,capabilities:e.capabilities,status:e.status,updatedAt:e.lastHeartbeat,metadata:e.metadata}))}getMergedAgentList(){let n=new Map;for(let e of this.getLocalAgentsForSync())n.set(e.id,e);for(let[e,t]of this.remoteAgents.entries())n.has(e)||n.set(e,t);return Array.from(n.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values())}getStats(){let n=this.registry.getAllAgents(),e=0,t=0;for(let i of this.remoteNodes.values())i.info.status==="online"?e++:t++;let s=null;for(let i of this.remoteNodes.values())i.lastSyncAt>(s||0)&&(s=i.lastSyncAt);return {localAgentCount:n.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:n.length+this.remoteAgents.size,onlineNodeCount:e,offlineNodeCount:t,lastSyncAt:s}}isRunning(){return this.running}addRemoteNode(n){this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"}),c.info("Remote node added",{nodeId:n.id,address:n.address});}removeRemoteNode(n){this.remoteNodes.delete(n);for(let[e,t]of this.remoteAgents.entries())t.sourceGatewayId===n&&this.remoteAgents.delete(e);c.info("Remote node removed",{nodeId:n});}};a();a();var l=class{constructor(){e(this,"version","1.0.0");e(this,"log");e(this,"config",null);e(this,"messageHandler",null);e(this,"_status","stopped");e(this,"lastActivity",0);}initLog(){this.log=a$1.create({service:`channel:${this.platform}`});}async start(n,e){if(this._status==="running"){this.log.warn("plugin is already running");return}this.log.info("starting channel plugin",{id:this.id,platform:this.platform}),this._status="starting",this.config=n,this.messageHandler=e;try{await this.doStart(),this._status="running",this.lastActivity=Date.now(),this.log.info("channel plugin started",{id:this.id});}catch(t){throw this._status="error",this.log.error("failed to start channel plugin",{error:String(t)}),t}}async stop(){if(this._status==="stopped"){this.log.warn("plugin is already stopped");return}this.log.info("stopping channel plugin",{id:this.id}),this._status="stopping";try{await this.doStop(),this._status="stopped",this.log.info("channel plugin stopped",{id:this.id});}catch(n){throw this._status="error",this.log.error("failed to stop channel plugin",{error:String(n)}),n}}async healthCheck(){try{return {healthy:await this.doHealthCheck(),lastCheck:Date.now()}}catch(n){return {healthy:false,lastCheck:Date.now(),error:n instanceof Error?n.message:String(n)}}}getStatus(){return {status:this._status,lastActivity:this.lastActivity}}async doHealthCheck(){return this._status==="running"}updateActivity(){this.lastActivity=Date.now();}async handleMessage(n){if(!this.messageHandler){this.log.warn("no message handler set, dropping message",{id:n.id});return}this.updateActivity(),await this.messageHandler.onMessage(n);}async handleEvent(n,e){if(!this.messageHandler){this.log.warn("no message handler set, dropping event",{type:n});return}await this.messageHandler.onEvent({type:n,channelId:this.id,data:e,timestamp:Date.now()});}};a();a();var _=class{constructor(n){e(this,"log");e(this,"config");e(this,"ws",null);e(this,"state","disconnected");e(this,"subscriptions",new Map);e(this,"messageCallbacks",new Set);e(this,"agentListCallbacks",new Set);e(this,"cachedAgentList",[]);e(this,"localAgentList",[]);e(this,"reconnectAttempts",0);e(this,"reconnectTimer",null);e(this,"heartbeatTimer",null);e(this,"agentListRequestId",null);e(this,"agentListRequestResolve",null);this.config={url:n.url,type:n.type,id:n.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,reconnect:{enabled:n.reconnect?.enabled??true,maxAttempts:n.reconnect?.maxAttempts??5,delay:n.reconnect?.delay??3e3},heartbeat:{enabled:n.heartbeat?.enabled??true,interval:n.heartbeat?.interval??3e4}},this.log=a$1.create({service:`gateway:client:${this.config.id}`});}async connect(){if(this.state==="connected"||this.state==="connecting"){this.log.warn("already connected or connecting");return}return this.state="connecting",this.log.info("connecting to gateway",{url:this.config.url}),new Promise((n,e)=>{try{this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{this.state="connected",this.reconnectAttempts=0,this.log.info("connected to gateway"),this.config.heartbeat.enabled&&this.startHeartbeat(),this.resubscribeAll(),n();},this.ws.onmessage=t=>{this.handleMessage(t.data);},this.ws.onclose=t=>{this.handleClose(t.code,t.reason);},this.ws.onerror=t=>{this.log.error("WebSocket error",{error:String(t)}),this.state==="connecting"&&e(new Error("Connection failed"));};}catch(t){this.state="disconnected",e(t);}})}async disconnect(){this.state!=="disconnected"&&(this.log.info("disconnecting from gateway"),this.stopHeartbeat(),this.stopReconnect(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.state="disconnected",this.log.info("disconnected from gateway"));}async subscribe(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"subscribe",sessionId:n,clientId:this.config.id}),this.log.info("subscribed to session",{sessionId:n});}async unsubscribe(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:n,clientId:this.config.id}),this.subscriptions.delete(n),this.log.info("unsubscribed from session",{sessionId:n});}async send(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:n});}onMessage(n){this.messageCallbacks.add(n);}offMessage(n){this.messageCallbacks.delete(n);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(n){this.localAgentList=n,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((n,e)=>{let t=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=t,this.agentListRequestResolve=n,this.sendData({type:"agent_list_request",requestId:t}),setTimeout(()=>{this.agentListRequestId===t&&(this.agentListRequestId=null,this.agentListRequestResolve=null,e(new Error("Agent list request timeout")));},1e4);})}getConnectableAgents(n={}){let{localAgents:e,preferLocal:t=true,filterOffline:s=true}=n,i=e||this.localAgentList,a=this.cachedAgentList,o=this.mergeAgentLists(i,a,t);return s?o.filter(u=>u.status!=="offline"):o}onAgentListChange(n){this.agentListCallbacks.add(n);}offAgentListChange(n){this.agentListCallbacks.delete(n);}mergeAgentLists(n,e,t){let s=new Map,i=t?e:n,a=t?n:e;for(let o of i)s.set(o.id,o);for(let o of a)s.set(o.id,o);return Array.from(s.values())}updateMergedAgentList(){let n=this.getConnectableAgents({filterOffline:false});for(let e of this.agentListCallbacks)try{e(n);}catch(t){this.log.error("agent list callback error",{error:String(t)});}}handleAgentListResponse(n,e){e&&this.agentListRequestId===e&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(n),this.agentListRequestResolve=null),this.cachedAgentList=n,this.updateMergedAgentList(),this.log.debug("received agent list",{count:n.length});}sendData(n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(n));}handleMessage(n){try{let e=JSON.parse(n);switch(e.type){case "message":this.handleGatewayMessage(e.message);break;case "subscribed":this.subscriptions.set(e.sessionId,e.subscription);break;case "unsubscribed":this.subscriptions.delete(e.sessionId);break;case "pong":break;case "agent_list_response":this.handleAgentListResponse(e.agents||[],e.requestId);break;case "agent_update":this.handleAgentUpdate(e.agent,e.action);break;default:this.log.debug("unknown message type",{type:e.type});}}catch(e){this.log.error("failed to parse message",{error:String(e)});}}handleAgentUpdate(n,e){switch(e){case "add":case "update":{let t=this.cachedAgentList.findIndex(s=>s.id===n.id);t>=0?this.cachedAgentList[t]=n:this.cachedAgentList.push(n);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(t=>t.id!==n.id);break}this.updateMergedAgentList();}handleGatewayMessage(n){for(let e of this.messageCallbacks)try{e(n);}catch(t){this.log.error("message callback error",{error:String(t)});}}handleClose(n,e){this.log.info("connection closed",{code:n,reason:e}),this.state="disconnected",this.ws=null,this.stopHeartbeat(),this.config.reconnect.enabled&&this.scheduleReconnect();}scheduleReconnect(){if(this.reconnectAttempts>=this.config.reconnect.maxAttempts){this.log.error("max reconnect attempts reached");return}this.reconnectAttempts++,this.state="reconnecting";let n=this.config.reconnect.delay*this.reconnectAttempts;this.log.info("scheduling reconnect",{attempt:this.reconnectAttempts,delay:n}),this.reconnectTimer=setTimeout(async()=>{try{await this.connect();}catch(e){this.log.error("reconnect failed",{error:String(e)});}},n);}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.state==="connected"&&this.sendData({type:"ping"});},this.config.heartbeat.interval);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);}async resubscribeAll(){for(let n of this.subscriptions.keys())try{await this.subscribe(n);}catch(e){this.log.error("failed to resubscribe",{sessionId:n,error:String(e)});}}};a();a();var b=class extends l{constructor(e$1="telegram-main"){super();e(this,"id");e(this,"platform","telegram");e(this,"name","Telegram Bot");e(this,"botConfig",null);e(this,"pollingInterval",null);e(this,"lastUpdateId",0);e(this,"baseUrl","");this.id=e$1,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");this.baseUrl=`https://api.telegram.org/bot${this.botConfig.botToken}`;let e=await this.getMe();this.log.info("Telegram bot connected",{id:e.id,username:e.username,first_name:e.first_name}),this.botConfig.polling?.enabled!==false&&this.startPolling();}async doStop(){this.stopPolling(),this.botConfig=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Chat ID is required");let s=this.extractText(e);return (await this.sendMessage(t,s)).message_id.toString()}startPolling(){if(this.pollingInterval)return;let e=this.botConfig?.polling?.interval??1e3;this.pollingInterval=setInterval(async()=>{try{await this.poll();}catch(t){this.log.error("Polling error",{error:String(t)});}},e),this.log.info("Polling started",{interval:e});}stopPolling(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null,this.log.info("Polling stopped"));}async poll(){let e=await this.getUpdates(this.lastUpdateId+1,100,0);for(let t of e)this.lastUpdateId=t.update_id,t.message&&await this.handleTelegramMessage(t.message);}async handleTelegramMessage(e){if(this.updateActivity(),e.from?.is_bot)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return c$1(t,"input",this.parseContent(e),{channel:{platform:"telegram",channelId:this.id,userId:e.from?.id.toString(),chatId:e.chat.id.toString(),username:e.from?.username,firstName:e.from?.first_name,lastName:e.from?.last_name,chatType:e.chat.type,chatTitle:e.chat.title},context:{replyTo:e.reply_to_message?.message_id.toString()}})}parseContent(e){let t=[];if(e.text&&t.push({type:"text",text:e.text}),e.photo&&e.photo.length>0){let s=e.photo[e.photo.length-1];s&&t.push({type:"image",image:s.file_id,mime:"image/jpeg"});}if(e.document&&t.push({type:"file",data:e.document.file_id,mime:e.document.mime_type}),e.caption&&t.length>0){let s=t[0];s&&s.type==="text"?t[0]={type:"text",text:`${s.text}
1
+ export{a as Gateway}from'./chunks/chunk-J2DSTELL.mjs';import {j,k,c as c$1,r}from'./chunks/chunk-YAKKDECJ.mjs';export{q as ChannelPluginLoader,j as DEFAULT_AGENT_REGISTRY_CONFIG,l as DEFAULT_CONNECTION_POOL_CONFIG,k as DEFAULT_SYNC_CONFIG,i as DEFAULT_TOKEN_AUTH_CONFIG,h as DEFAULT_WEBSOCKET_SERVER_CONFIG,s as GatewayServer,p as GatewaySessionManager,a as MessageLockManager,b as MessageRetryManager,m as MessageRouter,n as MessageStore,o as SessionStore,f as createDefaultSessionState,c as createGatewayMessage,d as createTextMessage,e as generateSessionId,g as generateSubscriptionId}from'./chunks/chunk-YAKKDECJ.mjs';import {a as a$1}from'./chunks/chunk-ETYFY7SI.mjs';export{q as AgentRegistryConfigSchema,l as AgentSyncConfigSchema,k as AuthConfigSchema,i as ChannelConfigSchema,p as CircuitBreakerConfigSchema,n as ConnectionPoolConfigSchema,d as FeishuChannelConfigSchema,m as GatewayClusterConfigSchema,t as GatewayConfigSchema,s as GatewayServerConfigSchema,j as HTTPSConfigSchema,o as MessageQueueConfigSchema,h as NostrChannelConfigSchema,r as SessionConfigSchema,g as SignalChannelConfigSchema,c as SlackChannelConfigSchema,b as TelegramChannelConfigSchema,e as WeChatChannelConfigSchema,f as WebChatChannelConfigSchema,A as clearConfigCache,H as getAgentRegistryConfig,K as getAuthConfig,D as getChannelConfig,G as getCircuitBreakerConfig,L as getClusterConfig,y as getConfig,B as getConfigDirectory,E as getConnectionPoolConfig,M as getDefaultAgent,J as getHTTPSConfig,N as getLogLevel,F as getMessageQueueConfig,C as getServerConfig,I as getSessionConfig,z as isConfigLoaded,x as loadConfig,v as parsePartialConfig,u as validateConfig}from'./chunks/chunk-ETYFY7SI.mjs';import {a}from'./chunks/chunk-SJNPXLNN.mjs';import {e}from'./chunks/chunk-TY6W6O7O.mjs';a();a();a();var f=a$1.create({service:"gateway:agent-registry"}),T=class{constructor(n={}){e(this,"config");e(this,"agents",new Map);e(this,"heartbeatTimer",null);e(this,"roundRobinIndex",0);this.config={...j,...n};}async register(n){if(this.agents.has(n.id))throw new Error(`Agent with ID "${n.id}" is already registered`);if(this.agents.size>=this.config.maxAgents)throw new Error(`Maximum number of agents (${this.config.maxAgents}) reached`);let e=Date.now(),t={...n,status:"healthy",lastHeartbeat:e,registeredAt:e,connectionCount:0};this.agents.set(n.id,t),f.info("Agent registered",{agentId:n.id,name:n.name,capabilities:n.capabilities,address:n.address,totalAgents:this.agents.size});}async deregister(n){let e=this.agents.get(n);if(!e){f.warn("Attempted to deregister unknown agent",{agentId:n});return}this.agents.delete(n),f.info("Agent deregistered",{agentId:n,name:e.name,totalAgents:this.agents.size});}async heartbeat(n,e){let t=this.agents.get(n);if(!t)throw f.warn("Heartbeat received from unknown agent",{agentId:n}),new Error(`Agent "${n}" is not registered`);t.lastHeartbeat=Date.now(),t.status="healthy",e&&(t.metadata={...t.metadata,...e}),f.debug("Agent heartbeat received",{agentId:n,lastHeartbeat:t.lastHeartbeat});}getAgent(n){return this.agents.get(n)}getAllAgents(){return Array.from(this.agents.values())}getHealthyAgents(){return this.getAllAgents().filter(n=>n.status==="healthy")}selectAgent(n){let{strategy:e,capabilities:t,healthyOnly:s=true}=n,i=s?this.getHealthyAgents():this.getAllAgents();if(t&&t.length>0&&(i=i.filter(o=>t.every(u=>o.capabilities.includes(u)))),i.length===0){f.warn("No agents available for selection",{strategy:e,capabilities:t,healthyOnly:s,totalAgents:this.agents.size});return}let a;switch(e){case "random":a=this.selectRandom(i);break;case "round-robin":a=this.selectRoundRobin(i);break;case "least-connections":a=this.selectLeastConnections(i);break;default:a=this.selectRandom(i);}return f.debug("Agent selected",{agentId:a.id,strategy:e,connectionCount:a.connectionCount}),a}incrementConnection(n){let e=this.agents.get(n);e&&(e.connectionCount++,f.debug("Agent connection incremented",{agentId:n,connectionCount:e.connectionCount}));}decrementConnection(n){let e=this.agents.get(n);e&&e.connectionCount>0&&(e.connectionCount--,f.debug("Agent connection decremented",{agentId:n,connectionCount:e.connectionCount}));}startHeartbeatCheck(){if(this.heartbeatTimer){f.warn("Heartbeat check is already running");return}f.info("Starting heartbeat check",{interval:this.config.heartbeatCheckInterval,timeout:this.config.heartbeatTimeout}),this.heartbeatTimer=setInterval(()=>this.checkHeartbeats(),this.config.heartbeatCheckInterval);}stopHeartbeatCheck(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null,f.info("Heartbeat check stopped"));}checkHeartbeats(){let n=Date.now(),{heartbeatTimeout:e,autoDeregisterTimeout:t}=this.config,s=[],i=0;for(let[a,o]of this.agents.entries()){let u=n-o.lastHeartbeat;if(u>t){s.push(a);continue}u>e&&o.status==="healthy"&&(o.status="unhealthy",i++,f.warn("Agent marked as unhealthy due to heartbeat timeout",{agentId:a,lastHeartbeat:o.lastHeartbeat,timeSinceLastHeartbeat:u,timeout:e}));}for(let a of s){let o=this.agents.get(a);o&&(f.info("Auto-deregistering agent due to timeout",{agentId:a,name:o.name,lastHeartbeat:o.lastHeartbeat,timeout:t}),this.agents.delete(a));}(i>0||s.length>0)&&f.info("Heartbeat check completed",{unhealthyCount:i,deregisteredCount:s.length,totalAgents:this.agents.size});}selectRandom(n){let e=Math.floor(Math.random()*n.length);return n[e]}selectRoundRobin(n){this.roundRobinIndex=this.roundRobinIndex%n.length;let e=n[this.roundRobinIndex];return this.roundRobinIndex++,e}selectLeastConnections(n){return n.reduce((e,t)=>t.connectionCount<e.connectionCount?t:e)}getStats(){let n=this.getAllAgents();return {totalAgents:n.length,healthyAgents:n.filter(e=>e.status==="healthy").length,unhealthyAgents:n.filter(e=>e.status==="unhealthy").length,offlineAgents:n.filter(e=>e.status==="offline").length,totalConnections:n.reduce((e,t)=>e+t.connectionCount,0)}}setAgentStatus(n,e){let t=this.agents.get(n);t&&(t.status=e);}setLastHeartbeat(n,e){let t=this.agents.get(n);t&&(t.lastHeartbeat=e);}};a();var c=a$1.create({service:"gateway:agent-sync-manager"}),x=class{constructor(n){e(this,"config");e(this,"registry");e(this,"localNodeId");e(this,"localNodeName");e(this,"remoteNodes",new Map);e(this,"remoteAgents",new Map);e(this,"syncTimer",null);e(this,"running",false);e(this,"httpClient");this.registry=n.registry,this.localNodeId=n.localNodeId,this.localNodeName=n.localNodeName,this.config={...k,...n.config},this.httpClient=n.httpClient||{fetch:globalThis.fetch.bind(globalThis)};}async start(){if(this.running){c.warn("Agent sync manager is already running");return}c.info("Starting agent sync manager",{localNodeId:this.localNodeId,mode:this.config.mode,interval:this.config.interval,remoteNodes:this.config.remoteNodes.length});for(let n of this.config.remoteNodes)this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"});(this.config.mode==="pull"||this.config.mode==="both")&&(this.syncTimer=setInterval(()=>this.pullFromAllNodes(),this.config.interval)),this.running=true,c.info("Agent sync manager started");}async stop(){if(!this.running){c.warn("Agent sync manager is not running");return}c.info("Stopping agent sync manager"),this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.remoteNodes.clear(),this.remoteAgents.clear(),this.running=false,c.info("Agent sync manager stopped");}async pullFromAllNodes(){for(let[n]of this.remoteNodes.entries())try{await this.pullFromNode(n);}catch(e){c.error("Failed to pull from node",{nodeId:n,error:e.message});}}async pullFromNode(n){let e=this.remoteNodes.get(n);if(!e)throw new Error(`Unknown remote node: ${n}`);e.status="syncing";let t=this.config.remoteNodes.find(s=>s.id===n);if(!t)throw new Error(`Remote node not found in config: ${n}`);c.debug("Pulling agent list from node",{nodeId:n,address:t.address});try{let s=`http://${t.address}:${t.port}/sync/agents`,i=await this.httpClient.fetch(s,{method:"GET",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId}});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);let o=(await i.json()).agents||[];for(let u of o)u.sourceGatewayId=n,this.remoteAgents.set(u.id,u);return e.lastSyncAt=Date.now(),e.status="synced",e.info.lastSyncAt=e.lastSyncAt,e.info.status="online",delete e.error,c.info("Pulled agent list from node",{nodeId:n,agentCount:o.length,lastSyncAt:e.lastSyncAt}),o}catch(s){throw e.status="error",e.error=s.message,e.info.status="offline",c.error("Failed to pull from node",{nodeId:n,error:s.message}),s}}async pushEvent(n){if(this.config.mode!=="push"&&this.config.mode!=="both")return;let e=[];for(let[t]of this.remoteNodes.entries())e.push(this.pushToNode(t,n));await Promise.allSettled(e);}async pushToNode(n,e){let t=this.config.remoteNodes.find(s=>s.id===n);if(!t){c.warn("Unknown remote node for push",{nodeId:n});return}try{let s=`http://${t.address}:${t.port}/sync/events`,i=await this.httpClient.fetch(s,{method:"POST",headers:{"Content-Type":"application/json","X-Gateway-Node-Id":this.localNodeId},body:JSON.stringify(e)});if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);c.debug("Pushed event to node",{nodeId:n,eventType:e.type});}catch(s){c.error("Failed to push to node",{nodeId:n,eventType:e.type,error:s.message});}}async handleSyncMessage(n){switch(c.debug("Received sync message",{type:n.type,sourceNodeId:n.sourceNodeId}),n.type){case "agent_list_request":await this.handleAgentListRequest(n);break;case "agent_list_response":await this.handleAgentListResponse(n);break;case "agent_register":await this.handleAgentRegister(n);break;case "agent_deregister":await this.handleAgentDeregister(n);break;case "agent_heartbeat":await this.handleAgentHeartbeat(n);break;case "agent_status_change":await this.handleAgentStatusChange(n);break;default:c.warn("Unknown sync message type",{type:n.type});}}async handleAgentListRequest(n){let e=this.getLocalAgentsForSync(),t={type:"agent_list_response",sourceNodeId:this.localNodeId,timestamp:Date.now(),requestId:n.requestId,agents:e,fullList:true,syncAt:Date.now()};await this.pushToNode(n.sourceNodeId,t);}async handleAgentListResponse(n){for(let e of n.agents)this.remoteAgents.set(e.id,e);c.info("Received agent list response",{sourceNodeId:n.sourceNodeId,agentCount:n.agents.length});}async handleAgentRegister(n){let{agent:e}=n,t=this.remoteAgents.get(e.id);if(t){let s=this.resolveConflict(t,e);this.remoteAgents.set(e.id,s);}else this.remoteAgents.set(e.id,e);c.info("Remote agent registered",{agentId:e.id,name:e.name,sourceNodeId:n.sourceNodeId});}async handleAgentDeregister(n){let{agentId:e}=n;this.remoteAgents.delete(e),c.info("Remote agent deregistered",{agentId:e,sourceNodeId:n.sourceNodeId});}async handleAgentHeartbeat(n){let{agentId:e,heartbeatAt:t,status:s}=n,i=this.remoteAgents.get(e);i&&(i.updatedAt=t,i.status=s),c.debug("Remote agent heartbeat received",{agentId:e,status:s,sourceNodeId:n.sourceNodeId});}async handleAgentStatusChange(n){let{agentId:e,newStatus:t,changedAt:s}=n,i=this.remoteAgents.get(e);i&&(i.status=t,i.updatedAt=s),c.info("Remote agent status changed",{agentId:e,newStatus:t,sourceNodeId:n.sourceNodeId});}resolveConflict(n,e){switch(this.config.conflictResolution){case "latest":return e.updatedAt>n.updatedAt?e:n;case "local":return n;case "remote":return e;default:return e.updatedAt>n.updatedAt?e:n}}getLocalAgentsForSync(){return this.registry.getAllAgents().map(e=>({id:e.id,name:e.name,sourceGatewayId:this.localNodeId,address:e.address,capabilities:e.capabilities,status:e.status,updatedAt:e.lastHeartbeat,metadata:e.metadata}))}getMergedAgentList(){let n=new Map;for(let e of this.getLocalAgentsForSync())n.set(e.id,e);for(let[e,t]of this.remoteAgents.entries())n.has(e)||n.set(e,t);return Array.from(n.values())}getRemoteAgents(){return Array.from(this.remoteAgents.values())}getStats(){let n=this.registry.getAllAgents(),e=0,t=0;for(let i of this.remoteNodes.values())i.info.status==="online"?e++:t++;let s=null;for(let i of this.remoteNodes.values())i.lastSyncAt>(s||0)&&(s=i.lastSyncAt);return {localAgentCount:n.length,remoteAgentCount:this.remoteAgents.size,totalAgentCount:n.length+this.remoteAgents.size,onlineNodeCount:e,offlineNodeCount:t,lastSyncAt:s}}isRunning(){return this.running}addRemoteNode(n){this.remoteNodes.set(n.id,{info:{id:n.id,name:n.id,address:n.address,port:n.port,lastSyncAt:0,status:"unknown"},lastSyncAt:0,status:"synced"}),c.info("Remote node added",{nodeId:n.id,address:n.address});}removeRemoteNode(n){this.remoteNodes.delete(n);for(let[e,t]of this.remoteAgents.entries())t.sourceGatewayId===n&&this.remoteAgents.delete(e);c.info("Remote node removed",{nodeId:n});}};a();a();var l=class{constructor(){e(this,"version","1.0.0");e(this,"log");e(this,"config",null);e(this,"messageHandler",null);e(this,"_status","stopped");e(this,"lastActivity",0);}initLog(){this.log=a$1.create({service:`channel:${this.platform}`});}async start(n,e){if(this._status==="running"){this.log.warn("plugin is already running");return}this.log.info("starting channel plugin",{id:this.id,platform:this.platform}),this._status="starting",this.config=n,this.messageHandler=e;try{await this.doStart(),this._status="running",this.lastActivity=Date.now(),this.log.info("channel plugin started",{id:this.id});}catch(t){throw this._status="error",this.log.error("failed to start channel plugin",{error:String(t)}),t}}async stop(){if(this._status==="stopped"){this.log.warn("plugin is already stopped");return}this.log.info("stopping channel plugin",{id:this.id}),this._status="stopping";try{await this.doStop(),this._status="stopped",this.log.info("channel plugin stopped",{id:this.id});}catch(n){throw this._status="error",this.log.error("failed to stop channel plugin",{error:String(n)}),n}}async healthCheck(){try{return {healthy:await this.doHealthCheck(),lastCheck:Date.now()}}catch(n){return {healthy:false,lastCheck:Date.now(),error:n instanceof Error?n.message:String(n)}}}getStatus(){return {status:this._status,lastActivity:this.lastActivity}}async doHealthCheck(){return this._status==="running"}updateActivity(){this.lastActivity=Date.now();}async handleMessage(n){if(!this.messageHandler){this.log.warn("no message handler set, dropping message",{id:n.id});return}this.updateActivity(),await this.messageHandler.onMessage(n);}async handleEvent(n,e){if(!this.messageHandler){this.log.warn("no message handler set, dropping event",{type:n});return}await this.messageHandler.onEvent({type:n,channelId:this.id,data:e,timestamp:Date.now()});}};a();a();var _=class{constructor(n){e(this,"log");e(this,"config");e(this,"ws",null);e(this,"state","disconnected");e(this,"subscriptions",new Map);e(this,"messageCallbacks",new Set);e(this,"agentListCallbacks",new Set);e(this,"cachedAgentList",[]);e(this,"localAgentList",[]);e(this,"reconnectAttempts",0);e(this,"reconnectTimer",null);e(this,"heartbeatTimer",null);e(this,"agentListRequestId",null);e(this,"agentListRequestResolve",null);this.config={url:n.url,type:n.type,id:n.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,reconnect:{enabled:n.reconnect?.enabled??true,maxAttempts:n.reconnect?.maxAttempts??5,delay:n.reconnect?.delay??3e3},heartbeat:{enabled:n.heartbeat?.enabled??true,interval:n.heartbeat?.interval??3e4}},this.log=a$1.create({service:`gateway:client:${this.config.id}`});}async connect(){if(this.state==="connected"||this.state==="connecting"){this.log.warn("already connected or connecting");return}return this.state="connecting",this.log.info("connecting to gateway",{url:this.config.url}),new Promise((n,e)=>{try{this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{this.state="connected",this.reconnectAttempts=0,this.log.info("connected to gateway"),this.config.heartbeat.enabled&&this.startHeartbeat(),this.resubscribeAll(),n();},this.ws.onmessage=t=>{this.handleMessage(t.data);},this.ws.onclose=t=>{this.handleClose(t.code,t.reason);},this.ws.onerror=t=>{this.log.error("WebSocket error",{error:String(t)}),this.state==="connecting"&&e(new Error("Connection failed"));};}catch(t){this.state="disconnected",e(t);}})}async disconnect(){this.state!=="disconnected"&&(this.log.info("disconnecting from gateway"),this.stopHeartbeat(),this.stopReconnect(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.state="disconnected",this.log.info("disconnected from gateway"));}async subscribe(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"subscribe",sessionId:n,clientId:this.config.id}),this.log.info("subscribed to session",{sessionId:n});}async unsubscribe(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:n,clientId:this.config.id}),this.subscriptions.delete(n),this.log.info("unsubscribed from session",{sessionId:n});}async send(n){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:n});}onMessage(n){this.messageCallbacks.add(n);}offMessage(n){this.messageCallbacks.delete(n);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(n){this.localAgentList=n,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((n,e)=>{let t=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=t,this.agentListRequestResolve=n,this.sendData({type:"agent_list_request",requestId:t}),setTimeout(()=>{this.agentListRequestId===t&&(this.agentListRequestId=null,this.agentListRequestResolve=null,e(new Error("Agent list request timeout")));},1e4);})}getConnectableAgents(n={}){let{localAgents:e,preferLocal:t=true,filterOffline:s=true}=n,i=e||this.localAgentList,a=this.cachedAgentList,o=this.mergeAgentLists(i,a,t);return s?o.filter(u=>u.status!=="offline"):o}onAgentListChange(n){this.agentListCallbacks.add(n);}offAgentListChange(n){this.agentListCallbacks.delete(n);}mergeAgentLists(n,e,t){let s=new Map,i=t?e:n,a=t?n:e;for(let o of i)s.set(o.id,o);for(let o of a)s.set(o.id,o);return Array.from(s.values())}updateMergedAgentList(){let n=this.getConnectableAgents({filterOffline:false});for(let e of this.agentListCallbacks)try{e(n);}catch(t){this.log.error("agent list callback error",{error:String(t)});}}handleAgentListResponse(n,e){e&&this.agentListRequestId===e&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(n),this.agentListRequestResolve=null),this.cachedAgentList=n,this.updateMergedAgentList(),this.log.debug("received agent list",{count:n.length});}sendData(n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(n));}handleMessage(n){try{let e=JSON.parse(n);switch(e.type){case "message":this.handleGatewayMessage(e.message);break;case "subscribed":this.subscriptions.set(e.sessionId,e.subscription);break;case "unsubscribed":this.subscriptions.delete(e.sessionId);break;case "pong":break;case "agent_list_response":this.handleAgentListResponse(e.agents||[],e.requestId);break;case "agent_update":this.handleAgentUpdate(e.agent,e.action);break;default:this.log.debug("unknown message type",{type:e.type});}}catch(e){this.log.error("failed to parse message",{error:String(e)});}}handleAgentUpdate(n,e){switch(e){case "add":case "update":{let t=this.cachedAgentList.findIndex(s=>s.id===n.id);t>=0?this.cachedAgentList[t]=n:this.cachedAgentList.push(n);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(t=>t.id!==n.id);break}this.updateMergedAgentList();}handleGatewayMessage(n){for(let e of this.messageCallbacks)try{e(n);}catch(t){this.log.error("message callback error",{error:String(t)});}}handleClose(n,e){this.log.info("connection closed",{code:n,reason:e}),this.state="disconnected",this.ws=null,this.stopHeartbeat(),this.config.reconnect.enabled&&this.scheduleReconnect();}scheduleReconnect(){if(this.reconnectAttempts>=this.config.reconnect.maxAttempts){this.log.error("max reconnect attempts reached");return}this.reconnectAttempts++,this.state="reconnecting";let n=this.config.reconnect.delay*this.reconnectAttempts;this.log.info("scheduling reconnect",{attempt:this.reconnectAttempts,delay:n}),this.reconnectTimer=setTimeout(async()=>{try{await this.connect();}catch(e){this.log.error("reconnect failed",{error:String(e)});}},n);}stopReconnect(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null);}startHeartbeat(){this.heartbeatTimer=setInterval(()=>{this.state==="connected"&&this.sendData({type:"ping"});},this.config.heartbeat.interval);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);}async resubscribeAll(){for(let n of this.subscriptions.keys())try{await this.subscribe(n);}catch(e){this.log.error("failed to resubscribe",{sessionId:n,error:String(e)});}}};a();a();var b=class extends l{constructor(e$1="telegram-main"){super();e(this,"id");e(this,"platform","telegram");e(this,"name","Telegram Bot");e(this,"botConfig",null);e(this,"pollingInterval",null);e(this,"lastUpdateId",0);e(this,"baseUrl","");this.id=e$1,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");this.baseUrl=`https://api.telegram.org/bot${this.botConfig.botToken}`;let e=await this.getMe();this.log.info("Telegram bot connected",{id:e.id,username:e.username,first_name:e.first_name}),this.botConfig.polling?.enabled!==false&&this.startPolling();}async doStop(){this.stopPolling(),this.botConfig=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Chat ID is required");let s=this.extractText(e);return (await this.sendMessage(t,s)).message_id.toString()}startPolling(){if(this.pollingInterval)return;let e=this.botConfig?.polling?.interval??1e3;this.pollingInterval=setInterval(async()=>{try{await this.poll();}catch(t){this.log.error("Polling error",{error:String(t)});}},e),this.log.info("Polling started",{interval:e});}stopPolling(){this.pollingInterval&&(clearInterval(this.pollingInterval),this.pollingInterval=null,this.log.info("Polling stopped"));}async poll(){let e=await this.getUpdates(this.lastUpdateId+1,100,0);for(let t of e)this.lastUpdateId=t.update_id,t.message&&await this.handleTelegramMessage(t.message);}async handleTelegramMessage(e){if(this.updateActivity(),e.from?.is_bot)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return c$1(t,"input",this.parseContent(e),{channel:{platform:"telegram",channelId:this.id,userId:e.from?.id.toString(),chatId:e.chat.id.toString(),username:e.from?.username,firstName:e.from?.first_name,lastName:e.from?.last_name,chatType:e.chat.type,chatTitle:e.chat.title},context:{replyTo:e.reply_to_message?.message_id.toString()}})}parseContent(e){let t=[];if(e.text&&t.push({type:"text",text:e.text}),e.photo&&e.photo.length>0){let s=e.photo[e.photo.length-1];s&&t.push({type:"image",image:s.file_id,mime:"image/jpeg"});}if(e.document&&t.push({type:"file",data:e.document.file_id,mime:e.document.mime_type}),e.caption&&t.length>0){let s=t[0];s&&s.type==="text"?t[0]={type:"text",text:`${s.text}
2
2
 
3
3
  ${e.caption}`}:t.unshift({type:"text",text:e.caption});}return t}getSessionId(e){let t=e.chat.id.toString(),s=e.from?.id.toString();return e.chat.type==="private"?`telegram_${this.id}_${t}`:`telegram_${this.id}_${t}_${s}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
4
4
  `)}async getMe(){return (await this.request("getMe")).result}async getUpdates(e,t,s){return (await this.request("getUpdates",{offset:e,limit:t,timeout:s})).result||[]}async sendMessage(e,t){return (await this.request("sendMessage",{chat_id:e,text:t,parse_mode:"Markdown"})).result}async request(e,t={}){let s=`${this.baseUrl}/${e}`,a=await(await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})).json();if(!a.ok)throw new Error(`Telegram API error: ${a.description}`);return a}};a();var C=class extends l{constructor(e$1="discord-main"){super();e(this,"id");e(this,"platform","discord");e(this,"name","Discord Bot");e(this,"botConfig",null);e(this,"baseUrl","https://discord.com/api/v10");e(this,"gatewayWs",null);e(this,"heartbeatInterval",null);e(this,"sessionId",null);e(this,"sequenceNumber",null);this.id=e$1,this.initLog();}async doStart(){if(!this.config)throw new Error("Config not set");if(this.botConfig=this.config.platform,!this.botConfig.botToken)throw new Error("Bot token is required");let e=await this.getCurrentUser();this.log.info("Discord bot connected",{id:e.id,username:e.username}),this.botConfig.gateway?.enabled!==false&&await this.startGateway();}async doStop(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.gatewayWs&&(this.gatewayWs.close(),this.gatewayWs=null),this.botConfig=null;}async send(e){let t=e.metadata.channel.chatId;if(!t)throw new Error("Channel ID is required");let s=this.extractText(e);return (await this.createMessage(t,s,e.metadata.context?.replyTo)).id}async startGateway(){let t=`${(await this.getGatewayBot()).url}/?v=10&encoding=json`;this.gatewayWs=new WebSocket(t),this.gatewayWs.onmessage=s=>{this.handleGatewayMessage(JSON.parse(s.data.toString()));},this.gatewayWs.onclose=()=>{this.log.info("Gateway disconnected"),setTimeout(()=>this.startGateway(),5e3);},this.gatewayWs.onerror=s=>{this.log.error("Gateway error",{error:String(s)});};}handleGatewayMessage(e){switch(this.updateActivity(),e.op){case 10:this.handleHello(e.d);break;case 11:this.log.debug("Heartbeat ACK");break;case 0:e.s&&(this.sequenceNumber=e.s),this.handleDispatch(e.t,e.d);break;case 9:this.log.warn("Invalid session, reconnecting"),this.gatewayWs?.close();break}return Promise.resolve()}handleHello(e){this.heartbeatInterval=setInterval(()=>{this.gatewayWs?.send(JSON.stringify({op:1,d:this.sequenceNumber}));},e.heartbeat_interval),this.gatewayWs?.send(JSON.stringify({op:2,d:{token:this.botConfig?.botToken,intents:this.botConfig?.gateway?.intents??513,properties:{os:"linux",browser:"easbot",device:"easbot"}}}));}handleDispatch(e,t){e==="MESSAGE_CREATE"&&this.handleDiscordMessage(t);}async handleDiscordMessage(e){if(e.author.bot)return;let t=this.toGatewayMessage(e);await this.handleMessage(t);}toGatewayMessage(e){let t=this.getSessionId(e);return c$1(t,"input",this.parseContent(e),{channel:{platform:"discord",channelId:this.id,userId:e.author.id,chatId:e.channel_id,messageId:e.id,guildId:e.guild_id,username:e.author.username,discriminator:e.author.discriminator},context:{threadId:e.message_reference?.message_id,conversationId:e.channel_id}})}parseContent(e){let t=[];e.content&&t.push({type:"text",text:e.content});for(let s of e.attachments)s.content_type?.startsWith("image/")?t.push({type:"image",image:s.url,mime:s.content_type}):t.push({type:"file",data:s.url,mime:s.content_type});return t}getSessionId(e){let t=e.channel_id,s=e.author.id;return `discord_${this.id}_${t}_${s}`}extractText(e){let t=[];for(let s of e.content)s.type==="text"&&s.text&&t.push(s.text);return t.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easbot/gateway",
3
- "version": "0.1.14",
3
+ "version": "0.1.15",
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",
@@ -14,6 +14,24 @@
14
14
  },
15
15
  "./package.json": "./package.json"
16
16
  },
17
+ "scripts": {
18
+ "dev": "cross-env NODE_ENV=development tsx src/cli.ts -- start",
19
+ "start": "cross-env NODE_ENV=production node dist/cli.mjs start",
20
+ "build": "tsup --env.NODE_ENV production",
21
+ "test": "vitest",
22
+ "test:run": "vitest run",
23
+ "lint": "biome check .",
24
+ "lint:fix": "biome check --write .",
25
+ "lint:report": "biome check --reporter=summary .",
26
+ "format": "biome format .",
27
+ "format:fix": "biome format --write .",
28
+ "type-check": "tsc --noEmit",
29
+ "clean": "npx rimraf dist node_modules",
30
+ "prepare": "echo norun",
31
+ "prepublishOnly": "pnpm build",
32
+ "publish:npm": "bash scripts/publish.sh",
33
+ "publish:npm:win": "powershell -ExecutionPolicy Bypass -File scripts/publish.ps1"
34
+ },
17
35
  "keywords": [
18
36
  "easbot",
19
37
  "gateway",
@@ -52,16 +70,16 @@
52
70
  "@ai-sdk/provider-utils": "^4.0.21",
53
71
  "@ai-sdk/openai-compatible": "2.0.37",
54
72
  "@ai-sdk/anthropic": "3.0.63",
73
+ "@easbot/plugin": "workspace:*",
74
+ "@easbot/sdk": "workspace:*",
75
+ "@easbot/types": "workspace:*",
76
+ "@easbot/utils": "workspace:*",
55
77
  "zod": "^4.3.6",
56
78
  "ws": "^8.20.0",
57
79
  "ai": "^6.0.136",
58
80
  "better-sqlite3": "^12.9.0",
59
81
  "jieba-wasm": "^2.4.0",
60
- "xdg-basedir": "^5.1.0",
61
- "@easbot/plugin": "0.1.14",
62
- "@easbot/types": "0.1.14",
63
- "@easbot/utils": "0.1.14",
64
- "@easbot/sdk": "0.1.14"
82
+ "xdg-basedir": "^5.1.0"
65
83
  },
66
84
  "devDependencies": {
67
85
  "@biomejs/biome": "^2.4.8",
@@ -79,21 +97,5 @@
79
97
  },
80
98
  "publishConfig": {
81
99
  "access": "public"
82
- },
83
- "scripts": {
84
- "dev": "cross-env NODE_ENV=development tsx src/cli.ts -- start",
85
- "start": "cross-env NODE_ENV=production node dist/cli.mjs start",
86
- "build": "tsup --env.NODE_ENV production",
87
- "test": "vitest",
88
- "test:run": "vitest run",
89
- "lint": "biome check .",
90
- "lint:fix": "biome check --write .",
91
- "lint:report": "biome check --reporter=summary .",
92
- "format": "biome format .",
93
- "format:fix": "biome format --write .",
94
- "type-check": "tsc --noEmit",
95
- "clean": "npx rimraf dist node_modules",
96
- "publish:npm": "bash scripts/publish.sh",
97
- "publish:npm:win": "powershell -ExecutionPolicy Bypass -File scripts/publish.ps1"
98
100
  }
99
- }
101
+ }
@@ -1 +0,0 @@
1
- 'use strict';var chunkOLIHERIJ_cjs=require('./chunk-OLIHERIJ.cjs');require('./chunk-XQVVSJRM.cjs');module.exports=chunkOLIHERIJ_cjs.a;
@@ -1 +0,0 @@
1
- export{a as default}from'./chunk-5B5ZM3Q7.mjs';import'./chunk-TY6W6O7O.mjs';