2023-12-08 16:18:20 -06:00
|
|
|
import { spawn } from 'child_process';
|
|
|
|
|
2023-12-10 20:18:20 -06:00
|
|
|
export class AgentProcess {
|
2024-10-12 20:40:16 -05:00
|
|
|
static runningCount = 0;
|
|
|
|
|
2024-10-10 17:37:02 -05:00
|
|
|
start(profile, load_memory=false, init_message=null, count_id=0) {
|
2023-12-21 15:11:38 -07:00
|
|
|
let args = ['src/process/init-agent.js', this.name];
|
2024-02-25 14:13:32 -06:00
|
|
|
args.push('-p', profile);
|
2024-10-10 17:37:02 -05:00
|
|
|
args.push('-c', count_id);
|
2024-02-25 14:13:32 -06:00
|
|
|
if (load_memory)
|
|
|
|
args.push('-l', load_memory);
|
2023-12-21 20:42:01 -07:00
|
|
|
if (init_message)
|
|
|
|
args.push('-m', init_message);
|
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',
|
|
|
|
});
|
2024-10-12 20:40:16 -05:00
|
|
|
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}`);
|
|
|
|
|
|
|
|
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) {
|
2024-10-12 20:40:16 -05:00
|
|
|
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-10-12 20:40:16 -05:00
|
|
|
this.start(profile, true, 'Agent process restarted.', count_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) => {
|
|
|
|
console.error('Failed to start agent process:', err);
|
|
|
|
});
|
|
|
|
}
|
2023-12-09 21:40:53 -06:00
|
|
|
}
|