← back to Designer Wallcoverings
DW-Agents/dw-agents/add-memory-to-all-agents.ts
164 lines
#!/usr/bin/env npx tsx
/**
* Automatically add memory system to all DW-Agents
*
* This script:
* 1. Finds all agent TypeScript files
* 2. Adds memory system import and initialization
* 3. Enhances chat endpoints with memory commands
* 4. Adds memory context to AI prompts
*/
import * as fs from 'fs';
import * as path from 'path';
const AGENTS_TO_UPDATE = [
{ file: '/root/Projects/Designer-Wallcoverings/DW-Agents/digital-samples-agent.ts', name: 'digital-samples' },
{ file: '/root/Projects/Designer-Wallcoverings/DW-Agents/marketing-agent.ts', name: 'marketing' },
{ file: '/root/Projects/Designer-Wallcoverings/DW-Agents/accounting-agent.ts', name: 'accounting' },
{ file: '/root/Projects/Designer-Wallcoverings/DW-Agents/purchasing-office-agent.ts', name: 'purchasing-office' },
{ file: '/root/Projects/Designer-Wallcoverings/DW-Agents/task-orchestrator-agent.ts', name: 'task-orchestrator' },
{ file: '/root/Projects/Designer-Wallcoverings/DW-Agents/zendesk-chat-agent.ts', name: 'zendesk-chat' },
{ file: '/root/Projects/Designer-Wallcoverings/DW-Agents/new-client-signup-agent.ts', name: 'new-client-signup' },
{ file: '/root/Projects/Designer-Wallcoverings/DW-Agents/todays-highlights-agent.ts', name: 'todays-highlights' },
{ file: '/root/Projects/Designer-Wallcoverings/DW-Agents/completed-tasks-agent.ts', name: 'completed-tasks' },
{ file: '/root/Projects/Designer-Wallcoverings/DW-Agents/in-parallel-agent.ts', name: 'in-parallel' },
{ file: '/root/Projects/Designer-Wallcoverings/DW-Agents/agent-legal-team/legal-agent.ts', name: 'legal-team' },
];
const MEMORY_IMPORT = `import { AgentMemory } from './shared-memory-system';`;
const MEMORY_INIT_TEMPLATE = (name: string) => `
// Initialize agent memory system
const agentMemory = new AgentMemory('${name}');
console.log('📚 Memory system initialized for ${name}');
`;
const MEMORY_CHAT_HANDLER = `
// Memory system commands
if (message.toLowerCase().match(/^(remember|note|preference|learning):/i)) {
const parts = message.split(':');
const type = parts[0].toLowerCase();
const content = parts.slice(1).join(':').trim();
const memType = type === 'remember' ? 'note' : type as any;
agentMemory.add(content, memType);
return res.json({
response: \`✅ Memory saved: "\${content}"\`,
success: true,
memoryAdded: true
});
}
if (message.toLowerCase().includes('show') && message.toLowerCase().includes('memor')) {
const summary = agentMemory.getContextSummary();
return res.json({ response: summary, success: true });
}
if (message.toLowerCase().includes('search memor')) {
const query = message.split(/for|about/i)[1]?.trim() || '';
const results = agentMemory.search(query);
return res.json({
response: results.length > 0
? 'Found memories:\\n' + results.map(m => \`- \${m.content}\`).join('\\n')
: 'No matching memories found.',
success: true
});
}
if (message.toLowerCase().includes('forget') || message.toLowerCase().includes('delete memor')) {
const query = message.split(/forget|delete/i)[1]?.trim() || '';
const results = agentMemory.search(query);
if (results.length > 0) {
agentMemory.delete(results[0].id);
return res.json({ response: \`✅ Forgot: "\${results[0].content}"\`, success: true });
}
return res.json({ response: 'Nothing found to forget.', success: true });
}
`;
function addMemoryToAgent(agentFile: string, agentName: string): boolean {
try {
if (!fs.existsSync(agentFile)) {
console.log(`⏭️ Skipping ${agentName} - file not found`);
return false;
}
let content = fs.readFileSync(agentFile, 'utf8');
// Check if already has memory system
if (content.includes('AgentMemory') || content.includes('agentMemory')) {
console.log(`✅ ${agentName} already has memory system`);
return true;
}
console.log(`📝 Adding memory to ${agentName}...`);
// Add import after other imports
const importRegex = /import .+ from .+;[\s\n]*$/m;
const lastImportMatch = content.match(/import[^;]+;(?=\s*\n)/g);
if (lastImportMatch) {
const lastImport = lastImportMatch[lastImportMatch.length - 1];
content = content.replace(lastImport, lastImport + '\n' + MEMORY_IMPORT);
}
// Add initialization after app/PORT declaration
const portRegex = /const PORT = \d+;/;
if (content.match(portRegex)) {
content = content.replace(portRegex, (match) => match + MEMORY_INIT_TEMPLATE(agentName));
}
// Find and enhance chat endpoint
const chatEndpointRegex = /app\.post\(['"]\/api\/chat['"],.*?async \(req.*?\{/s;
if (content.match(chatEndpointRegex)) {
content = content.replace(chatEndpointRegex, (match) => match + '\n' + MEMORY_CHAT_HANDLER);
}
// Save the modified file
const backupFile = agentFile + '.backup';
fs.writeFileSync(backupFile, fs.readFileSync(agentFile));
fs.writeFileSync(agentFile, content);
console.log(`✅ ${agentName} updated! Backup saved to ${backupFile}`);
return true;
} catch (error: any) {
console.error(`❌ Error updating ${agentName}:`, error.message);
return false;
}
}
// Main execution
console.log('🚀 Adding memory system to all agents...\n');
let successCount = 0;
let failCount = 0;
AGENTS_TO_UPDATE.forEach(({ file, name }) => {
if (addMemoryToAgent(file, name)) {
successCount++;
} else {
failCount++;
}
});
console.log(`
================================================================================
📊 SUMMARY
================================================================================
✅ Successfully updated: ${successCount} agents
❌ Failed/Skipped: ${failCount} agents
Next steps:
1. Restart all agents: pm2 restart all
2. Test memory commands in any agent chat
3. Check /root/Projects/Designer-Wallcoverings/DW-Agents/agent-*/memory.json files
Memory commands:
- "Remember: [text]" - Add a note
- "Preference: [text]" - Save a preference
- "Show my memories" - View all memories
- "Search memories for [query]" - Find specific memories
- "Forget about [query]" - Delete a memory
================================================================================
`);