cortexweaver
Version:
CortexWeaver is a command-line interface (CLI) tool that orchestrates a swarm of specialized AI agents, powered by Claude Code and Gemini CLI, to assist in software development. It transforms a high-level project plan (plan.md) into a series of coordinate
387 lines • 13.8 kB
JavaScript
"use strict";
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 () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Agent = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const claude_client_1 = require("./claude-client");
const workspace_1 = require("./workspace");
const cognitive_canvas_1 = require("./cognitive-canvas");
const session_1 = require("./session");
const agent_error_handling_1 = require("./agent-error-handling");
const agent_session_management_1 = require("./agent-session-management");
/**
* Abstract base class for all CortexWeaver agents
* Provides common functionality for specialized agent implementations
*/
class Agent {
constructor() {
this.config = null;
this.claudeClient = null;
this.workspace = null;
this.cognitiveCanvas = null;
this.sessionManager = null;
this.currentTask = null;
this.taskContext = null;
this.status = 'uninitialized';
this.lastError = null;
this.currentSession = null;
this.conversationHistory = [];
// Helper components
this.errorHandler = null;
this.sessionMgr = null;
}
/**
* Initialize the agent with configuration
*/
async initialize(config) {
this.validateConfig(config);
this.config = config;
// Initialize Claude client
this.claudeClient = new claude_client_1.ClaudeClient({
apiKey: config.claudeConfig.apiKey,
defaultModel: config.claudeConfig.defaultModel || claude_client_1.ClaudeModel.SONNET,
maxTokens: config.claudeConfig.maxTokens || 4096,
temperature: config.claudeConfig.temperature || 0.7
});
// Initialize workspace manager
this.workspace = new workspace_1.WorkspaceManager(config.workspaceRoot);
// Initialize cognitive canvas
this.cognitiveCanvas = new cognitive_canvas_1.CognitiveCanvas(config.cognitiveCanvasConfig);
// Initialize session manager
this.sessionManager = new session_1.SessionManager();
// Initialize helper components
this.errorHandler = new agent_error_handling_1.AgentErrorHandler(this.config, this.cognitiveCanvas, this.currentTask, this.taskContext, this.status, this.conversationHistory, this.currentSession, this.lastError);
this.sessionMgr = new agent_session_management_1.AgentSessionManager(this.config, this.sessionManager, this.workspace, this.currentTask, this.currentSession, this.status, this.conversationHistory, this.lastError, this.taskContext);
this.status = 'initialized';
}
/**
* Receive a task assignment with context
*/
async receiveTask(task, context) {
if (this.currentTask && this.status !== 'completed') {
throw new Error('Agent already has an assigned task');
}
this.currentTask = task;
this.taskContext = context;
this.status = 'assigned';
this.lastError = null;
this.conversationHistory = [];
// Update helper components
this.updateHelperComponents();
// Report task assignment
await this.reportProgress('assigned', `Received task: ${task.title}`);
}
/**
* Execute the assigned task
*/
async run() {
if (!this.currentTask) {
throw new Error('No task assigned');
}
this.status = 'running';
this.updateHelperComponents();
try {
await this.reportProgress('started', 'Beginning task execution');
// Execute the specific agent implementation
const result = await this.executeTask();
this.status = 'completed';
await this.reportProgress('completed', 'Task execution completed successfully');
return {
success: true,
result,
metadata: {
taskId: this.currentTask.id,
agentId: this.config.id,
completedAt: new Date().toISOString()
}
};
}
catch (error) {
this.status = 'error';
this.lastError = error;
await this.handleError(error);
throw error;
}
}
/**
* Send message to Claude API
*/
async sendToClaude(message, options = {}) {
if (!this.claudeClient) {
throw new Error('Claude client not initialized');
}
try {
const defaultOptions = {
model: this.config.claudeConfig.defaultModel || claude_client_1.ClaudeModel.SONNET,
maxTokens: this.config.claudeConfig.maxTokens || 4096,
temperature: this.config.claudeConfig.temperature || 0.7,
conversationHistory: this.conversationHistory,
...options
};
const response = await this.claudeClient.sendMessage(message, defaultOptions);
// Update conversation history
this.conversationHistory.push({ role: 'user', content: message }, { role: 'assistant', content: response.content });
return response;
}
catch (error) {
throw new Error(`Claude API error: ${error.message}`);
}
}
/**
* Read file from workspace
*/
async readFile(filePath) {
try {
const fullPath = path.resolve(this.config.workspaceRoot, filePath);
return fs.readFileSync(fullPath, 'utf-8');
}
catch (error) {
throw new Error(`Failed to read file: ${error.message}`);
}
}
/**
* Write file to workspace
*/
async writeFile(filePath, content) {
try {
const fullPath = path.resolve(this.config.workspaceRoot, filePath);
const directory = path.dirname(fullPath);
// Ensure directory exists
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory, { recursive: true });
}
fs.writeFileSync(fullPath, content, 'utf-8');
}
catch (error) {
throw new Error(`Failed to write file: ${error.message}`);
}
}
/**
* Execute command in workspace
*/
async executeCommand(command) {
if (!this.workspace || !this.currentTask) {
throw new Error('Workspace not initialized or no current task');
}
return await this.workspace.executeCommand(this.currentTask.id, command);
}
/**
* Report progress to Cognitive Canvas
*/
async reportProgress(status, details, strength = 0.5) {
if (!this.cognitiveCanvas || !this.config) {
return;
}
try {
const pheromoneData = {
id: `progress-${this.config.id}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
type: 'progress',
strength,
context: status,
metadata: {
details,
agentId: this.config.id,
taskId: this.currentTask?.id || null
},
createdAt: new Date().toISOString(),
expiresAt: new Date(Date.now() + 3600000).toISOString() // 1 hour expiry
};
await this.cognitiveCanvas.createPheromone(pheromoneData);
}
catch (error) {
// Don't throw on progress reporting errors, silently continue
}
}
/**
* Report impasse - delegated to error handler
*/
async reportImpasse(reason, context, urgency = 'medium') {
if (this.errorHandler) {
await this.errorHandler.reportImpasse(reason, context, urgency);
this.status = 'impasse';
}
}
/**
* Handle errors - delegated to error handler
*/
async handleError(error) {
this.lastError = error;
this.status = 'error';
this.updateHelperComponents();
if (this.errorHandler) {
await this.errorHandler.handleError(error);
}
}
/**
* Create session - delegated to session manager
*/
async createSession() {
if (!this.sessionMgr) {
throw new Error('Session manager not initialized');
}
const session = await this.sessionMgr.createSession();
this.currentSession = session;
this.updateHelperComponents();
return session;
}
/**
* Run command in session - delegated to session manager
*/
async runInSession(command) {
if (!this.sessionMgr) {
throw new Error('Session manager not initialized');
}
return await this.sessionMgr.runInSession(command);
}
/**
* Format prompt template with context variables
*/
formatPrompt(template, context) {
if (this.sessionMgr) {
return this.sessionMgr.formatPrompt(template, context);
}
let formatted = template;
for (const [key, value] of Object.entries(context)) {
const placeholder = `{{${key}}}`;
formatted = formatted.replace(new RegExp(placeholder, 'g'), String(value));
}
return formatted;
}
/**
* Reset agent state
*/
async reset() {
this.currentTask = null;
this.taskContext = null;
this.status = this.config ? 'initialized' : 'uninitialized';
this.lastError = null;
this.conversationHistory = [];
// Reset session
if (this.sessionMgr) {
await this.sessionMgr.reset();
}
this.currentSession = null;
this.updateHelperComponents();
}
/**
* Update configuration
*/
updateConfig(updates) {
if (!this.config) {
throw new Error('Agent not initialized');
}
Object.assign(this.config, updates);
this.updateHelperComponents();
}
// Getter methods
getId() {
return this.config?.id || '';
}
getRole() {
return this.config?.role || '';
}
getCapabilities() {
return this.config?.capabilities || [];
}
getStatus() {
return this.status;
}
getCurrentTask() {
return this.currentTask;
}
getTaskContext() {
return this.taskContext;
}
getLastError() {
return this.lastError;
}
/**
* Set the last error (primarily for testing purposes)
*/
setLastError(error) {
this.lastError = error;
this.updateHelperComponents();
}
getConfig() {
return this.config;
}
getWorkspace() {
return this.workspace;
}
getCognitiveCanvas() {
return this.cognitiveCanvas;
}
setStatus(status) {
this.status = status;
this.updateHelperComponents();
}
/**
* Update helper components with current state
*/
updateHelperComponents() {
if (this.errorHandler) {
this.errorHandler = new agent_error_handling_1.AgentErrorHandler(this.config, this.cognitiveCanvas, this.currentTask, this.taskContext, this.status, this.conversationHistory, this.currentSession, this.lastError);
}
if (this.sessionMgr) {
this.sessionMgr = new agent_session_management_1.AgentSessionManager(this.config, this.sessionManager, this.workspace, this.currentTask, this.currentSession, this.status, this.conversationHistory, this.lastError, this.taskContext);
}
}
/**
* Validate agent configuration
*/
validateConfig(config) {
if (!config.id || config.id.trim() === '') {
throw new Error('Agent ID is required');
}
if (!config.role || config.role.trim() === '') {
throw new Error('Agent role is required');
}
if (!config.capabilities || config.capabilities.length === 0) {
throw new Error('Agent capabilities are required');
}
if (!config.claudeConfig?.apiKey) {
throw new Error('Claude API key is required');
}
if (!config.workspaceRoot) {
throw new Error('Workspace root is required');
}
if (!config.cognitiveCanvasConfig?.uri) {
throw new Error('Cognitive Canvas configuration is required');
}
}
}
exports.Agent = Agent;
//# sourceMappingURL=agent-base.js.map