agentix-cli 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1493,6 +1493,66 @@ declare const daemonConfigSchema: z.ZodObject<{
1493
1493
  token?: string | undefined;
1494
1494
  agentBinding?: string | undefined;
1495
1495
  }>>;
1496
+ gitlab: z.ZodDefault<z.ZodObject<{
1497
+ enabled: z.ZodDefault<z.ZodBoolean>;
1498
+ webhookPort: z.ZodDefault<z.ZodNumber>;
1499
+ webhookSecret: z.ZodOptional<z.ZodString>;
1500
+ host: z.ZodDefault<z.ZodString>;
1501
+ token: z.ZodOptional<z.ZodString>;
1502
+ routes: z.ZodDefault<z.ZodArray<z.ZodObject<{
1503
+ project: z.ZodString;
1504
+ agent: z.ZodString;
1505
+ }, "strip", z.ZodTypeAny, {
1506
+ agent: string;
1507
+ project: string;
1508
+ }, {
1509
+ agent: string;
1510
+ project: string;
1511
+ }>, "many">>;
1512
+ agentMappings: z.ZodDefault<z.ZodArray<z.ZodObject<{
1513
+ agentId: z.ZodString;
1514
+ gitlabUsernames: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
1515
+ keywords: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
1516
+ }, "strip", z.ZodTypeAny, {
1517
+ agentId: string;
1518
+ gitlabUsernames: string[];
1519
+ keywords: string[];
1520
+ }, {
1521
+ agentId: string;
1522
+ gitlabUsernames?: string[] | undefined;
1523
+ keywords?: string[] | undefined;
1524
+ }>, "many">>;
1525
+ }, "strip", z.ZodTypeAny, {
1526
+ enabled: boolean;
1527
+ host: string;
1528
+ routes: {
1529
+ agent: string;
1530
+ project: string;
1531
+ }[];
1532
+ webhookPort: number;
1533
+ agentMappings: {
1534
+ agentId: string;
1535
+ gitlabUsernames: string[];
1536
+ keywords: string[];
1537
+ }[];
1538
+ token?: string | undefined;
1539
+ webhookSecret?: string | undefined;
1540
+ }, {
1541
+ enabled?: boolean | undefined;
1542
+ token?: string | undefined;
1543
+ host?: string | undefined;
1544
+ routes?: {
1545
+ agent: string;
1546
+ project: string;
1547
+ }[] | undefined;
1548
+ webhookPort?: number | undefined;
1549
+ webhookSecret?: string | undefined;
1550
+ agentMappings?: {
1551
+ agentId: string;
1552
+ gitlabUsernames?: string[] | undefined;
1553
+ keywords?: string[] | undefined;
1554
+ }[] | undefined;
1555
+ }>>;
1496
1556
  }, "strip", z.ZodTypeAny, {
1497
1557
  telegram: {
1498
1558
  enabled: boolean;
@@ -1521,6 +1581,22 @@ declare const daemonConfigSchema: z.ZodObject<{
1521
1581
  token?: string | undefined;
1522
1582
  agentBinding?: string | undefined;
1523
1583
  };
1584
+ gitlab: {
1585
+ enabled: boolean;
1586
+ host: string;
1587
+ routes: {
1588
+ agent: string;
1589
+ project: string;
1590
+ }[];
1591
+ webhookPort: number;
1592
+ agentMappings: {
1593
+ agentId: string;
1594
+ gitlabUsernames: string[];
1595
+ keywords: string[];
1596
+ }[];
1597
+ token?: string | undefined;
1598
+ webhookSecret?: string | undefined;
1599
+ };
1524
1600
  }, {
1525
1601
  telegram?: {
1526
1602
  enabled?: boolean | undefined;
@@ -1549,6 +1625,22 @@ declare const daemonConfigSchema: z.ZodObject<{
1549
1625
  token?: string | undefined;
1550
1626
  agentBinding?: string | undefined;
1551
1627
  } | undefined;
1628
+ gitlab?: {
1629
+ enabled?: boolean | undefined;
1630
+ token?: string | undefined;
1631
+ host?: string | undefined;
1632
+ routes?: {
1633
+ agent: string;
1634
+ project: string;
1635
+ }[] | undefined;
1636
+ webhookPort?: number | undefined;
1637
+ webhookSecret?: string | undefined;
1638
+ agentMappings?: {
1639
+ agentId: string;
1640
+ gitlabUsernames?: string[] | undefined;
1641
+ keywords?: string[] | undefined;
1642
+ }[] | undefined;
1643
+ } | undefined;
1552
1644
  }>>;
1553
1645
  crons: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
1554
1646
  enabled: z.ZodDefault<z.ZodBoolean>;
@@ -1679,6 +1771,22 @@ declare const daemonConfigSchema: z.ZodObject<{
1679
1771
  token?: string | undefined;
1680
1772
  agentBinding?: string | undefined;
1681
1773
  };
1774
+ gitlab: {
1775
+ enabled: boolean;
1776
+ host: string;
1777
+ routes: {
1778
+ agent: string;
1779
+ project: string;
1780
+ }[];
1781
+ webhookPort: number;
1782
+ agentMappings: {
1783
+ agentId: string;
1784
+ gitlabUsernames: string[];
1785
+ keywords: string[];
1786
+ }[];
1787
+ token?: string | undefined;
1788
+ webhookSecret?: string | undefined;
1789
+ };
1682
1790
  };
1683
1791
  crons: Record<string, {
1684
1792
  enabled: boolean;
@@ -1753,6 +1861,22 @@ declare const daemonConfigSchema: z.ZodObject<{
1753
1861
  token?: string | undefined;
1754
1862
  agentBinding?: string | undefined;
1755
1863
  } | undefined;
1864
+ gitlab?: {
1865
+ enabled?: boolean | undefined;
1866
+ token?: string | undefined;
1867
+ host?: string | undefined;
1868
+ routes?: {
1869
+ agent: string;
1870
+ project: string;
1871
+ }[] | undefined;
1872
+ webhookPort?: number | undefined;
1873
+ webhookSecret?: string | undefined;
1874
+ agentMappings?: {
1875
+ agentId: string;
1876
+ gitlabUsernames?: string[] | undefined;
1877
+ keywords?: string[] | undefined;
1878
+ }[] | undefined;
1879
+ } | undefined;
1756
1880
  } | undefined;
1757
1881
  crons?: Record<string, {
1758
1882
  agent: string;
@@ -1845,6 +1969,7 @@ declare class AgentXDaemon {
1845
1969
  private mesh?;
1846
1970
  private hooks;
1847
1971
  private httpServer?;
1972
+ private webhooks;
1848
1973
  private log;
1849
1974
  constructor(configPath?: string);
1850
1975
  start(): Promise<void>;
@@ -1852,9 +1977,32 @@ declare class AgentXDaemon {
1852
1977
  private startChannels;
1853
1978
  private startHttpApi;
1854
1979
  private handleHttp;
1980
+ /**
1981
+ * OpenAI-compatible chat completions endpoint.
1982
+ * Allows ElevenLabs, Cursor, or any OpenAI-compatible client to use an AgentX agent as an LLM.
1983
+ *
1984
+ * Routes:
1985
+ * POST /v1/chat/completions — uses "model" field as agent ID
1986
+ * POST /llm/:agentId/v1/chat/completions — explicit agent ID in URL
1987
+ *
1988
+ * Request format (OpenAI): { model, messages: [{role, content}], stream?, temperature? }
1989
+ * Response format (OpenAI): { id, object, choices: [{message: {role, content}}], usage }
1990
+ */
1991
+ private handleOpenAICompat;
1855
1992
  private json;
1856
1993
  }
1857
1994
 
1995
+ interface DailyUsage {
1996
+ date: string;
1997
+ agents: Record<string, AgentUsage>;
1998
+ }
1999
+ interface AgentUsage {
2000
+ tasks: number;
2001
+ estimatedTokens: number;
2002
+ totalDuration: number;
2003
+ errors: number;
2004
+ }
2005
+
1858
2006
  interface AgentPeer {
1859
2007
  id: string;
1860
2008
  name: string;
@@ -1868,6 +2016,11 @@ interface AgentTask {
1868
2016
  channel?: string;
1869
2017
  sender?: string;
1870
2018
  group?: string;
2019
+ /** Attached media file (image, audio, video, document) */
2020
+ mediaPath?: string;
2021
+ mediaType?: string;
2022
+ /** Text of the message being replied to */
2023
+ replyToText?: string;
1871
2024
  conversationHistory?: Array<{
1872
2025
  role: string;
1873
2026
  content: string;
@@ -1913,6 +2066,8 @@ declare class AgentRegistry {
1913
2066
  private providers;
1914
2067
  private sessions;
1915
2068
  private wiki;
2069
+ private rateLimiter;
2070
+ private tokenTracker;
1916
2071
  private log;
1917
2072
  constructor(config: DaemonConfig, log?: (...args: unknown[]) => void);
1918
2073
  /**
@@ -1929,13 +2084,13 @@ declare class AgentRegistry {
1929
2084
  */
1930
2085
  findAllMentioned(text: string): string[];
1931
2086
  /**
1932
- * Get the primary channel handle for an agent (e.g. "@noqta_devops_bot" on telegram).
2087
+ * Build peer list for context engine.
1933
2088
  */
1934
- private getChannelHandle;
2089
+ private buildPeerList;
1935
2090
  /**
1936
- * Enrich the task context with peer roster and channel handles.
2091
+ * Get the primary channel handle for an agent (e.g. "@noqta_devops_bot" on telegram).
1937
2092
  */
1938
- private enrichTaskContext;
2093
+ private getChannelHandle;
1939
2094
  /**
1940
2095
  * Execute a task on an agent. Respects maxConcurrent limit.
1941
2096
  */
@@ -1953,6 +2108,23 @@ declare class AgentRegistry {
1953
2108
  errors: number;
1954
2109
  lastActive?: Date;
1955
2110
  }>;
2111
+ /**
2112
+ * Get token usage summary.
2113
+ */
2114
+ getUsage(days?: number): {
2115
+ totalTasks: number;
2116
+ totalTokens: number;
2117
+ totalErrors: number;
2118
+ byAgent: Record<string, {
2119
+ tasks: number;
2120
+ tokens: number;
2121
+ avgDuration: number;
2122
+ }>;
2123
+ };
2124
+ /**
2125
+ * Get today's usage.
2126
+ */
2127
+ getTodayUsage(): DailyUsage;
1956
2128
  }
1957
2129
 
1958
2130
  interface IncomingMessage {
@@ -1970,7 +2142,13 @@ interface IncomingMessage {
1970
2142
  };
1971
2143
  text: string;
1972
2144
  replyTo?: string;
2145
+ replyToText?: string;
1973
2146
  timestamp: Date;
2147
+ media?: {
2148
+ path: string;
2149
+ type: string;
2150
+ fileName?: string;
2151
+ };
1974
2152
  raw?: unknown;
1975
2153
  resolvedAgent?: string;
1976
2154
  }
@@ -2005,6 +2183,7 @@ declare class MessageRouter {
2005
2183
  private channels;
2006
2184
  private hooks?;
2007
2185
  private mesh?;
2186
+ private groupLog;
2008
2187
  private log;
2009
2188
  constructor(registry: AgentRegistry, config: DaemonConfig, hooks?: HookRegistry, log?: (...args: unknown[]) => void);
2010
2189
  setMesh(mesh: A2AMesh): void;
@@ -2012,11 +2191,15 @@ declare class MessageRouter {
2012
2191
  startAll(): Promise<void>;
2013
2192
  stopAll(): Promise<void>;
2014
2193
  private handleMessage;
2194
+ private static readonly MAX_BOT_CHAIN_DEPTH;
2015
2195
  /**
2016
- * Check if an agent's response mentions another agent.
2017
- * If so, route the response as a new task to that agent.
2196
+ * Bot-to-bot conversation chain.
2197
+ * Guards:
2198
+ * 1. Max depth (default 3)
2199
+ * 2. No agent called twice in the same chain (prevents A→B→A→B loops)
2200
+ * 3. Only on channels that support it (Telegram)
2018
2201
  */
2019
- private handleBotToBotMentions;
2202
+ private handleBotToBotChain;
2020
2203
  private adapterSend;
2021
2204
  private adapterEdit;
2022
2205
  private adapterReact;
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import{a as de,b as pe,c as pt,d as gt,e as mt,f as ut,g as ft,h as ht,i as yt,j as kt,k as wt,l as St,m as vt,n as xt,o as bt,p as Ct,q as Pt}from"./chunk-S74N276K.js";import{a as H}from"./chunk-X7UN6JAA.js";import{a as Me,b as Ee,c as Oe,d as Ke,e as Be,f as We,g as ze,h as te,i as J,j as ot,k as rt,l as it,m as R,n as ne,o as at,p as ct,q as lt,r as dt,s as T,t as b,u as j}from"./chunk-KVWUPUR5.js";import{a as Ve,b as Ye,c as Xe,d as F,e as Qe,f as Ze,g as et,h as se,i as tt,j as st,k as nt}from"./chunk-PCAYW54Q.js";import{a as Z,b as qe,c as _,d as ee}from"./chunk-FRFR27IN.js";import{a as Q,b as x,c as U}from"./chunk-SFQUP3BP.js";import{a as Ne,b as _e,c as Fe,d as Je,e as Ue,f as He,g as G}from"./chunk-MGMZNJCE.js";import{a as m,b as Ie,c as Ge,d as je,e as Le,f as De}from"./chunk-M7HKBG3V.js";import"./chunk-MDR7SH7F.js";import{execa as $t}from"execa";import{existsSync as ge,promises as oe}from"fs";import C from"path";import fe from"node-fetch";async function Rt(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],r=t[1],n=t[2];try{let a=n?`${s}/${r}/${n}`:`${s}/${r}`;await $t("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let i=C.resolve(e,".skills",`${s}_${r}`);if(ge(i))return await ue(i,o);let c=C.resolve(e,".skills");return ge(c)?await ue(c,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${r}`),await Tt(s,r,n,e)}}async function Tt(o,e,t,s){let r=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await fe(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let c=(await a.json()).tree.filter(l=>l.type==="blob"&&l.path.endsWith("SKILL.md"));if(t){let l=c.find(g=>g.path.includes(`/${t}/`)||g.path===`${t}/SKILL.md`);if(l){let g=await me(o,e,l.path,s);g&&r.push(g)}}else for(let l of c){let g=await me(o,e,l.path,s);g&&r.push(g)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return r}async function me(o,e,t,s){try{let r=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await fe(r);if(!n.ok)return null;let a=await n.text(),i=_(a);if(i){i.source="remote",i.packageId=`${o}/${e}`;let c=C.dirname(t),l=C.resolve(s,".skills",`${o}_${e}`,c);await oe.mkdir(l,{recursive:!0}),await oe.writeFile(C.resolve(l,"SKILL.md"),a),i.path=C.resolve(l,"SKILL.md")}return i}catch{return null}}async function ue(o,e){let t=[],{default:s}=await import("fast-glob"),r=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of r)try{let a=C.resolve(o,n),i=await oe.readFile(a,"utf8"),c=_(i);c&&(c.source="remote",c.path=a,c.packageId=e,t.push(c))}catch{}return t}async function At(o,e,t,s,r){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(r?.length){n.push("globs:");for(let a of r)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
1
+ import{a as de,b as pe,c as pt,d as gt,e as mt,f as ut,g as ft,h as ht,i as yt,j as kt,k as wt,l as St,m as vt,n as xt,o as bt,p as Ct,q as Pt}from"./chunk-WT2UJMBC.js";import{a as H}from"./chunk-X7UN6JAA.js";import{a as Me,b as Ee,c as Oe,d as Ke,e as Be,f as We,g as ze,h as te,i as J,j as ot,k as rt,l as it,m as R,n as ne,o as at,p as ct,q as lt,r as dt,s as T,t as b,u as j}from"./chunk-F73GPYCO.js";import{a as Ve,b as Ye,c as Xe,d as F,e as Qe,f as Ze,g as et,h as se,i as tt,j as st,k as nt}from"./chunk-Z4GC5D6D.js";import{a as Z,b as qe,c as _,d as ee}from"./chunk-FRFR27IN.js";import{a as Q,b as x,c as U}from"./chunk-SFQUP3BP.js";import{a as Ne,b as _e,c as Fe,d as Je,e as Ue,f as He,g as G}from"./chunk-MGMZNJCE.js";import{a as m,b as Ie,c as Ge,d as je,e as Le,f as De}from"./chunk-M7HKBG3V.js";import"./chunk-4YCH6IZV.js";import{execa as $t}from"execa";import{existsSync as ge,promises as oe}from"fs";import C from"path";import fe from"node-fetch";async function Rt(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],r=t[1],n=t[2];try{let a=n?`${s}/${r}/${n}`:`${s}/${r}`;await $t("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let i=C.resolve(e,".skills",`${s}_${r}`);if(ge(i))return await ue(i,o);let c=C.resolve(e,".skills");return ge(c)?await ue(c,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${r}`),await Tt(s,r,n,e)}}async function Tt(o,e,t,s){let r=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await fe(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let c=(await a.json()).tree.filter(l=>l.type==="blob"&&l.path.endsWith("SKILL.md"));if(t){let l=c.find(g=>g.path.includes(`/${t}/`)||g.path===`${t}/SKILL.md`);if(l){let g=await me(o,e,l.path,s);g&&r.push(g)}}else for(let l of c){let g=await me(o,e,l.path,s);g&&r.push(g)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return r}async function me(o,e,t,s){try{let r=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await fe(r);if(!n.ok)return null;let a=await n.text(),i=_(a);if(i){i.source="remote",i.packageId=`${o}/${e}`;let c=C.dirname(t),l=C.resolve(s,".skills",`${o}_${e}`,c);await oe.mkdir(l,{recursive:!0}),await oe.writeFile(C.resolve(l,"SKILL.md"),a),i.path=C.resolve(l,"SKILL.md")}return i}catch{return null}}async function ue(o,e){let t=[],{default:s}=await import("fast-glob"),r=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of r)try{let a=C.resolve(o,n),i=await oe.readFile(a,"utf8"),c=_(i);c&&(c.source="remote",c.path=a,c.packageId=e,t.push(c))}catch{}return t}async function At(o,e,t,s,r){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(r?.length){n.push("globs:");for(let a of r)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
2
2
  `)}
3
3
 
4
- ${t}`}async function Mt(o){let{loadLocalSkills:e}=await import("./loader-RL2LKXIF.js");return e(o)}async function Et(o,e,t,s,r){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
4
+ ${t}`}async function Mt(o){let{loadLocalSkills:e}=await import("./loader-6VSM6FSY.js");return e(o)}async function Et(o,e,t,s,r){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
5
5
  You create high-quality SKILL.md files that provide reusable instructions for AI coding agents.
6
6
 
7
7
  A skill is a markdown document with YAML frontmatter that teaches an agent how to perform a specific task.
@@ -0,0 +1,2 @@
1
+ import{a,b,c,d}from"./chunk-FRFR27IN.js";import"./chunk-4YCH6IZV.js";export{a as loadLocalSkills,d as matchSkillsToTask,c as parseSkillContent,b as parseSkillFile};
2
+ //# sourceMappingURL=loader-6VSM6FSY.js.map
@@ -1,2 +1,2 @@
1
- import{e as a,f as b,g as c}from"./chunk-MGMZNJCE.js";import"./chunk-M7HKBG3V.js";import"./chunk-MDR7SH7F.js";export{b as ClaudeCodeProvider,a as ClaudeProvider,c as createProvider};
2
- //# sourceMappingURL=providers-Q3U3ONJO.js.map
1
+ import{e as a,f as b,g as c}from"./chunk-MGMZNJCE.js";import"./chunk-M7HKBG3V.js";import"./chunk-4YCH6IZV.js";export{b as ClaudeCodeProvider,a as ClaudeProvider,c as createProvider};
2
+ //# sourceMappingURL=providers-AVYG63KK.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agentix-cli",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "description": "Self-hosted multi-agent orchestrator — routes Telegram, WhatsApp, crons, and A2A mesh tasks to Claude Code, OpenAI, or any LLM provider",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -1,2 +0,0 @@
1
- import{s as a,t as b,u as c}from"./chunk-KVWUPUR5.js";import"./chunk-PCAYW54Q.js";import"./chunk-FRFR27IN.js";import"./chunk-SFQUP3BP.js";import"./chunk-MGMZNJCE.js";import"./chunk-M7HKBG3V.js";import"./chunk-MDR7SH7F.js";export{a as createAgentContext,b as generate,c as generateStream};
2
- //# sourceMappingURL=agent-CRA5PU6S.js.map
@@ -1,2 +0,0 @@
1
- var d=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+a+'" is not supported')});export{d as a};
2
- //# sourceMappingURL=chunk-MDR7SH7F.js.map
@@ -1,35 +0,0 @@
1
- import{i as X,j as Z}from"./chunk-PCAYW54Q.js";var M=class{baseUrl;token;constructor(e,t){this.baseUrl=e.replace(/\/$/,""),this.token=t}async getAgentCard(){let e=await fetch(`${this.baseUrl}/.well-known/agent-card.json`,{headers:this.headers()});if(!e.ok)throw new Error(`Failed to fetch agent card: ${e.status}`);return e.json()}async sendTask(e,t){let s=await this.rpc("tasks/send",{id:`task-${Date.now().toString(36)}`,message:{role:"user",parts:[{type:"text",text:e}]},metadata:t});if(s.error)throw new Error(`A2A error: ${s.error.message}`);return s.result}async*sendTaskStream(e,t){let s=JSON.stringify({jsonrpc:"2.0",id:1,method:"tasks/sendSubscribe",params:{id:`task-${Date.now().toString(36)}`,message:{role:"user",parts:[{type:"text",text:e}]},metadata:t}}),n=await fetch(this.baseUrl,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json",Accept:"text/event-stream"},body:s});if(!n.ok||!n.body)throw new Error(`A2A stream error: ${n.status}`);let r=n.body.getReader(),i=new TextDecoder,o="";for(;;){let{done:a,value:g}=await r.read();if(a)break;o+=i.decode(g,{stream:!0});let c=o.split(`
2
- `);o=c.pop()||"";for(let h of c)if(h.startsWith("data: "))try{let u=JSON.parse(h.slice(6));yield{state:u.state,message:u.message?.parts?.[0]?.text,final:u.final}}catch{}}}async getTask(e){let t=await this.rpc("tasks/get",{id:e});if(t.error)throw new Error(`A2A error: ${t.error.message}`);return t.result}async cancelTask(e){let t=await this.rpc("tasks/cancel",{id:e});if(t.error)throw new Error(`A2A error: ${t.error.message}`);return t.result}async rpc(e,t){let s=await fetch(this.baseUrl,{method:"POST",headers:{...this.headers(),"Content-Type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:Date.now(),method:e,params:t})});if(!s.ok)throw new Error(`A2A HTTP error: ${s.status}`);return s.json()}headers(){let e={};return this.token&&(e.Authorization=`Bearer ${this.token}`),e}};var D=class{peers=new Map;healthTimer;config;log;constructor(e,t=console.error.bind(console,"[mesh]")){this.config=e,this.log=t;for(let s of e.mesh.peers)this.peers.set(s.name,{peer:s,client:new M(s.url,s.token),healthy:!1,agents:[]})}async start(){this.log(`Mesh starting with ${this.peers.size} peer(s)`),await this.discoverAll();let e=this.config.mesh.healthCheck.interval*1e3;this.healthTimer=setInterval(()=>this.discoverAll(),e)}async stop(){this.healthTimer&&clearInterval(this.healthTimer)}async discoverAll(){let e=await Promise.allSettled(Array.from(this.peers.entries()).map(([s,n])=>this.discoverPeer(s,n))),t=Array.from(this.peers.values()).filter(s=>s.healthy).length;this.log(`Discovery complete: ${t}/${this.peers.size} peers healthy`)}async discoverPeer(e,t){let s=this.config.mesh.healthCheck.timeout*1e3;try{let n=new AbortController,r=setTimeout(()=>n.abort(),s),i=await t.client.getAgentCard();clearTimeout(r),t.healthy=!0,t.lastCheck=new Date,t.agentCard=i,t.agents=i.skills||[],this.log(`Peer "${e}" healthy: ${i.name} (${t.agents.length} skills)`)}catch(n){t.healthy=!1,t.lastCheck=new Date,this.log(`Peer "${e}" unreachable: ${n.message}`)}}async sendTask(e,t,s){let n=this.peers.get(e);if(!n)throw new Error(`Unknown peer: ${e}`);if(!n.healthy)throw new Error(`Peer "${e}" is not healthy`);let r=s||n.agents[0]?.id;if(!r)throw new Error(`Peer "${e}" has no agents`);let i=`${n.peer.url}/task`,o={"Content-Type":"application/json"};n.peer.token&&(o.Authorization=`Bearer ${n.peer.token}`);let a=await fetch(i,{method:"POST",headers:o,body:JSON.stringify({agent:r,message:t})});if(!a.ok)throw new Error(`Peer "${e}" /task error: ${a.status}`);let g=await a.json();if(g.error)throw new Error(`Peer "${e}" agent error: ${g.error}`);return g.content||"No response"}findPeerWithSkill(e){for(let t of this.peers.values())if(t.healthy&&t.agents.some(s=>s.id===e))return t}directory(){return Array.from(this.peers.entries()).map(([e,t])=>({peer:e,peerUrl:t.peer.url,healthy:t.healthy,skills:t.agents,lastCheck:t.lastCheck}))}};import{z as d}from"zod";import{readFileSync as ee,existsSync as I}from"fs";import{resolve as P}from"path";function ye(l){let e=P(l,".env");if(!I(e))return;let t=ee(e,"utf-8");for(let s of t.split(`
3
- `)){let n=s.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("=");if(r===-1)continue;let i=n.slice(0,r).trim(),o=n.slice(r+1).trim();process.env[i]||(process.env[i]=o)}}var we=d.object({apiKey:d.string().optional(),defaultModel:d.string().optional(),baseUrl:d.string().optional()}),ke=d.object({name:d.string(),workspace:d.string(),tier:d.enum(["claude-code","sdk","orchestrator"]).default("claude-code"),provider:d.string().optional(),model:d.string().optional(),systemPrompt:d.string().optional(),mentions:d.array(d.string()).default([]),maxConcurrent:d.number().default(1),permissionMode:d.string().default("default")}),ve=d.object({token:d.string(),agentBinding:d.string()}),Ae=d.object({telegram:d.object({enabled:d.boolean().default(!1),accounts:d.record(d.string(),ve).default({}),policy:d.object({dm:d.enum(["pair","block"]).default("pair"),group:d.enum(["mention-required","all"]).default("mention-required")}).default({})}).default({}),whatsapp:d.object({enabled:d.boolean().default(!1),sessionDir:d.string().default(".agentx/whatsapp-sessions"),defaultAgent:d.string().optional(),allowFrom:d.array(d.string()).optional(),routes:d.array(d.object({contact:d.string().optional(),group:d.string().optional(),agent:d.string()})).default([])}).default({}),discord:d.object({enabled:d.boolean().default(!1),token:d.string().optional(),agentBinding:d.string().optional()}).default({})}),$e=d.object({enabled:d.boolean().default(!0),schedule:d.string(),timezone:d.string().default("UTC"),agent:d.string(),prompt:d.string(),timeout:d.number().default(600),model:d.string().optional(),onError:d.enum(["log","notify","disable"]).default("log")}),be=d.object({url:d.string(),name:d.string(),token:d.string().optional()}),xe=d.object({enabled:d.boolean().default(!1),peers:d.array(be).default([]),discovery:d.enum(["static","mdns"]).default("static"),healthCheck:d.object({interval:d.number().default(60),timeout:d.number().default(10)}).default({})}),Se=d.object({node:d.object({id:d.string(),name:d.string(),bind:d.string().default("127.0.0.1:18800")}),providers:d.record(d.string(),we).default({}),agents:d.record(d.string(),ke).default({}),channels:Ae.default({}),crons:d.record(d.string(),$e).default({}),mesh:xe.default({})});function G(l){if(typeof l=="string")return l.replace(/\$\{(\w+)\}/g,(e,t)=>process.env[t]||"");if(Array.isArray(l))return l.map(G);if(l!==null&&typeof l=="object"){let e={};for(let[t,s]of Object.entries(l))e[t]=G(s);return e}return l}function te(l){let e=l?[l]:[P(process.cwd(),"agentx.json"),P(process.cwd(),".agentx/config.json")];ye(process.cwd());let t,s;for(let o of e)if(I(o)){t=ee(o,"utf-8"),s=o;break}if(!t||!s)throw new Error(`No config found. Create agentx.json or .agentx/config.json
4
- Searched: ${e.join(", ")}`);let n;try{n=JSON.parse(t)}catch(o){throw new Error(`Invalid JSON in ${s}: ${o.message}`)}let r=G(n),i=Se.safeParse(r);if(!i.success){let o=i.error.issues.map(a=>` ${a.path.join(".")}: ${a.message}`).join(`
5
- `);throw new Error(`Config validation failed (${s}):
6
- ${o}`)}return i.data}function se(l){let e=[];for(let[t,s]of Object.entries(l.agents)){if(!I(s.workspace)){e.push(`Agent "${t}": workspace not found at ${s.workspace}`);continue}if(s.tier==="claude-code"){let i=P(s.workspace,".claude");I(i)||e.push(`Agent "${t}": no .claude/ directory in workspace ${s.workspace}. Claude Code native features (hooks, MCP, skills) won't be available.`)}let n=s.provider||"claude",r=l.providers[n];s.tier!=="claude-code"&&(!r||!r.apiKey)&&e.push(`Agent "${t}": provider "${n}" has no API key configured. Set providers.${n}.apiKey in config or use tier "claude-code" for subscription.`)}for(let[t,s]of Object.entries(l.crons))l.agents[s.agent]||e.push(`Cron "${t}": references unknown agent "${s.agent}"`);if(l.channels.telegram.enabled)for(let[t,s]of Object.entries(l.channels.telegram.accounts))l.agents[s.agentBinding]||e.push(`Telegram account "${t}": references unknown agent "${s.agentBinding}"`);return e}import{execa as Te}from"execa";import{execFile as Ce}from"child_process";function ne(l,e,t){let s=[];if(l.systemPrompt&&s.push(l.systemPrompt),e.context){let n=e.context,r=["","[Environment]"];if(n.channel&&r.push(`Channel: ${n.channel}`),n.group&&r.push(`Group: ${n.group}`),n.sender&&r.push(`Message from: ${n.sender}`),n.myHandle&&r.push(`Your handle on this channel: ${n.myHandle}`),n.peers?.length){r.push(""),r.push("[Team \u2014 other agents you can mention to delegate or collaborate]");for(let i of n.peers){let o=i.handle?` (mention: ${i.handle})`:"",a=i.role?` \u2014 ${i.role}`:"";r.push(`\u2022 ${i.name}${o}${a}`)}r.push(""),r.push("To involve another agent, mention their handle in your response and they will automatically see it and reply.")}s.push(r.join(`
7
- `))}return t&&(s.push(""),s.push(t)),s.push(""),s.push(e.message),s.join(`
8
- `)}function re(l,e,t,s){let n=["-p",e,"--output-format",t?"stream-json":"json"];return t&&n.push("--verbose"),s&&n.push("--resume",s),l.model&&n.push("--model",l.model),l.permissionMode==="bypassPermissions"&&n.push("--dangerously-skip-permissions"),n}function Me(l){try{let e=JSON.parse(l);return{text:e.result||e.content||"",sessionId:e.session_id}}catch{return{text:l}}}async function De(l,e,t,s){let n=Date.now(),r=ne(l,e,s?void 0:t),i=re(l,r,!1,s);try{let{stdout:o,stderr:a,exitCode:g}=await new Promise((h,u)=>{let m=Ce("claude",i,{cwd:l.workspace,timeout:6e5,maxBuffer:10485760,env:{...process.env,HOME:process.env.HOME||"/home/"+(process.env.USER||"clawd")}},(f,y,p)=>{h({stdout:y||"",stderr:p||"",exitCode:f?f.code??1:0})})});if(!o&&g!==0)return{content:"",error:(a?.trim()||`Claude Code exited with code ${g}`).slice(0,300),duration:Date.now()-n};let c=Me(o);return{content:c.text,duration:Date.now()-n,claudeSessionId:c.sessionId}}catch(o){return console.error(`[runtime] execFile threw: ${o.message}`),{content:"",error:o.message||"Claude Code failed",duration:Date.now()-n}}}async function Ie(l,e,t,s,n){let r=Date.now(),i=ne(l,e,n?void 0:s),o=re(l,i,!0,n),a="";try{let g=Te("claude",o,{cwd:l.workspace,timeout:6e5,reject:!1,env:process.env,buffer:!1});if(g.stdout){let h="";g.stdout.on("data",u=>{h+=u.toString();let m=h.split(`
9
- `);h=m.pop()||"";for(let f of m)if(f.trim())try{let y=JSON.parse(f);if(y.type==="assistant"&&y.message?.content){for(let p of y.message.content)if(p.type==="text"&&p.text){let w=p.text.slice(a.length);w&&(a=p.text,t(w,a))}}if(y.type==="content_block_delta"&&y.delta?.text&&(a+=y.delta.text,t(y.delta.text,a)),y.type==="result"&&y.result){let p=(typeof y.result=="string",y.result);if(typeof p=="string"&&p.length>a.length){let w=p.slice(a.length);a=p,w&&t(w,a)}}}catch{f.trim()&&!f.startsWith("{")&&(a+=f+`
10
- `,t(f+`
11
- `,a))}})}let c=await g;return!a&&c.stdout&&(a=typeof c.stdout=="string"?c.stdout:""),c.exitCode!==0&&!a?{content:"",error:(typeof c.stderr=="string"?c.stderr:"")||`Claude Code exited with code ${c.exitCode}`,duration:Date.now()-r}:{content:a,duration:Date.now()-r}}catch(g){return{content:a||"",error:g.message,duration:Date.now()-r}}}async function Pe(l,e,t){let s=Date.now();try{let n=await import("@anthropic-ai/claude-agent-sdk"),{query:r}=n,i=l.systemPrompt?`${l.systemPrompt}
12
-
13
- ${e.message}`:e.message,o="",a=r({prompt:i,options:{model:l.model,cwd:l.workspace,permissionMode:"bypassPermissions"}});for await(let g of a)g.type==="result"&&g.subtype==="success"&&(o=g.result||"");return{content:o,duration:Date.now()-s}}catch(n){return{content:"",error:`SDK error: ${n.message}`,duration:Date.now()-s}}}async function Re(l,e,t){let s=Date.now();try{let{generate:n}=await import("./agent-CRA5PU6S.js"),r=l.provider||"claude-code",i=await n({task:e.message,cwd:l.workspace,provider:r,model:l.model,apiKey:t,overwrite:!0,interactive:!1,context7:!1});return{content:i.content||"Done.",tokensUsed:i.tokensUsed,duration:Date.now()-s}}catch(n){return{content:"",error:`Orchestrator error: ${n.message}`,duration:Date.now()-s}}}async function ie(l,e,t,s,n,r){switch(l.tier){case"claude-code":return s?Ie(l,e,s,n,r):De(l,e,n,r);case"sdk":{let i=l.provider||"claude",o=t[i]?.apiKey;return o?Pe(l,e,o):{content:"",error:`No API key for provider "${i}". Configure providers.${i}.apiKey`}}case"orchestrator":{let i=l.provider||"claude-code",o=t[i]?.apiKey;return Re(l,e,o)}default:return{content:"",error:`Unknown tier: ${l.tier}`}}}import{readFileSync as oe,writeFileSync as R,existsSync as _,mkdirSync as K,readdirSync as z,statSync as _e}from"fs";import{resolve as v,join as Ee,relative as E,dirname as je}from"path";var S=class{baseDir;rawDir;log;constructor(e=v(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki]")){this.baseDir=e,this.rawDir=v(e,"raw/entries"),this.log=t,K(this.rawDir,{recursive:!0}),K(v(e,"raw"),{recursive:!0})}canRead(e,t){return!!(e.access==="public"||e.owner===t||e.access==="shared"&&e.sharedWith?.includes(t))}canWrite(e,t){return e.owner===t}addEntry(e){let t=`${e.date}_${e.id}.md`,s=v(this.rawDir,t),n=["---",`id: ${e.id}`,`date: ${e.date}`,`agent: ${e.agentId}`,`source: ${e.source}`];if(e.sourceContext&&n.push(`context: ${e.sourceContext}`),e.meta)for(let[r,i]of Object.entries(e.meta))n.push(`${r}: ${JSON.stringify(i)}`);return n.push("---","",e.content),R(s,n.join(`
14
- `)),t}listEntries(e){if(!_(this.rawDir))return[];let t=z(this.rawDir).filter(n=>n.endsWith(".md")).sort(),s=[];for(let n of t){let r=oe(v(this.rawDir,n),"utf-8"),i=this.parseEntry(r,n);i&&(e?.agentId&&i.agentId!==e.agentId||e?.after&&i.date<e.after||e?.before&&i.date>e.before||s.push(i))}return s}parseEntry(e,t){let s=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let n=s[1],r=s[2].trim(),i=o=>n.match(new RegExp(`^${o}:\\s*(.+)$`,"m"))?.[1]?.trim()||"";return{id:i("id")||t.replace(".md",""),date:i("date"),agentId:i("agent"),source:i("source"),sourceContext:i("context")||void 0,content:r}}writeArticle(e,t,s,n){let r=this.readArticle(e);if(r&&!this.canWrite(r.meta,n))return this.log(`Permission denied: "${n}" cannot write "${e}" (owner: ${r.meta.owner})`),!1;let i=v(this.baseDir,e);K(je(i),{recursive:!0});let o=["---",`title: "${t.title}"`,`type: ${t.type}`,`owner: ${t.owner}`,`access: ${t.access}`];return t.sharedWith?.length&&o.push(`shared_with: [${t.sharedWith.map(a=>`"${a}"`).join(", ")}]`),o.push(`created: ${t.created}`,`last_updated: ${t.lastUpdated}`,`related: [${t.related.map(a=>`"${a}"`).join(", ")}]`,`sources: [${t.sources.map(a=>`"${a}"`).join(", ")}]`),t.tags?.length&&o.push(`tags: [${t.tags.map(a=>`"${a}"`).join(", ")}]`),o.push("---","",s),R(i,o.join(`
15
- `)),!0}readArticle(e){let t=v(this.baseDir,e);if(!_(t))return null;let s=oe(t,"utf-8");return this.parseArticle(s,e)}readArticleAs(e,t){let s=this.readArticle(e);return!s||!this.canRead(s.meta,t)?null:s}parseArticle(e,t){let s=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let n=s[1],r=s[2].trim(),i=a=>n.match(new RegExp(`^${a}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",o=a=>{let g=n.match(new RegExp(`^${a}:\\s*\\[(.*)\\]$`,"m"));return g?g[1].split(",").map(c=>c.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[]};return{meta:{title:i("title"),type:i("type"),owner:i("owner"),access:i("access")||"public",sharedWith:o("shared_with"),created:i("created"),lastUpdated:i("last_updated"),related:o("related"),sources:o("sources"),tags:o("tags")},content:r,path:t}}listArticles(e){let t=[];return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let n=E(this.baseDir,s);if(n.startsWith("raw/")||n.startsWith("_"))return;let r=this.readArticle(n);r&&this.canRead(r.meta,e)&&t.push(r)}),t}search(e,t,s=10){let n=e.toLowerCase(),r=[];return this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let o=E(this.baseDir,i);if(o.startsWith("raw/")||o.startsWith("_"))return;let a=this.readArticle(o);if(!a||!this.canRead(a.meta,t))return;let g=0,c=a.meta.title.toLowerCase(),h=a.content.toLowerCase();c.includes(n)&&(g+=10),a.meta.tags?.some(m=>m.toLowerCase().includes(n))&&(g+=5);let u=(h.match(new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"))||[]).length;g+=Math.min(u,5),g>0&&r.push({article:a,score:g})}),r.sort((i,o)=>o.score-i.score).slice(0,s).map(i=>i.article)}findRelevant(e,t,s=3){let n=new Set(["the","a","an","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","can","shall","to","of","in","for","on","with","at","by","from","as","into","about","through","and","but","or","not","no","if","then","so","what","how","when","where","who","which","that","this","it","i","you","we","they","he","she","me","my","your","our","their","please","just","also","very","much","some","any","all"]),r=e.toLowerCase().replace(/[^a-z0-9\s@_-]/g," ").split(/\s+/).filter(o=>o.length>2&&!n.has(o));if(r.length===0)return[];let i=new Map;for(let o of r){let a=this.search(o,t,5);for(let g of a){let c=i.get(g.path);c?c.score+=1:i.set(g.path,{article:g,score:1})}}return Array.from(i.values()).sort((o,a)=>a.score-o.score).slice(0,s).map(o=>o.article)}buildContext(e,t=4e3){if(e.length===0)return"";let s=["[Wiki Knowledge]"],n=0;for(let r of e){let i=`
16
- ## ${r.meta.title} (${r.meta.type})`,o=r.content.length>600?r.content.slice(0,600)+"...":r.content,a=i+`
17
- `+o;if(n+a.length>t)break;s.push(a),n+=a.length}return s.push(`
18
- [End Wiki Knowledge]`),s.join(`
19
- `)}rebuildIndex(){let e=[],t=new Map;this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let o=E(this.baseDir,i);if(o.startsWith("raw/")||o.startsWith("_"))return;let a=this.readArticle(o);if(!a)return;let g=a.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let h of g){let u=h.replace(/\[\[|\]\]/g,"");t.set(u,(t.get(u)||0)+1)}let c=[a.meta.title.toLowerCase()];a.meta.tags&&c.push(...a.meta.tags.map(h=>h.toLowerCase())),e.push({path:o,title:a.meta.title,type:a.meta.type,owner:a.meta.owner,access:a.meta.access,sharedWith:a.meta.sharedWith,aliases:c,backlinks:t.get(a.meta.title)||0})});let s={articles:e,lastRebuilt:new Date().toISOString()};R(v(this.baseDir,"_index.json"),JSON.stringify(s,null,2));let n=["# Wiki Index","",`Last rebuilt: ${s.lastRebuilt}`,""],r=new Map;for(let i of e){let o=r.get(i.type)||[];o.push(i),r.set(i.type,o)}for(let[i,o]of Array.from(r.entries()).sort()){n.push(`## ${i}`,"");for(let a of o.sort((g,c)=>g.title.localeCompare(c.title))){let g=a.access==="private"?" (private)":a.access==="shared"?" (shared)":"";n.push(`- [${a.title}](${a.path})${g} \u2014 owner: ${a.owner}`)}n.push("")}return R(v(this.baseDir,"WIKI.md"),n.join(`
20
- `)),this.log(`Index rebuilt: ${e.length} articles`),s}stats(){let e=0,t={},s={},n={};this.walkDir(this.baseDir,i=>{if(!i.endsWith(".md"))return;let o=E(this.baseDir,i);if(o.startsWith("raw/")||o.startsWith("_")||o==="WIKI.md")return;let a=this.readArticle(o);a&&(e++,t[a.meta.type]=(t[a.meta.type]||0)+1,s[a.meta.access]=(s[a.meta.access]||0)+1,n[a.meta.owner]=(n[a.meta.owner]||0)+1)});let r=_(this.rawDir)?z(this.rawDir).filter(i=>i.endsWith(".md")).length:0;return{totalArticles:e,totalEntries:r,articlesByType:t,articlesByAccess:s,articlesByOwner:n}}walkDir(e,t){if(_(e))for(let s of z(e)){let n=Ee(e,s);_e(n).isDirectory()?this.walkDir(n,t):t(n)}}};import{readFileSync as We,writeFileSync as Oe,mkdirSync as Le,existsSync as ae}from"fs";import{resolve as ce}from"path";var Be=12e3,le=30,j=class{sessionsDir;cache=new Map;constructor(e=process.cwd()){this.sessionsDir=ce(e,".agentx/sessions"),ae(this.sessionsDir)||Le(this.sessionsDir,{recursive:!0})}sessionKey(e,t,s){let n=new Date().toISOString().slice(0,10);return`${e}:${t}:${s}:${n}`}sessionFile(e){let t=e.replace(/[^a-zA-Z0-9_:-]/g,"_");return ce(this.sessionsDir,`${t}.json`)}getSession(e,t,s){let n=this.sessionKey(e,t,s);if(this.cache.has(n))return this.cache.get(n);let r=this.sessionFile(n);if(ae(r))try{let a=JSON.parse(We(r,"utf-8"));return this.cache.set(n,a),a}catch{}let i=new Date().toISOString().slice(0,10),o={id:n,agentId:e,channel:t,chatId:s,day:i,messages:[],createdAt:new Date().toISOString(),updatedAt:new Date().toISOString()};return this.cache.set(n,o),this.save(o),o}addUserMessage(e,t,s,n,r){let i=this.getSession(e,t,s);i.messages.push({role:"user",name:n,content:r,timestamp:new Date().toISOString()}),this.trim(i),i.updatedAt=new Date().toISOString(),this.save(i)}addAgentMessage(e,t,s,n){let r=this.getSession(e,t,s);r.messages.push({role:"agent",name:e,content:n,timestamp:new Date().toISOString()}),this.trim(r),r.updatedAt=new Date().toISOString(),this.save(r)}getClaudeSessionId(e,t,s){return this.getSession(e,t,s).claudeSessionId}setClaudeSessionId(e,t,s,n){let r=this.getSession(e,t,s);r.claudeSessionId=n,r.updatedAt=new Date().toISOString(),this.save(r)}buildHistoryContext(e,t,s){let n=this.getSession(e,t,s);if(n.messages.length===0)return"";let r=[`[Conversation history for today (${n.day})]`];for(let i of n.messages){let o=i.timestamp.slice(11,16);i.role==="user"?r.push(`[${o}] ${i.name||"User"}: ${i.content}`):r.push(`[${o}] ${i.name||"Agent"}: ${i.content}`)}return r.push("[End of history \u2014 respond to the latest message above]"),r.push(""),r.join(`
21
- `)}trim(e){e.messages.length>le&&(e.messages=e.messages.slice(-le));let t=e.messages.reduce((s,n)=>s+n.content.length,0);for(;t>Be&&e.messages.length>2;){let s=e.messages.shift();t-=s.content.length}}save(e){try{let t=this.sessionFile(e.id);Oe(t,JSON.stringify(e,null,2))}catch{}}};var W=class{agents=new Map;config;providers={};sessions;wiki;log;constructor(e,t=console.error.bind(console,"[agents]")){this.log=t,this.config=e,this.providers=e.providers,this.sessions=new j,this.wiki=new S;for(let[s,n]of Object.entries(e.agents))this.agents.set(s,{id:s,def:n,activeTasks:0,totalTasks:0,errors:0})}getAgent(e){return this.agents.get(e)?.def}findByMention(e){let t=e.toLowerCase(),s,n=0;for(let[r,i]of this.agents)for(let o of i.def.mentions){let a=o.toLowerCase();t.includes(a)&&a.length>n&&(s=r,n=a.length)}return s}findAllMentioned(e){let t=e.toLowerCase(),s=[];for(let[n,r]of this.agents)for(let i of r.def.mentions)if(t.includes(i.toLowerCase())){s.push(n);break}return s}getChannelHandle(e,t){let s=this.agents.get(e)?.def;if(s)return t==="telegram"?s.mentions.find(n=>n.startsWith("@")):s.mentions[0]}enrichTaskContext(e){let t=e.context?.channel,s=[];for(let[r,i]of this.agents)r!==e.agentId&&s.push({id:r,name:i.def.name,handle:this.getChannelHandle(r,t),role:i.def.systemPrompt?.split(`
22
- `)[0]?.slice(0,100)});let n=this.getChannelHandle(e.agentId,t);return{...e,context:{...e.context,myHandle:n,peers:s}}}async execute(e,t){let s=this.agents.get(e.agentId);if(!s)return{content:"",error:`Unknown agent: ${e.agentId}`};if(s.activeTasks>=s.def.maxConcurrent)return{content:"",error:`Agent "${e.agentId}" is busy (${s.activeTasks}/${s.def.maxConcurrent} tasks)`};s.activeTasks++,s.totalTasks++,s.lastActive=new Date,this.log(`[${e.agentId}] executing task (${s.activeTasks}/${s.def.maxConcurrent})`);let n=e.context?.channel||"api",r=e.context?.group||e.context?.sender||"default",i=e.context?.sender||"User";this.sessions.addUserMessage(e.agentId,n,r,i,e.message),e=this.enrichTaskContext(e);let o=this.wiki.findRelevant(e.message,e.agentId,3),a=this.wiki.buildContext(o),g=s.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,n,r):void 0,c=g?void 0:this.sessions.buildHistoryContext(e.agentId,n,r),h=[a,c].filter(Boolean).join(`
23
-
24
- `)||void 0;try{let u=await ie(s.def,e,this.providers,t,h,g);if(u.error)s.errors++,this.log(`[${e.agentId}] error: ${u.error}`);else{if(this.sessions.addAgentMessage(e.agentId,n,r,u.content),u.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,n,r,u.claudeSessionId),u.content.length>50)try{let m=`${e.agentId}-${Date.now().toString(36)}`;this.wiki.addEntry({id:m,date:new Date().toISOString().slice(0,10),agentId:e.agentId,source:n,sourceContext:e.context?.group||e.context?.sender,content:`User: ${e.message}
25
-
26
- Agent: ${u.content}`})}catch{}this.log(`[${e.agentId}] completed in ${u.duration}ms`+(u.tokensUsed?` (${u.tokensUsed} tokens)`:""))}return u}catch(u){return s.errors++,this.log(`[${e.agentId}] unexpected error: ${u.message}`),{content:"",error:u.message}}finally{s.activeTasks--}}list(){return Array.from(this.agents.values()).map(e=>({id:e.id,name:e.def.name,tier:e.def.tier,workspace:e.def.workspace,active:e.activeTasks,total:e.totalTasks,errors:e.errors,lastActive:e.lastActive}))}};var O=class{registry;config;channels=new Map;hooks;mesh;log;constructor(e,t,s,n=console.error.bind(console,"[router]")){this.registry=e,this.config=t,this.hooks=s,this.log=n}setMesh(e){this.mesh=e}addChannel(e){this.channels.set(e.name,e),e.onMessage(t=>this.handleMessage(e,t))}async startAll(){for(let[e,t]of this.channels)this.log(`Starting channel: ${e}`),await t.start()}async stopAll(){for(let[e,t]of this.channels)this.log(`Stopping channel: ${e}`),await t.stop()}async handleMessage(e,t){if(this.hooks?.has("pre:channel-message")){let p=await this.hooks.execute("pre:channel-message",{event:"pre:channel-message",channel:t.channel,sender:t.sender.name,text:t.text,group:t.group?.name});if(p.blocked){this.log(`Message blocked by hook: ${p.message}`);return}p.modified?.text&&(t={...t,text:p.modified.text})}let s=this.resolveAgent(t);if(!s)return;if(t.group&&t.channel==="telegram"){let p=this.getAccountForAgent(s);if(p&&p!==t.accountId)return}let n=t.group?.id||t.sender.id,i=this.registry.getAgent(s)?.name||s,o=this.getAccountForAgent(s)||t.accountId;this.log(`Routing [${t.channel}/${t.sender.name}] -> "${i}": ${t.text.slice(0,80)}`),this.adapterReact(e,n,t.id,"\u{1F440}",o);let a=this.startTypingLoop(e,n,o),g=typeof e.editMessage=="function",c,h=0,u=g?async(p,w)=>{let k=Date.now();if(!(k-h<1500))if(c)try{await this.adapterEdit(e,n,c,w,void 0,o),h=k}catch{}else{let x=w.length>20?w:`_${i} is writing..._
27
-
28
- ${w}`;try{c=await this.adapterSend(e,{channel:t.channel,chatId:n,text:x,replyTo:t.id,accountId:o}),h=k}catch{}}}:void 0,m=await this.registry.execute({message:t.text,agentId:s,context:{channel:t.channel,sender:t.sender.name,group:t.group?.name}},u);if(clearInterval(a),m.error){this.log(`Agent error: ${m.error}`);let p=`Error: ${m.error}`;c?await this.adapterEdit(e,n,c,p,"plain",o):await this.adapterSend(e,{channel:t.channel,chatId:n,text:p,replyTo:t.id,parseMode:"plain",accountId:o});return}let f=m.content;if(this.hooks?.has("post:channel-message")){let p=await this.hooks.execute("post:channel-message",{event:"post:channel-message",channel:t.channel,sender:t.sender.name,response:f,agentId:s});if(p.blocked){this.log(`Response blocked by hook: ${p.message}`);return}p.modified?.response&&(f=p.modified.response)}let y;f&&(c?(await this.adapterEdit(e,n,c,f,void 0,o),y=c):y=await this.adapterSend(e,{channel:t.channel,chatId:n,text:f,replyTo:t.id,accountId:o})),f&&y&&this.handleBotToBotMentions(e,t,s,f,y).catch(p=>{this.log(`Bot-to-bot error: ${p.message}`)})}async handleBotToBotMentions(e,t,s,n,r){for(let[i,o]of Object.entries(this.config.agents)){if(i===s||!o.mentions.some(h=>n.toLowerCase().includes(h.toLowerCase())))continue;this.log(`Bot-to-bot: "${s}" mentioned "${i}" \u2014 routing`);let g=t.group?.id||t.sender.id,c=this.getAccountForAgent(i);try{this.adapterReact(e,g,r,"\u{1F440}",c);let h=this.startTypingLoop(e,g,c),u=await this.registry.execute({message:n,agentId:i,context:{channel:t.channel,sender:`agent:${s}`,group:t.group?.name}});clearInterval(h),u.content&&!u.error?await this.adapterSend(e,{channel:t.channel,chatId:g,text:u.content,accountId:c}):u.error&&this.log(`Bot-to-bot "${i}" error: ${u.error}`)}catch(h){this.log(`Bot-to-bot "${i}" failed: ${h.message}`)}break}}async adapterSend(e,t){return e.name==="telegram"&&t.accountId?e.send({...t,parseMode:t.parseMode,accountId:t.accountId}):e.send(t)||""}async adapterEdit(e,t,s,n,r,i){return e.name==="telegram"&&i?e.editMessage(t,s,n,r,i):e.editMessage?.(t,s,n,r)??!1}adapterReact(e,t,s,n,r){e.name==="telegram"&&r?e.react(t,s,n,r):e.react?.(t,s,n)}startTypingLoop(e,t,s){let n=()=>{e.name==="telegram"&&s?e.sendTyping(t,s):e.sendTyping?.(t)};return n(),setInterval(n,4e3)}async handleViaMesh(e,t){if(!this.mesh)return!1;let s=t.text.toLowerCase(),n=this.mesh.directory();for(let r of n)if(r.healthy){for(let i of r.skills)if(s.includes(i.id.toLowerCase())||s.includes(i.name.toLowerCase())){this.log(`Mesh routing [${t.channel}/${t.sender.name}] -> peer "${r.peer}" agent "${i.id}"`);let o=t.group?.id||t.sender.id,a=t.accountId;this.adapterReact(e,o,t.id,"\u{1F440}",a);let g=this.startTypingLoop(e,o,a);try{let c=await this.mesh.sendTask(r.peer,t.text,i.id);if(clearInterval(g),c){let h=`**${i.name}** _(${r.peer})_:
29
-
30
- `;await this.adapterSend(e,{channel:t.channel,chatId:o,text:h+c,replyTo:t.id,accountId:a})}return!0}catch(c){return clearInterval(g),this.log(`Mesh routing error: ${c.message}`),await this.adapterSend(e,{channel:t.channel,chatId:o,text:`Error from ${r.peer}/${i.name}: ${c.message}`,replyTo:t.id,parseMode:"plain",accountId:a}),!0}}}return!1}getAccountForAgent(e){for(let[t,s]of Object.entries(this.config.channels.telegram.accounts))if(s.agentBinding===e)return t}resolveAgent(e){if(e.resolvedAgent)return e.resolvedAgent;if(!e.group)return e.channel==="telegram"?this.config.channels.telegram.accounts[e.accountId]?.agentBinding:e.channel==="whatsapp"?this.config.channels.whatsapp.defaultAgent:void 0;if(e.channel==="telegram"&&this.config.channels.telegram.policy.group==="mention-required"){let n=this.registry.findByMention(e.text);return n||void 0}let t=this.registry.findByMention(e.text);return t||(e.channel==="telegram"?this.config.channels.telegram.accounts[e.accountId]?.agentBinding:this.config.channels.whatsapp.defaultAgent)}};var Ne=/([_*\[\]()~`>#+=|{}.!\-\\])/g;function A(l){return l.replace(Ne,"\\$1")}function B(l){return l.replace(/([`\\])/g,"\\$1")}function V(l){let e=l.split(`
31
- `),t=[],s=!1,n="",r=[];for(let i=0;i<e.length;i++){let o=e[i];if(o.trimStart().startsWith("```"))if(s){s=!1;let h=r.join(`
32
- `);n?t.push("```"+B(n)):t.push("```"),t.push(B(h)),t.push("```");continue}else{s=!0,n=o.trimStart().slice(3).trim(),r=[];continue}if(s){r.push(o);continue}let a=o.match(/^(#{1,6})\s+(.+)$/);if(a){t.push(""),t.push("*"+ge(a[2])+"*");continue}if(/^[-*_]{3,}\s*$/.test(o.trim())){t.push("\u2014\u2014\u2014");continue}if(o.trimStart().startsWith("> ")){let h=o.replace(/^>\s*/,"");t.push(">"+L(h));continue}let g=o.match(/^(\s*)[-*+]\s+(.+)$/);if(g){let h=g[1].length>0?" ":"";t.push(h+"\u2022 "+L(g[2]));continue}let c=o.match(/^(\s*)\d+[.)]\s+(.+)$/);if(c){let h=c[1].length>0?" ":"",u=o.match(/^(\s*)(\d+)/)?.[2]||"1";t.push(h+A(u)+"\\. "+L(c[2]));continue}if(!o.trim()){t.push("");continue}t.push(L(o))}return s&&(t.push("```"),t.push(B(r.join(`
33
- `))),t.push("```")),t.join(`
34
- `).trim()}function L(l){let e=[],t=l.replace(/`([^`]+)`/g,(r,i)=>{let o=e.length;return e.push("`"+B(i)+"`"),`\0CODE${o}\0`}),s=[];t=t.replace(/@(\w{5,})/g,(r,i)=>{let o=s.length;return s.push("@"+A(i)),`\0MENTION${o}\0`});let n=[];return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,i,o)=>{let a=n.length;return n.push("["+ge(i)+"]("+o.replace(/([)\\])/g,"\\$1")+")"),`\0LINK${a}\0`}),t=t.replace(/\*\*\*(.+?)\*\*\*/g,(r,i)=>"*_"+A(i)+"_*"),t=t.replace(/\*\*(.+?)\*\*/g,(r,i)=>"*"+A(i)+"*"),t=t.replace(/(?<!\*)\*([^*]+?)\*(?!\*)/g,(r,i)=>"_"+A(i)+"_"),t=t.replace(/(?<!_)_([^_]+?)_(?!_)/g,(r,i)=>"_"+A(i)+"_"),t=t.replace(/~~(.+?)~~/g,(r,i)=>"~"+A(i)+"~"),t=Je(t),t=t.replace(/\x00CODE(\d+)\x00/g,(r,i)=>e[parseInt(i)]),t=t.replace(/\x00MENTION(\d+)\x00/g,(r,i)=>s[parseInt(i)]),t=t.replace(/\x00LINK(\d+)\x00/g,(r,i)=>n[parseInt(i)]),t}function ge(l){return A(l)}function Je(l){return l.split(/(\*[^*]+\*|_[^_]+_|~[^~]+~|\x00\w+\d+\x00)/g).map(t=>/^\*[^*]+\*$/.test(t)||/^_[^_]+_$/.test(t)||/^~[^~]+~$/.test(t)||/^\x00/.test(t)?t:A(t)).join("")}var N=class{name="telegram";accounts;offsets=new Map;handler;polling=!1;log;constructor(e,t=console.error.bind(console,"[telegram]")){this.accounts=new Map(Object.entries(e)),this.log=t}onMessage(e){this.handler=e}async start(){this.polling=!0;let e=Array.from(this.accounts.entries());this.log(`${e.length} Telegram account(s) to start`);for(let t=0;t<e.length;t++){let[s,n]=e[t];this.log(`Starting polling for account "${s}" (${t+1}/${e.length})`);try{let r=await this.apiCall(n.token,"getMe");this.log(`Bot @${r.result?.username} ready (account: ${s})`),this.pollLoop(s,n)}catch(r){this.log(`Failed to verify bot for account "${s}": ${r.message}`)}t<e.length-1&&await new Promise(r=>setTimeout(r,300))}this.log(`All ${e.length} Telegram account(s) started`)}async stop(){this.polling=!1}getTokenForAccount(e){return this.accounts.get(e)?.token}getDefaultToken(){let[,e]=Array.from(this.accounts.entries())[0];return e?.token}resolveToken(e,t){if(t){let s=this.getTokenForAccount(t);if(s)return s}return this.chatAccountMap.get(e)?this.getTokenForAccount(this.chatAccountMap.get(e)):this.getDefaultToken()}chatAccountMap=new Map;async send(e){let t=this.resolveToken(e.chatId,e.accountId);if(!t)return this.log("No telegram token found for sending"),"";let s=4096,n=e.text.length>s?e.text.slice(0,s-3)+"...":e.text,r=e.parseMode==="markdown"||e.parseMode===void 0?V(n):n,i={chat_id:e.chatId,text:r,parse_mode:"MarkdownV2"};e.replyTo&&(i.reply_to_message_id=parseInt(e.replyTo,10)),e.parseMode==="html"?(i.parse_mode="HTML",i.text=n):e.parseMode==="plain"&&(delete i.parse_mode,i.text=n);try{let o=await this.apiCall(t,"sendMessage",i);return String(o.result?.message_id||"")}catch(o){if(i.parse_mode){delete i.parse_mode,i.text=n;let a=await this.apiCall(t,"sendMessage",i);return String(a.result?.message_id||"")}throw o}}async editMessage(e,t,s,n,r){let i=this.resolveToken(e,r);if(!i)return!1;let o=4096,a=s.length>o?s.slice(0,o-3)+"...":s,g=n!=="html"&&n!=="plain"?V(a):a,c={chat_id:e,message_id:parseInt(t,10),text:g,parse_mode:"MarkdownV2"};n==="html"?(c.parse_mode="HTML",c.text=a):n==="plain"&&(delete c.parse_mode,c.text=a);try{return await this.apiCall(i,"editMessageText",c),!0}catch(h){if(h.message?.includes("message is not modified"))return!0;if(c.parse_mode){delete c.parse_mode,c.text=a;try{return await this.apiCall(i,"editMessageText",c),!0}catch{return!1}}return!1}}async react(e,t,s="\u{1F440}",n){let r=this.resolveToken(e,n);if(r)try{await this.apiCall(r,"setMessageReaction",{chat_id:e,message_id:parseInt(t,10),reaction:[{type:"emoji",emoji:s}]})}catch{}}async sendTyping(e,t){let s=this.resolveToken(e,t);if(s)try{await this.apiCall(s,"sendChatAction",{chat_id:e,action:"typing"})}catch{}}async pollLoop(e,t){for(;this.polling;)try{let s=this.offsets.get(e)||0,r=(await this.apiCall(t.token,"getUpdates",{offset:s||void 0,timeout:30,allowed_updates:["message"]})).result||[];for(let i of r)if(this.offsets.set(e,i.update_id+1),i.message?.text&&this.handler){let o=i.message,a={id:String(o.message_id),channel:"telegram",accountId:e,sender:{id:String(o.from.id),name:[o.from.first_name,o.from.last_name].filter(Boolean).join(" "),username:o.from.username},group:o.chat.type!=="private"?{id:String(o.chat.id),name:o.chat.title||""}:void 0,text:o.text,replyTo:o.reply_to_message?String(o.reply_to_message.message_id):void 0,timestamp:new Date(o.date*1e3),raw:i};this.chatAccountMap.set(String(o.chat.id),e),this.handler(a).catch(g=>{this.log(`Error handling message: ${g.message}`)})}}catch(s){this.log(`Poll error (${e}): ${s.message}`),await new Promise(n=>setTimeout(n,5e3))}}async apiCall(e,t,s){let n=`https://api.telegram.org/bot${e}/${t}`,r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:s?JSON.stringify(s):void 0});if(!r.ok){let i=await r.text();throw new Error(`Telegram API error: ${r.status} ${i}`)}return r.json()}};import{mkdirSync as He}from"fs";import{resolve as Fe}from"path";var J=class{name="whatsapp";sessionDir;defaultAgent;allowFrom;routes;handler;sock=null;sentMessageIds=new Set;log;constructor(e,t=console.error.bind(console,"[whatsapp]")){this.sessionDir=Fe(e.sessionDir),this.defaultAgent=e.defaultAgent,this.allowFrom=e.allowFrom,this.routes=e.routes||[],this.log=t}resolveAgent(e,t,s){for(let n of this.routes){if(n.contact){let r=n.contact.replace(/\+/g,"");if(e.includes(r)||r.includes(e))return n.agent}if(n.group&&(t||s)){let r=n.group.toLowerCase();if(t?.toLowerCase().includes(r)||s?.toLowerCase().includes(r))return n.agent}}return this.defaultAgent}onMessage(e){this.handler=e}async start(){let e,t,s,n;try{n=await import("@whiskeysockets/baileys"),e=n.default||n.makeWASocket,t=n.useMultiFileAuthState,s=n.DisconnectReason}catch{this.log("WhatsApp requires @whiskeysockets/baileys. Install with:"),this.log(" npm install @whiskeysockets/baileys");return}He(this.sessionDir,{recursive:!0});let{state:r,saveCreds:i}=await t(this.sessionDir),o;try{let{version:g}=await n.fetchLatestBaileysVersion();o=g,this.log(`WhatsApp Web version: ${g.join(".")}`)}catch{this.log("Could not fetch WA version, using default")}let a={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:(...g)=>this.log("WA error:",...g),child:()=>a};this.sock=e({auth:{creds:r.creds,keys:n.makeCacheableSignalKeyStore?n.makeCacheableSignalKeyStore(r.keys,a):r.keys},...o?{version:o}:{},logger:a,printQRInTerminal:!1,browser:["agentx","server","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1}),this.sock.ev.on("creds.update",i),this.sock.ev.on("messaging-history.set",g=>{this.log(`WA history sync: ${g.messages?.length||0} messages, ${g.isLatest?"latest":"partial"}`)}),this.sock.ev.on("connection.update",async g=>{let{connection:c,lastDisconnect:h,qr:u}=g;if(u){this.log("Scan QR code with WhatsApp to connect:");try{let{default:m}=await import("qrcode-terminal");m.generate(u,{small:!0})}catch{this.log(`QR: ${u}`),this.log("Install qrcode-terminal for visual QR: npm install qrcode-terminal")}}if(c==="close"){let m=h?.error?.output?.statusCode;this.log(`WhatsApp connection closed (status: ${m})`),m===515?(this.log("Stream error, reconnecting in 5s..."),setTimeout(()=>this.start(),5e3)):m===s?.loggedOut||m===401?this.log("Logged out. Delete session dir and restart to re-scan QR."):m!==void 0&&(this.log("Reconnecting in 3s..."),setTimeout(()=>this.start(),3e3))}c==="open"&&this.log("WhatsApp connected")}),this.sock.ev.on("messages.upsert",async g=>{if(this.log(`WA messages.upsert: ${g.messages?.length||0} messages, type: ${g.type}`),!!this.handler)for(let c of g.messages||[]){let h=(c.key.remoteJid||"").replace(/@.*/,"").slice(-6),u=!!(c.message?.conversation||c.message?.extendedTextMessage?.text);if(this.log(`WA msg: from=${h} fromMe=${c.key.fromMe} hasText=${u} type=${Object.keys(c.message||{}).join(",")}`),c.key.remoteJid==="status@broadcast")continue;if(c.key.id&&this.sentMessageIds.has(c.key.id)){this.sentMessageIds.delete(c.key.id);continue}if(c.key.fromMe){let b=this.sock?.user,U=c.key.remoteJid||"",C=b?.id?.replace(/:.*/,"")||"",fe=b?.lid?.replace(/:.*/,"")||"",Y=U.replace(/:.*/,"").replace(/@.*/,"");if(!(Y===C||Y===fe))continue}let m=c.message?.conversation||c.message?.extendedTextMessage?.text||c.message?.imageMessage?.caption||c.message?.videoMessage?.caption||"";if(!m)continue;let f=c.key.remoteJid||"",y=f.endsWith("@g.us"),p=f.replace(/@.*$/,""),k=(y?c.key.participant||"":f).replace(/@.*$/,"");if(this.allowFrom?.length&&!c.key.fromMe&&!this.allowFrom.some(U=>{let C=U.replace(/\+/g,"");return k.includes(C)||p.includes(C)}))continue;let x=c.key.fromMe?"me":c.pushName||k,$;if(y&&this.sock)try{$=(await this.sock.groupMetadata(f)).subject}catch{}let Q=this.resolveAgent(k,$,y?f:void 0);if(!Q){this.log(`No route for ${y?`group ${$||f}`:k}, skipping`);continue}let me={id:c.key.id||String(Date.now()),channel:"whatsapp",accountId:"default",sender:{id:c.key.fromMe?(this.sock?.user?.id?.replace(/:.*/,"")||k)+"@s.whatsapp.net":k,name:x,username:k},group:y?{id:f,name:$||f}:void 0,text:m,replyTo:c.message?.extendedTextMessage?.contextInfo?.stanzaId,timestamp:new Date((c.messageTimestamp||0)*1e3),raw:c,resolvedAgent:Q};this.handler(me).catch(b=>{this.log(`Error handling message: ${b.message}`)})}})}async stop(){this.sock&&(this.sock.end(),this.sock=null)}async send(e){if(!this.sock)return this.log("WhatsApp not connected"),"";let t=e.chatId.includes("@")?e.chatId:`${e.chatId}@s.whatsapp.net`;try{let n=(await this.sock.sendMessage(t,{text:e.text}))?.key?.id||"";return n&&this.sentMessageIds.add(n),n}catch(s){return this.log(`Send error: ${s.message}`),""}}async editMessage(e,t,s){if(!this.sock)return!1;let n=e.includes("@")?e:`${e}@s.whatsapp.net`;try{return await this.sock.sendMessage(n,{text:s,edit:{remoteJid:n,id:t,fromMe:!0}}),!0}catch{return!1}}async sendTyping(e){if(!this.sock)return;let t=e.includes("@")?e:`${e}@s.whatsapp.net`;try{await this.sock.sendPresenceUpdate("composing",t)}catch{}}async react(e,t,s="\u{1F440}"){if(!this.sock)return;let n=e.includes("@")?e:`${e}@s.whatsapp.net`;try{await this.sock.sendMessage(n,{react:{text:s,key:{remoteJid:n,id:t}}})}catch{}}};import{writeFileSync as Ue,mkdirSync as de,existsSync as he}from"fs";import{resolve as q}from"path";function T(l,e,t){let s=[];for(let n of l.split(","))if(n==="*")for(let r=e;r<=t;r++)s.push(r);else if(n.includes("/")){let[r,i]=n.split("/"),o=parseInt(i,10),a=r==="*"?e:parseInt(r,10);for(let g=a;g<=t;g+=o)s.push(g)}else if(n.includes("-")){let[r,i]=n.split("-").map(Number);for(let o=r;o<=i;o++)s.push(o)}else s.push(parseInt(n,10));return[...new Set(s)].sort((n,r)=>n-r)}function Ge(l,e,t){let s=l.trim().split(/\s+/);if(s.length!==5)throw new Error(`Invalid cron: ${l}`);let n=T(s[0],0,59),r=T(s[1],0,23),i=T(s[2],1,31),o=T(s[3],1,12),a=T(s[4],0,6),g=new Intl.DateTimeFormat("en-US",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}),c=new Date(e.getTime()+6e4);c.setSeconds(0,0);let h=new Date(c.getTime()+366*24*60*60*1e3);for(;c<h;){let u=g.formatToParts(c),m=x=>parseInt(u.find($=>$.type===x)?.value||"0",10),f=m("minute"),y=m("hour"),p=m("day"),w=m("month"),k=c.getDay();if(n.includes(f)&&r.includes(y)&&i.includes(p)&&o.includes(w)&&a.includes(k))return c;c.setTime(c.getTime()+6e4)}throw new Error(`No next run found for cron "${l}" within 1 year`)}var H=class{jobs=new Map;timers=new Map;registry;hooks;runsDir;running=!1;log;constructor(e,t,s,n=console.error.bind(console,"[cron]")){this.registry=t,this.hooks=s,this.log=n,this.runsDir=q(process.cwd(),".agentx/cron/runs");for(let[r,i]of Object.entries(e.crons))this.jobs.set(r,{id:r,enabled:i.enabled,schedule:i.schedule,timezone:i.timezone,agent:i.agent,prompt:i.prompt,timeout:i.timeout,model:i.model,onError:i.onError,consecutiveErrors:0,totalRuns:0})}async start(){this.running=!0,he(this.runsDir)||de(this.runsDir,{recursive:!0});for(let[e,t]of this.jobs){if(!t.enabled){this.log(`Job "${e}" is disabled, skipping`);continue}this.scheduleNext(e)}this.log(`${this.jobs.size} cron job(s) loaded, ${Array.from(this.jobs.values()).filter(e=>e.enabled).length} enabled`)}async stop(){this.running=!1;for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}scheduleNext(e){let t=this.jobs.get(e);if(!(!t||!t.enabled||!this.running))try{let s=Ge(t.schedule,new Date,t.timezone);t.nextRun=s;let n=s.getTime()-Date.now();this.log(`Job "${e}" next run: ${s.toISOString()} (in ${Math.round(n/1e3)}s)`);let r=setTimeout(()=>this.executeJob(e),n);this.timers.set(e,r)}catch(s){this.log(`Failed to schedule "${e}": ${s.message}`)}}async executeJob(e){let t=this.jobs.get(e);if(!t||!this.running)return;if(this.hooks?.has("pre:cron-run")){let n=await this.hooks.execute("pre:cron-run",{event:"pre:cron-run",jobId:e,agent:t.agent,prompt:t.prompt});if(n.blocked){this.log(`Job "${e}" blocked by hook: ${n.message}`),this.scheduleNext(e);return}}this.log(`Executing job "${e}" -> agent "${t.agent}"`);let s=new Date;t.lastRun=s,t.totalRuns++;try{let n=await this.registry.execute({message:t.prompt,agentId:t.agent,context:{channel:"cron"}}),r={jobId:e,startedAt:s,completedAt:new Date,success:!n.error,response:n.content,error:n.error,duration:n.duration||Date.now()-s.getTime()};n.error?(t.consecutiveErrors++,this.log(`Job "${e}" failed (${t.consecutiveErrors} consecutive): ${n.error}`),t.onError==="disable"&&t.consecutiveErrors>=3&&(t.enabled=!1,this.log(`Job "${e}" disabled after ${t.consecutiveErrors} consecutive errors`))):(t.consecutiveErrors=0,this.log(`Job "${e}" completed in ${r.duration}ms`)),this.logRun(r),this.hooks?.has("post:cron-run")&&await this.hooks.execute("post:cron-run",{event:"post:cron-run",jobId:e,success:r.success,duration:r.duration,error:r.error?new Error(r.error):void 0})}catch(n){t.consecutiveErrors++,this.log(`Job "${e}" threw: ${n.message}`)}this.scheduleNext(e)}logRun(e){try{let t=q(this.runsDir,e.jobId);he(t)||de(t,{recursive:!0});let s=`${e.startedAt.toISOString().replace(/[:.]/g,"-")}.json`;Ue(q(t,s),JSON.stringify(e,null,2))}catch{}}list(){return Array.from(this.jobs.values())}};import{createServer as Ke}from"http";var F=class{name="discord";token;agentBinding;handler;client=null;log;constructor(e,t=console.error.bind(console,"[discord]")){this.token=e.token,this.agentBinding=e.agentBinding,this.log=t}onMessage(e){this.handler=e}async start(){let e;try{e=await import("discord.js")}catch{this.log("Discord requires discord.js. Install with:"),this.log(" npm install discord.js");return}let{Client:t,GatewayIntentBits:s}=e;this.client=new t({intents:[s.Guilds,s.GuildMessages,s.MessageContent,s.DirectMessages]}),this.client.on("ready",()=>{this.log(`Discord connected as ${this.client.user?.tag}`)}),this.client.on("messageCreate",async n=>{if(!this.handler||n.author.bot)return;let r=n.mentions.users.has(this.client.user?.id),i=!n.guild;if(!r&&!i)return;let o=n.content;if(this.client.user&&(o=o.replace(new RegExp(`<@!?${this.client.user.id}>`,"g"),"").trim()),!o)return;let a={id:n.id,channel:"discord",accountId:"default",sender:{id:n.author.id,name:n.author.displayName||n.author.username,username:n.author.username},group:n.guild?{id:n.channelId,name:n.channel?.name||n.channelId}:void 0,text:o,replyTo:n.reference?.messageId,timestamp:n.createdAt,raw:n};this.handler(a).catch(g=>{this.log(`Error handling message: ${g.message}`)})});try{await this.client.login(this.token)}catch(n){this.log(`Discord login failed: ${n.message}`)}}async stop(){this.client&&(this.client.destroy(),this.client=null)}async send(e){if(!this.client)return"";try{let t=await this.client.channels.fetch(e.chatId);return t?.isTextBased()?(await t.send({content:e.text,...e.replyTo?{reply:{messageReference:e.replyTo}}:{}})).id:""}catch(t){return this.log(`Send error: ${t.message}`),""}}async editMessage(e,t,s){if(!this.client)return!1;try{let n=await this.client.channels.fetch(e);return n?.isTextBased()?(await(await n.messages.fetch(t)).edit(s),!0):!1}catch{return!1}}async sendTyping(e){if(this.client)try{let t=await this.client.channels.fetch(e);t?.isTextBased()&&await t.sendTyping()}catch{}}async react(e,t,s="\u{1F440}"){if(this.client)try{let n=await this.client.channels.fetch(e);if(!n?.isTextBased())return;await(await n.messages.fetch(t)).react(s)}catch{}}};var ue=class{config;registry;router;cron;mesh;hooks;httpServer;log;constructor(e){this.log=console.error.bind(console,"[agentx]"),this.log("Loading configuration..."),this.config=te(e);let t=se(this.config);for(let s of t)this.log(` \u26A0 ${s}`);this.hooks=new X,Z(process.cwd(),this.hooks),this.registry=new W(this.config,this.log),this.router=new O(this.registry,this.config,this.hooks,this.log),this.cron=new H(this.config,this.registry,this.hooks,this.log),this.config.mesh.enabled&&(this.mesh=new D(this.config,this.log),this.router.setMesh(this.mesh))}async start(){this.log(""),this.log(" \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),this.log(" \u2502 agentx daemon \u2502"),this.log(" \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),this.log(""),this.log(` Node: ${this.config.node.name} (${this.config.node.id})`),this.log(` Bind: ${this.config.node.bind}`),this.log(""),await this.startChannels(),await this.cron.start(),this.mesh&&await this.mesh.start(),await this.startHttpApi(),this.log(""),this.log(" Agents:");for(let t of this.registry.list())this.log(` ${t.id} (${t.tier}) \u2192 ${t.workspace}`);let e=this.cron.list();if(e.length){this.log(""),this.log(" Cron Jobs:");for(let t of e){let s=t.enabled?"enabled":"disabled";this.log(` ${t.id} [${s}] \u2192 ${t.agent} (${t.schedule})`)}}if(this.mesh){this.log(""),this.log(" Mesh Peers:");for(let t of this.mesh.directory()){let s=t.healthy?"\u2713":"\u2717";this.log(` ${s} ${t.peer} (${t.peerUrl})`)}}this.log(""),this.log(" Ready."),this.log(""),process.on("SIGINT",()=>this.stop()),process.on("SIGTERM",()=>this.stop())}async stop(){this.log("Shutting down..."),await this.router.stopAll(),await this.cron.stop(),this.mesh&&await this.mesh.stop(),this.httpServer&&this.httpServer.close(),this.log("Goodbye."),process.exit(0)}async startChannels(){if(this.config.channels.telegram.enabled){let e=this.config.channels.telegram.accounts;if(Object.keys(e).length>0){let t=new N(e,this.log);this.router.addChannel(t),this.log(" Telegram: enabled")}}if(this.config.channels.whatsapp.enabled){let e=new J({sessionDir:this.config.channels.whatsapp.sessionDir,defaultAgent:this.config.channels.whatsapp.defaultAgent,allowFrom:this.config.channels.whatsapp.allowFrom,routes:this.config.channels.whatsapp.routes},this.log);this.router.addChannel(e),this.log(` WhatsApp: enabled (${this.config.channels.whatsapp.routes.length} routes)`)}if(this.config.channels.discord?.enabled&&this.config.channels.discord.token){let e=new F({token:this.config.channels.discord.token,agentBinding:this.config.channels.discord.agentBinding},this.log);this.router.addChannel(e),this.log(" Discord: enabled")}await this.router.startAll()}async startHttpApi(){let[e,t]=this.config.node.bind.split(":"),s=parseInt(t||"18800",10);this.httpServer=Ke(async(n,r)=>{if(r.setHeader("Access-Control-Allow-Origin","*"),r.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),r.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),n.method==="OPTIONS"){r.writeHead(204),r.end();return}await this.handleHttp(n,r)}),this.httpServer.on("error",n=>{n.code==="EADDRINUSE"?(this.log(` ERROR: Port ${s} is already in use. Retrying in 5s...`),setTimeout(()=>{this.httpServer?.close(),this.httpServer?.listen(s,e||"0.0.0.0")},5e3)):this.log(` HTTP error: ${n.message}`)}),this.httpServer.listen(s,e||"0.0.0.0",()=>{this.log(` HTTP API: http://${e||"0.0.0.0"}:${s}`)})}async handleHttp(e,t){let n=new URL(e.url||"/",`http://${e.headers.host||"localhost"}`).pathname;try{switch(`${e.method} ${n}`){case"GET /health":this.json(t,200,{status:"ok",node:this.config.node,uptime:process.uptime(),agents:this.registry.list(),crons:this.cron.list().map(r=>({id:r.id,enabled:r.enabled,nextRun:r.nextRun})),mesh:this.mesh?.directory()||[]});break;case"GET /agents":this.json(t,200,this.registry.list());break;case"GET /crons":this.json(t,200,this.cron.list());break;case"GET /mesh":this.json(t,200,this.mesh?.directory()||[]);break;case"POST /task":{let r=await pe(e);if(!r.agent||!r.message){this.json(t,400,{error:"Missing: agent, message"});return}let i=await this.registry.execute({agentId:r.agent,message:r.message,context:r.context});this.json(t,i.error?500:200,i);break}case"POST /mesh/task":{let r=await pe(e);if(!r.peer||!r.message){this.json(t,400,{error:"Missing: peer, message"});return}if(!this.mesh){this.json(t,400,{error:"Mesh not enabled"});return}let i=await this.mesh.sendTask(r.peer,r.message);this.json(t,200,{response:i});break}case"GET /.well-known/agent-card.json":this.json(t,200,{name:this.config.node.name,description:`AgentX daemon node "${this.config.node.name}"`,url:`http://${this.config.node.bind}`,version:"1.0.0",capabilities:{streaming:!1,pushNotifications:!1,stateTransitionHistory:!1},skills:this.registry.list().map(r=>({id:r.id,name:r.name,description:`Agent "${r.name}" (${r.tier})`,tags:[r.tier]})),defaultInputModes:["text"],defaultOutputModes:["text"]});break;default:this.json(t,404,{error:"Not found",endpoints:["GET /health","GET /agents","GET /crons","GET /mesh","POST /task { agent, message, context? }","POST /mesh/task { peer, message }","GET /.well-known/agent-card.json"]})}}catch(r){this.json(t,500,{error:r.message})}}json(e,t,s){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(s,null,2))}};async function pe(l){return new Promise((e,t)=>{let s="";l.on("data",n=>s+=n.toString()),l.on("end",()=>{try{e(s?JSON.parse(s):{})}catch{e({})}}),l.on("error",t)})}import ze from"path";import Ve from"fs-extra";function Ut(){let l=ze.join("package.json");return Ve.readJSONSync(l)}export{M as a,D as b,Se as c,te as d,se as e,De as f,Pe as g,Re as h,ie as i,S as j,W as k,O as l,N as m,J as n,H as o,ue as p,Ut as q};
35
- //# sourceMappingURL=chunk-S74N276K.js.map