agentic-qe
Version:
Agentic Quality Engineering Fleet System - AI-driven quality management platform
272 lines • 11 kB
JavaScript
;
/**
* Agent Inspect Command
*
* Provides detailed inspection of agent configuration, state, metrics,
* and history. Supports multiple output formats and filtering options.
*
* @module cli/commands/agent/inspect
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AgentInspectCommand = void 0;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const AgentRegistry_1 = require("../../../mcp/services/AgentRegistry");
const Logger_1 = require("../../../utils/Logger");
const logger = Logger_1.Logger.getInstance();
/**
* Agent Inspect Command Implementation
*/
class AgentInspectCommand {
/**
* Execute agent inspection
*
* @param options - Inspect options
* @returns Detailed agent information
*/
static async execute(options) {
const { agentId, includeHistory = false, includeMetrics = true, includeLogs = false, format = 'json', depth = 'deep' } = options;
logger.info(`Inspecting agent: ${agentId}`, { includeHistory, includeMetrics, includeLogs });
try {
// Get agent registry
const registry = (0, AgentRegistry_1.getAgentRegistry)();
// Get registered agent
const registeredAgent = registry.getRegisteredAgent(agentId);
if (!registeredAgent) {
throw new Error(`Agent not found: ${agentId}`);
}
// Read agent configuration
const configPath = path.join(this.AGENT_DIR, `${agentId}.json`);
const config = await this.readAgentConfig(configPath);
// Build base result
const result = {
id: registeredAgent.id,
type: registeredAgent.type,
mcpType: registeredAgent.mcpType,
status: registeredAgent.status,
configuration: {
name: config.name,
description: config.description,
capabilities: config.capabilities || [],
resources: config.resources
},
lifecycle: {
spawnedAt: registeredAgent.spawnedAt,
lastActivity: registeredAgent.lastActivity,
uptime: Date.now() - registeredAgent.spawnedAt.getTime(),
restartCount: config.restartCount,
lastRestart: config.lastRestart
},
health: await this.checkHealth(registeredAgent)
};
// Add metrics if requested
if (includeMetrics) {
result.metrics = await this.getMetrics(agentId, registeredAgent);
}
// Add history if requested
if (includeHistory) {
result.history = await this.getHistory(agentId);
}
// Add logs if requested
if (includeLogs) {
result.logs = await this.getLogs(agentId, 50);
}
// Format output
return this.formatOutput(result, format);
}
catch (error) {
logger.error(`Failed to inspect agent ${agentId}:`, error);
throw new Error(`Agent inspection failed: ${error instanceof Error ? error.message : String(error)}`);
}
}
/**
* Read agent configuration
*/
static async readAgentConfig(configPath) {
if (!await fs.pathExists(configPath)) {
return {};
}
return await fs.readJson(configPath);
}
/**
* Get agent metrics
*/
static async getMetrics(agentId, agent) {
const registry = (0, AgentRegistry_1.getAgentRegistry)();
const registryMetrics = registry.getAgentMetrics(agentId);
// Calculate additional metrics
const tasksFailed = await this.countFailedTasks(agentId);
const tasksActive = agent.status === 'busy' ? 1 : 0;
const tasksCompleted = agent.tasksCompleted;
const successRate = tasksCompleted > 0
? (tasksCompleted - tasksFailed) / tasksCompleted
: 1.0;
return {
tasksCompleted,
tasksActive,
tasksFailed,
averageExecutionTime: registryMetrics?.averageExecutionTime || 0,
totalExecutionTime: agent.totalExecutionTime,
successRate
};
}
/**
* Count failed tasks
*/
static async countFailedTasks(agentId) {
const historyPath = path.join(this.HISTORY_DIR, `${agentId}.json`);
if (!await fs.pathExists(historyPath)) {
return 0;
}
const history = await fs.readJson(historyPath);
return history.events?.filter((e) => e.event === 'task_failed').length || 0;
}
/**
* Get agent history
*/
static async getHistory(agentId) {
const historyPath = path.join(this.HISTORY_DIR, `${agentId}.json`);
if (!await fs.pathExists(historyPath)) {
return [];
}
const history = await fs.readJson(historyPath);
return (history.events || []).map((event) => ({
timestamp: new Date(event.timestamp),
event: event.event,
details: event.details
}));
}
/**
* Get agent logs
*/
static async getLogs(agentId, lines) {
const logPath = path.join(this.LOGS_DIR, `${agentId}.log`);
if (!await fs.pathExists(logPath)) {
return [];
}
const logContent = await fs.readFile(logPath, 'utf-8');
const allLines = logContent.split('\n').filter(line => line.trim());
// Return last N lines
return allLines.slice(-lines);
}
/**
* Check agent health
*/
static async checkHealth(agent) {
const issues = [];
let status = 'healthy';
// Check agent status
if (agent.status === 'error') {
issues.push('Agent in error state');
status = 'unhealthy';
}
// Check last activity
const inactiveDuration = Date.now() - new Date(agent.lastActivity).getTime();
if (inactiveDuration > 3600000) { // 1 hour
issues.push('No activity for over 1 hour');
status = status === 'healthy' ? 'degraded' : status;
}
// Check task completion rate
if (agent.tasksCompleted === 0 && Date.now() - new Date(agent.spawnedAt).getTime() > 600000) {
issues.push('No tasks completed after 10 minutes');
status = status === 'healthy' ? 'degraded' : status;
}
return {
status,
issues,
lastCheck: new Date()
};
}
/**
* Format output
*/
static formatOutput(result, format) {
switch (format) {
case 'json':
return result;
case 'table':
// Return formatted table string
return this.formatAsTable(result);
case 'yaml':
// Return YAML formatted string
return this.formatAsYAML(result);
case 'detailed':
// Return detailed formatted string
return this.formatDetailed(result);
default:
return result;
}
}
/**
* Format as table
*/
static formatAsTable(result) {
const lines = [];
lines.push('╔══════════════════════════════════════════════════════════════╗');
lines.push(`║ Agent: ${result.id.padEnd(54)} ║`);
lines.push('╠══════════════════════════════════════════════════════════════╣');
lines.push(`║ Type: ${result.mcpType.padEnd(55)} ║`);
lines.push(`║ Status: ${result.status.padEnd(53)} ║`);
lines.push(`║ Health: ${result.health.status.padEnd(53)} ║`);
if (result.metrics) {
lines.push('╠══════════════════════════════════════════════════════════════╣');
lines.push(`║ Tasks Completed: ${String(result.metrics.tasksCompleted).padEnd(44)} ║`);
lines.push(`║ Success Rate: ${(result.metrics.successRate * 100).toFixed(2)}%`.padEnd(63) + '║');
}
lines.push('╚══════════════════════════════════════════════════════════════╝');
return lines.join('\n');
}
/**
* Format as YAML
*/
static formatAsYAML(result) {
// Simple YAML formatting
const yaml = [];
yaml.push(`id: ${result.id}`);
yaml.push(`type: ${result.type}`);
yaml.push(`mcpType: ${result.mcpType}`);
yaml.push(`status: ${result.status}`);
yaml.push('configuration:');
yaml.push(` capabilities: [${result.configuration.capabilities.join(', ')}]`);
if (result.metrics) {
yaml.push('metrics:');
yaml.push(` tasksCompleted: ${result.metrics.tasksCompleted}`);
yaml.push(` successRate: ${result.metrics.successRate}`);
}
return yaml.join('\n');
}
/**
* Format detailed
*/
static formatDetailed(result) {
return JSON.stringify(result, null, 2);
}
}
exports.AgentInspectCommand = AgentInspectCommand;
AgentInspectCommand.AGENT_DIR = path.join(process.cwd(), '.aqe', 'agents');
AgentInspectCommand.LOGS_DIR = path.join(process.cwd(), '.aqe', 'logs');
AgentInspectCommand.HISTORY_DIR = path.join(process.cwd(), '.aqe', 'history');
//# sourceMappingURL=inspect.js.map