| name | agent-resource-allocator |
| description | Agent skill for resource-allocator - invoke with $agent-resource-allocator |
name: Resource Allocator
type: agent
category: optimization
description: Adaptive resource allocation, predictive scaling and intelligent capacity planning
Resource Allocator Agent
Agent Profile
- Name: Resource Allocator
- Type: Performance Optimization Agent
- Specialization: Adaptive resource allocation and predictive scaling
- Performance Focus: Intelligent resource management and capacity planning
Core Capabilities
1. Adaptive Resource Allocation
class AdaptiveResourceAllocator {
constructor() {
this.allocators = {
cpu: new CPUAllocator(),
memory: new MemoryAllocator(),
storage: new StorageAllocator(),
network: new NetworkAllocator(),
agents: new AgentAllocator()
};
this.predictor = new ResourcePredictor();
this.optimizer = new AllocationOptimizer();
this.monitor = new ResourceMonitor();
}
async allocateResources(swarmId, workloadProfile, constraints = {}) {
const currentUsage = await this.analyzeCurrentUsage(swarmId);
const predictions = await this.predictor.predict(workloadProfile, currentUsage);
const allocation = await this.optimizer.optimize(predictions, constraints);
const rolloutPlan = await this.planGradualRollout(allocation, currentUsage);
const result = await this.executeAllocation(rolloutPlan);
return {
allocation,
rolloutPlan,
result,
monitoring: await this.setupMonitoring(allocation)
};
}
async analyzeWorkloadPatterns(historicalData, timeWindow = '7d') {
const patterns = {
temporal: {
hourly: this.analyzeHourlyPatterns(historicalData),
daily: this.analyzeDailyPatterns(historicalData),
weekly: this.analyzeWeeklyPatterns(historicalData),
seasonal: this.analyzeSeasonalPatterns(historicalData)
},
load: {
baseline: this.calculateBaselineLoad(historicalData),
peaks: this.identifyPeakPatterns(historicalData),
valleys: this.identifyValleyPatterns(historicalData),
spikes: this.detectAnomalousSpikes(historicalData)
},
correlations: {
cpu_memory: this.analyzeCPUMemoryCorrelation(historicalData),
network_load: this.analyzeNetworkLoadCorrelation(historicalData),
agent_resource: this.analyzeAgentResourceCorrelation(historicalData)
},
indicators: {
growth_rate: this.calculateGrowthRate(historicalData),
volatility: this.calculateVolatility(historicalData),
predictability: this.calculatePredictability(historicalData)
}
};
return patterns;
}
async optimizeResourceAllocation(resources, demands, objectives) {
const optimizationProblem = {
variables: this.defineOptimizationVariables(resources),
constraints: this.defineConstraints(resources, demands),
objectives: this.defineObjectives(objectives)
};
const solver = new MultiObjectiveGeneticSolver({
populationSize: 100,
generations: 200,
mutationRate: 0.1,
crossoverRate: 0.8
});
const solutions = await solver.solve(optimizationProblem);
const selectedSolution = this.selectFromParetoFront(solutions, objectives);
return {
optimalAllocation: selectedSolution.allocation,
paretoFront: solutions.paretoFront,
tradeoffs: solutions.tradeoffs,
confidence: selectedSolution.confidence
};
}
}
2. Predictive Scaling with Machine Learning
class PredictiveScaler {
constructor() {
this.models = {
time_series: new LSTMTimeSeriesModel(),
regression: new RandomForestRegressor(),
anomaly: new IsolationForestModel(),
ensemble: new EnsemblePredictor()
};
this.featureEngineering = new FeatureEngineer();
this.dataPreprocessor = new DataPreprocessor();
}
async predictScaling(swarmId, timeHorizon = 3600, confidence = 0.95) {
const trainingData = await this.collectTrainingData(swarmId);
const features = await this.featureEngineering.engineer(trainingData);
await this.updateModels(features);
predictions = .(timeHorizon, confidence);
scalingPlan = .(predictions);
{
predictions,
scalingPlan,
: predictions.,
timeHorizon,
: features.
};
}
() {
model = mcp.({
: ,
: .({
: data.,
: data.,
: data.
}),
: config. ||
});
validation = .(model, data.);
(validation. > ) {
mcp.({
: model.,
:
});
{
model,
validation,
:
};
}
{
: ,
validation,
: ,
:
};
}
() {
agent = ({
: environment.,
: environment.,
: ,
: ,
: ,
:
});
trainingHistory = [];
( episode = ; episode < episodes; episode++) {
state = environment.();
totalReward = ;
done = ;
(!done) {
action = agent.(state);
{ nextState, reward, terminated } = environment.(action);
agent.(state, action, reward, nextState, terminated);
state = nextState;
totalReward += reward;
done = terminated;
(agent.. > agent.) {
agent.();
}
}
trainingHistory.({
episode,
: totalReward,
: agent.
});
(episode % === ) {
.();
}
}
{
agent,
trainingHistory,
: .(trainingHistory)
};
}
}
3. Circuit Breaker and Fault Tolerance
class AdaptiveCircuitBreaker {
constructor(config = {}) {
this.failureThreshold = config.failureThreshold || 5;
this.recoveryTimeout = config.recoveryTimeout || 60000;
this.successThreshold = config.successThreshold || 3;
this.state = 'CLOSED';
this.failureCount = 0;
this.successCount = 0;
this.lastFailureTime = null;
this.adaptiveThresholds = new AdaptiveThresholdManager();
this.performanceHistory = new CircularBuffer(1000);
this.metrics = {
totalRequests: 0,
successfulRequests: 0,
failedRequests: 0,
: ,
: ,
:
};
}
() {
..++;
(. === ) {
(.()) {
. = ;
. = ;
..++;
} {
.(fallback);
}
}
{
startTime = performance.();
result = ();
endTime = performance.();
.(endTime - startTime);
result;
} (error) {
.(error);
(fallback) {
.(fallback);
}
error;
}
}
() {
analysis = ..(performanceData);
(analysis.) {
. = .(
,
.(. * analysis.)
);
. = .(
,
.(. * analysis.)
);
}
}
() {
resourcePools.( ({
: pool.,
: pool.,
: (),
: (pool.),
: (pool.),
: ()
}));
}
}
4. Performance Profiling and Optimization
class PerformanceProfiler {
constructor() {
this.profilers = {
cpu: new CPUProfiler(),
memory: new MemoryProfiler(),
io: new IOProfiler(),
network: new NetworkProfiler(),
application: new ApplicationProfiler()
};
this.analyzer = new ProfileAnalyzer();
this.optimizer = new PerformanceOptimizer();
}
async profilePerformance(swarmId, duration = 60000) {
const profilingSession = {
swarmId,
startTime: Date.now(),
duration,
profiles: new Map()
};
const profilingTasks = Object.entries(this.profilers).map(
([type, profiler]) => {
profile = profiler.(duration);
[type, profile];
}
);
profiles = .(profilingTasks);
( [type, profile] profiles) {
profilingSession..(type, profile);
}
analysis = ..(profilingSession);
recommendations = ..(analysis);
{
: profilingSession,
analysis,
recommendations,
: .(analysis, recommendations)
};
}
() {
cpuProfile = {
: [],
: (),
: [],
:
};
sampleInterval = ;
samples = duration / sampleInterval;
( i = ; i < samples; i++) {
sample = .();
cpuProfile..(sample);
.(cpuProfile., sample);
.(sampleInterval);
}
cpuProfile. = .(cpuProfile.);
cpuProfile. = .(cpuProfile.);
cpuProfile;
}
() {
memoryProfile = {
: [],
: [],
: [],
: [],
: []
};
previousSnapshot = .();
memoryProfile..(previousSnapshot);
snapshotInterval = ;
snapshots = duration / snapshotInterval;
( i = ; i < snapshots; i++) {
.(snapshotInterval);
snapshot = .();
memoryProfile..(snapshot);
changes = .(previousSnapshot, snapshot);
memoryProfile..(...changes.);
memoryProfile..(...changes.);
leaks = .(changes);
memoryProfile..(...leaks);
previousSnapshot = snapshot;
}
memoryProfile. = .(memoryProfile.);
memoryProfile;
}
}
MCP Integration Hooks
Resource Management Integration
const resourceIntegration = {
async allocateResources(swarmId, requirements) {
const currentUsage = await mcp.metrics_collect({
components: ['cpu', 'memory', 'network', 'agents']
});
const performance = await mcp.performance_report({ format: 'detailed' });
const bottlenecks = await mcp.bottleneck_analyze({});
const allocation = await this.calculateOptimalAllocation(
currentUsage,
performance,
bottlenecks,
requirements
);
const result = await mcp.daa_resource_alloc({
resources: allocation.resources,
agents: allocation.agents
});
return {
allocation,
result,
monitoring: await this.setupResourceMonitoring(allocation)
};
},
() {
status = mcp.({ swarmId });
scalingPlan = .(status, predictions);
(scalingPlan.) {
scalingResult = mcp.({
swarmId,
: scalingPlan.
});
(scalingResult.) {
mcp.({ swarmId });
}
{
: ,
: scalingPlan,
: scalingResult
};
}
{
: ,
: ,
: scalingPlan
};
},
() {
metrics = .([
mcp.({ : }),
mcp.({}),
mcp.({}),
mcp.({ : [, , ] })
]);
[performance, bottlenecks, agentMetrics, systemMetrics] = metrics;
optimizations = .({
performance,
bottlenecks,
agentMetrics,
systemMetrics
});
results = .(swarmId, optimizations);
{
optimizations,
results,
: .(swarmId, results)
};
}
};
Operational Commands
Resource Management Commands
npx claude-flow metrics-collect --components ["cpu", "memory", "network"]
npx claude-flow daa-resource-alloc --resources <resource-config>
npx claude-flow swarm-scale --swarm-id <id> --target-size <size>
npx claude-flow performance-report --format detailed --timeframe 24h
npx claude-flow fault-tolerance --strategy circuit-breaker --config <config>
Optimization Commands
npx claude-flow optimize-performance --swarm-id <id> --strategy adaptive
npx claude-flow forecast-resources --time-horizon 3600 --confidence 0.95
npx claude-flow profile-performance --duration 60000 --components all
npx claude-flow bottleneck-analyze --component swarm-coordination
Integration Points
With Other Optimization Agents
- Load Balancer: Provides resource allocation data for load balancing decisions
- Performance Monitor: Shares performance metrics and bottleneck analysis
- Topology Optimizer: Coordinates resource allocation with topology changes
With Swarm Infrastructure
- Task Orchestrator: Allocates resources for task execution
- Agent Coordinator: Manages agent resource requirements
- Memory System: Stores resource allocation history and patterns
Performance Metrics
Resource Allocation KPIs
const allocationMetrics = {
efficiency: {
utilization_rate: this.calculateUtilizationRate(),
waste_percentage: this.calculateWastePercentage(),
allocation_accuracy: this.calculateAllocationAccuracy(),
prediction_accuracy: this.calculatePredictionAccuracy()
},
performance: {
allocation_latency: this.calculateAllocationLatency(),
scaling_response_time: this.calculateScalingResponseTime(),
optimization_impact: this.calculateOptimizationImpact(),
cost_efficiency: this.calculateCostEfficiency()
},
reliability: {
availability: this.calculateAvailability(),
fault_tolerance: this.calculateFaultTolerance(),
recovery_time: this.calculateRecoveryTime(),
circuit_breaker_effectiveness: this.calculateCircuitBreakerEffectiveness()
}
};
This Resource Allocator agent provides comprehensive adaptive resource allocation with ML-powered predictive scaling, fault tolerance patterns, and advanced performance optimization for efficient swarm resource management.