agentix-cli 0.4.0 → 0.6.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/README.md +120 -187
- package/dist/chunk-WT2UJMBC.js +68 -0
- package/dist/chunk-WT2UJMBC.js.map +1 -0
- package/dist/cli.js +8 -8
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +176 -16
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-AIBBZF4E.js +0 -41
- package/dist/chunk-AIBBZF4E.js.map +0 -1
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;
|
|
@@ -1918,6 +2066,8 @@ declare class AgentRegistry {
|
|
|
1918
2066
|
private providers;
|
|
1919
2067
|
private sessions;
|
|
1920
2068
|
private wiki;
|
|
2069
|
+
private rateLimiter;
|
|
2070
|
+
private tokenTracker;
|
|
1921
2071
|
private log;
|
|
1922
2072
|
constructor(config: DaemonConfig, log?: (...args: unknown[]) => void);
|
|
1923
2073
|
/**
|
|
@@ -1934,13 +2084,13 @@ declare class AgentRegistry {
|
|
|
1934
2084
|
*/
|
|
1935
2085
|
findAllMentioned(text: string): string[];
|
|
1936
2086
|
/**
|
|
1937
|
-
*
|
|
2087
|
+
* Build peer list for context engine.
|
|
1938
2088
|
*/
|
|
1939
|
-
private
|
|
2089
|
+
private buildPeerList;
|
|
1940
2090
|
/**
|
|
1941
|
-
*
|
|
2091
|
+
* Get the primary channel handle for an agent (e.g. "@noqta_devops_bot" on telegram).
|
|
1942
2092
|
*/
|
|
1943
|
-
private
|
|
2093
|
+
private getChannelHandle;
|
|
1944
2094
|
/**
|
|
1945
2095
|
* Execute a task on an agent. Respects maxConcurrent limit.
|
|
1946
2096
|
*/
|
|
@@ -1958,6 +2108,23 @@ declare class AgentRegistry {
|
|
|
1958
2108
|
errors: number;
|
|
1959
2109
|
lastActive?: Date;
|
|
1960
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;
|
|
1961
2128
|
}
|
|
1962
2129
|
|
|
1963
2130
|
interface IncomingMessage {
|
|
@@ -2016,7 +2183,7 @@ declare class MessageRouter {
|
|
|
2016
2183
|
private channels;
|
|
2017
2184
|
private hooks?;
|
|
2018
2185
|
private mesh?;
|
|
2019
|
-
private
|
|
2186
|
+
private groupLog;
|
|
2020
2187
|
private log;
|
|
2021
2188
|
constructor(registry: AgentRegistry, config: DaemonConfig, hooks?: HookRegistry, log?: (...args: unknown[]) => void);
|
|
2022
2189
|
setMesh(mesh: A2AMesh): void;
|
|
@@ -2027,8 +2194,10 @@ declare class MessageRouter {
|
|
|
2027
2194
|
private static readonly MAX_BOT_CHAIN_DEPTH;
|
|
2028
2195
|
/**
|
|
2029
2196
|
* Bot-to-bot conversation chain.
|
|
2030
|
-
*
|
|
2031
|
-
*
|
|
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)
|
|
2032
2201
|
*/
|
|
2033
2202
|
private handleBotToBotChain;
|
|
2034
2203
|
private adapterSend;
|
|
@@ -2040,15 +2209,6 @@ declare class MessageRouter {
|
|
|
2040
2209
|
* Searches peer agent cards for mention matches.
|
|
2041
2210
|
*/
|
|
2042
2211
|
private handleViaMesh;
|
|
2043
|
-
/**
|
|
2044
|
-
* Log a message in the group conversation history.
|
|
2045
|
-
*/
|
|
2046
|
-
private logGroupMessage;
|
|
2047
|
-
/**
|
|
2048
|
-
* Build group conversation context for an agent.
|
|
2049
|
-
* Returns recent messages from the group so the agent knows what's been discussed.
|
|
2050
|
-
*/
|
|
2051
|
-
private buildGroupContext;
|
|
2052
2212
|
private getAccountForAgent;
|
|
2053
2213
|
private resolveAgent;
|
|
2054
2214
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
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-
|
|
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
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).
|
package/package.json
CHANGED
package/dist/chunk-AIBBZF4E.js
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
import{i as ge,j as he}from"./chunk-Z4GC5D6D.js";import{b as de}from"./chunk-4YCH6IZV.js";var L=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:d}=await r.read();if(a)break;o+=i.decode(d,{stream:!0});let c=o.split(`
|
|
2
|
-
`);o=c.pop()||"";for(let h of c)if(h.startsWith("data: "))try{let m=JSON.parse(h.slice(6));yield{state:m.state,message:m.message?.parts?.[0]?.text,final:m.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 B=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 L(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 d=await a.json();if(d.error)throw new Error(`Peer "${e}" agent error: ${d.error}`);return d.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 g}from"zod";import{readFileSync as ue,existsSync as H}from"fs";import{resolve as N}from"path";function De(l){let e=N(l,".env");if(!H(e))return;let t=ue(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 Ie=g.object({apiKey:g.string().optional(),defaultModel:g.string().optional(),baseUrl:g.string().optional()}),Pe=g.object({name:g.string(),workspace:g.string(),tier:g.enum(["claude-code","sdk","orchestrator"]).default("claude-code"),provider:g.string().optional(),model:g.string().optional(),systemPrompt:g.string().optional(),mentions:g.array(g.string()).default([]),maxConcurrent:g.number().default(1),permissionMode:g.string().default("default")}),Re=g.object({token:g.string(),agentBinding:g.string()}),_e=g.object({telegram:g.object({enabled:g.boolean().default(!1),accounts:g.record(g.string(),Re).default({}),policy:g.object({dm:g.enum(["pair","block"]).default("pair"),group:g.enum(["mention-required","all"]).default("mention-required")}).default({})}).default({}),whatsapp:g.object({enabled:g.boolean().default(!1),sessionDir:g.string().default(".agentx/whatsapp-sessions"),defaultAgent:g.string().optional(),allowFrom:g.array(g.string()).optional(),routes:g.array(g.object({contact:g.string().optional(),group:g.string().optional(),agent:g.string()})).default([])}).default({}),discord:g.object({enabled:g.boolean().default(!1),token:g.string().optional(),agentBinding:g.string().optional()}).default({})}),Ee=g.object({enabled:g.boolean().default(!0),schedule:g.string(),timezone:g.string().default("UTC"),agent:g.string(),prompt:g.string(),timeout:g.number().default(600),model:g.string().optional(),onError:g.enum(["log","notify","disable"]).default("log")}),je=g.object({url:g.string(),name:g.string(),token:g.string().optional()}),We=g.object({enabled:g.boolean().default(!1),peers:g.array(je).default([]),discovery:g.enum(["static","mdns"]).default("static"),healthCheck:g.object({interval:g.number().default(60),timeout:g.number().default(10)}).default({})}),Oe=g.object({node:g.object({id:g.string(),name:g.string(),bind:g.string().default("127.0.0.1:18800")}),providers:g.record(g.string(),Ie).default({}),agents:g.record(g.string(),Pe).default({}),channels:_e.default({}),crons:g.record(g.string(),Ee).default({}),mesh:We.default({})});function ne(l){if(typeof l=="string")return l.replace(/\$\{(\w+)\}/g,(e,t)=>process.env[t]||"");if(Array.isArray(l))return l.map(ne);if(l!==null&&typeof l=="object"){let e={};for(let[t,s]of Object.entries(l))e[t]=ne(s);return e}return l}function pe(l){let e=l?[l]:[N(process.cwd(),"agentx.json"),N(process.cwd(),".agentx/config.json")];De(process.cwd());let t,s;for(let o of e)if(H(o)){t=ue(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=ne(n),i=Oe.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 me(l){let e=[];for(let[t,s]of Object.entries(l.agents)){if(!H(s.workspace)){e.push(`Agent "${t}": workspace not found at ${s.workspace}`);continue}if(s.tier==="claude-code"){let i=N(s.workspace,".claude");H(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 Le}from"execa";import{execFile as Be}from"child_process";function fe(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 e.context?.replyToText&&(s.push(""),s.push(`[Replying to]: ${e.context.replyToText}`)),e.context?.mediaPath&&(s.push(""),s.push(`[Attached file: ${e.context.mediaPath}]`),s.push(`[File type: ${e.context.mediaType||"unknown"}]`),e.context.mediaType?.startsWith("image/")?s.push("Please read/view this image file and describe or respond to it."):e.context.mediaType?.startsWith("audio/")?s.push("Please transcribe this audio file and respond to its content."):e.context.mediaType?.startsWith("video/")?s.push("A video file is attached. Describe what you can determine about it."):s.push("Please read this file and respond based on its content.")),t&&(s.push(""),s.push(t)),s.push(""),s.push(e.message),s.join(`
|
|
8
|
-
`)}function ye(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 He(l){try{let e=JSON.parse(l);return{text:e.result||e.content||"",sessionId:e.session_id}}catch{return{text:l}}}async function Ne(l,e,t,s){let n=Date.now(),r=fe(l,e,s?void 0:t),i=ye(l,r,!1,s);try{let{stdout:o,stderr:a,exitCode:d}=await new Promise((h,m)=>{let p=Be("claude",i,{cwd:l.workspace,timeout:6e5,maxBuffer:10485760,env:{...process.env,HOME:process.env.HOME||"/home/"+(process.env.USER||"clawd")}},(v,u,f)=>{h({stdout:u||"",stderr:f||"",exitCode:v?v.code??1:0})})});if(!o&&d!==0)return{content:"",error:(a?.trim()||`Claude Code exited with code ${d}`).slice(0,300),duration:Date.now()-n};let c=He(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 Je(l,e,t,s,n){let r=Date.now(),i=fe(l,e,n?void 0:s),o=ye(l,i,!0,n),a="";try{let d=Le("claude",o,{cwd:l.workspace,timeout:6e5,reject:!1,env:process.env,buffer:!1});if(d.stdout){let h="";d.stdout.on("data",m=>{h+=m.toString();let p=h.split(`
|
|
9
|
-
`);h=p.pop()||"";for(let v of p)if(v.trim())try{let u=JSON.parse(v);if(u.type==="assistant"&&u.message?.content){for(let f of u.message.content)if(f.type==="text"&&f.text){let w=f.text.slice(a.length);w&&(a=f.text,t(w,a))}}if(u.type==="content_block_delta"&&u.delta?.text&&(a+=u.delta.text,t(u.delta.text,a)),u.type==="result"&&u.result){let f=(typeof u.result=="string",u.result);if(typeof f=="string"&&f.length>a.length){let w=f.slice(a.length);a=f,w&&t(w,a)}}}catch{v.trim()&&!v.startsWith("{")&&(a+=v+`
|
|
10
|
-
`,t(v+`
|
|
11
|
-
`,a))}})}let c=await d;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(d){return{content:a||"",error:d.message,duration:Date.now()-r}}}async function Fe(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 d of a)d.type==="result"&&d.subtype==="success"&&(o=d.result||"");return{content:o,duration:Date.now()-s}}catch(n){return{content:"",error:`SDK error: ${n.message}`,duration:Date.now()-s}}}async function Ue(l,e,t){let s=Date.now();try{let{generate:n}=await import("./agent-K2YOEOJ5.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 we(l,e,t,s,n,r){switch(l.tier){case"claude-code":return s?Je(l,e,s,n,r):Ne(l,e,n,r);case"sdk":{let i=l.provider||"claude",o=t[i]?.apiKey;return o?Fe(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 Ue(l,e,o)}default:return{content:"",error:`Unknown tier: ${l.tier}`}}}import{readFileSync as ve,writeFileSync as J,existsSync as F,mkdirSync as re,readdirSync as ie,statSync as Ge}from"fs";import{resolve as T,join as ze,relative as U,dirname as Ke}from"path";var R=class{baseDir;rawDir;log;constructor(e=T(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki]")){this.baseDir=e,this.rawDir=T(e,"raw/entries"),this.log=t,re(this.rawDir,{recursive:!0}),re(T(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=T(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),J(s,n.join(`
|
|
14
|
-
`)),t}listEntries(e){if(!F(this.rawDir))return[];let t=ie(this.rawDir).filter(n=>n.endsWith(".md")).sort(),s=[];for(let n of t){let r=ve(T(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=T(this.baseDir,e);re(Ke(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),J(i,o.join(`
|
|
15
|
-
`)),!0}readArticle(e){let t=T(this.baseDir,e);if(!F(t))return null;let s=ve(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 d=n.match(new RegExp(`^${a}:\\s*\\[(.*)\\]$`,"m"));return d?d[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=U(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=U(this.baseDir,i);if(o.startsWith("raw/")||o.startsWith("_"))return;let a=this.readArticle(o);if(!a||!this.canRead(a.meta,t))return;let d=0,c=a.meta.title.toLowerCase(),h=a.content.toLowerCase();c.includes(n)&&(d+=10),a.meta.tags?.some(p=>p.toLowerCase().includes(n))&&(d+=5);let m=(h.match(new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"))||[]).length;d+=Math.min(m,5),d>0&&r.push({article:a,score:d})}),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 d of a){let c=i.get(d.path);c?c.score+=1:i.set(d.path,{article:d,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=U(this.baseDir,i);if(o.startsWith("raw/")||o.startsWith("_"))return;let a=this.readArticle(o);if(!a)return;let d=a.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let h of d){let m=h.replace(/\[\[|\]\]/g,"");t.set(m,(t.get(m)||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()};J(T(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((d,c)=>d.title.localeCompare(c.title))){let d=a.access==="private"?" (private)":a.access==="shared"?" (shared)":"";n.push(`- [${a.title}](${a.path})${d} \u2014 owner: ${a.owner}`)}n.push("")}return J(T(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=U(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=F(this.rawDir)?ie(this.rawDir).filter(i=>i.endsWith(".md")).length:0;return{totalArticles:e,totalEntries:r,articlesByType:t,articlesByAccess:s,articlesByOwner:n}}walkDir(e,t){if(F(e))for(let s of ie(e)){let n=ze(e,s);Ge(n).isDirectory()?this.walkDir(n,t):t(n)}}};import{readFileSync as Ve,writeFileSync as qe,mkdirSync as Xe,existsSync as ke}from"fs";import{resolve as $e}from"path";var Qe=12e3,be=30,G=class{sessionsDir;cache=new Map;constructor(e=process.cwd()){this.sessionsDir=$e(e,".agentx/sessions"),ke(this.sessionsDir)||Xe(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 $e(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(ke(r))try{let a=JSON.parse(Ve(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>be&&(e.messages=e.messages.slice(-be));let t=e.messages.reduce((s,n)=>s+n.content.length,0);for(;t>Qe&&e.messages.length>2;){let s=e.messages.shift();t-=s.content.length}}save(e){try{let t=this.sessionFile(e.id);qe(t,JSON.stringify(e,null,2))}catch{}}};var z=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 G,this.wiki=new R;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),d=s.def.tier==="claude-code"?this.sessions.getClaudeSessionId(e.agentId,n,r):void 0,c=d?void 0:this.sessions.buildHistoryContext(e.agentId,n,r),h=[a,c].filter(Boolean).join(`
|
|
23
|
-
|
|
24
|
-
`)||void 0;try{let m=await we(s.def,e,this.providers,t,h,d);if(m.error)s.errors++,this.log(`[${e.agentId}] error: ${m.error}`);else{if(this.sessions.addAgentMessage(e.agentId,n,r,m.content),m.claudeSessionId&&this.sessions.setClaudeSessionId(e.agentId,n,r,m.claudeSessionId),m.content.length>50)try{let p=`${e.agentId}-${Date.now().toString(36)}`;this.wiki.addEntry({id:p,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: ${m.content}`})}catch{}this.log(`[${e.agentId}] completed in ${m.duration}ms`+(m.tokensUsed?` (${m.tokensUsed} tokens)`:""))}return m}catch(m){return s.errors++,this.log(`[${e.agentId}] unexpected error: ${m.message}`),{content:"",error:m.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 oe=class{registry;config;channels=new Map;hooks;mesh;groupLogs=new Map;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 y=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(y.blocked){this.log(`Message blocked by hook: ${y.message}`);return}y.modified?.text&&(t={...t,text:y.modified.text})}if(t.group){let y=t.group.id;this.logGroupMessage(y,t.sender.name,t.text)}let s=this.resolveAgent(t);if(!s)return;if(t.group&&t.channel==="telegram"){let y=this.getAccountForAgent(s);if(y&&y!==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),d=typeof e.editMessage=="function",c,h=0,m=d?async(y,k)=>{let A=Date.now();if(!(A-h<1500))if(c)try{await this.adapterEdit(e,n,c,k,void 0,o),h=A}catch{}else{let $=k.length>20?k:`_${i} is writing..._
|
|
27
|
-
|
|
28
|
-
${k}`;try{c=await this.adapterSend(e,{channel:t.channel,chatId:n,text:$,replyTo:t.id,accountId:o}),h=A}catch{}}}:void 0,p=t.group?this.buildGroupContext(n):"",v=p?`${p}
|
|
29
|
-
|
|
30
|
-
${t.sender.name}: ${t.text}`:t.text,u=await this.registry.execute({message:v,agentId:s,context:{channel:t.channel,sender:t.sender.name,group:t.group?.name,mediaPath:t.media?.path,mediaType:t.media?.type,replyToText:t.replyToText}},m);if(clearInterval(a),u.error){this.log(`Agent error: ${u.error}`);let y=`Error: ${u.error}`;c?await this.adapterEdit(e,n,c,y,"plain",o):await this.adapterSend(e,{channel:t.channel,chatId:n,text:y,replyTo:t.id,parseMode:"plain",accountId:o});return}let f=u.content;if(this.hooks?.has("post:channel-message")){let y=await this.hooks.execute("post:channel-message",{event:"post:channel-message",channel:t.channel,sender:t.sender.name,response:f,agentId:s});if(y.blocked){this.log(`Response blocked by hook: ${y.message}`);return}y.modified?.response&&(f=y.modified.response)}let w;f&&(c?(await this.adapterEdit(e,n,c,f,void 0,o),w=c):w=await this.adapterSend(e,{channel:t.channel,chatId:n,text:f,replyTo:t.id,accountId:o})),t.group&&f&&this.logGroupMessage(n,i,f),f&&w&&this.handleBotToBotChain(e,t,s,f,w,0).catch(y=>{this.log(`Bot-to-bot error: ${y.message}`)})}async handleBotToBotChain(e,t,s,n,r,i){if(i>=oe.MAX_BOT_CHAIN_DEPTH){this.log(`Bot-to-bot: max chain depth (${i}) reached, stopping`);return}for(let[o,a]of Object.entries(this.config.agents)){if(o===s||!a.mentions.some(p=>n.toLowerCase().includes(p.toLowerCase())))continue;this.log(`Bot-to-bot [${i+1}]: "${s}" -> "${o}"`);let c=t.group?.id||t.sender.id,h=this.getAccountForAgent(o),m=this.getAccountForAgent(s);try{this.adapterReact(e,c,r,"\u{1F440}",h);let p=this.startTypingLoop(e,c,h),v=i===0?`[Original from ${t.sender.name}]: ${t.text}
|
|
31
|
-
|
|
32
|
-
[${s} said]: ${n}`:n,u=await this.registry.execute({message:v,agentId:o,context:{channel:t.channel,sender:`agent:${s}`,group:t.group?.name}});if(clearInterval(p),u.content&&!u.error){let f=await this.adapterSend(e,{channel:t.channel,chatId:c,text:u.content,accountId:h});f&&u.content&&await this.handleBotToBotChain(e,t,o,u.content,f,i+1)}else u.error&&this.log(`Bot-to-bot "${o}" error: ${u.error}`)}catch(p){this.log(`Bot-to-bot "${o}" failed: ${p.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 d=this.startTypingLoop(e,o,a);try{let c=await this.mesh.sendTask(r.peer,t.text,i.id);if(clearInterval(d),c){let h=`**${i.name}** _(${r.peer})_:
|
|
33
|
-
|
|
34
|
-
`;await this.adapterSend(e,{channel:t.channel,chatId:o,text:h+c,replyTo:t.id,accountId:a})}return!0}catch(c){return clearInterval(d),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}logGroupMessage(e,t,s){if(!e)return;let n=this.groupLogs.get(e)||[];for(n.push({sender:t,text:s.slice(0,500),timestamp:Date.now()});n.length>20;)n.shift();this.groupLogs.set(e,n)}buildGroupContext(e){let t=this.groupLogs.get(e);if(!t||t.length<=1)return"";let s=["[Recent group conversation]"],n=0;for(let r=t.length-2;r>=0;r--){let i=t[r],o=`${i.sender}: ${i.text}`;if(n+o.length>6e3)break;s.splice(1,0,o),n+=o.length}return s.length<=1?"":(s.push("[End of conversation \u2014 respond to the latest message]"),s.join(`
|
|
35
|
-
`))}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)}},_=oe;de(_,"MAX_BOT_CHAIN_DEPTH",3);function K(l){return l.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function ae(l){let e=l.split(`
|
|
36
|
-
`),t=[],s=!1,n="",r=[],i=!1,o=[],a=!1;for(let c=0;c<e.length;c++){let h=e[c];if(h.trimStart().startsWith("```"))if(s){s=!1;let u=K(r.join(`
|
|
37
|
-
`)),f=n?`// ${n}
|
|
38
|
-
`:"";t.push(`<pre><code>${f}${u}</code></pre>`),n="";continue}else{s=!0,n=h.trimStart().slice(3).trim(),r=[];continue}if(s){r.push(h);continue}if(i&&!h.trimStart().startsWith(">")&&(t.push("</blockquote>"),i=!1),a&&!h.trim().startsWith("|")&&(a=!1,o=[]),h.trimStart().startsWith("> ")){let u=h.replace(/^>\s*/,"");i||(t.push("<blockquote>"),i=!0),t.push(C(u));continue}let m=h.match(/^(#{1,6})\s+(.+)$/);if(m){t.push(""),t.push(`<b>${C(m[2])}</b>`);continue}if(/^[-*_]{3,}\s*$/.test(h.trim())){t.push("\u2014\u2014\u2014");continue}if(h.trim().startsWith("|")&&h.trim().endsWith("|")){let u=h.split("|").slice(1,-1).map(f=>f.trim());if(/^\|[\s\-:|]+\|$/.test(h.trim())){a=!0;continue}if(!a){o=u,a=!0;continue}if(o.length>0&&u.length>0)if(u.length>=2){let f=[];for(let w=0;w<u.length;w++)if(w===0)f.push(`<b>${C(u[w])}</b>`);else{let y=o[w]?`${C(o[w])}: `:"";f.push(`${y}${C(u[w])}`)}t.push(`\u2022 ${f.join(" \u2014 ")}`)}else t.push(`\u2022 ${C(u[0])}`);continue}let p=h.match(/^(\s*)[-*+]\s+(.+)$/);if(p){let u=p[1].length>0?" ":"";t.push(`${u}\u2022 ${C(p[2])}`);continue}let v=h.match(/^(\s*)\d+[.)]\s+(.+)$/);if(v){let u=v[1].length>0?" ":"",f=h.match(/^(\s*)(\d+)/)?.[2]||"1";t.push(`${u}${f}. ${C(v[2])}`);continue}if(!h.trim()){t.push("");continue}t.push(C(h))}s&&t.push(`<pre><code>${K(r.join(`
|
|
39
|
-
`))}</code></pre>`),i&&t.push("</blockquote>");let d=t.join(`
|
|
40
|
-
`).trim();return d=Ze(d),d}function C(l){let e=K(l);return e=e.replace(/`([^`]+)`/g,"<code>$1</code>"),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(t,s,n)=>`<a href="${K(n)}">${s}</a>`),e=e.replace(/\*\*\*(.+?)\*\*\*/g,"<b><i>$1</i></b>"),e=e.replace(/\*\*(.+?)\*\*/g,"<b>$1</b>"),e=e.replace(/(?<!\*)\*([^*]+?)\*(?!\*)/g,"<i>$1</i>"),e=e.replace(/~~(.+?)~~/g,"<s>$1</s>"),e=e.replace(/\|\|(.+?)\|\|/g,"<tg-spoiler>$1</tg-spoiler>"),e}var Ye=/(?<=\w)\.(ts|js|py|rs|go|rb|cs|sh|md|yml|yaml|toml|json|env|css|html|xml|sql|tf|hcl)(?=[\s,;:)\]}<]|$)/gi;function Ze(l){let e=l.split(/(<\/?(?:code|pre|a)[^>]*>)/gi),t=!1;return e.map(s=>/<(?:code|pre|a)\b/i.test(s)?(t=!0,s):/<\/(?:code|pre|a)>/i.test(s)?(t=!1,s):t?s:s.replace(Ye,"<code>.$1</code>")).join("")}var V=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?ae(n):n,i={chat_id:e.chatId,text:r,parse_mode:"HTML"};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,d=n!=="html"&&n!=="plain"?ae(a):a,c={chat_id:e,message_id:parseInt(t,10),text:d,parse_mode:"HTML"};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&&this.handler){let o=i.message,a=o.text||o.caption||"",d,c=o.photo&&o.photo.length>0,h=!!o.voice,m=!!o.audio,p=!!o.video,v=!!o.document;if(c||h||m||p||v){let w,y="application/octet-stream";if(c?(w=o.photo[o.photo.length-1].file_id,y="image/jpeg",a||(a="[Photo attached \u2014 please describe what you see]")):h?(w=o.voice.file_id,y=o.voice.mime_type||"audio/ogg",a||(a="[Voice message \u2014 please transcribe and respond]")):m?(w=o.audio.file_id,y=o.audio.mime_type||"audio/mpeg",a||(a=`[Audio: ${o.audio.title||"audio file"}]`)):p?(w=o.video.file_id,y=o.video.mime_type||"video/mp4",a||(a="[Video attached]")):v&&(w=o.document.file_id,y=o.document.mime_type||"application/octet-stream",a||(a=`[Document: ${o.document.file_name||"file"}]`)),w)try{let A=(await this.apiCall(t.token,"getFile",{file_id:w})).result?.file_path;if(A){let $=`https://api.telegram.org/file/bot${t.token}/${A}`,M=await fetch($);if(M.ok){let Y=Buffer.from(await M.arrayBuffer()),le=y.split("/")[1]?.split(";")[0]||"bin",{mkdirSync:x,writeFileSync:Z}=await import("fs"),{randomUUID:I}=await import("crypto"),{resolve:j,join:W}=await import("path"),O=j(process.cwd(),".agentx/media/telegram");x(O,{recursive:!0});let b=o.document?.file_name||`${I()}.${le}`,S=W(O,b);Z(S,Y),d={path:S,type:y,fileName:b}}}}catch(k){this.log(`Media download failed: ${k.message}`)}}if(!a)continue;let f={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:a,media:d,replyTo:o.reply_to_message?String(o.reply_to_message.message_id):void 0,replyToText:o.reply_to_message?o.reply_to_message.text||o.reply_to_message.caption||`[message from ${o.reply_to_message.from?.first_name||"unknown"}]`:void 0,timestamp:new Date(o.date*1e3),raw:i};this.chatAccountMap.set(String(o.chat.id),e),this.handler(f).catch(w=>{this.log(`Error handling message: ${w.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 Ae,writeFileSync as et}from"fs";import{resolve as xe,join as tt}from"path";import{randomUUID as st}from"crypto";var q=class{name="whatsapp";sessionDir;defaultAgent;allowFrom;routes;handler;sock=null;sentMessageIds=new Set;log;constructor(e,t=console.error.bind(console,"[whatsapp]")){this.sessionDir=xe(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}Ae(this.sessionDir,{recursive:!0});let{state:r,saveCreds:i}=await t(this.sessionDir),o;try{let{version:d}=await n.fetchLatestBaileysVersion();o=d,this.log(`WhatsApp Web version: ${d.join(".")}`)}catch{this.log("Could not fetch WA version, using default")}let a={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:(...d)=>this.log("WA error:",...d),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",d=>{this.log(`WA history sync: ${d.messages?.length||0} messages, ${d.isLatest?"latest":"partial"}`)}),this.sock.ev.on("connection.update",async d=>{let{connection:c,lastDisconnect:h,qr:m}=d;if(m){this.log("Scan QR code with WhatsApp to connect:");try{let{default:p}=await import("qrcode-terminal");p.generate(m,{small:!0})}catch{this.log(`QR: ${m}`),this.log("Install qrcode-terminal for visual QR: npm install qrcode-terminal")}}if(c==="close"){let p=h?.error?.output?.statusCode;this.log(`WhatsApp connection closed (status: ${p})`),p===515?(this.log("Stream error, reconnecting in 5s..."),setTimeout(()=>this.start(),5e3)):p===s?.loggedOut||p===401?this.log("Logged out. Delete session dir and restart to re-scan QR."):p!==void 0&&(this.log("Reconnecting in 3s..."),setTimeout(()=>this.start(),3e3))}c==="open"&&this.log("WhatsApp connected")}),this.sock.ev.on("messages.upsert",async d=>{if(this.log(`WA messages.upsert: ${d.messages?.length||0} messages, type: ${d.type}`),!!this.handler)for(let c of d.messages||[]){let h=(c.key.remoteJid||"").replace(/@.*/,"").slice(-6),m=!!(c.message?.conversation||c.message?.extendedTextMessage?.text);if(this.log(`WA msg: from=${h} fromMe=${c.key.fromMe} hasText=${m} 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,S=c.key.remoteJid||"",D=b?.id?.replace(/:.*/,"")||"",ee=b?.lid?.replace(/:.*/,"")||"",P=S.replace(/:.*/,"").replace(/@.*/,"");if(!(P===D||P===ee))continue}let p=c.message?.conversation||c.message?.extendedTextMessage?.text||c.message?.imageMessage?.caption||c.message?.videoMessage?.caption||"",v=c.message||{},u=!!v.imageMessage,f=!!v.audioMessage,w=!!v.videoMessage,y=!!v.documentMessage,k=!!v.stickerMessage,A=u||f||w||y||k;if(A&&!p&&(u?p="[Image attached \u2014 please describe what you see]":f?p="[Voice message attached \u2014 please transcribe and respond]":w?p="[Video attached]":y?p=`[Document: ${v.documentMessage?.fileName||"file"}]`:k&&(p="[Sticker]")),!p)continue;let $=c.key.remoteJid||"",M=$.endsWith("@g.us"),Y=$.replace(/@.*$/,""),x=(M?c.key.participant||"":$).replace(/@.*$/,"");if(this.allowFrom?.length&&!c.key.fromMe&&!this.allowFrom.some(S=>{let D=S.replace(/\+/g,"");return x.includes(D)||Y.includes(D)}))continue;let Z=c.key.fromMe?"me":c.pushName||x,I;if(M&&this.sock)try{I=(await this.sock.groupMetadata($)).subject}catch{}let j=this.resolveAgent(x,I,M?$:void 0);if(!j){this.log(`No route for ${M?`group ${I||$}`:x}, skipping`);continue}let W;if(A&&this.sock)try{let S=await(await import("@whiskeysockets/baileys")).downloadMediaMessage(c,"buffer",{},{reuploadRequest:this.sock.updateMediaMessage,logger:this.sock.logger});if(S){let D=v.imageMessage?.mimetype||v.audioMessage?.mimetype||"audio/ogg",ee=D.split("/")[1]?.split(";")[0]||"bin",P=xe(this.sessionDir,"../media/inbound");Ae(P,{recursive:!0});let te=v.documentMessage?.fileName||`${st()}.${ee}`,se=tt(P,te);et(se,S),W={path:se,type:D,fileName:te},this.log(`WA media saved: ${D} -> ${se}`)}}catch(b){this.log(`WA media download failed: ${b.message}`)}let O={id:c.key.id||String(Date.now()),channel:"whatsapp",accountId:"default",sender:{id:c.key.fromMe?(this.sock?.user?.id?.replace(/:.*/,"")||x)+"@s.whatsapp.net":x,name:Z,username:x},group:M?{id:$,name:I||$}:void 0,text:p,media:W,replyTo:c.message?.extendedTextMessage?.contextInfo?.stanzaId,timestamp:new Date((c.messageTimestamp||0)*1e3),raw:c,resolvedAgent:j};this.handler(O).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 nt,mkdirSync as Se,existsSync as Te}from"fs";import{resolve as ce}from"path";function E(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 d=a;d<=t;d+=o)s.push(d)}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 rt(l,e,t){let s=l.trim().split(/\s+/);if(s.length!==5)throw new Error(`Invalid cron: ${l}`);let n=E(s[0],0,59),r=E(s[1],0,23),i=E(s[2],1,31),o=E(s[3],1,12),a=E(s[4],0,6),d=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 m=d.formatToParts(c),p=k=>parseInt(m.find(A=>A.type===k)?.value||"0",10),v=p("minute"),u=p("hour"),f=p("day"),w=p("month"),y=c.getDay();if(n.includes(v)&&r.includes(u)&&i.includes(f)&&o.includes(w)&&a.includes(y))return c;c.setTime(c.getTime()+6e4)}throw new Error(`No next run found for cron "${l}" within 1 year`)}var X=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=ce(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,Te(this.runsDir)||Se(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=rt(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=ce(this.runsDir,e.jobId);Te(t)||Se(t,{recursive:!0});let s=`${e.startedAt.toISOString().replace(/[:.]/g,"-")}.json`;nt(ce(t,s),JSON.stringify(e,null,2))}catch{}}list(){return Array.from(this.jobs.values())}};import{createServer as it}from"http";var Q=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(d=>{this.log(`Error handling message: ${d.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 Ce=class{config;registry;router;cron;mesh;hooks;httpServer;log;constructor(e){this.log=console.error.bind(console,"[agentx]"),this.log("Loading configuration..."),this.config=pe(e);let t=me(this.config);for(let s of t)this.log(` \u26A0 ${s}`);this.hooks=new ge,he(process.cwd(),this.hooks),this.registry=new z(this.config,this.log),this.router=new _(this.registry,this.config,this.hooks,this.log),this.cron=new X(this.config,this.registry,this.hooks,this.log),this.config.mesh.enabled&&(this.mesh=new B(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 V(e,this.log);this.router.addChannel(t),this.log(" Telegram: enabled")}}if(this.config.channels.whatsapp.enabled){let e=new q({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 Q({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=it(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 Me(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 Me(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 Me(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 ot from"path";import at from"fs-extra";function rs(){let l=ot.join("package.json");return at.readJSONSync(l)}export{L as a,B as b,Oe as c,pe as d,me as e,Ne as f,Fe as g,Ue as h,we as i,R as j,z as k,_ as l,V as m,q as n,X as o,Ce as p,rs as q};
|
|
41
|
-
//# sourceMappingURL=chunk-AIBBZF4E.js.map
|