mindcraft/controller/agent-process.js

39 lines
1.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 {
2023-12-12 13:39:35 -06:00
constructor(name) {
this.name = name;
}
start(clear_memory=false, autostart=false) {
let args = ['controller/init-agent.js', this.name];
2023-12-10 20:18:20 -06:00
if (clear_memory)
args.push('-c');
if (autostart)
args.push('-a');
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',
});
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}`);
if (code !== 0) {
2023-12-09 21:40:53 -06:00
// agent must run for at least 30 seconds before restarting
if (Date.now() - last_restart < 30 * 1000) {
console.error('Agent process exited too quickly. Killing entire process. Goodbye.');
process.exit(1);
}
2023-12-08 16:18:20 -06:00
console.log('Restarting agent...');
2023-12-10 20:18:20 -06:00
this.start(false, true);
2023-12-09 21:40:53 -06:00
last_restart = Date.now();
2023-12-08 16:18:20 -06:00
}
});
agentProcess.on('error', (err) => {
console.error('Failed to start agent process:', err);
});
}
2023-12-09 21:40:53 -06:00
}