UNPKG

@oliverpople/agency-x

Version:

🚀 **Transform feature requests into production-ready code in seconds**

1,298 lines (1,195 loc) • 67.2 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var index_exports = {}; __export(index_exports, { runOrchestrator: () => runOrchestrator }); module.exports = __toCommonJS(index_exports); // src/utils/contextStore.ts var import_promises = __toESM(require("fs/promises")); var import_path = __toESM(require("path")); var currentContext = null; var sessionsDir = import_path.default.join(process.cwd(), "sessions"); var backupDir = import_path.default.join(sessionsDir, "backups"); var ensureDirectories = async () => { await import_promises.default.mkdir(sessionsDir, { recursive: true }); await import_promises.default.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 import_promises.default.stat(filePath); if (stats.isFile()) { const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-"); const fileName = import_path.default.basename(filePath, ".json"); const backupPath = import_path.default.join(backupDir, `${fileName}-${timestamp}.json`); await import_promises.default.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 = import_path.default.join(sessionsDir, `${currentContext.specId}.json`); if (createBackupFlag) { await createBackup(filePath); } const tempPath = `${filePath}.tmp`; try { await import_promises.default.writeFile(tempPath, JSON.stringify(currentContext, null, 2)); await import_promises.default.rename(tempPath, filePath); console.log(`\u2705 Context saved successfully: ${filePath}`); return filePath; } catch (error) { try { await import_promises.default.unlink(tempPath); } catch { } throw new Error(`Failed to save context: ${error}`); } }; var loadContext = async (specId) => { const filePath = import_path.default.join(sessionsDir, `${specId}.json`); try { const data = await import_promises.default.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/logger.ts var import_chalk = __toESM(require("chalk")); var agentStyles = { productManager: import_chalk.default.bold.blue, frontendDeveloper: import_chalk.default.green, backendDeveloper: import_chalk.default.yellow.italic, qaEngineer: import_chalk.default.red.underline, documentationAgent: import_chalk.default.cyan, fullstackIntegrator: import_chalk.default.magenta, infraEngineer: import_chalk.default.gray, securityEngineer: import_chalk.default.yellow, uxDesigner: import_chalk.default.blue, copywriter: import_chalk.default.green, releaseManager: import_chalk.default.magenta.bold, aiPromptEngineer: import_chalk.default.blue.italic, dataEngineer: import_chalk.default.yellow, orchestratorAgent: import_chalk.default.bold.magenta, voiceNarratorAgent: import_chalk.default.italic.gray, reviewerAgent: import_chalk.default.bold.yellow, assumptionChallenger: import_chalk.default.bold.red, userEmpathyAgent: import_chalk.default.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, import_chalk.default.white(message), "\u2139\uFE0F"), success: (message) => log(agentName, import_chalk.default.greenBright(message), "\u2705"), error: (message) => log(agentName, import_chalk.default.redBright(message), "\u274C"), warn: (message) => log(agentName, import_chalk.default.yellowBright(message), "\u26A0\uFE0F"), debug: (message) => { if (process.env.DEBUG === "true") { log(agentName, import_chalk.default.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/voice.ts var say = require("say"); var voiceEnabled = false; var setVoiceEnabled = (enabled) => { voiceEnabled = enabled; }; // 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/agentOrchestrator.ts var DependencyGraph = class { agents = /* @__PURE__ */ new Map(); completed = /* @__PURE__ */ new Set(); failed = /* @__PURE__ */ new Set(); running = /* @__PURE__ */ new Set(); addAgent(definition) { this.agents.set(definition.name, definition); } canRunAgent(agentName) { const agent = this.agents.get(agentName); if (!agent) return false; if (this.completed.has(agentName) || this.failed.has(agentName) || this.running.has(agentName)) { return false; } return agent.dependencies.every((dep) => this.completed.has(dep)); } getReadyAgents() { return Array.from(this.agents.keys()).filter((name) => this.canRunAgent(name)); } markCompleted(agentName) { this.completed.add(agentName); this.running.delete(agentName); } markFailed(agentName) { this.failed.add(agentName); this.running.delete(agentName); } markRunning(agentName) { this.running.add(agentName); } getStatus() { return { total: this.agents.size, completed: this.completed.size, failed: this.failed.size, running: this.running.size, pending: this.agents.size - this.completed.size - this.failed.size - this.running.size }; } getCriticalFailures() { return Array.from(this.failed).filter((name) => { const agent = this.agents.get(name); return agent?.critical === true; }); } isComplete() { return this.completed.size + this.failed.size === this.agents.size; } canContinue() { const criticalFailures = this.getCriticalFailures(); const hasReadyAgents = this.getReadyAgents().length > 0; const hasRunningAgents = this.running.size > 0; return criticalFailures.length === 0 && (hasReadyAgents || hasRunningAgents); } }; var AgentOrchestrator = class { graph = new DependencyGraph(); maxConcurrent; saveInterval = 3e4; // Save every 30 seconds saveTimer; onProgress; constructor(maxConcurrent = 5, onProgress) { this.maxConcurrent = maxConcurrent; this.onProgress = onProgress; this.startPeriodicSave(); } startPeriodicSave() { this.saveTimer = setInterval(async () => { try { await saveContext(false); } catch (error) { console.warn("Periodic save failed:", error); } }, this.saveInterval); } stopPeriodicSave() { if (this.saveTimer) { clearInterval(this.saveTimer); this.saveTimer = void 0; } } addAgent(definition) { this.graph.addAgent(definition); } async runAgent(agentName) { const agent = this.graph.agents.get(agentName); if (!agent) throw new Error(`Agent ${agentName} not found`); const config = { name: agentName, dependencies: agent.dependencies, ...DEFAULT_AGENT_CONFIG, ...agent.critical ? { retryConfig: CRITICAL_RETRY_CONFIG } : {}, ...agent.config, critical: agent.critical }; const runner = createAgentRunner(config); const startTime = Date.now(); try { this.graph.markRunning(agentName); updateAgentOutput(agentName, { completed: false, startTime, retryCount: 0 }); const isVerbose = process.env.DEBUG === "true"; const output = await runner(agent.runner); const executionTime = Date.now() - startTime; updateAgentOutput(agentName, { output, completed: true, executionTime }); this.graph.markCompleted(agentName); if (isVerbose) console.log(`\u2705 Agent completed: ${agentName} (${executionTime}ms)`); if (this.onProgress) { const status = this.graph.getStatus(); this.onProgress({ completed: status.completed, failed: status.failed, running: status.running }); } } catch (error) { const executionTime = Date.now() - startTime; const agentError = error instanceof AgentError ? error : new AgentError(agentName, String(error)); updateAgentOutput(agentName, { completed: false, error: agentError.message, executionTime }); this.graph.markFailed(agentName); if (agent.critical) { console.error(`\u{1F4A5} Critical agent failed: ${agentName} - ${agentError.message}`); throw agentError; } else { console.warn(`\u26A0\uFE0F Non-critical agent failed: ${agentName} - ${agentError.message}`); } } } async runAll() { const isVerbose = process.env.DEBUG === "true"; if (isVerbose) console.log("\u{1F3AC} Starting orchestration..."); try { while (!this.graph.isComplete() && this.graph.canContinue()) { const readyAgents = this.graph.getReadyAgents(); const currentlyRunning = this.graph.running.size; if (readyAgents.length === 0 && currentlyRunning === 0) { if (isVerbose) console.warn("\u26A0\uFE0F No agents ready to run and none currently running. Possible dependency deadlock."); break; } const availableSlots = this.maxConcurrent - currentlyRunning; const agentsToStart = readyAgents.slice(0, availableSlots); if (agentsToStart.length > 0) { if (isVerbose) { console.log(`\u{1F4CA} Status: ${JSON.stringify(this.graph.getStatus())}`); console.log(`\u{1F504} Starting ${agentsToStart.length} agents: ${agentsToStart.join(", ")}`); } const promises = agentsToStart.map( (agentName) => this.runAgent(agentName).catch((error) => { if (error instanceof AgentError && this.graph.agents.get(agentName)?.critical) { throw error; } }) ); await Promise.allSettled(promises); } else { await new Promise((resolve) => setTimeout(resolve, 1e3)); } } const status = this.graph.getStatus(); const criticalFailures = this.graph.getCriticalFailures(); if (isVerbose) console.log(`\u{1F4CA} Final Status: ${JSON.stringify(status)}`); if (criticalFailures.length > 0) { throw new Error(`Orchestration failed due to critical agent failures: ${criticalFailures.join(", ")}`); } if (status.failed > 0) { const failedAgents = Array.from(this.graph.failed); console.warn(`\u26A0\uFE0F Orchestration completed with ${status.failed} non-critical failures: ${failedAgents.join(", ")}`); } const completionRate = status.total > 0 ? Math.round(status.completed / status.total * 100) : 0; console.log(`\u{1F389} Orchestration completed! ${status.completed}/${status.total} agents (${completionRate}%) succeeded`); } finally { this.stopPeriodicSave(); try { await saveContext(); } catch (error) { if (isVerbose) console.error("Failed to save final context:", error); } } } getStatus() { return this.graph.getStatus(); } // Cleanup method cleanup() { this.stopPeriodicSave(); } }; // src/llm/claudeClient.ts var import_sdk = __toESM(require("@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 import_sdk.default({ 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 var import_openai = __toESM(require("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 import_openai.default({ 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 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/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)