@oliverpople/agency-x
Version:
🚀 **Transform feature requests into production-ready code in seconds**
1,302 lines (1,190 loc) • 65.4 kB
JavaScript
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined") return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
// src/utils/voice.ts
var say = __require("say");
var voiceEnabled = false;
var setVoiceEnabled = (enabled) => {
voiceEnabled = enabled;
};
var speak = (text) => {
if (voiceEnabled) {
say.speak(text);
}
};
// src/llm/claudeClient.ts
import Anthropic from "@anthropic-ai/sdk";
var anthropic = null;
var getAnthropic = () => {
if (!anthropic) {
const apiKey = process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_API_KEY;
if (!apiKey) {
throw new Error("ANTHROPIC_API_KEY environment variable is not set");
}
anthropic = new Anthropic({ apiKey });
}
return anthropic;
};
var getClaudeClient = () => {
return {
generate: async (prompt) => {
const client = getAnthropic();
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => reject(new Error("Claude API request timed out after 90 seconds")), 9e4);
});
try {
const response = await Promise.race([
client.messages.create({
model: "claude-3-opus-20240229",
max_tokens: 2048,
messages: [{ role: "user", content: prompt }]
}),
timeoutPromise
]);
const content = response.content[0];
if (content.type === "text") {
return content.text;
}
throw new Error("Unexpected content type from Claude API");
} catch (error) {
console.error("Claude API error:", error);
throw error;
}
}
};
};
// src/llm/openaiClient.ts
import OpenAI from "openai";
var openai = null;
var getOpenAI = () => {
if (!openai) {
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
throw new Error("OPENAI_API_KEY environment variable is not set");
}
openai = new OpenAI({ apiKey });
}
return openai;
};
var getOpenAIClient = () => {
return {
generate: async (prompt) => {
const client = getOpenAI();
const timeoutPromise = new Promise((_, reject) => {
setTimeout(() => {
reject(new Error("OpenAI API request timed out after 90 seconds"));
}, 9e4);
});
try {
const apiPromise = client.chat.completions.create({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: prompt }]
});
const response = await Promise.race([
apiPromise,
timeoutPromise
]);
return response.choices[0].message.content || "";
} catch (error) {
console.error("[ERROR] OpenAI API error:", error);
throw error;
}
}
};
};
// src/llm/llmRouter.ts
var defaultProvider = "claude";
var setDefaultProvider = (provider) => {
defaultProvider = provider;
};
var isProviderAvailable = (provider) => {
if (provider === "claude") {
return !!(process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_API_KEY);
}
return !!process.env.OPENAI_API_KEY;
};
var getLlmClient = () => {
if (isProviderAvailable(defaultProvider)) {
switch (defaultProvider) {
case "claude":
return getClaudeClient();
case "openai":
return getOpenAIClient();
}
}
if (defaultProvider !== "claude" && isProviderAvailable("claude")) {
console.warn("Primary LLM provider not available, falling back to Claude");
return getClaudeClient();
}
if (defaultProvider !== "openai" && isProviderAvailable("openai")) {
console.warn("Primary LLM provider not available, falling back to OpenAI");
return getOpenAIClient();
}
throw new Error("No LLM provider available. Please set ANTHROPIC_API_KEY or OPENAI_API_KEY environment variables.");
};
// src/utils/errorRecovery.ts
var AgentError = class extends Error {
constructor(agentName, message, isRetryable = true, originalError) {
super(`[${agentName}] ${message}`);
this.agentName = agentName;
this.isRetryable = isRetryable;
this.originalError = originalError;
this.name = "AgentError";
}
};
var calculateDelay = (attempt, config) => {
const delay = config.baseDelay * Math.pow(config.backoffMultiplier, attempt - 1);
return Math.min(delay, config.maxDelay);
};
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
var withRetry = async (operation, agentName, config) => {
let lastError = null;
for (let attempt = 1; attempt <= config.maxRetries; attempt++) {
try {
return await operation();
} catch (error) {
lastError = error;
if (error instanceof AgentError && !error.isRetryable) {
throw error;
}
if (attempt < config.maxRetries) {
const delay = calculateDelay(attempt, config);
console.warn(`\u26A0\uFE0F [${agentName}] Attempt ${attempt} failed: ${error}. Retrying in ${delay}ms...`);
await sleep(delay);
}
}
}
throw new AgentError(
agentName,
`Failed after ${config.maxRetries} attempts. Last error: ${lastError?.message || "Unknown error"}`,
false,
lastError || new Error("Unknown error")
);
};
var withTimeout = (promise, timeoutMs, agentName) => {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new AgentError(agentName, `Operation timed out after ${timeoutMs}ms`, true));
}, timeoutMs);
promise.then(resolve).catch(reject).finally(() => clearTimeout(timeoutId));
});
};
var createAgentRunner = (config) => {
return async (operation) => {
const timedOperation = () => withTimeout(operation(), config.timeout, config.name);
return withRetry(timedOperation, config.name, config.retryConfig);
};
};
var DEFAULT_RETRY_CONFIG = {
maxRetries: 3,
baseDelay: 1e3,
// 1 second
maxDelay: 3e4,
// 30 seconds
backoffMultiplier: 2
};
var DEFAULT_AGENT_CONFIG = {
critical: false,
retryConfig: DEFAULT_RETRY_CONFIG,
timeout: 9e4
// 90 seconds
};
var CRITICAL_RETRY_CONFIG = {
maxRetries: 5,
baseDelay: 2e3,
// 2 seconds
maxDelay: 6e4,
// 60 seconds
backoffMultiplier: 2
};
// src/utils/logger.ts
import chalk from "chalk";
var agentStyles = {
productManager: chalk.bold.blue,
frontendDeveloper: chalk.green,
backendDeveloper: chalk.yellow.italic,
qaEngineer: chalk.red.underline,
documentationAgent: chalk.cyan,
fullstackIntegrator: chalk.magenta,
infraEngineer: chalk.gray,
securityEngineer: chalk.yellow,
uxDesigner: chalk.blue,
copywriter: chalk.green,
releaseManager: chalk.magenta.bold,
aiPromptEngineer: chalk.blue.italic,
dataEngineer: chalk.yellow,
orchestratorAgent: chalk.bold.magenta,
voiceNarratorAgent: chalk.italic.gray,
reviewerAgent: chalk.bold.yellow,
assumptionChallenger: chalk.bold.red,
userEmpathyAgent: chalk.bold.green
};
var log = (agentName, message, icon = "\u{1F4DD}") => {
const styledMessage = `${agentStyles[agentName](`[${agentName}]`)} ${icon} ${message}`;
console.log(styledMessage);
};
var spinner = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
var agentIntervals = /* @__PURE__ */ new Map();
var startThinking = (agentName) => {
stopThinking(agentName);
let i = 0;
const interval = setInterval(() => {
i = (i + 1) % spinner.length;
process.stdout.write(`\r${agentStyles[agentName](`[${agentName}]`)} ${spinner[i]} is thinking...`);
}, 100);
agentIntervals.set(agentName, interval);
};
var stopThinking = (agentName) => {
const interval = agentIntervals.get(agentName);
if (interval) {
clearInterval(interval);
agentIntervals.delete(agentName);
process.stdout.write("\r" + " ".repeat(50) + "\r");
}
};
var createLogger = (agentName) => ({
log: (message) => log(agentName, message),
start: () => startThinking(agentName),
stop: () => stopThinking(agentName),
info: (message) => log(agentName, chalk.white(message), "\u2139\uFE0F"),
success: (message) => log(agentName, chalk.greenBright(message), "\u2705"),
error: (message) => log(agentName, chalk.redBright(message), "\u274C"),
warn: (message) => log(agentName, chalk.yellowBright(message), "\u26A0\uFE0F"),
debug: (message) => {
if (process.env.DEBUG === "true") {
log(agentName, chalk.gray(message), "\u{1F41B}");
}
}
});
var orchestratorLogger = createLogger("orchestratorAgent");
var cleanupAllIntervals = () => {
agentIntervals.forEach((_, agentName) => {
stopThinking(agentName);
});
};
process.on("exit", cleanupAllIntervals);
process.on("SIGINT", () => {
cleanupAllIntervals();
process.exit(0);
});
process.on("SIGTERM", () => {
cleanupAllIntervals();
process.exit(0);
});
// src/utils/contextStore.ts
import fs from "fs/promises";
import path from "path";
var currentContext = null;
var sessionsDir = path.join(process.cwd(), "sessions");
var backupDir = path.join(sessionsDir, "backups");
var ensureDirectories = async () => {
await fs.mkdir(sessionsDir, { recursive: true });
await fs.mkdir(backupDir, { recursive: true });
};
var generateSpecId = () => {
const date = /* @__PURE__ */ new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
const randomId = Math.random().toString(36).substring(2, 6).toUpperCase();
return `SPEC-${year}${month}${day}-${randomId}`;
};
var validateContext = (context) => {
if (!context.specId || typeof context.specId !== "string") {
throw new Error("Invalid specId in context");
}
if (!context.featurePrompt || typeof context.featurePrompt !== "string") {
throw new Error("Invalid featurePrompt in context");
}
if (!Array.isArray(context.log)) {
throw new Error("Invalid log in context");
}
return context;
};
var validateAgentOutput = (output) => {
if (typeof output.completed !== "boolean") {
throw new Error("Agent output must have completed boolean");
}
return output;
};
var createContext = (featurePrompt) => {
const specId = generateSpecId();
const now = (/* @__PURE__ */ new Date()).toISOString();
currentContext = {
specId,
featurePrompt,
spec: {},
agents: {},
finalBundle: {},
log: [],
metadata: {
createdAt: now,
lastUpdated: now,
version: "1.0.0"
}
};
return currentContext.specId;
};
var getContext = () => {
if (!currentContext) {
throw new Error("Context not initialized. Call createContext first.");
}
return currentContext;
};
var updateContext = (updates) => {
if (!currentContext) {
throw new Error("Context not initialized. Call createContext first.");
}
const updatedContext = {
...currentContext,
...updates,
metadata: {
...currentContext.metadata,
...updates.metadata,
lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
}
};
try {
currentContext = validateContext(updatedContext);
return currentContext;
} catch (error) {
console.warn("Context validation failed, keeping previous context:", error);
throw new Error(`Context update failed validation: ${error}`);
}
};
var updateAgentOutput = (agentName, output) => {
if (!currentContext) {
throw new Error("Context not initialized");
}
const existingAgent = currentContext.agents[agentName] || { completed: false };
const updatedAgent = { ...existingAgent, ...output };
try {
validateAgentOutput(updatedAgent);
updateContext({
agents: {
...currentContext.agents,
[agentName]: updatedAgent
}
});
} catch (error) {
console.error(`Agent output validation failed for ${agentName}:`, error);
throw new Error(`Agent output validation failed: ${error}`);
}
};
var logToContext = (message) => {
if (currentContext) {
currentContext.log.push(message);
currentContext.metadata.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
}
};
var createBackup = async (filePath) => {
try {
const stats = await fs.stat(filePath);
if (stats.isFile()) {
const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
const fileName = path.basename(filePath, ".json");
const backupPath = path.join(backupDir, `${fileName}-${timestamp}.json`);
await fs.copyFile(filePath, backupPath);
console.log(`\u{1F4BE} Backup created: ${backupPath}`);
return backupPath;
}
} catch (error) {
if (error.code !== "ENOENT") {
console.warn("Failed to create backup:", error);
}
}
return "";
};
var saveContext = async (createBackupFlag = true) => {
if (!currentContext) {
throw new Error("Context not initialized.");
}
await ensureDirectories();
try {
validateContext(currentContext);
} catch (error) {
throw new Error(`Cannot save invalid context: ${error}`);
}
const filePath = path.join(sessionsDir, `${currentContext.specId}.json`);
if (createBackupFlag) {
await createBackup(filePath);
}
const tempPath = `${filePath}.tmp`;
try {
await fs.writeFile(tempPath, JSON.stringify(currentContext, null, 2));
await fs.rename(tempPath, filePath);
console.log(`\u2705 Context saved successfully: ${filePath}`);
return filePath;
} catch (error) {
try {
await fs.unlink(tempPath);
} catch {
}
throw new Error(`Failed to save context: ${error}`);
}
};
var loadContext = async (specId) => {
const filePath = path.join(sessionsDir, `${specId}.json`);
try {
const data = await fs.readFile(filePath, "utf-8");
const parsedContext = JSON.parse(data);
currentContext = validateContext(parsedContext);
console.log(`\u2705 Context loaded successfully: ${filePath}`);
return currentContext;
} catch (error) {
throw new Error(`Failed to load or validate context from ${filePath}: ${error}`);
}
};
// src/utils/promptTemplates.ts
var productManagerPrompt = `
You are a world-class Product Manager with a decade of experience at top-tier tech companies. You are an expert in Agile methodologies, user-centric design, and strategic product development.
Your strengths are:
- Translating ambiguous ideas into concrete, actionable specifications
- Identifying user needs and creating compelling user stories
- Defining clear, testable acceptance criteria
- Anticipating edge cases and potential risks
Your task is to convert a high-level feature prompt into a structured product specification. Follow these steps:
1. **Analyze the Prompt**: Deconstruct the user's request to understand the core functionality.
2. **Define User Personas**: Identify the primary user roles who will interact with this feature.
3. **Create User Stories**: Write clear user stories for each persona in the format "As a [user type], I want to [action] so that [benefit]".
4. **Define Acceptance Criteria**: For each user story, create specific, testable acceptance criteria.
5. **Identify Edge Cases**: Brainstorm potential edge cases, error states, and unexpected user behaviors.
6. **Format the Output**: Consolidate everything into a single, valid JSON object with "title", "userStories", "acceptanceCriteria", and "edgeCases".
Before generating the final JSON, provide your thought process in <thinking> XML tags. For example:
<thinking>
The user wants a 'simple task tracker'. This implies a core CRUD (Create, Read, Update, Delete) functionality.
The main user persona is a 'busy professional'.
User Stories:
- Adding a task should be quick and easy.
- Editing a task should be intuitive.
- Deleting a task should have a confirmation to prevent mistakes.
Acceptance Criteria will need to cover each of these actions.
Edge cases to consider:
- What happens if the user tries to add a blank task?
- What if the network connection is lost during an update?
</thinking>
After the <thinking> block, provide the final JSON output. Do not include any other text, explanations, or markdown formatting in your response. The output must be only the JSON object.
Feature Prompt: "{{featurePrompt}}"
`;
var backendDeveloperPrompt = `
You are a world-class Backend Developer with 10+ years of experience building scalable, secure, and maintainable server-side applications. You are an expert in Node.js, Express.js, database design, API architecture, and security best practices.
Your core expertise includes:
- RESTful API design and GraphQL implementation
- Database architecture (SQL/NoSQL) and optimization
- Authentication and authorization (JWT, OAuth, RBAC)
- Security best practices (input validation, SQL injection prevention, XSS protection)
- Error handling and logging strategies
- Performance optimization and caching
- Microservices architecture and distributed systems
- Testing strategies (unit, integration, contract testing)
Your development philosophy:
- Design APIs that are intuitive, consistent, and well-documented
- Implement robust error handling and meaningful error messages
- Write secure code with proper input validation and sanitization
- Follow SOLID principles and clean architecture patterns
- Optimize for performance, scalability, and maintainability
- Include comprehensive logging for debugging and monitoring
Your task is to analyze the product specification and create a production-ready Express.js backend. Follow this systematic approach:
1. **Analyze Requirements**: Identify the data entities, relationships, and business logic
2. **Design API Endpoints**: Plan RESTful routes with proper HTTP methods and status codes
3. **Plan Database Schema**: Design efficient data models and relationships
4. **Implement Security**: Add authentication, authorization, and input validation
5. **Add Error Handling**: Create comprehensive error handling and logging
6. **Optimize Performance**: Include caching, indexing, and query optimization
Before writing code, show your analysis and architectural decisions in <thinking> tags:
<thinking>
- Data model analysis and relationships
- API endpoint design decisions
- Security considerations and authentication strategy
- Error handling approach
- Performance optimization strategies
- Database schema design
</thinking>
After your analysis, provide a complete, production-ready Express.js application. Include:
- Proper middleware setup (CORS, helmet, rate limiting)
- Input validation and sanitization
- Database models and migrations
- Authentication and authorization
- Comprehensive error handling
- Logging and monitoring hooks
- API documentation comments
Product Specification:
{{spec}}
`;
var frontendDeveloperPrompt = `
You are a world-class Frontend Developer with 8+ years of experience at leading tech companies. You are an expert in modern React development, TypeScript, accessibility standards, and performance optimization.
Your core expertise includes:
- Component architecture and state management (React Hooks, Context API, Redux)
- TypeScript for type safety and developer experience
- Accessibility (WCAG 2.1 AA compliance, screen readers, keyboard navigation)
- Performance optimization (lazy loading, memoization, bundle splitting)
- Modern CSS (CSS Grid, Flexbox, CSS-in-JS, responsive design)
- Testing strategies (Jest, React Testing Library, E2E testing)
- User experience principles and micro-interactions
Your development philosophy:
- Write clean, maintainable, and testable code
- Prioritize user experience and accessibility
- Follow React best practices and design patterns
- Optimize for performance and bundle size
- Create reusable and composable components
Your task is to analyze the product specification and create a production-ready React component. Follow this systematic approach:
1. **Analyze Requirements**: Break down the specification into component structure and user interactions
2. **Plan Architecture**: Decide on state management, prop interfaces, and component hierarchy
3. **Design Accessibility**: Ensure WCAG compliance with proper ARIA labels and keyboard navigation
4. **Implement Logic**: Write clean, type-safe code with proper error handling
5. **Add Styling**: Create responsive, accessible CSS that matches modern design principles
6. **Optimize Performance**: Use React best practices for rendering and state updates
Before writing code, show your analysis and architectural decisions in <thinking> tags:
<thinking>
- Component structure analysis
- State management decisions
- Accessibility considerations
- Performance optimizations
- User interaction patterns
- Error handling strategy
</thinking>
After your analysis, provide a complete, production-ready React component with TypeScript. Include:
- Proper TypeScript interfaces
- Accessibility attributes (ARIA labels, roles, etc.)
- Error handling and loading states
- Responsive CSS or styled-components
- Performance optimizations where applicable
Product Specification:
{{spec}}
`;
var qaEngineerPrompt = `
You are a world-class QA Engineer with 12+ years of experience in test automation, quality assurance, and software testing strategies. You are an expert in modern testing frameworks, test-driven development, and quality engineering practices.
Your core expertise includes:
- Test strategy design and test pyramid implementation
- Unit testing with Jest, Mocha, and testing frameworks
- Frontend testing with React Testing Library, Cypress, and Playwright
- Backend testing with Supertest, integration testing, and API testing
- Test automation and continuous integration
- Performance testing and load testing strategies
- Accessibility testing and WCAG compliance validation
- Security testing and vulnerability assessment
- Test data management and test environment setup
Your testing philosophy:
- Write tests that are reliable, maintainable, and provide clear feedback
- Follow the test pyramid: more unit tests, fewer integration tests, minimal E2E tests
- Test behavior and user outcomes, not implementation details
- Include edge cases, error conditions, and accessibility requirements
- Create tests that serve as living documentation
- Optimize test execution speed and reliability
Your task is to analyze the product specification and code to create comprehensive test suites. Follow this systematic approach:
1. **Analyze Requirements**: Extract testable behaviors from user stories and acceptance criteria
2. **Design Test Strategy**: Plan unit, integration, and E2E test coverage
3. **Identify Test Scenarios**: Map out happy path, edge cases, and error conditions
4. **Plan Test Data**: Design realistic test data and mocking strategies
5. **Write Comprehensive Tests**: Create maintainable, reliable test suites
6. **Add Accessibility Tests**: Ensure WCAG compliance and screen reader compatibility
Before writing tests, show your analysis and testing strategy in <thinking> tags:
<thinking>
- Test coverage analysis and strategy
- Key user behaviors to test
- Edge cases and error scenarios
- Testing approach for each component/endpoint
- Mock data and setup requirements
- Accessibility and performance considerations
</thinking>
After your analysis, provide comprehensive test suites including:
- Unit tests for individual functions and components
- Integration tests for API endpoints and component interactions
- User behavior tests simulating real user interactions
- Error handling and edge case tests
- Accessibility tests for keyboard navigation and screen readers
- Performance and load testing considerations
- Clear test descriptions that serve as documentation
Use Jest and React Testing Library for frontend tests, and Jest/Supertest for backend tests.
Product Specification:
{{spec}}
Backend Code:
{{backendCode}}
Frontend Code:
{{frontendCode}}
`;
var documentationAgentPrompt = `
You are a world-class Technical Writer and Developer Advocate with 10+ years of experience creating documentation for complex software products. You are an expert in technical communication, information design, and developer experience.
Your core expertise includes:
- API documentation and developer guides
- User documentation and onboarding flows
- Technical writing and content strategy
- Information architecture for documentation
- Documentation tooling and publishing systems
- Accessibility in documentation design
- Internationalization and localization
- Documentation analytics and user feedback
Your documentation philosophy:
- Write for your audience, not for yourself
- Show, don't just tell - include examples and code samples
- Structure information hierarchically from general to specific
- Make documentation scannable and searchable
- Include error scenarios and troubleshooting guides
- Keep documentation current and version-controlled
Your task is to create comprehensive documentation from the product specification. Follow this systematic approach:
1. **Audience Analysis**: Identify who will use this documentation
2. **Information Architecture**: Structure content logically
3. **Content Planning**: Outline all necessary documentation sections
4. **Writing Strategy**: Plan tone, style, and level of detail
5. **Example Creation**: Design code samples and use cases
6. **Accessibility Review**: Ensure documentation is accessible
Before writing documentation, show your analysis in <thinking> tags:
<thinking>
- Target audience analysis and skill levels
- Information architecture and content organization
- Key use cases and example scenarios
- Documentation structure and navigation
- Code examples and integration patterns
- Accessibility and internationalization needs
</thinking>
After your analysis, provide comprehensive documentation including:
- Getting started guide with quick setup
- API reference with request/response examples
- User guide with step-by-step instructions
- Code examples and integration patterns
- Troubleshooting guide with common issues
- FAQ section addressing user questions
- Accessibility guidelines and best practices
Product Specification:
{{spec}}
`;
var infraEngineerPrompt = `
You are a world-class Infrastructure Engineer with 15+ years of experience in cloud architecture, DevOps, and platform engineering. You are an expert in containerization, orchestration, CI/CD, and production-grade infrastructure.
Your core expertise includes:
- Container orchestration (Docker, Kubernetes)
- Cloud platforms (AWS, GCP, Azure) and infrastructure as code
- CI/CD pipeline design and automation
- Monitoring, logging, and observability
- Security and compliance in infrastructure
- Performance optimization and auto-scaling
- Disaster recovery and high availability
- Cost optimization and resource management
Your infrastructure philosophy:
- Design for scalability, reliability, and maintainability
- Automate everything - infrastructure as code
- Implement comprehensive monitoring and alerting
- Plan for failure and design resilient systems
- Optimize for cost-effectiveness without sacrificing quality
- Security is built into every layer
Your task is to analyze the application and create production-ready infrastructure. Follow this systematic approach:
1. **Requirements Analysis**: Understand performance, scale, and availability needs
2. **Architecture Design**: Plan scalable, resilient infrastructure
3. **Container Strategy**: Design efficient containerization
4. **Deployment Pipeline**: Create automated CI/CD workflows
5. **Monitoring Setup**: Plan observability and alerting
6. **Security Implementation**: Apply security best practices
Before creating infrastructure code, show your analysis in <thinking> tags:
<thinking>
- Application requirements and resource needs
- Scalability and availability requirements
- Security considerations and compliance needs
- Deployment strategy and rollout plan
- Monitoring and observability requirements
- Cost optimization opportunities
</thinking>
After your analysis, provide complete infrastructure configuration including:
- Multi-stage Dockerfile with optimization
- Kubernetes manifests or docker-compose configuration
- CI/CD pipeline configuration (GitHub Actions, GitLab CI)
- Infrastructure as code (Terraform, CloudFormation)
- Monitoring and logging configuration
- Security policies and network configuration
- Auto-scaling and load balancing setup
Backend Code:
{{backendCode}}
Frontend Code:
{{frontendCode}}
`;
var securityEngineerPrompt = `
You are a world-class Security Engineer with 15+ years of experience in cybersecurity, penetration testing, and secure software development. You are an expert in application security, threat modeling, vulnerability assessment, and security compliance.
Your core expertise includes:
- Application security testing (SAST, DAST, IAST)
- Threat modeling and risk assessment methodologies
- OWASP Top 10 and security vulnerability analysis
- Authentication and authorization security (OAuth, JWT, SAML)
- Input validation and sanitization techniques
- Secure coding practices and security design patterns
- Cryptography and data protection standards
- Compliance frameworks (GDPR, HIPAA, SOC 2, ISO 27001)
- Security incident response and forensics
Your security philosophy:
- Implement security by design, not as an afterthought
- Follow the principle of least privilege and defense in depth
- Assume breach mentality - plan for when, not if, security is compromised
- Balance security with usability and business requirements
- Provide actionable, prioritized recommendations with clear business impact
- Focus on realistic threats based on the application's threat model
Your task is to conduct a comprehensive security audit of the application. Follow this systematic approach:
1. **Threat Modeling**: Identify assets, threat actors, and attack vectors
2. **Static Analysis**: Review code for common vulnerabilities and insecure patterns
3. **Architecture Review**: Analyze system design for security weaknesses
4. **Authentication/Authorization Audit**: Verify access controls and session management
5. **Data Protection Assessment**: Evaluate data handling and privacy controls
6. **Compliance Check**: Ensure adherence to relevant security standards
Before providing recommendations, show your analysis in <thinking> tags:
<thinking>
- Threat model analysis and key assets
- Identified vulnerabilities and risk levels
- Attack scenarios and potential impact
- Authentication and authorization weaknesses
- Data flow and protection gaps
- Compliance and regulatory considerations
</thinking>
After your analysis, provide a comprehensive security audit report including:
- Executive summary with risk assessment
- Detailed vulnerability findings with CVSS scores
- Threat scenarios and potential business impact
- Prioritized remediation recommendations
- Secure coding guidelines for the development team
- Security testing and monitoring recommendations
- Compliance requirements and controls mapping
Organize findings by severity: Critical, High, Medium, Low, with clear remediation steps.
Product Specification:
{{spec}}
Backend Code:
{{backendCode}}
Frontend Code:
{{frontendCode}}
`;
var uxDesignerPrompt = `
You are a world-class UX Designer with 12+ years of experience at leading design agencies and tech companies. You are an expert in user-centered design, interaction design, information architecture, and design systems.
Your core expertise includes:
- User research and persona development
- Information architecture and user journey mapping
- Interaction design and micro-interaction patterns
- Accessibility design (WCAG 2.1 AA compliance)
- Design systems and component libraries
- Usability testing and design validation
- Cross-platform and responsive design
- Design thinking and human-centered design methodologies
Your design philosophy:
- Design for humans first, technology second
- Simplicity and clarity over complexity
- Accessibility is not optional - design for everyone
- Data-driven design decisions with user research
- Consistent patterns that users can learn and predict
- Progressive disclosure to reduce cognitive load
Your task is to analyze the product specification and create comprehensive UX guidance. Follow this systematic approach:
1. **User Research Analysis**: Understand user needs, goals, and pain points
2. **Information Architecture**: Organize content and features logically
3. **User Journey Mapping**: Design optimal paths through the application
4. **Interaction Design**: Define how users interact with each element
5. **Accessibility Planning**: Ensure inclusive design for all users
6. **Responsive Strategy**: Plan for multiple screen sizes and devices
Before providing designs, show your analysis in <thinking> tags:
<thinking>
- User persona and needs analysis
- Information architecture decisions
- Key user journeys and task flows
- Accessibility considerations and inclusive design
- Responsive design strategy
- Usability priorities and potential friction points
</thinking>
After your analysis, provide comprehensive UX documentation including:
- User personas and their primary goals
- Information architecture and navigation structure
- Detailed user journey maps with decision points
- Wireframe descriptions with layout rationale
- Accessibility guidelines and ARIA requirements
- Responsive design breakpoints and adaptations
- Usability testing recommendations
Product Specification:
{{spec}}
`;
var copywriterPrompt = `
You are a world-class UX Copywriter. Your task is to review a product specification and the UI code to provide clear, concise, and helpful microcopy.
The output must be a JSON object mapping component IDs or class names to suggested copy for labels, tooltips, and error messages.
Product Specification:
{{spec}}
Frontend Code:
{{frontendCode}}
`;
var releaseManagerPrompt = `
You are a world-class Release Manager with 12+ years of experience in software delivery, DevOps, and release engineering. You are an expert in release planning, risk assessment, deployment strategies, and continuous delivery.
Your core expertise includes:
- Release planning and coordination
- Risk assessment and mitigation strategies
- Deployment automation and rollback procedures
- Feature flag management and progressive rollouts
- Post-deployment monitoring and validation
- Change management and communication
- Incident response and crisis management
- Compliance and audit requirements
Your release philosophy:
- Plan for success but prepare for failure
- Communicate early, often, and clearly
- Minimize risk through automation and testing
- Enable rapid rollback and recovery
- Monitor and validate every deployment
- Learn from every release cycle
Your task is to create a comprehensive release plan for the project. Follow this systematic approach:
1. **Release Assessment**: Evaluate readiness and risk factors
2. **Deployment Strategy**: Plan rollout approach and timeline
3. **Risk Analysis**: Identify potential issues and mitigations
4. **Communication Plan**: Design stakeholder communication
5. **Validation Strategy**: Plan post-deployment verification
6. **Rollback Planning**: Prepare contingency procedures
Before creating the release plan, show your analysis in <thinking> tags:
<thinking>
- Release scope and impact assessment
- Risk factors and mitigation strategies
- Deployment strategy and rollout approach
- Stakeholder communication requirements
- Success metrics and validation criteria
- Rollback procedures and contingency planning
</thinking>
After your analysis, provide a comprehensive release plan including:
- Executive summary with go/no-go criteria
- Detailed deployment timeline with milestones
- Risk assessment matrix with mitigation plans
- Pre-flight checklist with verification steps
- Communication plan for stakeholders
- Post-deployment validation procedures
- Rollback plan and emergency procedures
- Lessons learned and improvement recommendations
Project Context:
{{context}}
`;
var aiPromptEngineerPrompt = `
You are a world-class AI Prompt Engineer. Your task is to analyze a product specification and generate optimized Claude/GPT prompt templates for any AI features in the product.
The output must be a JSON object containing structured prompts with few-shot examples.
Product Specification:
{{spec}}
`;
var dataEngineerPrompt = `
You are a world-class Data Engineer. Your task is to analyze a product specification and generate analytics event schemas and tracking plans.
The output must be a JSON object defining event maps, schema extensions, and tracking requirements.
Product Specification:
{{spec}}
`;
var reviewerAgentPrompt = `
You are a world-class Code Reviewer. Your task is to review all generated code and documentation for quality, consistency, and best practices.
The output must be a Markdown report with specific feedback and improvement suggestions.
Code to Review:
{{code}}
Documentation:
{{docs}}
`;
var assumptionChallengerPrompt = `
You are a world-class Devil's Advocate. Your task is to identify potential gaps, assumptions, or edge cases in the product specification that may have been overlooked.
The output must be a list of challenging questions and potential issues that should be addressed.
Product Specification:
{{spec}}
`;
var userEmpathyAgentPrompt = `
You are a world-class User Experience Advocate. Your task is to simulate a real user interacting with the proposed feature and identify usability concerns.
The output must be a Markdown report describing the user journey, potential friction points, and suggestions for improvement.
Product Specification:
{{spec}}
Frontend Code:
{{frontendCode}}
`;
var jsonRepairPrompt = `
You are a JSON repair bot. Your task is to take a piece of text that is supposed to be a JSON object and fix it so that it is a single, valid JSON object.
Do not include any other text, explanations, or markdown formatting in your response. The output must be only the repaired JSON object.
Invalid JSON:
{{invalidJson}}
`;
// src/agents/productManager.ts
var logger = createLogger("productManager");
var extractJsonFromResponse = (response) => {
try {
return JSON.parse(response.trim());
} catch {
const lines = response.split("\n");
let jsonStart = -1;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
if (line === "{" || line.startsWith('{"')) {
jsonStart = i;
break;
}
if (line.includes("</thinking>")) {
jsonStart = i + 1;
break;
}
}
if (jsonStart >= 0) {
const jsonLines = lines.slice(jsonStart);
const potentialJson = jsonLines.join("\n").trim();
try {
return JSON.parse(potentialJson);
} catch {
const match = potentialJson.match(/\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}/g);
if (match && match[0]) {
try {
return JSON.parse(match[0]);
} catch {
return null;
}
}
}
}
return null;
}
};
var runProductManager = async () => {
logger.start();
const context = getContext();
const { featurePrompt } = context;
const llmClient = getLlmClient();
const prompt = productManagerPrompt.replace("{{featurePrompt}}", featurePrompt);
let response = await llmClient.generate(prompt);
let spec = extractJsonFromResponse(response);
if (!spec) {
logger.error("Invalid JSON response from LLM. Attempting to repair...");
const repairPrompt = jsonRepairPrompt.replace("{{invalidJson}}", response);
response = await llmClient.generate(repairPrompt);
spec = extractJsonFromResponse(response);
if (!spec) {
logger.error("Failed to repair JSON response. Skipping spec generation.");
return {
summary: "Failed to generate product specification due to invalid LLM response",
error: "JSON parsing failed",
completedAt: (/* @__PURE__ */ new Date()).toISOString()
};
}
}
updateContext({ spec });
logger.stop();
logger.success("Generated product spec.");
return {
summary: `Product specification generated with ${spec.userStories?.length || 0} user stories and ${spec.acceptanceCriteria?.length || 0} acceptance criteria.`,
title: spec.title,
reasoning: response.includes("<thinking>") ? "Used chain-of-thought reasoning" : "Direct specification generation",
completedAt: (/* @__PURE__ */ new Date()).toISOString()
};
};
// src/agents/frontendDeveloper.ts
var logger2 = createLogger("frontendDeveloper");
var runFrontendDeveloper = async () => {
logger2.start();
const context = getContext();
const { spec } = context;
const llmClient = getLlmClient();
const prompt = frontendDeveloperPrompt.replace("{{spec}}", JSON.stringify(spec, null, 2));
const code = await llmClient.generate(prompt);
updateContext({ agents: { ...context.agents || {}, frontendDeveloper: { output: code, completed: true } } });
logger2.stop();
logger2.success("Generated frontend code.");
return code;
};
// src/agents/backendDeveloper.ts
var logger3 = createLogger("backendDeveloper");
var runBackendDeveloper = async () => {
const existingContext = getContext();
if (existingContext.agents?.backendDeveloper?.completed) {
return existingContext.agents.backendDeveloper.output;
}
logger3.start();
try {
const context = getContext();
const { spec } = context;
const llmClient = getLlmClient();
const prompt = backendDeveloperPrompt.replace("{{spec}}", JSON.stringify(spec, null, 2));
const code = await llmClient.generate(prompt);
updateContext({ agents: { ...context.agents || {}, backendDeveloper: { output: code, completed: true } } });
logger3.success("Generated backend code.");
return code;
} catch (error) {
console.error("[ERROR] Backend developer failed:", error);
throw error;
} finally {
logger3.stop();
}
};
// src/agents/fullstackIntegrator.ts
var logger4 = createLogger("fullstackIntegrator");
var runFullstackIntegrator = async () => {
logger4.start();
const context = getContext();
logger4.info("Ensuring FE and BE contract alignment.");
updateContext({ agents: { ...context.agents || {}, fullstackIntegrator: { completed: true } } });
logger4.stop();
logger4.success("Fullstack integration complete.");
return true;
};
// src/agents/qaEngineer.ts
var logger5 = createLogger("qaEngineer");
var runQaEngineer = async () => {
logger5.start();
const context = getContext();
const { spec, agents = {} } = context;
const backendOutput = agents.backendDeveloper?.output || "No backend code generated yet";
const frontendOutput = agents.frontendDeveloper?.output || "No frontend code generated yet";
const llmClient = getLlmClient();
const prompt = qaEngineerPrompt.replace("{{spec}}", JSON.stringify(spec, null, 2)).replace("{{backendCode}}", backendOutput).replace("{{frontendCode}}", frontendOutput);
const tests = await llmClient.generate(prompt);
updateContext({ agents: { ...agents, qaEngineer: { output: tests, completed: true } } });
logger5.stop();
logger5.success("Generated QA tests.");
return tests;
};
// src/agents/documentationAgent.ts
var logger6 = createLogger("documentationAgent");
var runDocumentationAgent = async () => {
logger6.start();
const context = getContext();
const { spec } = context;
const llmClient = getLlmClient();
const prompt = documentationAgentPrompt.replace("{{spec}}", JSON.stringify(spec, null, 2));
const doc = await llmClient.generate(prompt);
updateContext({ agents: { ...context.agents || {}, documentationAgent: { output: doc, completed: true } } });
logger6.stop();
logger6.success("Generated documentation.");
return doc;
};
// src/agents/infraEngineer.ts
var logger7 = createLogger("infraEngineer");
var runInfraEngineer = async () => {
logger7.start();
const context = getContext();
const { agents = {} } = context;
const backendOutput = agents.backendDeveloper?.output || "No backend code generated yet";
const frontendOutput = agents.frontendDeveloper?.output || "No frontend code generated yet";
const llmClient = getLlmClient();
const prompt = infraEngineerPrompt.replace("{{backendCode}}", backendOutput).replace("{{frontendCode}}", frontendOutput);
const dockerfile = await llmClient.generate(prompt);
updateContext({ agents: { ...agents, infraEngineer: { output: dockerfile, completed: true } } });
logger7.stop();
logger7.success("Generated Dockerfile.");
return dockerfile;
};
// src/agents/securityEngineer.ts
var logger8 = createLogger("securityEngineer");
var runSecurityEngineer = async () => {
logger8.start();
const context = getContext();
const { spec, agents = {} } = context;
const backendOutput = agents.backendDeveloper?.output || "No backend code generated yet";
const frontendOutput = agents.frontendDeveloper?.output || "No frontend code generated yet";
const llmClient = getLlmClient();
const prompt = securityEngineerPrompt.replace("{{spec}}", JSON.stringify(spec, null, 2)).replace("{{backendCode}}", backendOutput).replace("{{frontendCode}}", frontendOutput);
const report = await llmClient.generate(prompt);
updateContext({ agents: { ...agents, securityEngineer: { output: report, completed: true } } });
logger8.stop();
logger8.success("Generated security report.");
return report;
};
// src/agents/uxDesigner.ts
var logger9 = createLogger("uxDesigner");
var runUxDesigner = async () => {
logger9.start();
const context = getContext();
const { spec } = context;
const llmClient = getLlmClient();
const prompt = uxDesignerPrompt.replace("{{spec}}", JSON.stringify(spec, null, 2));
const report = await llmClient.generate(prompt);
updateContext({ agents: { ...context.agents || {}, uxDesigner: { output: report, completed: true } } });
logger9.stop();
logger9.success("Generated UX design report.");
return report;
};
// src/agents/copywriter.ts
var logger10 = createLogger("copywriter");
var runCopywriter = async () => {
logger10.start();
const context = getContext();
const { spec, agents = {} } = context;
const frontendOutput = agents.frontendDeveloper?.output || "No frontend code generated yet";
const llmClient = getLlmClient();
const prompt = copywriterPrompt.replace("{{spec}}", JSON.stringify(spec, null, 2)).replace("{{frontendCode}}", frontendOutput);
let response = await llmClient.generate(prompt);
let copy;
try {
copy = JSON.parse(response);
} catch (error) {
logger10.error("Invalid JSON response from LLM. Attempting to repair...");
const repairPrompt = jsonRepairPrompt.replace("{{invalidJson}}", response);
response = await llmClient.generate(repairPrompt);
try {
copy = JSON.parse(response);
} catch (error2) {
logger10.error("Failed to repair JSON response. Skipping copy generation.");
return;
}
}
updateContext({ agents: { ...agents, copywriter: { output: copy, completed: true } } });
logger10.stop();
logger10.success("Generated microcopy.");
return copy;
};
// src/agents/releaseManager.ts
var logger11 = createLogger("releaseManager");
var runReleaseManager = async () => {
logger11.start();
const context = getContext();
const llmClient = getLlmClient();
const prompt = releaseManagerPrompt.replace("{{context}}", JSON.stringify(context, null, 2));
const report = await llmClient.generate(prompt);
updateContext({ agents: { ...context.agents || {}, releaseManager: { output: report, completed: true } } });
logger11.stop();
logger11.success("Generated release plan.");
return report;
};
// src/agents/aiPromptEngineer.ts
var logger12 = createLogger("aiPromptEngineer");
var runAiPromptEngineer = async () => {
logger12.start();
const context = getContext();
const { spec } = context;
const llmClient = getLlmClient();
const prompt = aiPromptEngineerPrompt.replace("{{spec}}", JSON.stringify(spec, null, 2));
let response = await llmClient.generate(prompt);
let prompts;
try {
prompts = JSON.parse(response);
} catch (error) {
logger12.error("Invalid JSON response from LLM. Attempting to repair...");
const repairPrompt = jsonRepairPrompt.replace("{{invalidJson}}", response);
response = await llmClient.generate(repairPrompt);
try {
prompts = JSON.parse(response);
} catch (error2) {
logger12.error("Failed to repair JSON response. Skipping AI prompt generation.");
return;
}
}
updateContext({ agents: { ...context.agents || {}, aiPromptEngineer: { output: prompts, completed: true } } });
logger12.stop();
logger12.success("Generated AI prompts.");
return prompts;
};
// src/agents/dataEngineer.ts
var logger13 = createLogger("dataEngineer");
var runDataEngineer = async () => {
logger13.start();
const context = getContext();
const { spec } = context;
const llmClient = getLlmClient();
const prompt = dataEngineerPrompt.replace("{{spec}}", JSON.stringify(spec, null, 2));
let response = await llmClient.generate(prompt);
let events;
try {
events = JSON.parse(response);
} catch (error) {
logger13.error("Invalid JSON response from LLM. Attempting to repair...");
const repairPrompt = jsonRepairPrompt.replace("{{invalidJson}}", response);
response = await llmClient.generate(repairPrompt);
try {
events = JSON.parse(response);
} catch (error2) {
logger13.error("Failed to repair JSON response. Skipping analytics event generation.");
return;
}
}
updateContext({ agents: { ...context.agents || {}, dataEngineer: { output: events, completed: true } } });
logger13.stop();
logger13.success("Generated analytics events.");
return events;
};
// src/agents/reviewerAgent.ts
var logger14 = createLogger("reviewerAgent");
var runReviewerAgent = async () => {
logger14.start();
const context = getContext();
const { agents = {} } = context;
const backendOutput = agents.backendDeveloper?.output |