mindcraft/src/process/agent_process.js

68 lines
2 KiB
JavaScript
Raw Normal View History

2023-12-08 16:18:20 -06:00
import { spawn } from 'child_process';
2025-06-11 16:41:54 -05:00
import { logoutAgent } from '../mindcraft/mindserver.js';
2023-12-08 16:18:20 -06:00
2023-12-10 20:18:20 -06:00
export class AgentProcess {
2025-06-13 13:02:48 -05:00
constructor(name, port) {
this.name = name;
2025-06-11 16:41:54 -05:00
this.port = port;
}
2025-06-11 16:41:54 -05:00
start(load_memory=false, init_message=null, count_id=0) {
this.count_id = count_id;
this.running = true;
let args = ['src/process/init_agent.js', this.name];
args.push('-n', this.name);
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);
2025-06-11 16:41:54 -05:00
args.push('-p', this.port);
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}`);
this.running = false;
logoutAgent(this.name);
2024-12-09 16:30:44 -08:00
2024-12-09 17:06:22 -08:00
if (code > 1) {
console.log(`Ending task`);
process.exit(code);
}
2024-12-09 16:30:44 -08:00
if (code !== 0 && signal !== 'SIGINT') {
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 exited too quickly and will not be restarted.`);
return;
2023-12-09 21:40:53 -06:00
}
2023-12-08 16:18:20 -06:00
console.log('Restarting agent...');
2025-06-13 13:02:48 -05:00
this.start(true, 'Agent process restarted.', count_id, this.port);
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
});
this.process = agentProcess;
}
stop() {
if (!this.running) return;
this.process.kill('SIGINT');
}
continue() {
if (!this.running) {
this.start(true, 'Agent process restarted.', this.count_id);
}
2023-12-08 16:18:20 -06:00
}
2023-12-09 21:40:53 -06:00
}