agentix-cli 0.2.0 → 0.3.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 +192 -107
- package/dist/agent-CRA5PU6S.js +2 -0
- package/dist/chunk-KVWUPUR5.js +106 -0
- package/dist/chunk-KVWUPUR5.js.map +1 -0
- package/dist/chunk-M7HKBG3V.js +2 -0
- package/dist/chunk-M7HKBG3V.js.map +1 -0
- package/dist/chunk-MDR7SH7F.js +2 -0
- package/dist/chunk-MGMZNJCE.js +46 -0
- package/dist/chunk-MGMZNJCE.js.map +1 -0
- package/dist/chunk-PCAYW54Q.js +12 -0
- package/dist/chunk-PCAYW54Q.js.map +1 -0
- package/dist/chunk-S74N276K.js +35 -0
- package/dist/chunk-S74N276K.js.map +1 -0
- package/dist/{chunk-6PVFYFUE.js → chunk-X7UN6JAA.js} +2 -2
- package/dist/{chunk-6PVFYFUE.js.map → chunk-X7UN6JAA.js.map} +1 -1
- package/dist/cli.js +9 -155
- package/dist/cli.js.map +1 -1
- package/dist/heal-RDZZJXDZ.js +2 -0
- package/dist/index.d.ts +239 -8
- package/dist/index.js +85 -1
- package/dist/index.js.map +1 -1
- package/dist/loader-RL2LKXIF.js +2 -0
- package/dist/providers-Q3U3ONJO.js +2 -0
- package/dist/providers-Q3U3ONJO.js.map +1 -0
- package/package.json +3 -1
- package/dist/agent-AI6DUEPU.js +0 -2
- package/dist/chunk-FUYKPFUV.js +0 -46
- package/dist/chunk-FUYKPFUV.js.map +0 -1
- package/dist/chunk-NZ6W33BD.js +0 -116
- package/dist/chunk-NZ6W33BD.js.map +0 -1
- package/dist/chunk-THMHQELC.js +0 -106
- package/dist/chunk-THMHQELC.js.map +0 -1
- package/dist/heal-MJLBETRV.js +0 -2
- package/dist/loader-PHU6STSZ.js +0 -2
- package/dist/providers-MPYTYJVB.js +0 -2
- /package/dist/{agent-AI6DUEPU.js.map → agent-CRA5PU6S.js.map} +0 -0
- /package/dist/{heal-MJLBETRV.js.map → chunk-MDR7SH7F.js.map} +0 -0
- /package/dist/{loader-PHU6STSZ.js.map → heal-RDZZJXDZ.js.map} +0 -0
- /package/dist/{providers-MPYTYJVB.js.map → loader-RL2LKXIF.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.**
|
|
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
|
-
|
|
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
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
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
|
-
|
|
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
|
-
|
|
81
|
+
### Cron jobs
|
|
27
82
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
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
|
-
|
|
90
|
+
### Mesh (multi-machine)
|
|
41
91
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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
|
-
|
|
98
|
+
### Skills
|
|
49
99
|
|
|
50
100
|
```bash
|
|
51
|
-
|
|
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
|
-
|
|
54
|
-
cp node_modules/agentx-cli/agentx.example.json agentx.json
|
|
106
|
+
### Hooks
|
|
55
107
|
|
|
56
|
-
|
|
57
|
-
agentx
|
|
108
|
+
```bash
|
|
109
|
+
agentx hook add <agent> # Interactive: event, type (command/http), matcher
|
|
58
110
|
```
|
|
59
111
|
|
|
60
|
-
|
|
112
|
+
### Migration
|
|
61
113
|
|
|
62
114
|
```bash
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
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
|
-
|
|
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:
|
|
193
|
+
{ "url": "http://100.67.108.119:19900", "name": "server-2" }
|
|
129
194
|
]
|
|
130
195
|
}
|
|
131
196
|
}
|
|
132
197
|
```
|
|
133
198
|
|
|
134
|
-
|
|
199
|
+
## Agent workspace
|
|
135
200
|
|
|
136
|
-
Each agent
|
|
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,
|
|
206
|
+
│ ├── settings.json # Permissions, hooks, env vars
|
|
142
207
|
│ ├── .mcp.json # MCP servers
|
|
143
208
|
│ ├── agents/ # Subagents
|
|
144
|
-
│ └── skills/ #
|
|
145
|
-
├── CLAUDE.md # Agent identity
|
|
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
|
|
264
|
+
| `/agents` | GET | List agents |
|
|
157
265
|
| `/crons` | GET | List cron jobs |
|
|
158
266
|
| `/mesh` | GET | Mesh peer directory |
|
|
159
|
-
| `/task` | POST |
|
|
160
|
-
| `/mesh/task` | POST |
|
|
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
|
-
##
|
|
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
|
-
|
|
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
|
-
|
|
|
181
|
-
|
|
|
182
|
-
| `
|
|
183
|
-
| `exec-approvals.json` |
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
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-KVWUPUR5.js";import"./chunk-PCAYW54Q.js";import"./chunk-FRFR27IN.js";import"./chunk-SFQUP3BP.js";import"./chunk-MGMZNJCE.js";import"./chunk-M7HKBG3V.js";import"./chunk-MDR7SH7F.js";export{a as createAgentContext,b as generate,c as generateStream};
|
|
2
|
+
//# sourceMappingURL=agent-CRA5PU6S.js.map
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import{d as X,g as v,k as c}from"./chunk-PCAYW54Q.js";import{a as Ce,d as fe}from"./chunk-FRFR27IN.js";import{a as _e,b as Pe,c as ge}from"./chunk-SFQUP3BP.js";import{a as de,c as ue,g as me}from"./chunk-MGMZNJCE.js";import{a as F,b as ce,f as pe}from"./chunk-M7HKBG3V.js";import{z as R}from"zod";var Se=R.object({provider:R.enum(["claude-code","claude","openai","ollama","custom"]).default("claude-code"),model:R.string().optional(),apiKey:R.string().optional(),skills:R.array(R.string()).default([]),output:R.object({dir:R.string().default("./generated")}).default({}),context7:R.object({enabled:R.boolean().default(!0),apiKey:R.string().optional()}).default({}),agentic:R.object({maxIterations:R.number().default(20),enabledTools:R.array(R.string()).default(["create_files","ask_user","read_file","search_files","list_directory","run_command","edit_file"]),disabledTools:R.array(R.string()).default([])}).default({})}),pt=["component","page","api","website","document","script","config","skill","media","report","test","workflow","schema","email","diagram","auto"],dt={component:"UI component (any framework)",page:"Full page or screen",api:"API endpoint, route handler, or service",website:"Multi-page website or app",document:"Markdown, documentation, or specification",script:"Standalone script or utility",config:"Configuration file or setup",skill:"Agent skill (SKILL.md format for skills.sh)",media:"Media generation prompt (image/audio/video description)",report:"Analysis report or audit",test:"Test suite, test fixtures, or test data",workflow:"CI/CD pipeline, GitHub Actions, or automation",schema:"Database schema, Zod validators, or GraphQL types",email:"Email template (React Email, MJML, HTML)",diagram:"Mermaid, D2, or PlantUML diagram",auto:"Auto-detect the best output type"};import{existsSync as He,promises as Ke}from"fs";import q from"path";import Ye from"fast-glob";var Te={"prisma/schema.prisma":{type:"prisma",category:"database"},"drizzle/schema.ts":{type:"drizzle",category:"database"},"schema.graphql":{type:"graphql",category:"api"},"schema.gql":{type:"graphql",category:"api"},"openapi.yaml":{type:"openapi",category:"api"},"openapi.json":{type:"openapi",category:"api"},"swagger.yaml":{type:"openapi",category:"api"},"swagger.json":{type:"openapi",category:"api"}};async function Re(o){let e={},t=await Ye.glob("**/*",{cwd:o,deep:4,ignore:["**/node_modules/**","**/dist/**","**/build/**","**/.next/**","**/target/**","**/__pycache__/**","**/vendor/**","**/.git/**"],onlyFiles:!0});for(let[s,i]of Object.entries(Te)){let l=t.find(a=>a.endsWith(s)||a===s);if(l&&i.category==="database"){let a=await K(q.resolve(o,l));if(a){e.database={type:i.type,content:Z(a,3e3),tables:Je(a,i.type)};break}}}for(let[s,i]of Object.entries(Te)){let l=t.find(a=>a.endsWith(s)||a===s);if(l&&i.category==="api"){let a=await K(q.resolve(o,l));if(a){e.api={type:i.type,content:Z(a,3e3)};break}}}if(!e.api){let s=t.find(i=>i.includes("trpc")&&(i.endsWith("router.ts")||i.endsWith("router.js")));if(s){let i=await K(q.resolve(o,s));i&&(e.api={type:"trpc",content:Z(i,3e3)})}}let n=t.find(s=>s===".env.example"||s===".env.local.example"||s===".env.template");if(n){let s=await K(q.resolve(o,n));s&&(e.env=Qe(s))}let r=t.filter(s=>(s.includes("models")||s.includes("types")||s.includes("schemas"))&&(s.endsWith(".ts")||s.endsWith(".py")||s.endsWith(".rs")||s.endsWith(".go")));if(r.length){e.models=[];for(let s of r.slice(0,5)){let i=await K(q.resolve(o,s));i&&e.models.push({path:s,content:Z(i,2e3),type:q.extname(s).slice(1)})}}return e}function Je(o,e){if(e==="prisma"){let t=o.match(/model\s+(\w+)\s*\{/g);return t?t.map(n=>n.replace(/model\s+/,"").replace(/\s*\{/,"")):[]}return[]}function Qe(o){return{variables:o.split(`
|
|
2
|
+
`).filter(n=>n.trim()&&!n.trim().startsWith("#")).map(n=>{let[r]=n.split("="),s=r.trim(),i=n.includes("=")&&n.split("=")[1]?.trim().length>0;return{key:s,required:!i}})}}async function K(o){try{return He(o)?await Ke.readFile(o,"utf8"):null}catch{return null}}function Z(o,e){return o.length<=e?o:o.slice(0,e)+`
|
|
3
|
+
... (truncated)`}function Ae(o){let e=[];if(o.database&&e.push(`## Database Schema (${o.database.type})
|
|
4
|
+
`+(o.database.tables?.length?`Tables: ${o.database.tables.join(", ")}
|
|
5
|
+
`:"")+"```\n"+o.database.content+"\n```"),o.api&&e.push(`## API Schema (${o.api.type})
|
|
6
|
+
\`\`\`
|
|
7
|
+
`+o.api.content+"\n```"),o.env&&e.push(`## Environment Variables
|
|
8
|
+
`+o.env.variables.map(t=>`- ${t.key}${t.required?" (required)":""}`).join(`
|
|
9
|
+
`)),o.models?.length)for(let t of o.models)e.push(`## Model: ${t.path}
|
|
10
|
+
\`\`\``+t.type+`
|
|
11
|
+
`+t.content+"\n```");return e.join(`
|
|
12
|
+
|
|
13
|
+
`)}import Me from"node-fetch";var je="https://api.context7.com/v1";async function Ve(o,e){try{let t={"Content-Type":"application/json"};e&&(t.Authorization=`Bearer ${e}`);let n=await Me(`${je}/libraries/resolve`,{method:"POST",headers:t,body:JSON.stringify({name:o})});if(!n.ok)return null;let r=await n.json();return r?.libraries?.length?r.libraries[0]:null}catch{return null}}async function Xe(o,e,t=5e3,n){try{let r={"Content-Type":"application/json"};n&&(r.Authorization=`Bearer ${n}`);let s=await Me(`${je}/libraries/${encodeURIComponent(o)}/docs`,{method:"POST",headers:r,body:JSON.stringify({topic:e,maxTokens:t})});return s.ok&&(await s.json())?.content||null}catch{return null}}async function $e(o,e,t){let n=[];for(let i of o.frameworks.slice(0,3))n.push(i.name);let r=["react","vue","svelte","angular","next","nuxt","express","fastify","hono","prisma","drizzle-orm","tailwindcss","shadcn","@tanstack/react-query","zod","trpc"];for(let i of r)(o.dependencies[i]||o.devDependencies[i])&&(n.includes(i)||n.push(i));let s=[];for(let i of n.slice(0,5)){let l=await Ve(i,t);if(l){let a=await Xe(l.id,e,3e3,t);a&&s.push(`## ${l.name} Documentation
|
|
14
|
+
${a}`)}}return s.length?`# Relevant Library Documentation (via Context7)
|
|
15
|
+
|
|
16
|
+
${s.join(`
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
`)}`:""}var Ie={component:{type:"component",baseDir:"src/components",filePatterns:["*.tsx","*.vue","*.svelte","*.jsx","*.ts"],description:"UI component"},page:{type:"page",baseDir:"src/app",filePatterns:["*.tsx","*.vue","*.svelte","*.jsx","*.astro"],description:"Page or screen"},api:{type:"api",baseDir:"src/api",filePatterns:["*.ts","*.js","*.py","*.go","*.rs"],description:"API route or endpoint"},website:{type:"website",baseDir:".",filePatterns:["*"],description:"Multi-file website"},document:{type:"document",baseDir:"docs",filePatterns:["*.md","*.mdx","*.txt","*.rst"],description:"Documentation"},script:{type:"script",baseDir:"scripts",filePatterns:["*.ts","*.js","*.py","*.sh","*.go"],description:"Standalone script"},config:{type:"config",baseDir:".",filePatterns:["*.json","*.yaml","*.yml","*.toml","*.env"],description:"Configuration file"},skill:{type:"skill",baseDir:".skills",filePatterns:["SKILL.md"],description:"Agent skill (SKILL.md)"},media:{type:"media",baseDir:"media",filePatterns:["*.md","*.json","*.txt"],description:"Media generation prompt/description"},report:{type:"report",baseDir:"reports",filePatterns:["*.md","*.html","*.json"],description:"Analysis report"},test:{type:"test",baseDir:"src",filePatterns:["*.test.ts","*.test.tsx","*.spec.ts","*.test.js","*.test.py","*.test.go"],description:"Test suite or fixture"},workflow:{type:"workflow",baseDir:".github/workflows",filePatterns:["*.yml","*.yaml"],description:"CI/CD pipeline or automation"},schema:{type:"schema",baseDir:"src",filePatterns:["*.ts","*.prisma","*.graphql","*.gql","*.py"],description:"Database schema, validators, or types"},email:{type:"email",baseDir:"src/emails",filePatterns:["*.tsx","*.jsx","*.html","*.mjml"],description:"Email template"},diagram:{type:"diagram",baseDir:"docs",filePatterns:["*.md","*.mmd","*.d2","*.puml"],description:"Architecture or data diagram"}};function he(o,e){if(o&&o!=="auto")return o;let t=e.toLowerCase(),n=[[/\b(component|button|card|modal|dialog|form|input|dropdown|nav|sidebar|header|footer|widget|ui)\b/i,"component"],[/\b(page|screen|view|route|layout|dashboard|landing)\b/i,"page"],[/\b(api|endpoint|route handler|rest|graphql|webhook|middleware|server)\b/i,"api"],[/\b(website|site|web app|landing page|portfolio|blog)\b/i,"website"],[/\b(document|doc|readme|guide|tutorial|specification|spec|changelog)\b/i,"document"],[/\b(script|cli|command|tool|utility|migration|seed|cron)\b/i,"script"],[/\b(config|configuration|setup|env|settings)\b/i,"config"],[/\b(skill|agent skill|skill\.md)\b/i,"skill"],[/\b(video|audio|image|media|animation|thumbnail|podcast)\b/i,"media"],[/\b(report|audit|analysis|review|assessment|benchmark)\b/i,"report"],[/\b(test|spec|unit test|integration test|e2e|coverage|fixture|mock)\b/i,"test"],[/\b(workflow|ci|cd|pipeline|github action|deploy|automation|ci\/cd)\b/i,"workflow"],[/\b(schema|model|migration|prisma|drizzle|zod|validator|graphql type)\b/i,"schema"],[/\b(email|newsletter|transactional|invite|welcome email|notification email)\b/i,"email"],[/\b(diagram|erd|flowchart|architecture diagram|sequence diagram|mermaid|plantuml|d2)\b/i,"diagram"]];for(let[r,s]of n)if(r.test(t))return s;return"component"}import{existsSync as ot,promises as Ee}from"fs";import te from"path";import Ze from"prompts";import et from"chalk";import{z as D}from"zod";var Oe=["default","acceptEdits","plan","yolo"],Ue=D.enum(Oe),ye=D.object({mode:Ue.default("default"),allow:D.array(D.string()).default([]),deny:D.array(D.string()).default([]),confirm:D.array(D.string()).default([])});function tt(o,e){let t=e.replace(/\./g,"\\.").replace(/\*\*/g,"{{GLOBSTAR}}").replace(/\*/g,"[^/]*").replace(/\{\{GLOBSTAR\}\}/g,".*").replace(/\?/g,"[^/]");return new RegExp(`^${t}$`).test(o)}var ee=class{mode;allowPatterns;denyPatterns;confirmPatterns;autoAllowAll=!1;constructor(e){let t=ye.parse(e||{});this.mode=t.mode,this.allowPatterns=t.allow,this.denyPatterns=t.deny,this.confirmPatterns=t.confirm}getMode(){return this.mode}setMode(e){this.mode=e,this.autoAllowAll=!1,v.context("permissions",`mode set to ${e}`)}async checkFileWrite(e){if(v.context("permissions",`checking write: ${e} (mode: ${this.mode})`),this.matchesAny(e,this.denyPatterns))return v.context("permissions",`denied by pattern: ${e}`),"deny";switch(this.mode){case"yolo":return"allow";case"plan":return"skip";case"acceptEdits":return"allow";case"default":return this.autoAllowAll||this.matchesAny(e,this.allowPatterns)?"allow":this.promptUser(e);default:return"allow"}}async checkCommand(e){return this.mode==="yolo"?"allow":this.mode==="plan"?"deny":"allow"}matchesAny(e,t){return t.some(n=>tt(e,n))}async promptUser(e){let{action:t}=await Ze({type:"select",name:"action",message:`Write file ${et.cyan(e)}?`,choices:[{title:"Yes",value:"allow"},{title:"No",value:"deny"},{title:"All (allow remaining)",value:"all"},{title:"Skip",value:"skip"}],initial:0});return t==="all"?(this.autoAllowAll=!0,"allow"):t||"deny"}},N=new ee;async function oe(o,e){let t={written:[],skipped:[],errors:[]};for(let n of o){let r=te.isAbsolute(n.path)?n.path:te.resolve(e.cwd,e.outputDir||"",n.path);try{let s=n.content;if(c.has("pre:file-write")){let x=await c.execute("pre:file-write",{event:"pre:file-write",file:r,fileContent:s,cwd:e.cwd});if(x.blocked){t.skipped.push(r);continue}x.modified?.fileContent&&(s=String(x.modified.fileContent))}let i=te.relative(e.cwd,r),l=await N.checkFileWrite(i);if(l==="deny"){t.skipped.push(r);continue}if(l==="skip"){t.written.push(r);continue}if(ot(r)&&!e.overwrite){t.skipped.push(r);continue}if(e.dryRun){t.written.push(r);continue}let a=te.dirname(r);await Ee.mkdir(a,{recursive:!0}),await Ee.writeFile(r,s,"utf8"),t.written.push(r),c.has("post:file-write")&&await c.execute("post:file-write",{event:"post:file-write",file:r,fileContent:s,cwd:e.cwd})}catch(s){t.errors.push(`${r}: ${s.message}`)}}return t}function ne(o,e,t){if(t)return t;let n=Ie[o];if(!n)return"generated";let r=n.baseDir;return o==="component"&&(e.srcDir?r=`${e.srcDir}/components`:r="components"),o==="page"&&e.frameworks.find(i=>i.name==="nextjs")&&e.srcDir&&(r=`${e.srcDir}/app`),o==="api"&&e.frameworks.find(i=>i.name==="nextjs")&&(r=e.srcDir?`${e.srcDir}/app/api`:"app/api"),o==="test"&&(e.testing.includes("vitest")||e.testing.includes("jest"))&&(r=e.srcDir||"src"),o==="workflow"&&(r=".github/workflows"),o==="schema"&&(e.databases.includes("prisma")?r="prisma":e.srcDir&&(r=`${e.srcDir}/schemas`)),o==="email"&&(r=e.srcDir?`${e.srcDir}/emails`:"emails"),r}import nt from"os";var rt=nt.homedir(),Y=class{constructor(e){this.cwd=e;this.userMemory=new ge(rt),this.projectMemory=new ge(e)}userMemory;projectMemory;async load(){await Promise.all([this.userMemory.load(),this.projectMemory.load()])}async save(){await Promise.all([this.userMemory.save(),this.projectMemory.save()])}buildMemoryContext(e){let t=this.userMemory.buildMemoryContext(e),n=this.projectMemory.buildMemoryContext(e);if(!t&&!n)return"";let r=[];return n&&r.push(n),t&&r.push(t.replace("# Memory (learned from past interactions)","# Global Memory (cross-project patterns)")),r.join(`
|
|
21
|
+
|
|
22
|
+
`)}async learnPreference(e,t,n){await this.userMemory.learnPreference(e,t,n)}async recordGeneration(e){return this.projectMemory.recordGeneration(e)}getPreferences(){let e=this.userMemory.getPreferences(),t=this.projectMemory.getPreferences(),n=new Map;for(let r of e)n.set(r.key,r);for(let r of t)n.set(r.key,r);return Array.from(n.values())}getPatterns(){let e=this.userMemory.getPatterns();return[...this.projectMemory.getPatterns(),...e]}getStats(){return{user:this.userMemory.getStats(),project:this.projectMemory.getStats()}}getRecentGenerations(e=10){return this.projectMemory.getRecentGenerations(e)}};import{existsSync as De,readFileSync as Ge}from"fs";import Fe from"path";function Ne(o,e){return o.replace(/@([\w./-]+)/g,(t,n)=>{let r=Fe.resolve(e,n);if(De(r))try{return Ge(r,"utf8")}catch{return t}return t})}function be(o){let e=["SHADXN.md","CLAUDE.md"];for(let t of e){let n=Fe.join(o,t);if(De(n))try{let r=Ge(n,"utf8");return r=Ne(r,o),r}catch{}}return""}function st(o){return Math.ceil(o.length/4)}function it(o,e){let t=new Set(e.toLowerCase().split(/\s+/).filter(s=>s.length>3));if(t.size===0)return 0;let n=new Set(o.toLowerCase().split(/\s+/).filter(s=>s.length>3)),r=0;for(let s of t)n.has(s)&&r++;return r/t.size}var we=class{sections=[];addSection(e,t,n=50){t.trim()&&this.sections.push({label:e,content:t,priority:n})}buildContext(e,t=12e3){if(this.sections.length===0)return"";let n=this.sections.map(i=>({...i,relevance:it(i.content,e),tokens:st(i.content)}));n.sort((i,l)=>l.priority+l.relevance*100-(i.priority+i.relevance*100));let r=[],s=0;for(let i of n)s+i.tokens>t&&r.length>0||(r.push(i),s+=i.tokens);return r.map(i=>i.content).join(`
|
|
23
|
+
|
|
24
|
+
`)}};import{promises as J}from"fs";import re from"path";import{execa as at}from"execa";import Le from"fast-glob";var Q=class{cwd;options;constructor(e,t={}){this.cwd=e,this.options=t}async execute(e){if(v.context("tool-executor",`executing: ${e.name}`),c.has("pre:tool-call")){let n=await c.execute("pre:tool-call",{event:"pre:tool-call",toolName:e.name,toolInput:e.input,cwd:this.cwd});if(n.blocked)return{tool_use_id:e.id,content:n.message||`Tool ${e.name} blocked by pre:tool-call hook`,is_error:!0}}let t;try{switch(e.name){case"read_file":t=await this.readFile(e);break;case"search_files":t=await this.searchFiles(e);break;case"list_directory":t=await this.listDirectory(e);break;case"run_command":t=await this.runCommand(e);break;case"edit_file":t=await this.editFile(e);break;case"create_files":t=await this.createFiles(e);break;case"ask_user":t=await this.askUser(e);break;default:t={tool_use_id:e.id,content:`Unknown tool: ${e.name}`,is_error:!0}}}catch(n){t={tool_use_id:e.id,content:`Error executing ${e.name}: ${n.message}`,is_error:!0}}return c.has("post:tool-call")&&await c.execute("post:tool-call",{event:"post:tool-call",toolName:e.name,toolInput:e.input,toolResult:t.content,cwd:this.cwd}),t}async readFile(e){let t=String(e.input.path||""),n=Number(e.input.max_lines)||500,r=re.resolve(this.cwd,t),s=await J.readFile(r,"utf8"),i=s.split(`
|
|
25
|
+
`),a=i.length>n?i.slice(0,n).join(`
|
|
26
|
+
`)+`
|
|
27
|
+
|
|
28
|
+
... (truncated, ${i.length-n} more lines)`:s;return{tool_use_id:e.id,content:a}}async searchFiles(e){let t=String(e.input.pattern||"**/*"),n=e.input.content_regex?String(e.input.content_regex):void 0,r=Number(e.input.max_results)||50,s=await Le(t,{cwd:this.cwd,ignore:["node_modules/**",".git/**","dist/**",".next/**"],dot:!1});if(!n){let a=s.slice(0,r);return{tool_use_id:e.id,content:a.length?a.join(`
|
|
29
|
+
`)+(s.length>r?`
|
|
30
|
+
|
|
31
|
+
... (${s.length-r} more files)`:""):"No files matched the pattern."}}let i=new RegExp(n,"gm"),l=[];for(let a of s){if(l.length>=r)break;try{let p=(await J.readFile(re.resolve(this.cwd,a),"utf8")).split(`
|
|
32
|
+
`);for(let g=0;g<p.length&&!(l.length>=r);g++)i.test(p[g])&&l.push(`${a}:${g+1}: ${p[g]}`),i.lastIndex=0}catch{}}return{tool_use_id:e.id,content:l.length?l.join(`
|
|
33
|
+
`):"No matches found."}}async listDirectory(e){let t=String(e.input.path||"."),n=!!e.input.recursive,r=Number(e.input.max_depth)||3,s=re.resolve(this.cwd,t);if(n){let x=await Le("**/*",{cwd:s,onlyFiles:!1,markDirectories:!0,deep:r,ignore:["node_modules/**",".git/**","dist/**",".next/**"]});return{tool_use_id:e.id,content:x.length?x.join(`
|
|
34
|
+
`):"Empty directory."}}let l=(await J.readdir(s,{withFileTypes:!0})).map(a=>a.isDirectory()?`${a.name}/`:a.name);return{tool_use_id:e.id,content:l.length?l.join(`
|
|
35
|
+
`):"Empty directory."}}async runCommand(e){let t=String(e.input.command||""),n=Number(e.input.timeout)||3e4;if(await N.checkCommand(t)==="deny")return{tool_use_id:e.id,content:`Command blocked by permissions (mode: ${N.getMode()}): ${t}`,is_error:!0};if(c.has("pre:command")){let a=await c.execute("pre:command",{event:"pre:command",command:t,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`Command blocked by pre:command hook: ${t}`,is_error:!0}}let s=await at("sh",["-c",t],{cwd:this.cwd,timeout:n,reject:!1,stdin:"ignore"}),i=[s.stdout,s.stderr].filter(Boolean).join(`
|
|
36
|
+
`),l=i.length>1e4?i.slice(0,1e4)+`
|
|
37
|
+
|
|
38
|
+
... (output truncated)`:i;return s.exitCode!==0?{tool_use_id:e.id,content:`Command exited with code ${s.exitCode}:
|
|
39
|
+
${l}`,is_error:!0}:{tool_use_id:e.id,content:l||"(no output)"}}async editFile(e){let t=String(e.input.path||""),n=e.input.edits,r=re.resolve(this.cwd,t);if(!n||n.length===0)return{tool_use_id:e.id,content:"No edits provided.",is_error:!0};let s=await N.checkFileWrite(t);if(s==="deny")return{tool_use_id:e.id,content:`File write blocked by permissions: ${t}`,is_error:!0};if(s==="skip")return{tool_use_id:e.id,content:`File write skipped (plan mode): ${t}`};if(c.has("pre:file-write")){let a=await c.execute("pre:file-write",{event:"pre:file-write",file:r,cwd:this.cwd});if(a.blocked)return{tool_use_id:e.id,content:a.message||`File edit blocked by pre:file-write hook: ${t}`,is_error:!0}}let i=await J.readFile(r,"utf8"),l=[];for(let a of n)i.includes(a.old_text)?(i=i.replace(a.old_text,a.new_text),l.push(`Replaced: "${a.old_text.slice(0,40)}..."`)):l.push(`Not found: "${a.old_text.slice(0,40)}..."`);return this.options.dryRun||await J.writeFile(r,i,"utf8"),c.has("post:file-write")&&await c.execute("post:file-write",{event:"post:file-write",file:r,fileContent:i,cwd:this.cwd}),{tool_use_id:e.id,content:`Edited ${t}:
|
|
40
|
+
${l.join(`
|
|
41
|
+
`)}`}}async createFiles(e){let t=e.input,n=t.files||[];return{tool_use_id:e.id,content:t.summary||`Queued ${n.length} file(s) for creation.`,files:n}}async askUser(e){let t=String(e.input.question||""),n=e.input.options,r=t;return n?.length&&(r+=`
|
|
42
|
+
Options: ${n.join(", ")}`),{tool_use_id:e.id,content:"Question sent to user.",followUp:r}}};async function xe(o){let{provider:e,systemPrompt:t,messages:n,providerOptions:r,cwd:s,maxIterations:i=20,enabledTools:l,interactive:a=!0,overwrite:x=!1,dryRun:p=!1,onProgress:g}=o;if(!e.generateRaw)return We(o);let b=new Q(s,{interactive:a,overwrite:x,dryRun:p}),w=de(l),$=n.filter(k=>k.role!=="system").map(k=>({role:k.role,content:k.content})),G=[],C=0,S="",O,M=0;for(;M<i;){M++,g?.({type:"iteration_start",iteration:M}),v.step(M,`Agentic loop iteration (${w.length} tools available)`);let k;try{k=await e.generateRaw($,t,w,r)}catch(h){if(h.message?.includes("not available"))return We(o);throw h}C+=k.usage.input_tokens+k.usage.output_tokens;for(let h of k.content)h.type==="text"&&(S+=h.text,g?.({type:"text_delta",text:h.text}));if(k.stop_reason==="end_turn"||k.stop_reason==="max_tokens")break;if(k.stop_reason==="tool_use"){let h=k.content.filter(_=>_.type==="tool_use");if(h.length===0)break;$.push({role:"assistant",content:k.content});let j=[];for(let _ of h){g?.({type:"tool_call",name:_.name,id:_.id,input:_.input}),v.step(M,`Tool call: ${_.name}`);let y=await b.execute({name:_.name,id:_.id,input:_.input});g?.({type:"tool_result",name:_.name,id:_.id,content:y.content.slice(0,200),is_error:y.is_error}),y.files?.length&&(G.push(...y.files),g?.({type:"files_created",files:y.files})),y.followUp&&(O=y.followUp),j.push({type:"tool_result",tool_use_id:y.tool_use_id,content:y.content,is_error:y.is_error})}if($.push({role:"user",content:j}),O)break;continue}break}return g?.({type:"complete",iterations:M,totalTokens:C}),{files:G,content:S,followUp:O,tokensUsed:C,iterations:M}}async function We(o){let{provider:e,systemPrompt:t,messages:n,providerOptions:r,maxIterations:s=5}=o,l=[{role:"system",content:t+`
|
|
43
|
+
|
|
44
|
+
`+ue()},...n.filter(w=>w.role!=="system")],a=[],x=0,p="",g,b=0;for(;b<s;){b++,v.step(b,`Legacy loop step (model: ${r.model||"default"})`);let w=await e.generate(l,r);if(x+=w.tokensUsed||0,p=w.content,w.files.length&&a.push(...w.files),w.followUp){g=w.followUp;break}if(w.files.length===0&&b>1||!(w.content.includes("[CONTINUE]")||w.content.includes("Next, I'll")||w.content.includes("Now let me")||w.content.includes("I'll also generate")))break;let G=w.files.map(C=>`Created: ${C.path}${C.description?` \u2014 ${C.description}`:""}`).join(`
|
|
45
|
+
`);l.push({role:"assistant",content:w.content+(G?`
|
|
46
|
+
|
|
47
|
+
Files created:
|
|
48
|
+
${G}`:"")}),l.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."})}return{files:a,content:p,followUp:g,tokensUsed:x,iterations:b}}function ke(o){return typeof o.generateRaw=="function"}var se=class{queue=[];resolvers=[];closed=!1;push(e){if(this.closed)return;let t=this.resolvers.shift();if(t){t({value:e,done:!1});return}this.queue.push(e)}close(){if(!this.closed){this.closed=!0;for(let e of this.resolvers.splice(0))e({value:void 0,done:!0})}}async next(){return this.queue.length?{value:this.queue.shift(),done:!1}:this.closed?{value:void 0,done:!0}:new Promise(e=>{this.resolvers.push(e)})}async*[Symbol.asyncIterator](){for(;;){let{value:e,done:t}=await this.next();if(t)return;yield e}}};async function qe(o,e,t){let n=Se.parse(t||{}),r=new Y(o);await r.load();let[s,i,l]=await Promise.all([_e(o),Re(o),Ce(o)]),a="";if(n.context7.enabled)try{a=await $e(s,e,n.context7.apiKey)}catch{}let x=r.buildMemoryContext(e),p=be(o);return v.context("memory",x?"loaded":"empty"),v.context("instructions",p?"loaded from project":"none"),{techStack:s,schemas:i,skills:l,docs:a,config:n,memoryContext:x,projectInstructions:p}}async function Ro(o){let{task:e,cwd:t,overwrite:n=!1,dryRun:r=!1,provider:s="claude-code",model:i,apiKey:l,context7:a=!0,interactive:x=!0}=o,p=e;if(c.has("pre:prompt")){let u=await c.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(u.blocked)throw new Error(u.message||"Blocked by pre:prompt hook");u.modified?.task&&(p=String(u.modified.task))}if(c.has("pre:generate")){let u=await c.execute("pre:generate",{event:"pre:generate",task:p,cwd:t});if(u.blocked)throw new Error(u.message||"Blocked by pre:generate hook")}F.info("Analyzing project...");let g=await qe(t,p,{provider:s,context7:{enabled:a,apiKey:l}}),b=he(o.outputType,p);F.info(`Output type: ${b}`);let w=fe(g.skills,p,b);w.length&&F.info(`Loaded ${w.length} relevant skill(s): ${w.map(u=>u.skill.frontmatter.name).join(", ")}`);let $=Be(g,b,w.map(u=>u.skill));if(!await pe(l))throw new Error("No credentials configured. Run `agentx model` to set up.");let C=me(s,l),S=i||ce()?.model,O=[...o.sessionMessages||[],{role:"user",content:p}];F.info("Generating...");let M=ke(C),k=o.maxSteps??(M?20:5),h=await xe({provider:C,systemPrompt:$,messages:[{role:"system",content:$},...O],providerOptions:{model:S,maxTokens:8192},cwd:t,maxIterations:k,enabledTools:g.config.agentic.enabledTools.filter(u=>!g.config.agentic.disabledTools.includes(u)),interactive:x,overwrite:n,dryRun:r,onProgress:u=>{u.type==="iteration_start"&&u.iteration>1&&F.info(`Step ${u.iteration}/${k}...`),u.type==="tool_call"&&v.step(0,`Tool: ${u.name}`)}});if(h.tokensUsed){let u=S||"claude-sonnet-4-20250514",L=Math.round(h.tokensUsed*.3),ie=h.tokensUsed-L;X.recordStep(1,u,L,ie)}let{content:j}=h,{followUp:_,tokensUsed:y}=h;if(h.iterations>1&&F.info(`Completed in ${h.iterations} step(s)`),c.has("post:response")){let u=await c.execute("post:response",{event:"post:response",content:j,task:p,cwd:t});if(u.blocked)throw new Error(u.message||"Blocked by post:response hook");u.modified?.content&&(j=String(u.modified.content))}if(_&&x)return{files:{written:[],skipped:[],errors:[]},content:j,outputType:b,followUp:_,tokensUsed:y};let U=new Map;for(let u of h.files)U.set(u.path,u);let A=ne(b,g.techStack,o.outputDir),T=await oe(Array.from(U.values()),{cwd:t,overwrite:n,dryRun:r,outputDir:A}),I;if(o.heal!==!1&&!r&&T.written.length>0){let{HealEngine:u}=await import("./heal-RDZZJXDZ.js");I=await new u(t,{enabled:!0,testCommand:o.healConfig?.testCommand,buildCommand:o.healConfig?.buildCommand,lintCommand:o.healConfig?.lintCommand,maxAttempts:o.healConfig?.maxAttempts??3,provider:s,model:S,apiKey:l}).detectAndHeal(T.written,p),!I.healed&&I.error&&await c.execute("on:error",{event:"on:error",error:new Error(I.error),task:p,cwd:t})}return c.has("post:generate")&&await c.execute("post:generate",{event:"post:generate",task:p,content:j,cwd:t}),{files:T,content:j,outputType:b,tokensUsed:y,healResult:I}}async function*Ao(o){let{task:e,cwd:t,overwrite:n=!1,dryRun:r=!1,provider:s="claude-code",model:i,apiKey:l,context7:a=!0,interactive:x=!0}=o,p=e;if(c.has("pre:prompt")){let d=await c.execute("pre:prompt",{event:"pre:prompt",task:e,cwd:t});if(d.blocked){yield{type:"error",error:d.message||"Blocked by pre:prompt hook"};return}d.modified?.task&&(p=String(d.modified.task))}if(c.has("pre:generate")){let d=await c.execute("pre:generate",{event:"pre:generate",task:p,cwd:t});if(d.blocked){yield{type:"error",error:d.message||"Blocked by pre:generate hook"};return}}let g=await qe(t,p,{provider:s,context7:{enabled:a,apiKey:l}}),b=he(o.outputType,p);yield{type:"context_ready",outputType:b};let w=fe(g.skills,p,b),$=Be(g,b,w.map(d=>d.skill));if(!await pe(l)){yield{type:"error",error:"No credentials configured. Run `agentx model` to set up."};return}let C=me(s,l),S=i||ce()?.model,O=ke(C),M=o.maxSteps??(O?20:5),k=[...o.sessionMessages||[],{role:"user",content:p}];if(O){let d=new se,P,f,W=(async()=>{try{P=await xe({provider:C,systemPrompt:$,messages:[{role:"system",content:$},...k],providerOptions:{model:S,maxTokens:8192},cwd:t,maxIterations:M,enabledTools:g.config.agentic.enabledTools.filter(m=>!g.config.agentic.disabledTools.includes(m)),interactive:x,overwrite:n,dryRun:r,onProgress:m=>{m.type==="text_delta"&&d.push({type:"text_delta",text:m.text}),m.type==="iteration_start"&&d.push({type:"iteration",iteration:m.iteration}),m.type==="tool_call"&&d.push({type:"tool_call",name:m.name,id:m.id}),m.type==="tool_result"&&d.push({type:"tool_result",name:m.name,id:m.id,is_error:m.is_error}),m.type==="files_created"&&d.push({type:"step_complete",step:0,filesCount:m.files.length})}})}catch(m){f=m}finally{d.close()}})();for await(let m of d)yield m;if(await W,f){yield{type:"error",error:f instanceof Error?f.message:String(f)};return}if(!P){yield{type:"error",error:"Agentic loop failed without a result"};return}yield{type:"done",result:{content:P.content,files:P.files,tokensUsed:P.tokensUsed,followUp:P.followUp}};let{content:E}=P;if(c.has("post:response")){let m=await c.execute("post:response",{event:"post:response",content:E,task:p,cwd:t});if(m.blocked){yield{type:"error",error:m.message||"Blocked by post:response hook"};return}m.modified?.content&&(E=String(m.modified.content))}if(P.followUp&&x){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:E,outputType:b,followUp:P.followUp,tokensUsed:P.tokensUsed}};return}let z=new Map;for(let m of P.files)z.set(m.path,m);let le=ne(b,g.techStack,o.outputDir),V=await oe(Array.from(z.values()),{cwd:t,overwrite:n,dryRun:r,outputDir:le}),H;if(o.heal!==!1&&!r&&V.written.length>0){let{HealEngine:m}=await import("./heal-RDZZJXDZ.js");H=await new m(t,{enabled:!0,testCommand:o.healConfig?.testCommand,buildCommand:o.healConfig?.buildCommand,lintCommand:o.healConfig?.lintCommand,maxAttempts:o.healConfig?.maxAttempts??3,provider:s,model:S,apiKey:l}).detectAndHeal(V.written,p)}c.has("post:generate")&&await c.execute("post:generate",{event:"post:generate",task:p,content:E,cwd:t}),yield{type:"generate_result",result:{files:V,content:E,outputType:b,tokensUsed:P.tokensUsed,healResult:H}};return}let h=[{role:"system",content:$},...k],j=[],_=0,y="",U,A=0;A++,v.step(A,`Starting generation (model: ${S||"default"})`);let T;if(C.stream){let d="",P;for await(let f of C.stream(h,{model:S,maxTokens:8192}))yield f,f.type==="text_delta"&&(d+=f.text),f.type==="done"&&(P=f.result);T=P||{content:d,files:[],tokensUsed:0}}else{let d=await C.generate(h,{model:S,maxTokens:8192});d.content&&(yield{type:"text_delta",text:d.content}),yield{type:"done",result:d},T=d}_+=T.tokensUsed||0,y=T.content;let I=T.tokensUsed||0,u=S||"claude-sonnet-4-20250514",L=Math.round(I*.3),ie=I-L;if(X.recordStep(A,u,L,ie),v.api("generate",u,I),v.step(A,`Generated ${T.files.length} file(s), ${I} tokens`),T.files.length&&j.push(...T.files),T.followUp&&(U=T.followUp),yield{type:"step_complete",step:A,filesCount:T.files.length},!U&&(y.includes("[CONTINUE]")||y.includes("Next, I'll")||y.includes("Now let me")||y.includes("I'll also generate"))&&T.files.length>0){let P=T.files.map(f=>`Created: ${f.path}${f.description?` \u2014 ${f.description}`:""}`).join(`
|
|
49
|
+
`);for(h.push({role:"assistant",content:y+(P?`
|
|
50
|
+
|
|
51
|
+
Files created:
|
|
52
|
+
${P}`:"")}),h.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."});A<M;){A++,v.step(A,`Starting generation (model: ${S||"default"})`);let f=await C.generate(h,{model:S,maxTokens:8192});_+=f.tokensUsed||0,y=f.content;let W=f.tokensUsed||0,E=S||"claude-sonnet-4-20250514",z=Math.round(W*.3),le=W-z;if(X.recordStep(A,E,z,le),v.api("generate",E,W),v.step(A,`Generated ${f.files.length} file(s), ${W} tokens`),f.files.length&&j.push(...f.files),yield{type:"step_complete",step:A,filesCount:f.files.length},f.followUp){U=f.followUp;break}if(f.files.length===0&&A>1||!(f.content.includes("[CONTINUE]")||f.content.includes("Next, I'll")||f.content.includes("Now let me")||f.content.includes("I'll also generate")))break;let H=f.files.map(m=>`Created: ${m.path}${m.description?` \u2014 ${m.description}`:""}`).join(`
|
|
53
|
+
`);h.push({role:"assistant",content:f.content+(H?`
|
|
54
|
+
|
|
55
|
+
Files created:
|
|
56
|
+
${H}`:"")}),h.push({role:"user",content:"Continue generating the remaining files. Build on what you've already created. When finished, do not include [CONTINUE] in your response."})}}if(c.has("post:response")){let d=await c.execute("post:response",{event:"post:response",content:y,task:p,cwd:t});if(d.blocked){yield{type:"error",error:d.message||"Blocked by post:response hook"};return}d.modified?.content&&(y=String(d.modified.content))}if(U&&x){yield{type:"generate_result",result:{files:{written:[],skipped:[],errors:[]},content:y,outputType:b,followUp:U,tokensUsed:_}};return}let ve=new Map;for(let d of j)ve.set(d.path,d);let ze=ne(b,g.techStack,o.outputDir),ae=await oe(Array.from(ve.values()),{cwd:t,overwrite:n,dryRun:r,outputDir:ze}),B;if(o.heal!==!1&&!r&&ae.written.length>0){let{HealEngine:d}=await import("./heal-RDZZJXDZ.js");B=await new d(t,{enabled:!0,testCommand:o.healConfig?.testCommand,buildCommand:o.healConfig?.buildCommand,lintCommand:o.healConfig?.lintCommand,maxAttempts:o.healConfig?.maxAttempts??3,provider:s,model:S,apiKey:l}).detectAndHeal(ae.written,p),!B.healed&&B.error&&await c.execute("on:error",{event:"on:error",error:new Error(B.error),task:p,cwd:t})}c.has("post:generate")&&await c.execute("post:generate",{event:"post:generate",task:p,content:y,cwd:t}),yield{type:"generate_result",result:{files:ae,content:y,outputType:b,tokensUsed:_,healResult:B}}}function Be(o,e,t){let n=[];n.push(`You are agentx, an agentic code generation tool. You generate high-quality, production-ready output for any tech stack.
|
|
57
|
+
|
|
58
|
+
Your primary tool is \`create_files\` \u2014 use it to output all generated code, documents, and configs as files.
|
|
59
|
+
If the request is ambiguous or you need critical information to proceed correctly, use \`ask_user\` to ask a clarifying question.
|
|
60
|
+
|
|
61
|
+
You also have tools to inspect the codebase before generating code:
|
|
62
|
+
- \`read_file\` \u2014 read existing files to understand patterns, styles, and implementations
|
|
63
|
+
- \`search_files\` \u2014 search for files by glob pattern, optionally grep content with regex
|
|
64
|
+
- \`list_directory\` \u2014 explore the project structure
|
|
65
|
+
- \`run_command\` \u2014 run shell commands (build, test, lint, etc.)
|
|
66
|
+
- \`edit_file\` \u2014 apply targeted search/replace edits to existing files
|
|
67
|
+
|
|
68
|
+
AGENTIC WORKFLOW:
|
|
69
|
+
- Before generating code, use \`read_file\` and \`search_files\` to understand the existing codebase
|
|
70
|
+
- Match the project's existing patterns, naming conventions, and code style
|
|
71
|
+
- After creating files, consider running tests or build commands to verify correctness
|
|
72
|
+
- Use \`edit_file\` for small, targeted changes instead of rewriting entire files
|
|
73
|
+
|
|
74
|
+
IMPORTANT RULES:
|
|
75
|
+
- Generate complete, working code \u2014 not stubs or placeholders
|
|
76
|
+
- Follow the project's existing patterns and conventions
|
|
77
|
+
- Use the detected tech stack to choose the right language, framework, and patterns
|
|
78
|
+
- File paths should be relative to the project root
|
|
79
|
+
- Include all necessary imports
|
|
80
|
+
- Do NOT add unnecessary dependencies
|
|
81
|
+
|
|
82
|
+
MULTI-STEP GENERATION:
|
|
83
|
+
For complex tasks that require multiple related files (e.g., schema + API + UI + tests), you can chain steps:
|
|
84
|
+
- Generate the foundational files first (schemas, types, configs)
|
|
85
|
+
- Include "[CONTINUE]" in your response text when there are more files to generate
|
|
86
|
+
- In subsequent steps, you'll see what was already created \u2014 build on it
|
|
87
|
+
- When all files are generated, do NOT include "[CONTINUE]"
|
|
88
|
+
- This enables you to generate a schema first, then an API that references it, then a UI that calls the API`),n.push(`# Project Tech Stack
|
|
89
|
+
${Pe(o.techStack)}`);let r=Object.keys(o.techStack.dependencies).slice(0,30);r.length&&n.push(`# Key Dependencies
|
|
90
|
+
${r.join(", ")}`);let s=Ae(o.schemas);return s&&n.push(`# Project Schemas
|
|
91
|
+
${s}`),t.length&&n.push(`# Active Skills
|
|
92
|
+
Follow these skill instructions when applicable:
|
|
93
|
+
|
|
94
|
+
`+t.map(i=>`## Skill: ${i.frontmatter.name}
|
|
95
|
+
${i.frontmatter.description}
|
|
96
|
+
|
|
97
|
+
${i.instructions}`).join(`
|
|
98
|
+
|
|
99
|
+
---
|
|
100
|
+
|
|
101
|
+
`)),o.docs&&n.push(o.docs),o.projectInstructions&&n.push(`# Project Instructions
|
|
102
|
+
${o.projectInstructions}`),o.memoryContext&&n.push(o.memoryContext),n.push(`# Output Type: ${e}
|
|
103
|
+
Generate output appropriate for: ${e}. Use the \`create_files\` tool to output all files.`),n.join(`
|
|
104
|
+
|
|
105
|
+
`)}export{Se as a,pt as b,dt as c,Re as d,Ae as e,$e as f,Ie as g,he as h,Oe as i,Ue as j,ye as k,ee as l,N as m,Y as n,Ne as o,be as p,we as q,Q as r,qe as s,Ro as t,Ao as u};
|
|
106
|
+
//# sourceMappingURL=chunk-KVWUPUR5.js.map
|