mindcraft/src/process/agent_process.js

67 lines
2.2 KiB
JavaScript
Raw Normal View History

2023-12-08 16:18:20 -06:00
import { spawn } from 'child_process';
2025-06-02 13:47:07 -06:00
import { mindserverProxy } from './mindserver_proxy.js.js';
2023-12-08 16:18:20 -06:00
2023-12-10 20:18:20 -06:00
export class AgentProcess {
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) {
this.profile = profile;
this.count_id = count_id;
this.running = true;
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',
});
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;
2025-06-02 13:47:07 -06:00
mindserverProxy.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 ${profile} 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...');
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
});
this.process = agentProcess;
}
stop() {
if (!this.running) return;
this.process.kill('SIGINT');
}
continue() {
if (!this.running) {
this.start(this.profile, true, 'Agent process restarted.', this.count_id);
}
2023-12-08 16:18:20 -06:00
}
2023-12-09 21:40:53 -06:00
}