agentix-cli 0.2.0 → 0.4.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.
Files changed (39) hide show
  1. package/README.md +192 -107
  2. package/dist/agent-K2YOEOJ5.js +2 -0
  3. package/dist/chunk-4YCH6IZV.js +2 -0
  4. package/dist/chunk-AIBBZF4E.js +41 -0
  5. package/dist/chunk-AIBBZF4E.js.map +1 -0
  6. package/dist/chunk-F73GPYCO.js +106 -0
  7. package/dist/chunk-F73GPYCO.js.map +1 -0
  8. package/dist/chunk-M7HKBG3V.js +2 -0
  9. package/dist/chunk-M7HKBG3V.js.map +1 -0
  10. package/dist/chunk-MGMZNJCE.js +46 -0
  11. package/dist/chunk-MGMZNJCE.js.map +1 -0
  12. package/dist/{chunk-6PVFYFUE.js → chunk-X7UN6JAA.js} +2 -2
  13. package/dist/{chunk-6PVFYFUE.js.map → chunk-X7UN6JAA.js.map} +1 -1
  14. package/dist/chunk-Z4GC5D6D.js +12 -0
  15. package/dist/chunk-Z4GC5D6D.js.map +1 -0
  16. package/dist/cli.js +9 -155
  17. package/dist/cli.js.map +1 -1
  18. package/dist/heal-UV5A6B5T.js +2 -0
  19. package/dist/index.d.ts +265 -11
  20. package/dist/index.js +85 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/loader-6VSM6FSY.js +2 -0
  23. package/dist/providers-AVYG63KK.js +2 -0
  24. package/dist/providers-AVYG63KK.js.map +1 -0
  25. package/package.json +3 -1
  26. package/dist/agent-AI6DUEPU.js +0 -2
  27. package/dist/chunk-FUYKPFUV.js +0 -46
  28. package/dist/chunk-FUYKPFUV.js.map +0 -1
  29. package/dist/chunk-NZ6W33BD.js +0 -116
  30. package/dist/chunk-NZ6W33BD.js.map +0 -1
  31. package/dist/chunk-THMHQELC.js +0 -106
  32. package/dist/chunk-THMHQELC.js.map +0 -1
  33. package/dist/heal-MJLBETRV.js +0 -2
  34. package/dist/loader-PHU6STSZ.js +0 -2
  35. package/dist/providers-MPYTYJVB.js +0 -2
  36. /package/dist/{agent-AI6DUEPU.js.map → agent-K2YOEOJ5.js.map} +0 -0
  37. /package/dist/{heal-MJLBETRV.js.map → chunk-4YCH6IZV.js.map} +0 -0
  38. /package/dist/{loader-PHU6STSZ.js.map → heal-UV5A6B5T.js.map} +0 -0
  39. /package/dist/{providers-MPYTYJVB.js.map → loader-6VSM6FSY.js.map} +0 -0
package/README.md CHANGED
@@ -1,76 +1,132 @@
1
1
  # AgentX
2
2
 
3
- **Self-hosted multi-agent orchestrator.** Routes messages from Telegram, WhatsApp, crons, and cross-machine A2A mesh to AI agents running on Claude Code, OpenAI, Ollama, or any LLM provider.
3
+ **Self-hosted multi-agent orchestrator.** Routes messages from Telegram, WhatsApp, Discord, crons, and cross-machine A2A mesh to AI agents running on Claude Code, OpenAI, Ollama, or any LLM provider.
4
4
 
