-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
351 lines (255 loc) · 10 KB
/
server.py
File metadata and controls
351 lines (255 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#!/usr/bin/env python3
"""
Agent Builder - Web UI for creating Claude Code agents
Uses claude --print opus to generate agent prompts
"""
import os
import json
import subprocess
import re
from pathlib import Path
from typing import Optional
from fastapi import FastAPI, HTTPException, Request
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from pydantic import BaseModel, Field
import yaml
app = FastAPI(title="Agent Builder", version="1.0.0")
# Paths
AGENTS_DIR = Path.home() / ".claude" / "agents"
HOOKS_DIR = Path.home() / ".claude" / "hooks" / "validators"
SETTINGS_FILE = Path.home() / ".claude" / "settings.json"
# Templates and static files
BASE_DIR = Path(__file__).parent
app.mount("/static", StaticFiles(directory=BASE_DIR / "static"), name="static")
templates = Jinja2Templates(directory=BASE_DIR / "templates")
# Available tools for agents
AVAILABLE_TOOLS = [
"Bash", "Read", "Write", "Edit", "Glob", "Grep",
"Task", "WebSearch", "WebFetch", "NotebookEdit",
"AskUserQuestion", "EnterPlanMode", "ExitPlanMode"
]
# Available models
AVAILABLE_MODELS = ["haiku", "sonnet", "opus", "inherit"]
# Available colors
AVAILABLE_COLORS = [
"blue", "green", "purple", "orange", "cyan", "red", "yellow", "pink"
]
# Hook event types
HOOK_EVENTS = ["PreToolUse", "PostToolUse", "Stop"]
class AgentConfig(BaseModel):
"""Agent configuration model"""
name: str = Field(..., pattern=r"^[a-z][a-z0-9-]*$")
description: str
tools: list[str] = []
disallowedTools: list[str] = []
model: str = "haiku"
color: Optional[str] = None
permissionMode: Optional[str] = None
skills: list[str] = []
prompt: str = ""
hooks: Optional[dict] = None
class GeneratePromptRequest(BaseModel):
"""Request to generate agent prompt using Claude"""
name: str
description: str
tools: list[str]
context: Optional[str] = None
class HookConfig(BaseModel):
"""Hook configuration for an agent"""
event: str # PreToolUse, PostToolUse, Stop
matcher: str # Tool name or pattern
command: str # Command to run
def parse_agent_file(filepath: Path) -> Optional[dict]:
"""Parse an agent markdown file with YAML frontmatter"""
try:
content = filepath.read_text()
# Extract YAML frontmatter
match = re.match(r'^---\n(.*?)\n---\n(.*)$', content, re.DOTALL)
if not match:
return None
frontmatter = yaml.safe_load(match.group(1))
prompt = match.group(2).strip()
return {
**frontmatter,
"prompt": prompt,
"filepath": str(filepath)
}
except Exception as e:
print(f"Error parsing {filepath}: {e}")
return None
def build_agent_file(config: AgentConfig) -> str:
"""Build agent markdown file content from config"""
frontmatter = {
"name": config.name,
"description": config.description,
}
if config.tools:
frontmatter["tools"] = ", ".join(config.tools)
if config.disallowedTools:
frontmatter["disallowedTools"] = ", ".join(config.disallowedTools)
if config.model:
frontmatter["model"] = config.model
if config.color:
frontmatter["color"] = config.color
if config.permissionMode:
frontmatter["permissionMode"] = config.permissionMode
if config.skills:
frontmatter["skills"] = config.skills
if config.hooks:
frontmatter["hooks"] = config.hooks
yaml_content = yaml.dump(frontmatter, default_flow_style=False, sort_keys=False)
return f"---\n{yaml_content}---\n\n{config.prompt}"
def generate_prompt_with_claude(request: GeneratePromptRequest) -> str:
"""Use claude --print opus to generate an agent prompt"""
tool_list = ", ".join(request.tools) if request.tools else "Bash, Read"
meta_prompt = f'''You are creating a system prompt for a Claude Code subagent.
Agent Name: {request.name}
Description: {request.description}
Available Tools: {tool_list}
{f"Additional Context: {request.context}" if request.context else ""}
Create a detailed, actionable system prompt for this agent. The prompt should:
1. Define the agent's role clearly in the first line
2. Specify when and how to use each available tool
3. Include a step-by-step workflow for common tasks
4. List key practices and guidelines
5. Define output format and reporting structure
6. Include error handling guidance
Write ONLY the system prompt content - no YAML frontmatter, no markdown code blocks, just the prompt text that will guide the agent's behavior.
Be specific and practical. Include concrete examples where helpful.'''
try:
result = subprocess.run(
["claude", "--print", "--model", "opus", meta_prompt],
capture_output=True,
text=True,
timeout=120,
cwd=str(Path.home())
)
if result.returncode != 0:
raise Exception(f"Claude CLI error: {result.stderr}")
return result.stdout.strip()
except subprocess.TimeoutExpired:
raise Exception("Claude CLI timed out after 120 seconds")
except FileNotFoundError:
raise Exception("Claude CLI not found. Make sure 'claude' is in PATH")
# API Routes
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
"""Serve the main UI"""
return templates.TemplateResponse("index.html", {"request": request})
@app.get("/api/agents")
async def list_agents():
"""List all user agents"""
agents = []
if AGENTS_DIR.exists():
for filepath in AGENTS_DIR.glob("*.md"):
agent = parse_agent_file(filepath)
if agent:
agents.append(agent)
return {"agents": sorted(agents, key=lambda x: x.get("name", ""))}
@app.get("/api/agents/{name}")
async def get_agent(name: str):
"""Get a specific agent by name"""
filepath = AGENTS_DIR / f"{name}.md"
if not filepath.exists():
raise HTTPException(status_code=404, detail="Agent not found")
agent = parse_agent_file(filepath)
if not agent:
raise HTTPException(status_code=500, detail="Failed to parse agent file")
return agent
@app.post("/api/agents")
async def create_agent(config: AgentConfig):
"""Create a new agent"""
filepath = AGENTS_DIR / f"{config.name}.md"
if filepath.exists():
raise HTTPException(status_code=400, detail="Agent already exists")
# Ensure directory exists
AGENTS_DIR.mkdir(parents=True, exist_ok=True)
content = build_agent_file(config)
filepath.write_text(content)
return {"message": "Agent created", "name": config.name, "filepath": str(filepath)}
@app.put("/api/agents/{name}")
async def update_agent(name: str, config: AgentConfig):
"""Update an existing agent"""
filepath = AGENTS_DIR / f"{name}.md"
if not filepath.exists():
raise HTTPException(status_code=404, detail="Agent not found")
# If name changed, handle rename
if config.name != name:
new_filepath = AGENTS_DIR / f"{config.name}.md"
if new_filepath.exists():
raise HTTPException(status_code=400, detail="An agent with that name already exists")
filepath.unlink()
filepath = new_filepath
content = build_agent_file(config)
filepath.write_text(content)
return {"message": "Agent updated", "name": config.name}
@app.delete("/api/agents/{name}")
async def delete_agent(name: str):
"""Delete an agent"""
filepath = AGENTS_DIR / f"{name}.md"
if not filepath.exists():
raise HTTPException(status_code=404, detail="Agent not found")
filepath.unlink()
return {"message": "Agent deleted", "name": name}
@app.post("/api/generate-prompt")
async def generate_prompt(request: GeneratePromptRequest):
"""Generate agent prompt using Claude"""
try:
prompt = generate_prompt_with_claude(request)
return {"prompt": prompt}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/tools")
async def get_tools():
"""Get available tools"""
return {"tools": AVAILABLE_TOOLS}
@app.get("/api/models")
async def get_models():
"""Get available models"""
return {"models": AVAILABLE_MODELS}
@app.get("/api/colors")
async def get_colors():
"""Get available colors"""
return {"colors": AVAILABLE_COLORS}
@app.get("/api/hooks/events")
async def get_hook_events():
"""Get available hook event types"""
return {"events": HOOK_EVENTS}
@app.post("/api/preview")
async def preview_agent(config: AgentConfig):
"""Preview agent file content without saving"""
content = build_agent_file(config)
return {"content": content}
@app.get("/api/validators")
async def list_validators():
"""List existing validator scripts"""
validators = []
if HOOKS_DIR.exists():
for filepath in HOOKS_DIR.glob("*.py"):
validators.append({
"name": filepath.stem,
"path": str(filepath)
})
return {"validators": validators}
@app.post("/api/validators")
async def create_validator(name: str, content: str):
"""Create a new validator script"""
HOOKS_DIR.mkdir(parents=True, exist_ok=True)
filepath = HOOKS_DIR / f"{name}.py"
filepath.write_text(content)
filepath.chmod(0o755)
return {"message": "Validator created", "path": str(filepath)}
@app.get("/api/health")
async def health():
"""Health check endpoint"""
return {
"status": "healthy",
"agents_dir": str(AGENTS_DIR),
"agents_count": len(list(AGENTS_DIR.glob("*.md"))) if AGENTS_DIR.exists() else 0
}
if __name__ == "__main__":
import uvicorn
port = int(os.environ.get("PORT", 8086))
uvicorn.run(app, host="0.0.0.0", port=port)