contaigents
Version:
Modular AI Content Ecosystem with Audio Generation
275 lines (274 loc) • 8.58 kB
JavaScript
import { Router } from 'express';
import { AgentCLI } from '../agents/AgentCLI.js';
import { ProjectContext } from '../agents/ProjectContext.js';
import { LearningEngine } from '../memory/LearningEngine.js';
import { ToolRegistry } from '../tools/ToolRegistry.js';
const router = Router();
// Global agent instance for the session
let globalAgent = null;
let projectContext = null;
/**
* Initialize or get existing agent
*/
async function getAgent() {
if (!globalAgent) {
if (!projectContext) {
projectContext = new ProjectContext();
}
const agentConfig = {
id: 'web-agent',
name: 'Web AI Assistant',
systemPrompt: 'You are a helpful AI assistant for file editing and project management. Provide clear, actionable responses.',
capabilities: ['analyze', 'generate', 'edit', 'summarize'],
maxIterations: 5,
temperature: 0.6,
provider: 'OpenAI',
model: 'gpt-4'
};
globalAgent = new AgentCLI(agentConfig);
}
return globalAgent;
}
/**
* Start a new conversation with the agent
*/
router.post('/agent/conversation/start', async (req, res) => {
try {
const { message, projectPath } = req.body;
if (!message) {
return res.status(400).json({ error: 'Message is required' });
}
const agent = await getAgent();
const response = await agent.startConversation(message, projectPath || process.cwd());
res.json({
success: true,
response,
conversationId: agent.getConversationHistory()?.id
});
}
catch (error) {
console.error('Error starting conversation:', error);
res.status(500).json({
error: 'Failed to start conversation',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
/**
* Send message to existing conversation
*/
router.post('/agent/conversation/message', async (req, res) => {
try {
const { message } = req.body;
if (!message) {
return res.status(400).json({ error: 'Message is required' });
}
const agent = await getAgent();
const response = await agent.processMessage(message);
res.json({
success: true,
response,
conversationId: agent.getConversationHistory()?.id
});
}
catch (error) {
console.error('Error processing message:', error);
res.status(500).json({
error: 'Failed to process message',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
/**
* Get conversation history
*/
router.get('/agent/conversation/history', async (req, res) => {
try {
const agent = await getAgent();
const history = await agent.getConversationHistory();
res.json({
success: true,
history
});
}
catch (error) {
console.error('Error getting conversation history:', error);
res.status(500).json({
error: 'Failed to get conversation history',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
/**
* Analyze files using the agent
*/
router.post('/agent/analyze', async (req, res) => {
try {
const { files, analysisType = 'detailed' } = req.body;
const agent = await getAgent();
let analysisRequest;
if (files && files.length > 0) {
analysisRequest = `Analyze these files with ${analysisType} analysis: ${files.join(', ')}`;
}
else {
analysisRequest = `Analyze this project comprehensively with ${analysisType} analysis`;
}
const response = await agent.processMessage(analysisRequest);
res.json({
success: true,
analysis: response,
files: files || []
});
}
catch (error) {
console.error('Error analyzing files:', error);
res.status(500).json({
error: 'Failed to analyze files',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
/**
* Generate content using the agent
*/
router.post('/agent/generate', async (req, res) => {
try {
const { type, target, style = 'professional', length = 'medium' } = req.body;
if (!type || !target) {
return res.status(400).json({ error: 'Type and target are required' });
}
const agent = await getAgent();
const generateRequest = `Generate ${length} ${type} content in ${style} style for: ${target}`;
const response = await agent.processMessage(generateRequest);
res.json({
success: true,
content: response,
metadata: { type, target, style, length }
});
}
catch (error) {
console.error('Error generating content:', error);
res.status(500).json({
error: 'Failed to generate content',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
/**
* Get project context
*/
router.get('/agent/context', async (req, res) => {
try {
if (!projectContext) {
projectContext = new ProjectContext();
}
const context = await projectContext.initializeContext(process.cwd());
res.json({
success: true,
context: {
projectPath: context.projectPath,
metadata: context.metadata,
fileCount: context.fileTree.length,
dependencyCount: context.dependencies.length,
knowledgeBaseSize: context.knowledgeBase.length
}
});
}
catch (error) {
console.error('Error getting project context:', error);
res.status(500).json({
error: 'Failed to get project context',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
/**
* Get available tools
*/
router.get('/agent/tools', async (req, res) => {
try {
const { category } = req.query;
const registry = new ToolRegistry();
const tools = category
? registry.getToolsByCategory(category)
: registry.getAvailableTools();
res.json({
success: true,
tools,
totalCount: registry.getToolCount()
});
}
catch (error) {
console.error('Error getting tools:', error);
res.status(500).json({
error: 'Failed to get tools',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
/**
* Get learning insights
*/
router.get('/agent/insights', async (req, res) => {
try {
const learningEngine = new LearningEngine();
const insights = await learningEngine.generateInsights();
res.json({
success: true,
insights
});
}
catch (error) {
console.error('Error getting insights:', error);
res.status(500).json({
error: 'Failed to get insights',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
/**
* End current conversation
*/
router.post('/agent/conversation/end', async (req, res) => {
try {
if (globalAgent) {
await globalAgent.endConversation();
globalAgent = null;
}
res.json({
success: true,
message: 'Conversation ended'
});
}
catch (error) {
console.error('Error ending conversation:', error);
res.status(500).json({
error: 'Failed to end conversation',
message: error instanceof Error ? error.message : 'Unknown error'
});
}
});
/**
* Health check for agent system
*/
router.get('/agent/health', async (req, res) => {
try {
const registry = new ToolRegistry();
const validation = registry.validateDependencies();
res.json({
success: true,
status: 'healthy',
toolsAvailable: registry.getToolCount(),
dependenciesValid: validation.valid,
errors: validation.errors
});
}
catch (error) {
res.status(500).json({
success: false,
status: 'unhealthy',
error: error instanceof Error ? error.message : 'Unknown error'
});
}
});
export default router;