-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathorchestrator.py
More file actions
855 lines (711 loc) · 35.1 KB
/
orchestrator.py
File metadata and controls
855 lines (711 loc) · 35.1 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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
#!/usr/bin/env python3
"""
Voice Vibe Coding Orchestrator - Simplified Version
Coordinates agents to transform voice conversations into deployed web applications.
This simplified version (~250 lines) replaces the complex 1,062-line orchestrator
with a clean, maintainable implementation following CLAUDE.md architecture.
"""
import os
import asyncio
import json
import pathlib
import time
import tempfile
import shutil
import re
from datetime import datetime
from dotenv import load_dotenv
from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient, AgentDefinition, query as claude_query
# Load environment variables (but remove ones that conflict with Claude CLI OAuth)
load_dotenv()
os.environ.pop("ANTHROPIC_API_KEY", None)
os.environ.pop("ANTHROPIC_BASE_URL", None)
# Ensure gh CLI uses the breagent service account (GITHUB_TOKEN -> GH_TOKEN)
if os.environ.get("GITHUB_TOKEN") and not os.environ.get("GH_TOKEN"):
os.environ["GH_TOKEN"] = os.environ["GITHUB_TOKEN"]
# Constants
PROJECT_ROOT = pathlib.Path(__file__).parent.resolve()
WEBHOOKS_DIR = PROJECT_ROOT / "webhooks"
# Agent descriptions for the orchestrator (tells Claude WHEN to use each agent)
AGENT_DESCRIPTIONS = {
"voice-requirements-analyst": "Extracts structured requirements from voice conversation transcripts. Use as the FIRST step for any new project.",
"github-manager": "Manages git repositories and GitHub integration with privacy-first anonymous ID mapping. Use for workspace setup, commits, and pushes.",
"content-strategist": "Generates all text content, marketing copy, headlines, and CTAs. Use for content-heavy projects.",
"ui-ux-designer": "Creates design specifications including colors, typography, layouts, and component styling. Use for visual projects.",
"static-html-generator": "Generates complete self-contained HTML files with inline CSS. Use for simple static websites.",
"project-scaffolder": "Initializes Next.js projects with TypeScript and Tailwind CSS. Use for React/Next.js applications.",
"component-architect": "Plans React component hierarchy, props, state, and data flow. Use before building components.",
"component-builder": "Builds actual React/TypeScript components from architecture plans. Use after component architecture is planned.",
"page-assembler": "Assembles components into complete Next.js pages with routing. Use after components are built.",
"styling-finisher": "Applies final styling polish, animations, and design refinements. Use as final visual step.",
"nextjs-validator": "Validates Next.js builds, fixes TypeScript errors, ensures production readiness. Use after development.",
"browser-functionality-validator": "Tests UI in real browser via Playwright, validates interactions and responsive design. Use for interactive apps.",
"vercel-deployer": "Deploys projects to Vercel from GitHub. Use after code is committed and pushed.",
"notification-agent": "Sends SMS notifications to users about project completion. Use as the final step when phone number is available.",
}
def parse_frontmatter(content: str) -> tuple[dict, str]:
"""Parse YAML frontmatter from markdown content.
Returns (frontmatter_dict, body_text)."""
if not content.startswith('---'):
return {}, content
end = content.find('---', 3)
if end == -1:
return {}, content
frontmatter_str = content[3:end].strip()
body = content[end + 3:].strip()
# Simple YAML parsing (key: value)
fm = {}
for line in frontmatter_str.split('\n'):
if ':' in line:
key, _, value = line.partition(':')
fm[key.strip()] = value.strip()
return fm, body
def load_agent_definitions() -> dict[str, AgentDefinition]:
"""Load all agent definitions from .claude/agents/ markdown files.
Parses everything from the frontmatter — the agent files are the single source of truth.
"""
agents = {}
agents_dir = PROJECT_ROOT / ".claude" / "agents"
if not agents_dir.exists():
print("⚠️ No .claude/agents/ directory found!")
return agents
for agent_file in agents_dir.glob("*.md"):
agent_name = agent_file.stem
content = agent_file.read_text()
# Parse frontmatter for description, model, tools
fm, body = parse_frontmatter(content)
description = fm.get('description', AGENT_DESCRIPTIONS.get(agent_name, f"Specialized agent: {agent_name}"))
model = fm.get('model', 'sonnet') # Use model from frontmatter
tools = [t.strip() for t in fm.get('tools', '').split(',') if t.strip()] or None
agents[agent_name] = AgentDefinition(
description=description,
prompt=content, # Full markdown including frontmatter = agent's system prompt
tools=tools,
model=model,
)
return agents
PROJECTS_DIR = PROJECT_ROOT / "projects"
# MCP Agent Management Functions
def agent_needs_mcp(agent_name: str) -> bool:
"""Check if an agent requires MCP tools."""
mcp_agents = [
'browser-functionality-validator',
'content-strategist',
'ui-ux-designer',
'styling-finisher',
'static-html-generator'
]
return agent_name in mcp_agents
def extract_agent_system_prompt(agent_md_content: str) -> str:
"""Extract the system prompt from agent markdown file."""
# Parse the markdown to extract everything between <role> and </instructions>
role_match = re.search(r'<role>(.*?)</role>', agent_md_content, re.DOTALL)
context_match = re.search(r'<context>(.*?)</context>', agent_md_content, re.DOTALL)
instructions_match = re.search(r'<instructions>(.*?)</instructions>', agent_md_content, re.DOTALL)
parts = []
if role_match:
parts.append(role_match.group(1).strip())
if context_match:
parts.append(context_match.group(1).strip())
if instructions_match:
parts.append(instructions_match.group(1).strip())
return "\n\n".join(parts)
def extract_agent_tools(agent_md_content: str) -> list:
"""Extract tools list from agent markdown frontmatter."""
# Parse YAML frontmatter
if agent_md_content.startswith('---'):
yaml_end = agent_md_content.find('---', 3)
if yaml_end != -1:
frontmatter = agent_md_content[3:yaml_end]
tools_match = re.search(r'tools:\s*(.+)', frontmatter)
if tools_match:
tools_str = tools_match.group(1)
# Split by comma and clean up
tools = [t.strip() for t in tools_str.split(',')]
return tools
return ["Read", "Write", "Edit"] # Default tools
def setup_isolation(temp_dir):
"""Set up isolated environment with Voice Vibe agents and settings."""
# Create .claude structure in temp directory
claude_dir = pathlib.Path(temp_dir) / ".claude"
claude_dir.mkdir(parents=True, exist_ok=True)
# Copy Voice Vibe agents to isolated location
agents_dir = claude_dir / "agents"
agents_dir.mkdir(exist_ok=True)
source_dir = PROJECT_ROOT / "voice_vibe_agents"
if source_dir.exists():
for agent_file in source_dir.glob("*.md"):
shutil.copy(agent_file, agents_dir / agent_file.name)
else:
print("⚠️ Warning: voice_vibe_agents directory not found!")
# Copy project settings to isolated environment
project_claude = PROJECT_ROOT / ".claude"
if project_claude.exists():
# Copy settings.json if it exists
settings_file = project_claude / "settings.json"
if settings_file.exists():
shutil.copy(settings_file, claude_dir / "settings.json")
# Copy settings.local.json if it exists
local_settings = project_claude / "settings.local.json"
if local_settings.exists():
shutil.copy(local_settings, claude_dir / "settings.local.json")
return temp_dir
def extract_phone_number(webhook_path):
"""Extract phone number from webhook data."""
try:
with open(webhook_path, "r") as f:
data = json.load(f)
# Try to get phone number from the webhook data
if "data" in data and "conversation_initiation_client_data" in data["data"]:
dynamic_vars = data["data"]["conversation_initiation_client_data"].get("dynamic_variables", {})
caller_id = dynamic_vars.get("system__caller_id", "unknown")
# Clean phone number (remove + and special chars)
return caller_id.replace("+", "").replace("-", "").replace(" ", "")
except Exception as e:
print(f"⚠️ Could not extract phone number: {e}")
return "unknown"
def log(msg: str):
"""Simple logging with timestamp."""
timestamp = datetime.now().strftime("%H:%M:%S")
print(f"[{timestamp}] {msg}", flush=True)
def get_agent_context(agent_name: str, project_dir: pathlib.Path) -> str:
"""Extract minimal relevant context for a specific agent from CLAUDE.md
This function implements targeted context extraction to avoid rate limiting
by only passing relevant sections to each agent instead of the entire file.
"""
# Define what each agent needs to see
AGENT_DEPENDENCIES = {
'voice-requirements-analyst': {
'sections': [], # First agent, needs nothing from CLAUDE.md
'summary': False
},
'github-manager': {
'sections': ['Requirements Analysis'], # Needs to know project details
'summary': False
},
'workflow-orchestrator': {
'sections': ['Requirements Analysis'],
'summary': False
},
'content-strategist': {
'sections': ['Requirements Analysis'],
'summary': False
},
'ui-ux-designer': {
'sections': ['Requirements Analysis', 'Content Strategy'],
'summary': False
},
'static-html-generator': {
'sections': ['Requirements Analysis'],
'summary': True,
'summary_sections': ['Content Strategy', 'Design Specifications']
},
'project-scaffolder': {
'sections': ['Requirements Analysis', 'Execution Plan'],
'summary': False
},
'component-architect': {
'sections': ['Requirements Analysis'],
'summary': True,
'summary_sections': ['Content Strategy', 'Design Specifications', 'Project Scaffolding']
},
'component-builder': {
'sections': ['Component Architecture'],
'summary': True,
'summary_sections': ['Requirements Analysis', 'Design Specifications']
},
'page-assembler': {
'sections': ['Component Implementation'],
'summary': True,
'summary_sections': ['Requirements Analysis', 'Design Specifications', 'Component Architecture']
},
'styling-finisher': {
'sections': ['Design Specifications'],
'summary': True,
'summary_sections': ['Page Assembly', 'Component Implementation']
},
'nextjs-validator': {
'sections': [], # Just needs to know project exists
'summary': True,
'summary_sections': ['Requirements Analysis', 'Execution Plan']
},
'browser-functionality-validator': {
'sections': [], # Works with actual files
'summary': True,
'summary_sections': ['Requirements Analysis', 'Validation Report']
},
'vercel-deployer': {
'sections': ['GitHub Setup'],
'summary': True,
'summary_sections': ['Requirements Analysis']
},
'notification-agent': {
'sections': ['Requirements Analysis'],
'summary': True,
'summary_sections': ['Deployment Report']
}
}
claude_md_path = project_dir / "CLAUDE.md"
if not claude_md_path.exists():
return ""
content = claude_md_path.read_text()
agent_config = AGENT_DEPENDENCIES.get(agent_name, {'sections': [], 'summary': False})
# Build context
context_parts = []
# Add project header (always included for context)
header = extract_project_header(content)
if header:
context_parts.append(header)
# Add full sections this agent needs
for section_name in agent_config['sections']:
section = extract_section(content, section_name)
if section:
context_parts.append(section)
# Add summaries if needed
if agent_config.get('summary'):
for section_name in agent_config.get('summary_sections', []):
summary = create_section_summary(content, section_name)
if summary:
context_parts.append(f"## {section_name} (Summary)\n{summary}\n")
return "\n".join(context_parts)
def extract_section(content: str, section_name: str) -> str:
"""Extract a specific section from CLAUDE.md
Finds a section by its heading and returns everything until the next section or end.
"""
# Handle both "## Section Name" and "## Section Name\n*Generated by..."
pattern = rf"## {re.escape(section_name)}\n(.*?)(?=\n## |\n---\n|$)"
match = re.search(pattern, content, re.DOTALL)
if match:
return f"## {section_name}\n{match.group(1).strip()}\n"
return ""
def extract_project_header(content: str) -> str:
"""Extract just the project overview from CLAUDE.md
Gets the essential project information that all agents need.
"""
lines = content.split('\n')
header_lines = ['# Voice Vibe Project Context (Excerpt)\n']
in_overview = False
for line in lines:
if '### Project Overview' in line:
in_overview = True
header_lines.append(line)
elif in_overview:
if line.startswith('###') and 'Project Overview' not in line:
break
header_lines.append(line)
if 'GitHub Repository' in line:
break
return '\n'.join(header_lines) if len(header_lines) > 1 else ""
def create_section_summary(content: str, section_name: str) -> str:
"""Create a 3-5 line summary of a section
Extracts key points to give agents awareness without full context.
"""
section = extract_section(content, section_name)
if not section:
return ""
lines = section.split('\n')
summary_lines = []
# Look for key markers
for line in lines:
# Capture important bullets, headers, or key info
if any([
line.strip().startswith('- **'),
line.strip().startswith('### '),
'Type:' in line,
'Status:' in line,
'Repository:' in line,
'Primary' in line
]):
# Clean up the line
clean_line = line.strip()
if clean_line and clean_line not in summary_lines:
summary_lines.append(clean_line)
if len(summary_lines) >= 5:
break
if summary_lines:
return '\n'.join(summary_lines)
else:
# Fallback: just take first 200 chars
text = ' '.join(lines[1:6]) # Skip header, take next 5 lines
return text[:200] + "..." if len(text) > 200 else text
async def invoke_mcp_agent(agent_name: str, task_description: str, project_dir: pathlib.Path, agent_context: str, phone: str = "unknown"):
"""Directly invoke an agent with MCP support using Claude SDK.
This bypasses the Task tool to maintain MCP server access.
"""
log(f" Starting MCP-enabled agent: {agent_name}")
# Read agent definition
agent_file = PROJECT_ROOT / f"voice_vibe_agents/{agent_name}.md"
if not agent_file.exists():
log(f" ERROR: Agent file not found: {agent_file}")
return
agent_md = agent_file.read_text()
# Extract system prompt and tools
system_prompt = extract_agent_system_prompt(agent_md)
tools = extract_agent_tools(agent_md)
# Replace 'mcp__playwright' in tools list with full MCP tool name
if 'mcp__playwright' in tools:
tools.remove('mcp__playwright')
tools.append('mcp__playwright') # Ensure it's recognized as MCP
# Add the agent identifier to system prompt
full_system_prompt = f"{system_prompt}\n\nYou are the {agent_name} agent."
# Configure Claude SDK with MCP support
agent_options = ClaudeAgentOptions(
system_prompt=full_system_prompt,
allowed_tools=tools,
mcp_servers={
"playwright": {
"command": "npx",
"args": ["-y", "@playwright/mcp@latest"],
"type": "stdio"
}
},
model=os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-4-5-20250929"),
permission_mode="acceptEdits",
max_turns=20
)
# Create the task prompt for the agent
agent_prompt = f"""
<task>
{task_description}
</task>
<context>
Project directory: {project_dir}
Phone number: {phone}
Relevant context from previous agents:
{agent_context if agent_context else "No previous context needed."}
</context>
<instructions>
1. Read the full context from {project_dir}/CLAUDE.md if needed
2. Perform your specialized task as defined in your role
3. Append your results to {project_dir}/CLAUDE.md following the cumulative context pattern
4. Use MCP Playwright tools as needed for browser automation
</instructions>
"""
# Run the agent in its own SDK client
try:
async with ClaudeSDKClient(options=agent_options) as agent_client:
log(f" MCP agent {agent_name} initialized with Playwright support")
# Send the task
await agent_client.query(agent_prompt)
# Stream response (same as orchestrator does)
async for message in agent_client.receive_response():
if content := getattr(message, "content", None):
for block in content:
if text := getattr(block, "text", None):
print(text, end="", flush=True)
print()
log(f" MCP agent {agent_name} completed successfully")
except Exception as e:
log(f" ERROR in MCP agent {agent_name}: {str(e)}")
raise
async def run_phase(client, phase_name, agent_name, description, project_dir, phone="unknown"):
"""Execute a standard phase with XML-structured prompt and filtered context."""
log(f"Starting {phase_name}")
# Get targeted context for this agent
agent_context = get_agent_context(agent_name, project_dir)
context_lines = len(agent_context.split('\n')) if agent_context else 0
log(f" Context size for {agent_name}: {context_lines} lines (filtered from CLAUDE.md)")
# Check if this agent needs MCP
if agent_needs_mcp(agent_name):
log(f" Agent {agent_name} requires MCP - using direct SDK invocation")
await invoke_mcp_agent(agent_name, description, project_dir, agent_context, phone)
else:
# Use Task tool — keep prompt MINIMAL so the agent's own system prompt controls behavior
prompt = f"""Use the Task tool with subagent_type="{agent_name}" and this prompt:
"{description}. Project directory: {project_dir}. Phone: {phone}."
Do NOT add your own instructions to the prompt. The agent already knows what to do from its system prompt. Keep the task prompt short.
"""
await client.query(prompt)
# Stream response
async for message in client.receive_response():
if content := getattr(message, "content", None):
for block in content:
if text := getattr(block, "text", None):
print(text, end="", flush=True)
print()
log(f"Completed {phase_name}")
async def run_execution_phase(client, project_dir):
"""Special handling for execution phase with context filtering and MCP support."""
log("Starting Execution Phase")
# Extract just the workflow section for execution
claude_md_path = project_dir / "CLAUDE.md"
workflow_section = ""
if claude_md_path.exists():
content = claude_md_path.read_text()
workflow_section = extract_section(content, "Execution Plan")
if workflow_section:
log(f" Workflow section size: {len(workflow_section.split(chr(10)))} lines")
# Parse agents from workflow to check for MCP agents
agents_to_run = []
if workflow_section:
# Look for agent names in the workflow - checking multiple formats
for line in workflow_section.split('\n'):
# Check for "**Agents**: agent1, agent2" format
if '**Agents**:' in line or '- **Agents**:' in line:
# Extract agent names after the colon
agents_part = line.split(':', 1)[1].strip()
# Split by comma and clean up
agent_names = [a.strip() for a in agents_part.split(',')]
agents_to_run.extend(agent_names)
# Also check for arrow format (legacy)
elif '→' in line and not line.strip().startswith('#'):
agent_match = re.search(r'→\s*(\S+)', line)
if agent_match:
agent_name = agent_match.group(1).strip(':')
if agent_name and agent_name != 'finalize':
agents_to_run.append(agent_name)
# Check if any agents need MCP
has_mcp_agents = any(agent_needs_mcp(agent) for agent in agents_to_run)
if has_mcp_agents:
log(f" Found MCP agents in workflow - handling individually")
# Execute each agent individually
for agent_name in agents_to_run:
agent_context = get_agent_context(agent_name, project_dir)
if agent_needs_mcp(agent_name):
log(f" Executing MCP agent: {agent_name}")
task = f"Execute your specialized role as part of the Voice Vibe Coding pipeline"
await invoke_mcp_agent(agent_name, task, project_dir, agent_context)
else:
# Use orchestrator client to invoke via Task tool
log(f" Executing regular agent: {agent_name}")
prompt = f"""
<task>
Invoke the {agent_name} agent.
</task>
<context>
Project directory: {project_dir}
Agent context:
{agent_context if agent_context else "No context needed."}
</context>
<instructions>
Use the Task tool with subagent_type="{agent_name}"
</instructions>
"""
await client.query(prompt)
async for message in client.receive_response():
if content := getattr(message, "content", None):
for block in content:
if text := getattr(block, "text", None):
print(text, end="", flush=True)
print()
else:
# No MCP agents - use the original approach
prompt = f"""
<task>
Execute the workflow plan agents sequentially.
</task>
<context>
Project directory: {project_dir}
Workflow plan to execute:
{workflow_section if workflow_section else "No workflow section found - check CLAUDE.md"}
</context>
<instructions>
<steps>
1. Parse the agent list from the workflow plan above
2. For each agent listed, invoke it using the Task tool with the appropriate subagent_type
3. Each agent will receive filtered context specific to their needs
4. Agents must run sequentially (one at a time) to preserve CLAUDE.md integrity
</steps>
<critical>
- Parse the list naturally, don't try to use code
- Each agent appends its output to CLAUDE.md
- Trust that each agent completes successfully
- Skip any agent marked with :finalize (handled in Phase 5)
</critical>
</instructions>
"""
await client.query(prompt)
# Stream response
async for message in client.receive_response():
if content := getattr(message, "content", None):
for block in content:
if text := getattr(block, "text", None):
print(text, end="", flush=True)
print()
log("Completed Execution Phase")
async def run_conditional_phase(client, phase_name, agent_name, project_dir, phone="unknown"):
"""Execute a conditional phase (deployment/notification) with filtered context and MCP support."""
log(f"Checking {phase_name} requirements...")
# Get workflow section to check if agent is needed
workflow_section = ""
claude_md_path = project_dir / "CLAUDE.md"
if claude_md_path.exists():
content = claude_md_path.read_text()
workflow_section = extract_section(content, "Execution Plan")
# Check if this agent needs MCP (though currently none of the conditional agents do)
if agent_needs_mcp(agent_name):
# If a conditional agent needs MCP in the future
log(f" Agent {agent_name} requires MCP - using direct SDK invocation")
agent_context = get_agent_context(agent_name, project_dir)
task = f"Execute your role for {phase_name} if required by the workflow plan"
await invoke_mcp_agent(agent_name, task, project_dir, agent_context, phone)
else:
# Regular Task tool approach for conditional agents
agent_context = get_agent_context(agent_name, project_dir)
prompt = f"""
<task>
Check if {agent_name} is required and execute if needed.
</task>
<context>
Project directory: {project_dir}
Phone number: {phone}
Workflow plan:
{workflow_section if workflow_section else "No workflow section found"}
Agent context (if needed):
{agent_context if agent_context else "No previous context needed for this agent."}
</context>
<instructions>
1. Check the Workflow plan above to see if {agent_name} is listed
2. If yes, invoke {agent_name} using the Task tool with subagent_type="{agent_name}"
- The agent should work from the filtered context provided above
- The agent will append its output to {project_dir}/CLAUDE.md
3. If no, skip this phase and log that it was skipped
</instructions>
"""
await client.query(prompt)
# Stream response
async for message in client.receive_response():
if content := getattr(message, "content", None):
for block in content:
if text := getattr(block, "text", None):
print(text, end="", flush=True)
print()
async def main():
"""Main orchestrator - coordinates the Voice Vibe Coding pipeline."""
# Parse minimal command line arguments
import argparse
parser = argparse.ArgumentParser(description="Voice Vibe Coding Orchestrator (Simplified)")
parser.add_argument("--phone", help="Phone number to process")
parser.add_argument("--verbose", action="store_true", default=True, help="Show detailed output")
args = parser.parse_args()
# Extract phone number
phone = args.phone if args.phone else "unknown"
webhook_path = WEBHOOKS_DIR / "latest_raw.json"
if phone == "unknown" and webhook_path.exists():
phone = extract_phone_number(webhook_path)
# Print header
print("\n" + "=" * 50)
print("🚀 Voice Vibe Coding Pipeline (Simplified)")
print(f"📞 Phone: {phone}")
print("=" * 50)
# Setup project directory
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
project_dir = PROJECTS_DIR / ".temp" / phone / timestamp
project_dir.mkdir(parents=True, exist_ok=True)
log(f"Project directory: {project_dir}")
# Setup isolation
isolated_dir = tempfile.mkdtemp(prefix="vvc_isolated_")
setup_isolation(isolated_dir)
log(f"Isolated environment: {isolated_dir}")
# Save environment (do NOT override HOME — it breaks Claude CLI OAuth auth)
original_cwd = os.getcwd()
# IMPORTANT: Do NOT change working directory - agents need access to project files
# os.chdir(isolated_dir) # This was causing file access issues!
# Load agent definitions from .claude/agents/ markdown files
agent_defs = load_agent_definitions()
log(f"Loaded {len(agent_defs)} agent definitions")
# Configure Claude SDK with agents defined programmatically
options = ClaudeAgentOptions(
system_prompt="""
You are the Voice Vibe Coding orchestrator. You coordinate specialized agents via the Task tool to transform voice conversations into deployed web applications.
Think carefully about which agents to use and in what order based on the complexity of the project.
Example pipelines (adapt based on project complexity):
- Simple landing page: voice-requirements-analyst → github-manager → content-strategist → static-html-generator → github-manager (commit) → vercel-deployer → notification-agent
- Full Next.js app: voice-requirements-analyst → github-manager → content-strategist → ui-ux-designer → project-scaffolder → component-architect → component-builder → page-assembler → styling-finisher → nextjs-validator → github-manager (commit) → vercel-deployer → notification-agent
Match the pipeline to the project. Don't over-engineer simple requests or under-serve complex ones.
**NOTE:** All projects have their code stored on GitHub in separate repos per project. The GitHub Manager agent is responsible for creating and managing these repos. All projects are also deployed to Vercel. As a result, you must keep in mind that for every job you get, you will need to invoke these agents in order to get the project deployed. The notification agent is repsonsible for sending the user a notification via SMS about the project completion. This agent will also need to be called for each job.
CLAUDE.md CUMULATIVE CONTEXT PATTERN:
Agents share context through a CLAUDE.md file in the project directory. Each agent reads previous agents' output from CLAUDE.md and appends its own results. When invoking agents, always include the project directory path so they know where to find and update CLAUDE.md. This is how the pipeline maintains continuity — each agent builds on the work of previous agents.
CRITICAL — HOW TO USE THE TASK TOOL:
Each agent has a comprehensive system prompt with all its instructions. You MUST NOT add instructions, steps, or guidance in your Task tool prompt. ONLY pass the essential context. The agent already knows what to do.
CORRECT Task prompt example:
"Project dir: /path/to/project. Phone: 1555555xxxx. Project name: Task Manager."
WRONG Task prompt example:
"You are the github-manager agent. Create a new GitHub repository. Step 1: Initialize git. Step 2: Create repo..."
The shorter your Task prompt, the better the agent performs — because it follows its OWN instructions instead of yours.
Ultrathink
""",
allowed_tools=[
"Task", # For invoking agents
"Read", # For reading files
"Write", # For writing files
"Edit", # For editing files
"Bash", # For running commands
"Grep", # For searching
"Glob", # For file matching
"TodoWrite", # For task management
"WebSearch", # For web searching capabilities
"WebFetch", # For fetching web content
"mcp__playwright" # For Playwright MCP browser automation
],
mcp_servers={
"playwright": {
"command": "npx",
"args": ["-y", "@playwright/mcp@latest"]
}
},
model=os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-4-5-20250929"),
permission_mode="acceptEdits",
max_turns=50,
agents=agent_defs, # Programmatic agent definitions — each agent gets its own system prompt
)
pipeline_success = False
try:
# Single orchestration prompt - let Claude decide the pipeline
orchestration_prompt = f"""A user called and described a project they want built. Transform their voice conversation into a deployed web application.
PROJECT CONTEXT:
- Phone number: {phone}
- Project directory: {project_dir}
- Webhook transcript: {WEBHOOKS_DIR}/latest_raw.json
- Artifacts directory: {project_dir}/artifacts/
YOUR JOB: Orchestrate the full pipeline by invoking the right agents in the right order using the Task tool.
Typical flow (adapt based on project needs):
1. voice-requirements-analyst - extract requirements from the transcript
2. github-manager - set up GitHub repo (uses anonymous IDs for privacy)
3. Decide which build agents to run based on requirements (content, design, build, etc.)
4. Run the build agents in the right order
5. github-manager - commit and push final code
6. vercel-deployer - deploy if appropriate
7. notification-agent - notify user via SMS if phone number available
Remember: keep Task tool prompts SHORT. Each agent has its own detailed instructions. Just tell it what to do and pass the project directory and phone number. Do NOT write custom instructions for agents.
Begin by invoking the voice-requirements-analyst to extract requirements from the webhook transcript."""
# Use query() instead of ClaudeSDKClient — query() correctly passes AgentDefinitions
async for message in claude_query(prompt=orchestration_prompt, options=options):
if hasattr(message, "content") and message.content:
for block in message.content:
if hasattr(block, "text") and block.text:
print(block.text, end="", flush=True)
if hasattr(message, "result"):
print(f"\n{message.result}")
print()
log("✅ Pipeline complete!")
pipeline_success = True
except Exception as e:
log(f"❌ Pipeline failed: {e}")
raise
finally:
# Restore environment
if original_cwd:
os.chdir(original_cwd)
# Cleanup isolated directory
if isolated_dir and os.path.exists(isolated_dir):
shutil.rmtree(isolated_dir, ignore_errors=True)
log("Cleaned up isolated environment")
# Cleanup project directory on success
if pipeline_success and project_dir.exists() and ".temp" in str(project_dir):
log(f"🧹 Cleaning up temporary workspace: {project_dir}")
shutil.rmtree(project_dir, ignore_errors=True)
if __name__ == "__main__":
# Note: Claude CLI uses OAuth auth. Do NOT require ANTHROPIC_API_KEY.
# Start timer
start_time = time.time()
# Run the orchestrator
try:
asyncio.run(main())
elapsed = round(time.time() - start_time, 1)
print(f"\n⏱️ Total time: {elapsed}s\n")
except KeyboardInterrupt:
print("\n⚠️ Pipeline interrupted by user")
except Exception as e:
print(f"\n❌ Pipeline error: {e}")
raise