Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 7x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 7x 7x 9x 9x 9x 9x 9x 11x 5x 5x 5x 6x 6x 6x 6x 6x 11x 6x 6x 6x 6x 6x 11x 11x 9x 9x 9x 9x 9x 4x 4x 4x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 4x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 3x 3x 3x 3x 3x 3x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 3x 3x 3x 4x 4x 4x 3x 3x 3x 3x 4x 4x 3x 3x 3x 3x 3x 2x 2x 3x 4x 9x 9x 9x 9x 9x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 9x 9x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 6x 6x 6x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 1x | /**
* BuildHive Agent - Core Agent Implementation
*
* Core agent class that manages the lifecycle of the BuildHive agent,
* including registration, job execution, and communication with the platform.
*
* Requirements: 1.1, 1.2, 1.5, 1.6, 4.1, 4.2, 4.3, 4.4, 4.5
*/
import { AgentConfig } from './config/types.js';
import { JobExecutor } from './jobExecutor.js';
import { WebSocketClient } from './websocketClient.js';
import { MetricsCollector } from './metrics.js';
import { createLogger } from './utils/logger.js';
import { AgentCapabilities, JobSubmissionRequest } from './types.js';
import { detectCapabilities } from './utils/capabilities.js';
import { JobStatusApi } from './api/jobStatusApi.js';
import { RecoveryManager } from './recovery.js';
import { join } from 'path';
import { EnhancedJobExecutor, EnhancedJobRequest, EnhancedJobExecutorConfig } from './enhancedJobExecutor.js';
import { RecipeRegistry } from './recipes/recipeRegistry.js';
import { CacheManager } from './cacheManager.js';
import { AcceptanceChecker } from './acceptanceChecker.js';
import { ResourceGovernor } from './resourceGovernor.js';
const logger = createLogger('agent');
export interface JobResult {
jobId: string;
status: 'COMPLETED' | 'FAILED' | 'CANCELLED';
exitCode?: number;
logs?: string;
errorMessage?: string;
artifactUrls?: string[];
actualDuration?: number;
startedAt: Date;
completedAt: Date;
}
export class BuildHiveAgent {
private config: AgentConfig;
private jobExecutor: JobExecutor;
private enhancedJobExecutor: EnhancedJobExecutor | null = null;
private websocketClient: WebSocketClient;
private metricsCollector: MetricsCollector;
private jobStatusApi: JobStatusApi;
private recoveryManager: RecoveryManager;
private heartbeatInterval: NodeJS.Timeout | null = null;
private metricsInterval: NodeJS.Timeout | null = null;
private dockerHealthMonitor: NodeJS.Timeout | null = null;
private isRunning = false;
private capabilities: AgentCapabilities;
private activeJobs = new Map<string, { startTime: Date; job: JobSubmissionRequest }>();
constructor(config: AgentConfig, capabilities?: AgentCapabilities) {
this.config = config;
// If capabilities provided (from async detection), use them; otherwise use empty placeholder
this.capabilities = capabilities || {
os: '',
arch: '',
cpuCores: 0,
memoryGB: 0,
diskSpaceGB: 0
};
// Initialize components
this.jobExecutor = new JobExecutor(config);
this.websocketClient = new WebSocketClient(config, this.capabilities);
this.metricsCollector = new MetricsCollector(config);
this.recoveryManager = new RecoveryManager();
// Initialize JobStatusApi for REST-based job status updates (MVP.4.2.2)
this.jobStatusApi = new JobStatusApi(
config.platformUrl,
config.apiKey
);
// Initialize EnhancedJobExecutor if enhanced config sections are present
this.enhancedJobExecutor = this.initEnhancedExecutor(config);
// Set up event handlers
this.setupEventHandlers();
}
/**
* Create agent with capability detection
*/
static async create(config: AgentConfig): Promise<BuildHiveAgent> {
const capabilities = await detectCapabilities();
return new BuildHiveAgent(config, capabilities);
}
/**
* Start the agent
*/
async start(): Promise<void> {
if (this.isRunning) {
logger.warn('Agent is already running');
return;
}
try {
logger.info(`Starting BuildHive Agent: ${this.config.name}`);
logger.info('Detected capabilities:', this.capabilities);
// Start metrics collection
await this.metricsCollector.start();
logger.info('Metrics collector started');
// Connect to platform via WebSocket
await this.websocketClient.connect();
logger.info('Connected to BuildHive platform');
// Start heartbeat
this.startHeartbeat();
logger.info('Heartbeat started');
// Start metrics reporting
this.startMetricsReporting();
logger.info('Metrics reporting started');
// Start Docker health monitoring (MVP.4.3.2)
this.startDockerHealthMonitoring();
logger.info('Docker health monitoring started');
this.isRunning = true;
logger.info('BuildHive Agent started successfully');
} catch (error) {
logger.error('Failed to start agent:', error);
await this.cleanup();
throw error;
}
}
/**
* Stop the agent
*/
async stop(): Promise<void> {
if (!this.isRunning) {
logger.warn('Agent is not running');
return;
}
logger.info('Stopping BuildHive Agent...');
try {
// Cancel all active jobs
for (const [jobId] of this.activeJobs) {
logger.info(`Cancelling active job: ${jobId}`);
await this.jobExecutor.cancelJob(jobId);
}
await this.cleanup();
this.isRunning = false;
logger.info('BuildHive Agent stopped successfully');
} catch (error) {
logger.error('Error during agent shutdown:', error);
throw error;
}
}
/**
* Execute a job
*/
async executeJob(job: JobSubmissionRequest): Promise<JobResult> {
const startTime = new Date();
logger.info(`Starting job execution: ${job.externalId}`);
// Check if we can accept more jobs
if (this.activeJobs.size >= this.config.maxConcurrentJobs) {
throw new Error(`Agent is at maximum capacity (${this.config.maxConcurrentJobs} jobs)`);
}
// Add to active jobs
this.activeJobs.set(job.externalId, { startTime, job });
try {
// Update agent status to busy if this is our first job
if (this.activeJobs.size === 1) {
await this.websocketClient.updateStatus('BUSY');
}
// Mark job as RUNNING via REST API with retry (MVP.4.2.2 + MVP.4.3.2)
await this.recoveryManager.retryOperation(
() => this.jobStatusApi.markJobRunning(job.externalId),
{},
`mark job ${job.externalId} as RUNNING`
);
logger.info(`Job ${job.externalId} marked as RUNNING`);
// Progress and log callbacks for REST API streaming
const progressCallback = (progress: any) => {
this.recoveryManager.retryOperation(
() => this.jobStatusApi.updateJobProgress(job.externalId, progress),
{ maxAttempts: 2 },
`progress update for ${job.externalId}`
).catch(error => {
logger.error('Failed to send progress update after retries', error);
});
};
const logsCallback = (logs: string) => {
this.recoveryManager.retryOperation(
() => this.jobStatusApi.appendJobLogs(job.externalId, logs),
{ maxAttempts: 2 },
`log update for ${job.externalId}`
).catch(error => {
logger.error('Failed to send log update after retries', error);
});
};
let result: { success: boolean; exitCode?: number; logs?: string; errorMessage?: string; artifactUrls?: string[] };
if (this.enhancedJobExecutor) {
// Use enhanced pipeline with recipe detection, caching, and lifecycle
logger.info(`Using enhanced pipeline for job ${job.externalId}`);
const workDir = join(process.cwd(), 'workspaces', job.externalId);
const enhancedRequest = this.toEnhancedRequest(job, workDir);
const enhancedResult = await this.enhancedJobExecutor.executeJob(enhancedRequest, {
onProgress: (percent, stage) => progressCallback({ percentage: percent, currentStep: stage }),
onLog: (log) => logsCallback(log),
});
if (enhancedResult.rejection) {
logger.warn(`Job ${job.externalId} rejected: ${enhancedResult.rejection.reason}`);
}
result = {
success: enhancedResult.success,
exitCode: enhancedResult.exitCode,
logs: enhancedResult.logs,
errorMessage: enhancedResult.rejection?.reason,
artifactUrls: enhancedResult.artifacts,
};
} else {
// Fallback to basic executor
result = await this.jobExecutor.executeJob(job, progressCallback, logsCallback);
}
const completedAt = new Date();
const actualDuration = Math.floor((completedAt.getTime() - startTime.getTime()) / 1000);
const jobResult: JobResult = {
jobId: job.externalId,
status: result.success ? 'COMPLETED' : 'FAILED',
exitCode: result.exitCode,
logs: result.logs,
errorMessage: result.errorMessage,
artifactUrls: result.artifactUrls,
actualDuration,
startedAt: startTime,
completedAt
};
// Report job completion via REST API with retry (MVP.4.2.2 + MVP.4.3.2)
await this.recoveryManager.retryOperation(
() => this.jobStatusApi.markJobCompleted(job.externalId, {
exitCode: result.exitCode || (result.success ? 0 : 1),
logs: result.logs || this.jobStatusApi.getCurrentLogs(job.externalId),
artifactUrls: result.artifactUrls,
actualDuration,
errorMessage: result.errorMessage
}),
{},
`mark job ${job.externalId} as COMPLETED`
);
logger.info(`Job completed: ${job.externalId} (${jobResult.status})`);
return jobResult;
} catch (error) {
logger.error(`Job execution failed: ${job.externalId}`, error);
const completedAt = new Date();
const actualDuration = Math.floor((completedAt.getTime() - startTime.getTime()) / 1000);
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
// Report job failure via REST API with retry (MVP.4.2.2 + MVP.4.3.2)
try {
await this.recoveryManager.retryOperation(
() => this.jobStatusApi.markJobFailed(
job.externalId,
errorMessage,
this.jobStatusApi.getCurrentLogs(job.externalId)
),
{},
`mark job ${job.externalId} as FAILED`
);
} catch (apiError) {
logger.error('Failed to report job failure to server after retries', apiError);
}
return {
jobId: job.externalId,
status: 'FAILED',
errorMessage,
actualDuration,
startedAt: startTime,
completedAt
};
} finally {
// Remove from active jobs
this.activeJobs.delete(job.externalId);
// Update status back to online if no more jobs
if (this.activeJobs.size === 0) {
await this.websocketClient.updateStatus('ONLINE');
}
}
}
/**
* Get current agent status
*/
getStatus(): {
isRunning: boolean;
activeJobs: number;
capabilities: AgentCapabilities;
uptime: number;
} {
return {
isRunning: this.isRunning,
activeJobs: this.activeJobs.size,
capabilities: this.capabilities,
uptime: this.isRunning ? Date.now() - this.startTime : 0
};
}
private startTime = Date.now();
/**
* Initialize the EnhancedJobExecutor from config.
* Returns null if enhanced config sections are missing (backward compat).
*/
private initEnhancedExecutor(config: AgentConfig): EnhancedJobExecutor | null {
if (!config.acceptanceRules || !config.resourceGovernance || !config.cacheConfig) {
logger.info('Enhanced executor not initialized: missing config sections, using basic executor');
return null;
}
const recipeRegistry = new RecipeRegistry();
const cacheManager = new CacheManager({
directory: config.cacheConfig.directory,
maxSizeGB: config.cacheConfig.maxSizeGB,
strategy: config.cacheConfig.strategy,
volumes: config.cacheConfig.volumes,
});
const acceptanceChecker = new AcceptanceChecker(config.acceptanceRules);
const resourceGovernor = new ResourceGovernor(
config.resourceGovernance,
config.maxConcurrentJobs,
);
const executorConfig: EnhancedJobExecutorConfig = {
executionMode: config.executionConfig?.defaultMode ?? 'docker',
dockerAvailable: true,
};
const snapshotProvider = () => ({
cpuPercent: 10,
memoryPercent: 30,
diskFreeGB: 50,
activeJobs: this.activeJobs.size,
});
logger.info('Enhanced job executor initialized with recipe detection and caching');
return new EnhancedJobExecutor(
recipeRegistry,
cacheManager,
acceptanceChecker,
resourceGovernor,
executorConfig,
snapshotProvider,
);
}
/**
* Convert a JobSubmissionRequest to an EnhancedJobRequest
*/
private toEnhancedRequest(job: JobSubmissionRequest, workDir: string): EnhancedJobRequest {
return {
id: job.externalId,
repository: job.repository,
buildCommand: job.buildCommand,
dockerImage: job.dockerImage,
environment: job.environment,
workDir,
artifacts: job.artifacts,
};
}
/**
* Set up event handlers for WebSocket client
*/
private setupEventHandlers(): void {
// Handle job assignments
this.websocketClient.onJobAssigned(async (jobData) => {
logger.info(`Received job assignment: ${jobData.externalId}`);
try {
const result = await this.executeJob(jobData);
// Send job completion notification
await this.websocketClient.sendJobResult(result);
} catch (error) {
logger.error(`Failed to execute assigned job: ${jobData.externalId}`, error);
// Send job failure notification
await this.websocketClient.sendJobResult({
jobId: jobData.externalId,
status: 'FAILED',
errorMessage: error instanceof Error ? error.message : 'Unknown error',
startedAt: new Date(),
completedAt: new Date()
});
}
});
// Handle connection status changes
this.websocketClient.onConnectionChange((connected) => {
if (connected) {
logger.info('Connected to BuildHive platform');
} else {
logger.warn('Disconnected from BuildHive platform');
}
});
// Handle reconnection
this.websocketClient.onReconnected(() => {
logger.info('Reconnected to BuildHive platform');
// Re-register agent capabilities
this.websocketClient.registerAgent();
});
}
/**
* Start heartbeat mechanism
*/
private startHeartbeat(): void {
this.heartbeatInterval = setInterval(async () => {
try {
const metrics = await this.metricsCollector.getCurrentMetrics();
await this.websocketClient.sendHeartbeat({
currentLoad: this.calculateCurrentLoad(),
activeJobs: this.activeJobs.size,
metrics: {
cpuUsage: metrics.cpuUsage,
memoryUsage: metrics.memoryUsage,
diskUsage: metrics.diskUsage
}
});
} catch (error) {
logger.error('Failed to send heartbeat:', error);
}
}, this.config.heartbeatInterval * 1000);
}
/**
* Start metrics reporting
*/
private startMetricsReporting(): void {
if (!this.config.enableMetrics) {
return;
}
this.metricsInterval = setInterval(async () => {
try {
const metrics = await this.metricsCollector.getCurrentMetrics();
await this.websocketClient.sendMetrics(metrics);
} catch (error) {
logger.error('Failed to send metrics:', error);
}
}, 60000); // Send metrics every minute
}
/**
* Start Docker health monitoring (MVP.4.3.2)
*
* Continuously monitors Docker daemon health and attempts recovery on failure
*/
private startDockerHealthMonitoring(): void {
// Initial health check
this.recoveryManager.checkDockerHealth().then(isHealthy => {
if (!isHealthy) {
logger.warn('Initial Docker health check failed, attempting recovery');
this.recoveryManager.recoverDockerConnection();
}
});
// Start continuous monitoring
this.dockerHealthMonitor = this.recoveryManager.startDockerHealthMonitoring(
60000, // Check every minute
() => {
// Callback when Docker becomes unhealthy and recovery fails
logger.error('Docker daemon is unhealthy and recovery failed');
logger.error('Agent may not be able to execute new jobs until Docker is restored');
// Update agent status to reflect Docker issue
this.websocketClient.updateStatus('OFFLINE').catch(err => {
logger.error('Failed to update agent status:', err);
});
}
);
logger.debug('Docker health monitoring interval started');
}
/**
* Calculate current load based on active jobs and system metrics
*/
private calculateCurrentLoad(): number {
const jobLoad = this.activeJobs.size / this.config.maxConcurrentJobs;
return Math.min(jobLoad * 100, 100);
}
/**
* Clean up resources
*/
private async cleanup(): Promise<void> {
// Stop intervals
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
if (this.metricsInterval) {
clearInterval(this.metricsInterval);
this.metricsInterval = null;
}
if (this.dockerHealthMonitor) {
clearInterval(this.dockerHealthMonitor);
this.dockerHealthMonitor = null;
}
// Disconnect WebSocket
try {
await this.websocketClient.disconnect();
} catch (error) {
logger.error('Error disconnecting WebSocket:', error);
}
// Stop metrics collector
try {
await this.metricsCollector.stop();
} catch (error) {
logger.error('Error stopping metrics collector:', error);
}
// Clean up job executor
try {
await this.jobExecutor.cleanup();
} catch (error) {
logger.error('Error cleaning up job executor:', error);
}
// Clean up job status API
try {
this.jobStatusApi.cleanup();
} catch (error) {
logger.error('Error cleaning up job status API:', error);
}
}
} |