mindcraft/src/process/agent-process.js

65 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-12-08 16:18:20 -06:00
import { spawn } from 'child_process';
2023-12-10 20:18:20 -06:00
export class AgentProcess {
static runningCount = 0;
2024-12-09 16:30:44 -08:00
start(profile, load_memory=false, init_message=null, count_id=0, task_path=null, task_id=null) {
2023-12-21 15:11:38 -07:00
let args = ['src/process/init-agent.js', this.name];
args.push('-p', profile);
args.push('-c', count_id);
if (load_memory)
args.push('-l', load_memory);
2023-12-21 20:42:01 -07:00
if (init_message)
args.push('-m', init_message);
2024-12-09 16:30:44 -08:00
if (task_path)
args.push('-t', task_path);
if (task_id)
args.push('-i', task_id);
2023-12-09 21:40:53 -06:00
2023-12-08 16:18:20 -06:00
const agentProcess = spawn('node', args, {
stdio: 'inherit',
stderr: 'inherit',
});
AgentProcess.runningCount++;
2023-12-09 21:40:53 -06:00
let last_restart = Date.now();
2023-12-08 16:18:20 -06:00
agentProcess.on('exit', (code, signal) => {
console.log(`Agent process exited with code ${code} and signal ${signal}`);
2024-12-09 16:30:44 -08:00
if (code === 2) {
console.log(`Task completed successfully`);
process.exit(2, signal);
}
if (code === 3) {
console.log(`Task failed due to reaching timeout`);
process.exit(3);
}
if (code === 4) {
console.log(`Task failed as all agents weren't correctly spawned `);
process.exit(4);
}
2024-12-09 16:30:44 -08:00
2023-12-08 16:18:20 -06:00
if (code !== 0) {
2023-12-20 20:41:15 -08:00
// agent must run for at least 10 seconds before restarting
if (Date.now() - last_restart < 10000) {
console.error(`Agent process ${profile} exited too quickly and will not be restarted.`);
AgentProcess.runningCount--;
if (AgentProcess.runningCount <= 0) {
console.error('All agent processes have ended. Exiting.');
process.exit(0);
}
return;
2023-12-09 21:40:53 -06:00
}
2023-12-08 16:18:20 -06:00
console.log('Restarting agent...');
2024-12-09 16:30:44 -08:00
this.start(profile, true, 'Agent process restarted.', count_id, task_path, task_id);
2023-12-09 21:40:53 -06:00
last_restart = Date.now();
2023-12-08 16:18:20 -06:00
}
});
agentProcess.on('error', (err) => {
2024-11-07 10:48:45 -06:00
console.error('Agent process error:', err);
2023-12-08 16:18:20 -06:00
});
}
2023-12-09 21:40:53 -06:00
}