5
- > **Experimental.** This project is a rapid response to [Anthropic's updated terms of use](https://www.anthropic.com/policies) restricting third-party OAuth integrations (affecting tools like OpenClaw). AgentX is a self-hosted, bring-your-own-key alternative — you run it on your own machines with your own API keys or Claude subscription.
5
+ > **Experimental.** Built as a self-hosted, bring-your-own-key alternative to third-party AI orchestrators affected by [Anthropic's updated terms of use](https://www.anthropic.com/policies). You run it on your own machines with your own API keys or Claude subscription.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install -g agentix-cli
11
+ ```
12
+
13
+ ## Quick start
14
+
15
+ ```bash
16
+ # 1. Initialize
17
+ agentx init
18
+
19
+ # 2. Add an agent (interactive)
20
+ agentx agent add
21
+
22
+ # 3. Add a Telegram bot (interactive, verifies token)
23
+ agentx channel add
24
+
25
+ # 4. Start
26
+ agentx daemon start
27
+ ```
28
+
29
+ That's it. Your agent is live on Telegram.
6
30
 
7
31
  ## How it works
8
32
 
9
- AgentX is **not** an AI runtime. It's a thin orchestration layer:
33
+ ```
34
+ Telegram ──┐
35
+ WhatsApp ──┤ agentx ┌─ claude -p --cwd /workspace
36
+ Discord ───┤ daemon ───┤─ openai API
37
+ Cron ──────┤ └─ ollama generate
38
+ A2A mesh ──┘
39
+ │
40
+ routes messages to the right
41
+ agent workspace with wiki context
42
+ ```
43
+
44
+ Each agent = a workspace directory. For Claude Code agents, permissions, hooks, MCP servers, skills, and memory live in the workspace's `.claude/` directory. AgentX just orchestrates when and where agents run.
45
+
46
+ ## CLI Commands
47
+
48
+ ### Daemon (core)
49
+
50
+ ```bash
51
+ agentx daemon start # Start foreground
52
+ agentx daemon start --detach # Start background
53
+ agentx daemon stop # Stop daemon
54
+ agentx daemon status # Show agents, crons, mesh health
55
+ agentx daemon logs -f # Follow logs
56
+ agentx daemon send <agent> <msg> # Send a task to an agent
57
+ agentx daemon send <agent> <msg> --peer server-2 # Send to remote agent
58
+ agentx daemon deploy <host> -i ~/.ssh/key --restart # Deploy + restart remote
59
+ ```
60
+
61
+ ### Agents
10
62
 
63
+ ```bash
64
+ agentx agent add # Interactive: creates workspace, CLAUDE.md, settings, wiki skill
65
+ agentx agent list # List all agents
66
+ agentx agent remove <id> # Remove from config (keeps workspace)
11
67
  ```
12
- ┌──────────────┐
13
- Telegram ──────────┤ │
14
- WhatsApp ──────────┤ agentx │──── claude -p "task" --cwd /workspace
15
- Cron trigger ──────┤ daemon │──── openai API call
16
- A2A remote call ───┤ │──── ollama generate
17
- └──────┬───────┘
18
- │
19
- routes messages to
20
- the right workspace
21
- with the right prompt
68
+
69
+ ### Channels
70
+
71
+ ```bash
72
+ agentx channel add # Interactive: Telegram bot token, verify, bind to agent
73
+ agentx channel list # List all channel bindings
22
74
  ```
23
75
 
24
- Each agent = a workspace directory. For Claude Code agents, permissions, hooks, MCP servers, skills, and memory are all configured in the workspace's `.claude/` directory — no AgentX code needed.
76
+ **Supported channels:**
77
+ - **Telegram** — Multi-account bots, streaming responses, MarkdownV2, typing indicators, seen reactions, bot-to-bot delegation
78
+ - **WhatsApp** — Via Baileys (QR pairing), self-chat mode (message yourself to talk to agent), per-contact/group agent routing
79
+ - **Discord** — Via discord.js, mention-based routing, DM support
25
80
 
26
- ## Features
81
+ ### Cron jobs
27
82
 
28
- - **Multi-channel**: Telegram (polling, multi-account), WhatsApp (planned)
29
- - **Multi-agent**: Named agents with custom permissions, concurrent limits, mention routing
30
- - **Cron scheduler**: Timezone-aware recurring tasks with run logging
31
- - **A2A mesh**: Cross-machine agent communication via HTTP, peer discovery, health checks
32
- - **Streaming**: Real-time response streaming to Telegram with progressive message edits
33
- - **Typing indicators**: Bots show typing status while processing
34
- - **Bot-to-bot**: Agents can mention each other to delegate tasks
35
- - **Session memory**: One conversation session per agent/chat/day for context continuity
36
- - **Hooks**: Pre/post hooks for channels, crons, and A2A tasks (command, script, or LLM-based)
37
- - **Provider abstraction**: Switch providers per-agent via config, with capability warnings
38
- - **Markdown rendering**: Claude's markdown output converted to Telegram MarkdownV2
83
+ ```bash
84
+ agentx cron add # Interactive: schedule, agent, prompt, timezone
85
+ agentx cron list # List all jobs with status
86
+ agentx cron enable <id> # Enable a job
87
+ agentx cron disable <id> # Disable a job
88
+ ```
39
89
 
40
- ## Three execution tiers
90
+ ### Mesh (multi-machine)
41
91
 
42
- | Tier | How | Auth | Best for |
43
- |------|-----|------|----------|
44
- | `claude-code` | Spawns `claude` CLI | Subscription | Full power: subagents, MCP, skills, hooks, 1M context |
45
- | `sdk` | Claude Agent SDK | API key | Programmatic control, headless servers |
46
- | `orchestrator` | AgentX's own loop | Any provider key | Non-Claude providers (OpenAI, Ollama, Gemini) |
92
+ ```bash
93
+ agentx mesh add # Interactive: URL, name, verifies connectivity
94
+ agentx mesh list # List peers with health status
95
+ agentx mesh remove <name> # Remove a peer
96
+ ```
47
97
 
48
- ## Quick start
98
+ ### Skills
49
99
 
50
100
  ```bash
51
- npm install -g agentx-cli
101
+ agentx skill add ./path/to/skill --agent my-agent # Add to one agent
102
+ agentx skill add ./path/to/skill --all # Add to all agents
103
+ agentx skill list # List skills per agent
104
+ ```
52
105
 
53
- # Copy and edit the example config
54
- cp node_modules/agentx-cli/agentx.example.json agentx.json
106
+ ### Hooks
55
107
 
56
- # Start the daemon
57
- agentx daemon
108
+ ```bash
109
+ agentx hook add <agent> # Interactive: event, type (command/http), matcher
58
110
  ```
59
111
 
60
- Or clone and run from source:
112
+ ### Migration
61
113
 
62
114
  ```bash
63
- git clone https://github.com/nooqta/agentx.git
64
- cd agentx
65
- npm install && npm run build
66
- cp agentx.example.json agentx.json
67
- # Edit agentx.json with your agents, channels, etc.
68
- node dist/cli.js daemon
115
+ agentx migrate openclaw # Auto-detect ~/.openclaw/
116
+ agentx migrate openclaw /path/to/config # Explicit path
117
+ agentx migrate openclaw --dry-run # Preview without writing
118
+ ```
119
+
120
+ ### Setup
121
+
122
+ ```bash
123
+ agentx init # Create agentx.json, .env, workspace dirs
124
+ agentx init --force # Overwrite existing config
69
125
  ```
70
126
 
71
127
  ## Configuration
72
128
 
73
- AgentX uses a single `agentx.json` file. Environment variables are expanded (`${VAR_NAME}`).
129
+ Single `agentx.json` file. Environment variables expanded (`${VAR_NAME}`). Auto-loads `.env`.
74
130
 
75
131
  ```jsonc
76
132
  {
@@ -81,8 +137,7 @@ AgentX uses a single `agentx.json` file. Environment variables are expanded (`${
81
137
  },
82
138
 
83
139
  "providers": {
84
- "claude": { "apiKey": "${ANTHROPIC_API_KEY}" },
85
- "openai": { "apiKey": "${OPENAI_API_KEY}" }
140
+ "claude": { "apiKey": "${ANTHROPIC_API_KEY}" }
86
141
  },
87
142
 
88
143
  "agents": {
@@ -93,8 +148,7 @@ AgentX uses a single `agentx.json` file. Environment variables are expanded (`${
93
148
  "model": "claude-sonnet-4-6",
94
149
  "mentions": ["@my_bot"],
95
150
  "maxConcurrent": 2,
96
- "systemPrompt": "You are a helpful assistant.",
97
- "permissionMode": "default"
151
+ "systemPrompt": "You are a helpful assistant."
98
152
  }
99
153
  },
100
154
 
@@ -102,12 +156,23 @@ AgentX uses a single `agentx.json` file. Environment variables are expanded (`${
102
156
  "telegram": {
103
157
  "enabled": true,
104
158
  "accounts": {
105
- "default": {
106
- "token": "${TG_BOT_TOKEN}",
107
- "agentBinding": "assistant"
108
- }
159
+ "default": { "token": "${TG_BOT_TOKEN}", "agentBinding": "assistant" }
109
160
  },
110
161
  "policy": { "dm": "pair", "group": "mention-required" }
162
+ },
163
+ "whatsapp": {
164
+ "enabled": true,
165
+ "sessionDir": ".agentx/whatsapp-sessions",
166
+ "defaultAgent": "assistant",
167
+ "routes": [
168
+ { "contact": "+1234567890", "agent": "assistant" },
169
+ { "group": "Team Chat", "agent": "devops" }
170
+ ]
171
+ },
172
+ "discord": {
173
+ "enabled": true,
174
+ "token": "${DISCORD_BOT_TOKEN}",
175
+ "agentBinding": "assistant"
111
176
  }
112
177
  },
113
178
 
@@ -125,27 +190,70 @@ AgentX uses a single `agentx.json` file. Environment variables are expanded (`${
125
190
  "mesh": {
126
191
  "enabled": true,
127
192
  "peers": [
128
- { "url": "http://100.67.108.119:18800", "name": "server-2" }
193
+ { "url": "http://100.67.108.119:19900", "name": "server-2" }
129
194
  ]
130
195
  }
131
196
  }
132
197
  ```
133
198
 
134
- ### Agent workspace setup (Claude Code tier)
199
+ ## Agent workspace
135
200
 
136
- Each agent's workspace is a directory with Claude Code configuration:
201
+ Each agent is a directory with Claude Code configuration:
137
202
 
138
203
  ```
139
204
  my-workspace/
140
205
  ├── .claude/
141
- │ ├── settings.json # Permissions, hooks, model
206
+ │ ├── settings.json # Permissions, hooks, env vars
142
207
  │ ├── .mcp.json # MCP servers
143
208
  │ ├── agents/ # Subagents
144
- │ └── skills/ # Domain skills
145
- ├── CLAUDE.md # Agent identity & instructions
209
+ │ └── skills/ # SKILL.md files (gitlab, wiki, etc.)
210
+ ├── CLAUDE.md # Agent identity and instructions
146
211
  └── ... (project files)
147
212
  ```
148
213
 
214
+ New agents created via `agentx agent add` get `CLAUDE.md`, `settings.json`, and the wiki skill automatically.
215
+
216
+ ## Three execution tiers
217
+
218
+ | Tier | How | Auth | Best for |
219
+ |------|-----|------|----------|
220
+ | `claude-code` | Spawns `claude` CLI | Subscription | Full power: subagents, MCP, skills, hooks, 1M context |
221
+ | `sdk` | Claude Agent SDK | API key | Programmatic control, headless servers |
222
+ | `orchestrator` | AgentX's own loop | Any provider key | Non-Claude providers (OpenAI, Ollama) |
223
+
224
+ ## Session continuity
225
+
226
+ Agents remember conversations:
227
+ - **Claude Code tier**: `--resume SESSION_ID` with reliable ID from `--output-format json`
228
+ - **Other tiers**: Recent conversation history injected into each prompt
229
+ - **Wiki context**: Relevant knowledge articles injected before each response
230
+
231
+ ## Wiki knowledge base
232
+
233
+ Inspired by [Karpathy's LLM knowledge base](https://x.com/karpathy/status/2040572272944324650) and [Farzapedia](https://gist.github.com/farzaa/c35ac0cfbeb957788650e36aabea836d).
234
+
235
+ Agents build a shared Markdown wiki from conversations. Token-efficient: ~1K tokens for wiki context vs ~10K for session replay.
236
+
237
+ ```
238
+ .agentx/wiki/
239
+ ├── WIKI.md # Master index
240
+ ├── raw/entries/ # Auto-ingested conversations
241
+ ├── projects/ # Compiled knowledge
242
+ ├── decisions/
243
+ └── patterns/
244
+ ```
245
+
246
+ **Permissions**: `private` (owner only), `shared` (listed agents), `public` (all agents).
247
+
248
+ ## A2A Mesh
249
+
250
+ Run `agentx daemon` on multiple machines. Agents communicate cross-machine via HTTP over Tailscale/VPN.
251
+
252
+ ```
253
+ MacBook (Nadia, DevOps) ←── Tailscale ──→ Server (Atlas, MTGL, KSI, ...)
254
+ :18800 :19900
255
+ ```
256
+
149
257
  ## HTTP API
150
258
 
151
259
  The daemon exposes a REST API:
@@ -153,63 +261,40 @@ The daemon exposes a REST API:
153
261
  | Endpoint | Method | Description |
154
262
  |----------|--------|-------------|
155
263
  | `/health` | GET | System status, agents, crons, mesh |
156
- | `/agents` | GET | List agents and their status |
264
+ | `/agents` | GET | List agents |
157
265
  | `/crons` | GET | List cron jobs |
158
266
  | `/mesh` | GET | Mesh peer directory |
159
- | `/task` | POST | Execute a task: `{ "agent": "id", "message": "..." }` |
160
- | `/mesh/task` | POST | Send task to remote peer: `{ "peer": "name", "message": "..." }` |
267
+ | `/task` | POST | `{ "agent": "id", "message": "..." }` |
268
+ | `/mesh/task` | POST | `{ "peer": "name", "message": "..." }` |
161
269
  | `/.well-known/agent-card.json` | GET | A2A agent discovery |
162
270
 
163
- ## A2A Mesh
164
-
165
- Run `agentx daemon` on multiple machines. Each node discovers peers and exposes agents via A2A agent cards. Tasks are routed to the correct node automatically.
271
+ ## Migrating from OpenClaw
166
272
 
273
+ ```bash
274
+ agentx migrate openclaw
167
275
  ```
168
- MacBook (Nadia, DevOps) ←─── Tailscale ───→ Server (Atlas, MTGL)
169
- :18800 :18800
170
- ```
171
-
172
- Peers communicate over HTTP. Use Tailscale or a VPN for secure cross-machine communication.
173
-
174
- ## Migrating from OpenClaw
175
276
 
176
- AgentX is designed as a drop-in replacement for OpenClaw's agent orchestration:
277
+ Auto-imports agents, Telegram bots, cron jobs, and WhatsApp config. Also ports:
278
+ - Skills to workspace `.claude/skills/`
279
+ - Permissions to `.claude/settings.json`
280
+ - Agent identity to `CLAUDE.md`
281
+ - WhatsApp sessions (reuses existing pairing)
177
282
 
178
283
  | OpenClaw | AgentX |
179
284
  |----------|--------|
180
- | `openclaw.json` agents | `agentx.json` agents section |
181
- | `openclaw.json` channels.telegram | `agentx.json` channels.telegram |
182
- | `cron/jobs.json` | `agentx.json` crons section |
183
- | `exec-approvals.json` | Workspace `.claude/settings.json` permissions |
184
- | Gateway + Node architecture | Single daemon per machine |
185
- | OAuth proxy | Direct API key or CLI subscription |
186
-
187
- ### Migration steps
188
-
189
- 1. **Stop OpenClaw**
190
- - macOS: `launchctl unload ~/Library/LaunchAgents/ai.openclaw.*.plist`
191
- - Linux: `systemctl --user stop openclaw-gateway openclaw-node`
192
- 2. **Install AgentX**: `npm install -g agentx-cli`
193
- 3. **Convert config**: Map your `openclaw.json` agents, channels, and cron jobs to `agentx.json` (see `agentx.example.json`)
194
- 4. **Set up workspaces**: Ensure each agent's workspace has a `.claude/` directory with permissions and hooks
195
- 5. **Move secrets to `.env`**: Bot tokens, API keys — AgentX auto-loads `.env` from the working directory
196
- 6. **Start daemon**: `agentx daemon`
197
-
198
- ### Key differences from OpenClaw
199
-
200
- - **No OAuth proxy**: You run your own daemon with your own credentials
201
- - **Workspace = Agent**: Permissions, hooks, and tools live in the workspace `.claude/` dir
202
- - **Claude Code native**: `tier: "claude-code"` gives you the full Claude Code feature set (subagents, MCP, skills, hooks, memory, worktrees, 1M context)
203
- - **Provider-agnostic**: Switch any agent to OpenAI, Ollama, or other providers via config
204
- - **A2A mesh**: Agents across machines communicate natively (OpenClaw required a gateway)
205
-
206
- ## Built with
207
-
208
- - [Claude Code CLI](https://claude.ai/code) — AI agent runtime (subscription or API)
209
- - [Claude Agent SDK](https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk) — Programmatic agent control
210
- - [Telegram Bot API](https://core.telegram.org/bots/api) — Channel adapter (zero dependencies)
211
- - [Zod](https://github.com/colinhacks/zod) — Config validation
212
- - [Commander](https://github.com/tj/commander.js) — CLI framework
285
+ | Gateway + Node | Single daemon per machine |
286
+ | OAuth proxy | Direct API key or subscription |
287
+ | `openclaw.json` | `agentx.json` |
288
+ | `exec-approvals.json` | `.claude/settings.json` per workspace |
289
+
290
+ ## Use cases
291
+
292
+ - **Team of Telegram bots** — each project gets its own bot + agent with isolated workspace
293
+ - **WhatsApp assistant** — message yourself, agent replies in self-chat
294
+ - **Scheduled content** — cron jobs generate blog posts, reports, social media drafts
295
+ - **Multi-machine swarm** — agents on MacBook + server collaborate via mesh
296
+ - **Bot-to-bot delegation** — Nadia mentions @devops in her response, DevOps agent picks up
297
+ - **Wiki knowledge** — agents accumulate knowledge, share insights across the team
213
298
 
214
299
  ## Legal
215
300
 
@@ -0,0 +1,2 @@
1
+ import{s as a,t as b,u as c}from"./chunk-F73GPYCO.js";import"./chunk-Z4GC5D6D.js";import"./chunk-FRFR27IN.js";import"./chunk-SFQUP3BP.js";import"./chunk-MGMZNJCE.js";import"./chunk-M7HKBG3V.js";import"./chunk-4YCH6IZV.js";export{a as createAgentContext,b as generate,c as generateStream};
2
+ //# sourceMappingURL=agent-K2YOEOJ5.js.map
@@ -0,0 +1,2 @@
1
+ var d=Object.defineProperty;var e=(a,b,c)=>b in a?d(a,b,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[b]=c;var f=(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')});var g=(a,b,c)=>(e(a,typeof b!="symbol"?b+"":b,c),c);export{f as a,g as b};
2
+ //# sourceMappingURL=chunk-4YCH6IZV.js.map
@@ -0,0 +1,41 @@
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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}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