shipdeck
Version:
Ship MVPs in 48 hours. Fix bugs in 30 seconds. The command deck for developers who ship.
560 lines (508 loc) • 19.2 kB
JavaScript
/**
* Agent Factory for generating specialized agents from templates
* Efficiently creates the remaining 30+ agents for the Multi-Agent System
*/
const BaseAgent = require('./base-agent');
const fs = require('fs').promises;
const path = require('path');
/**
* Factory class for generating agents based on templates and specifications
*/
class AgentFactory {
constructor() {
this.agentSpecs = this.loadAgentSpecifications();
this.templates = this.loadTemplates();
}
/**
* Load agent specifications for all remaining agents
* @returns {Object} Agent specifications
*/
loadAgentSpecifications() {
return {
// Design Agents
'ui-designer': {
name: 'UIDesigner',
description: 'Specializes in creating beautiful, functional interfaces',
capabilities: ['design', 'components', 'layouts', 'color-schemes', 'typography'],
category: 'design',
methods: ['createDesignSystem', 'generateComponents', 'optimizeLayouts']
},
'ux-researcher': {
name: 'UXResearcher',
description: 'Conducts user research and validates design decisions',
capabilities: ['research', 'testing', 'journey-mapping', 'personas', 'analytics'],
category: 'design',
methods: ['conductResearch', 'createJourneyMaps', 'analyzeUserBehavior']
},
'brand-guardian': {
name: 'BrandGuardian',
description: 'Maintains brand consistency across all touchpoints',
capabilities: ['branding', 'guidelines', 'consistency', 'assets', 'identity'],
category: 'design',
methods: ['enforceBrandGuidelines', 'createBrandAssets', 'auditConsistency']
},
'visual-storyteller': {
name: 'VisualStoryteller',
description: 'Creates compelling visual narratives and infographics',
capabilities: ['storytelling', 'infographics', 'presentations', 'data-viz'],
category: 'design',
methods: ['createInfographics', 'buildPresentations', 'visualizeData']
},
// Marketing Agents
'tiktok-strategist': {
name: 'TikTokStrategist',
description: 'Creates viral TikTok content and growth strategies',
capabilities: ['tiktok', 'viral-content', 'trends', 'gen-z', 'short-form'],
category: 'marketing',
methods: ['createViralContent', 'analyzeTrends', 'optimizeForAlgorithm']
},
'instagram-curator': {
name: 'InstagramCurator',
description: 'Manages Instagram visual content and engagement strategies',
capabilities: ['instagram', 'visual-content', 'stories', 'reels', 'engagement'],
category: 'marketing',
methods: ['curateContent', 'createStories', 'buildEngagement']
},
'twitter-engager': {
name: 'TwitterEngager',
description: 'Manages real-time Twitter engagement and viral strategies',
capabilities: ['twitter', 'real-time', 'engagement', 'threads', 'viral-tweets'],
category: 'marketing',
methods: ['createViralTweets', 'engageInRealTime', 'buildThreads']
},
'reddit-community-builder': {
name: 'RedditCommunityBuilder',
description: 'Builds authentic Reddit community presence',
capabilities: ['reddit', 'community', 'authentic-engagement', 'value-first'],
category: 'marketing',
methods: ['buildCommunity', 'provideValue', 'engageAuthentically']
},
'content-creator': {
name: 'ContentCreator',
description: 'Creates cross-platform content from blog posts to videos',
capabilities: ['content', 'blogging', 'seo', 'copywriting', 'multimedia'],
category: 'marketing',
methods: ['createContent', 'optimizeForSEO', 'adaptAcrossPlatforms']
},
'app-store-optimizer': {
name: 'AppStoreOptimizer',
description: 'Optimizes app store listings for maximum visibility',
capabilities: ['aso', 'keywords', 'conversion', 'app-store', 'play-store'],
category: 'marketing',
methods: ['optimizeListing', 'researchKeywords', 'improveConversion']
},
// Product Agents
'feedback-synthesizer': {
name: 'FeedbackSynthesizer',
description: 'Analyzes and synthesizes user feedback into insights',
capabilities: ['feedback', 'analysis', 'insights', 'patterns', 'prioritization'],
category: 'product',
methods: ['analyzeFeedback', 'identifyPatterns', 'prioritizeFeatures']
},
'sprint-prioritizer': {
name: 'SprintPrioritizer',
description: 'Prioritizes features and manages sprint planning',
capabilities: ['planning', 'prioritization', 'sprints', 'roadmaps', 'trade-offs'],
category: 'product',
methods: ['prioritizeTasks', 'planSprints', 'createRoadmaps']
},
'trend-researcher': {
name: 'TrendResearcher',
description: 'Identifies market trends and opportunities',
capabilities: ['research', 'trends', 'market-analysis', 'opportunities'],
category: 'product',
methods: ['researchTrends', 'analyzeMarket', 'identifyOpportunities']
},
// Studio Operations
'analytics-reporter': {
name: 'AnalyticsReporter',
description: 'Generates insights from data and creates reports',
capabilities: ['analytics', 'reporting', 'insights', 'dashboards', 'metrics'],
category: 'operations',
methods: ['generateReports', 'createDashboards', 'analyzeMetrics']
},
'finance-tracker': {
name: 'FinanceTracker',
description: 'Manages budgets and tracks financial performance',
capabilities: ['budgeting', 'costs', 'revenue', 'forecasting', 'roi'],
category: 'operations',
methods: ['trackBudget', 'forecastRevenue', 'calculateROI']
},
'infrastructure-maintainer': {
name: 'InfrastructureMaintainer',
description: 'Monitors system health and manages infrastructure',
capabilities: ['monitoring', 'scaling', 'reliability', 'performance', 'health'],
category: 'operations',
methods: ['monitorHealth', 'optimizePerformance', 'ensureReliability']
},
'legal-compliance-checker': {
name: 'LegalComplianceChecker',
description: 'Ensures regulatory compliance and legal requirements',
capabilities: ['compliance', 'gdpr', 'security', 'privacy', 'regulations'],
category: 'operations',
methods: ['checkCompliance', 'auditPrivacy', 'ensureRegulations']
},
'support-responder': {
name: 'SupportResponder',
description: 'Handles customer support and creates documentation',
capabilities: ['support', 'documentation', 'automation', 'patterns', 'responses'],
category: 'operations',
methods: ['handleSupport', 'createDocumentation', 'automateResponses']
},
// Project Management
'experiment-tracker': {
name: 'ExperimentTracker',
description: 'Tracks A/B tests and feature experiments',
capabilities: ['experiments', 'a-b-testing', 'features', 'metrics', 'results'],
category: 'project',
methods: ['trackExperiments', 'analyzeResults', 'manageFeaturesFlags']
},
'project-shipper': {
name: 'ProjectShipper',
description: 'Coordinates releases and launch activities',
capabilities: ['releases', 'launches', 'coordination', 'deployment', 'marketing'],
category: 'project',
methods: ['coordinateRelease', 'manageLaunch', 'executeGoToMarket']
},
'studio-producer': {
name: 'StudioProducer',
description: 'Coordinates cross-functional teams and resources',
capabilities: ['coordination', 'resources', 'workflows', 'teams', 'optimization'],
category: 'project',
methods: ['coordinateTeams', 'allocateResources', 'optimizeWorkflows']
},
// Testing Agents
'api-tester': {
name: 'APITester',
description: 'Performs comprehensive API testing',
capabilities: ['api-testing', 'load-testing', 'contract-testing', 'performance'],
category: 'testing',
methods: ['testAPIs', 'performLoadTests', 'validateContracts']
},
'performance-benchmarker': {
name: 'PerformanceBenchmarker',
description: 'Benchmarks and optimizes performance',
capabilities: ['benchmarking', 'profiling', 'optimization', 'speed', 'metrics'],
category: 'testing',
methods: ['benchmarkPerformance', 'profileCode', 'optimizeSpeed']
},
'test-results-analyzer': {
name: 'TestResultsAnalyzer',
description: 'Analyzes test results and identifies patterns',
capabilities: ['analysis', 'patterns', 'insights', 'quality-metrics', 'reporting'],
category: 'testing',
methods: ['analyzeResults', 'identifyPatterns', 'generateMetrics']
},
'tool-evaluator': {
name: 'ToolEvaluator',
description: 'Evaluates and recommends development tools',
capabilities: ['evaluation', 'comparison', 'recommendations', 'assessment'],
category: 'testing',
methods: ['evaluateTools', 'compareOptions', 'recommendSolutions']
},
'workflow-optimizer': {
name: 'WorkflowOptimizer',
description: 'Optimizes development workflows and processes',
capabilities: ['optimization', 'efficiency', 'automation', 'workflows', 'processes'],
category: 'testing',
methods: ['optimizeWorkflows', 'automateProcesses', 'improveEfficiency']
},
// Orchestration Agents
'task-coordinator': {
name: 'TaskCoordinator',
description: 'Coordinates parallel task execution',
capabilities: ['coordination', 'delegation', 'monitoring', 'synchronization'],
category: 'orchestration',
methods: ['coordinateTasks', 'delegateWork', 'synchronizeResults']
},
'variant-generator': {
name: 'VariantGenerator',
description: 'Generates multiple solution variants',
capabilities: ['variants', 'alternatives', 'approaches', 'generation'],
category: 'orchestration',
methods: ['generateVariants', 'createAlternatives', 'exploreApproaches']
},
'worktree-manager': {
name: 'WorktreeManager',
description: 'Manages Git worktrees for parallel development',
capabilities: ['worktrees', 'git', 'parallel-development', 'branches'],
category: 'orchestration',
methods: ['createWorktrees', 'manageWorktrees', 'mergeResults']
},
'conflict-detector': {
name: 'ConflictDetector',
description: 'Detects and resolves file conflicts',
capabilities: ['conflict-detection', 'resolution', 'file-analysis', 'dependencies'],
category: 'orchestration',
methods: ['detectConflicts', 'analyzeOverlaps', 'suggestResolutions']
},
// Bonus Agents
'joker': {
name: 'Joker',
description: 'Lightens the mood with humor and dad jokes',
capabilities: ['humor', 'jokes', 'morale', 'entertainment', 'fun'],
category: 'bonus',
methods: ['tellJoke', 'lightenMood', 'createPuns']
},
'studio-coach': {
name: 'StudioCoach',
description: 'Provides motivation and team guidance',
capabilities: ['motivation', 'guidance', 'coaching', 'team-building', 'morale'],
category: 'bonus',
methods: ['motivateTeam', 'provideGuidance', 'buildMorale']
},
// Additional Required Agents
'test-writer-fixer': {
name: 'TestWriterFixer',
description: 'Writes and fixes comprehensive test suites',
capabilities: ['testing', 'test-writing', 'test-fixing', 'coverage', 'validation'],
category: 'testing',
methods: ['writeTests', 'fixTests', 'ensureCoverage']
},
'devops-automator': {
name: 'DevOpsAutomator',
description: 'Automates CI/CD and deployment processes',
capabilities: ['ci-cd', 'deployment', 'automation', 'monitoring', 'infrastructure'],
category: 'engineering',
methods: ['setupCICD', 'automateDeployment', 'configureMonitoring']
}
};
}
/**
* Load agent template structure
* @returns {Object} Template structure
*/
loadTemplates() {
return {
basic: this.getBasicTemplate(),
advanced: this.getAdvancedTemplate()
};
}
/**
* Get basic agent template
* @returns {string} Basic template
*/
getBasicTemplate() {
return `/**
* {{NAME}} Agent
* {{DESCRIPTION}}
*/
const BaseAgent = require('./base-agent');
const { AnthropicClient } = require('../anthropic/client');
/**
* {{NAME}} - {{DESCRIPTION}}
*/
class {{CLASS_NAME}} extends BaseAgent {
constructor(config = {}) {
super('{{CLASS_NAME}}', {
...config,
description: '{{DESCRIPTION}}',
version: '1.0.0'
});
this.capabilities = {{CAPABILITIES}};
this.anthropicClient = config.anthropicClient || new AnthropicClient();
}
/**
* Get agent capabilities
* @returns {Array} List of capabilities
*/
getCapabilities() {
return this.capabilities;
}
/**
* Get system prompt for the agent
* @returns {string} System prompt
*/
getSystemPrompt() {
return \`You are {{CLASS_NAME}}, an AI agent specialized in {{SPECIALIZATION}}.
Your core responsibilities:
{{RESPONSIBILITIES}}
Always provide practical, production-ready solutions.\`;
}
/**
* Execute agent task
* @param {Object} task - Task to execute
* @param {Object} context - Execution context
* @returns {Promise<Object>} Execution result
*/
async execute(task, context = {}) {
try {
this.validateTask(task);
const systemPrompt = this.getSystemPrompt();
const userPrompt = this.createPrompt(task, context);
const response = await this.anthropicClient.createMessage(
\`\${systemPrompt}\n\n\${userPrompt}\`,
{
maxTokens: 4096,
temperature: 0.7
}
);
return this.parseResponse(response, task.type);
} catch (error) {
this.emit('error', error);
throw new Error(\`{{CLASS_NAME}} execution failed: \${error.message}\`);
}
}
/**
* Create prompt for the task
* @param {Object} task - Task object
* @param {Object} context - Context object
* @returns {string} Generated prompt
*/
createPrompt(task, context) {
const { type, description, requirements = [] } = task;
return \`Task Type: \${type}
Description: \${description}
Requirements: \${requirements.join(', ')}
Please provide a comprehensive solution.\`;
}
/**
* Parse agent response
* @param {Object} response - API response
* @param {string} type - Task type
* @returns {Object} Parsed result
*/
parseResponse(response, type) {
const content = response.content?.[0]?.text || '';
return {
success: true,
type: type,
content: content,
timestamp: new Date().toISOString()
};
}
{{METHODS}}
}
module.exports = {{CLASS_NAME}};
`;
}
/**
* Get advanced agent template with more features
* @returns {string} Advanced template
*/
getAdvancedTemplate() {
// Advanced template for complex agents
return this.getBasicTemplate(); // For now, use basic template
}
/**
* Generate an agent from specification
* @param {string} agentKey - Agent identifier
* @param {Object} spec - Agent specification
* @returns {Promise<string>} Generated agent code
*/
async generateAgent(agentKey, spec) {
const template = this.templates.basic;
const className = spec.name + 'Agent';
// Generate methods code
const methodsCode = this.generateMethods(spec.methods, className);
// Generate responsibilities list
const responsibilities = spec.capabilities.map(cap => `- ${cap}`).join('\n');
// Replace template placeholders
let agentCode = template
.replace(/{{NAME}}/g, spec.name)
.replace(/{{CLASS_NAME}}/g, className)
.replace(/{{DESCRIPTION}}/g, spec.description)
.replace(/{{CAPABILITIES}}/g, JSON.stringify(spec.capabilities))
.replace(/{{SPECIALIZATION}}/g, spec.capabilities.join(', '))
.replace(/{{RESPONSIBILITIES}}/g, responsibilities)
.replace(/{{METHODS}}/g, methodsCode);
return agentCode;
}
/**
* Generate method implementations
* @param {Array} methods - Method names
* @param {string} className - Class name
* @returns {string} Methods code
*/
generateMethods(methods, className) {
if (!methods || methods.length === 0) return '';
return methods.map(method => `
/**
* ${method} implementation
* @param {Object} params - Method parameters
* @returns {Promise<Object>} Method result
*/
async ${method}(params = {}) {
const task = {
type: '${method}',
...params
};
return this.execute(task);
}`).join('\n');
}
/**
* Generate all remaining agents
* @returns {Promise<Object>} Generation results
*/
async generateAllAgents() {
const results = {
generated: [],
failed: [],
total: 0
};
for (const [key, spec] of Object.entries(this.agentSpecs)) {
try {
const agentCode = await this.generateAgent(key, spec);
const fileName = `${key}.js`;
const filePath = path.join(__dirname, fileName);
// Write agent file
await fs.writeFile(filePath, agentCode);
results.generated.push({
name: spec.name,
file: fileName,
category: spec.category
});
} catch (error) {
results.failed.push({
name: spec.name,
error: error.message
});
}
}
results.total = results.generated.length + results.failed.length;
return results;
}
/**
* Generate a single agent by key
* @param {string} agentKey - Agent key
* @returns {Promise<Object>} Generation result
*/
async generateSingleAgent(agentKey) {
const spec = this.agentSpecs[agentKey];
if (!spec) {
throw new Error(`Agent specification not found for: ${agentKey}`);
}
const agentCode = await this.generateAgent(agentKey, spec);
const fileName = `${agentKey}.js`;
const filePath = path.join(__dirname, fileName);
await fs.writeFile(filePath, agentCode);
return {
name: spec.name,
file: fileName,
category: spec.category,
capabilities: spec.capabilities
};
}
/**
* List all available agent specifications
* @returns {Array} List of agent specs
*/
listAgentSpecs() {
return Object.entries(this.agentSpecs).map(([key, spec]) => ({
key,
name: spec.name,
description: spec.description,
category: spec.category,
capabilities: spec.capabilities
}));
}
/**
* Get agent specification by key
* @param {string} agentKey - Agent key
* @returns {Object} Agent specification
*/
getAgentSpec(agentKey) {
return this.agentSpecs[agentKey];
}
}
module.exports = AgentFactory;