always connect agents to localhost

This commit is contained in:
MaxRobinsonTheGreat 2025-06-13 13:02:48 -05:00
parent 1eea05f576
commit 317c01e340
11 changed files with 43 additions and 40 deletions

3
.gitignore vendored
View file

@ -26,4 +26,5 @@ tasks/construction_tasks/train_multiagent_construction_tasks.json
tasks/construction_tasks/test/**
tasks/construction_tasks/train/**
server_data*
**/.DS_Store
**/.DS_Store
src/mindcraft-py/__pycache__/

View file

@ -63,7 +63,7 @@ if (process.env.LOG_ALL) {
settings.log_all_prompts = process.env.LOG_ALL;
}
Mindcraft.init(settings.mindserver_host, settings.mindserver_port);
Mindcraft.init(false, settings.mindserver_port);
for (let profile of settings.profiles) {
const profile_json = JSON.parse(readFileSync(profile, 'utf8'));

View file

@ -5,8 +5,6 @@ const settings = {
"auth": "offline", // or "microsoft"
// the mindserver manages all agents and hosts the UI
"host_mindserver": true, // if true, the mindserver will be hosted on this machine. otherwise, specify a public IP address
"mindserver_host": "localhost",
"mindserver_port": 8080,
// the base profile is shared by all bots for default prompts/examples/modes

View file

@ -2,6 +2,9 @@ import { io } from 'socket.io-client';
import convoManager from './conversation.js';
import { setSettings } from './settings.js';
// agents connection to mindserver
// always connect to localhost
class MindServerProxy {
constructor() {
if (MindServerProxy.instance) {
@ -14,11 +17,11 @@ class MindServerProxy {
MindServerProxy.instance = this;
}
async connect(name, host, port) {
async connect(name, port) {
if (this.connected) return;
this.name = name;
this.socket = io(`http://${host}:${port}`);
this.socket = io(`http://localhost:${port}`);
await new Promise((resolve, reject) => {
this.socket.on('connect', resolve);

View file

@ -17,5 +17,11 @@ try:
settings = {"profile": profile_data}
mindcraft.create_agent(settings)
settings_copy = settings.copy()
settings_copy['profile']['name'] = 'andy2'
mindcraft.create_agent(settings_copy)
except FileNotFoundError:
print(f"Error: Could not find andy.json at {profile_path}")
mindcraft.wait()

View file

@ -5,11 +5,6 @@ import { hideBin } from 'yargs/helpers';
function parseArguments() {
return yargs(hideBin(process.argv))
.option('mindserver_host', {
type: 'string',
describe: 'Mindserver host',
default: settings.mindserver_host
})
.option('mindserver_port', {
type: 'number',
describe: 'Mindserver port',
@ -22,9 +17,8 @@ function parseArguments() {
const args = parseArguments();
settings.mindserver_host = args.mindserver_host;
settings.mindserver_port = args.mindserver_port;
Mindcraft.init(settings.mindserver_host, settings.mindserver_port);
Mindcraft.init(settings.mindserver_port);
console.log(`Mindcraft initialized with MindServer at ${settings.mindserver_host}:${settings.mindserver_port}`);
console.log(`Mindcraft initialized with MindServer at localhost:${settings.mindserver_port}`);

View file

@ -6,6 +6,7 @@ import os
import atexit
import threading
import sys
import signal
class Mindcraft:
def __init__(self):
@ -19,11 +20,10 @@ class Mindcraft:
sys.stdout.write(f'[Node.js] {line}')
sys.stdout.flush()
def init(self, host='localhost', port=8080):
def init(self, port=8080):
if self.process:
return
self.host = host
self.port = port
node_script_path = os.path.abspath(os.path.join(os.path.dirname(__file__), 'init-mindcraft.js'))
@ -31,7 +31,6 @@ class Mindcraft:
self.process = subprocess.Popen([
'node',
node_script_path,
'--mindserver_host', self.host,
'--mindserver_port', str(self.port)
], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1)
@ -40,12 +39,12 @@ class Mindcraft:
self.log_thread.start()
atexit.register(self.shutdown)
time.sleep(2)
time.sleep(2) # Give server time to start before connecting
try:
self.sio.connect(f'http://{self.host}:{self.port}')
self.sio.connect(f'http://localhost:{self.port}')
self.connected = True
print("Connected to MindServer")
print("Connected to MindServer. Mindcraft is initialized.")
except socketio.exceptions.ConnectionError as e:
print(f"Failed to connect to MindServer: {e}")
self.shutdown()
@ -64,7 +63,6 @@ class Mindcraft:
print(f"Error creating agent: {response.get('error', 'Unknown error')}")
self.sio.emit('create-agent', settings_json, callback=callback)
self.sio.wait()
def shutdown(self):
if self.sio.connected:
@ -76,10 +74,20 @@ class Mindcraft:
self.process = None
print("Mindcraft shut down.")
def wait(self):
"""Block the main thread until Ctrl+C is pressed so the server stays up,"""
print("Server is running. Press Ctrl+C to exit.")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("\nCtrl+C detected. Exiting...")
self.shutdown()
mindcraft_instance = Mindcraft()
def init(host='localhost', port=8080):
mindcraft_instance.init(host, port)
def init(port=8080):
mindcraft_instance.init(port)
def create_agent(settings_json):
mindcraft_instance.create_agent(settings_json)
@ -88,4 +96,4 @@ def shutdown():
mindcraft_instance.shutdown()
def wait():
mindcraft_instance.wait()
mindcraft_instance.wait()

View file

@ -8,13 +8,12 @@ let agent_count = 0;
let host = 'localhost';
let port = 8080;
export async function init(host='localhost', port=8080) {
export async function init(host_public=false, port=8080) {
if (connected) {
console.error('Already initiliazed!');
return;
}
mindserver = createMindServer(host, port);
host = host;
mindserver = createMindServer(host_public, port);
port = port;
connected = true;
}
@ -29,7 +28,7 @@ export async function createAgent(settings) {
registerAgent(settings);
let load_memory = settings.load_memory || false;
let init_message = settings.init_message || null;
const agentProcess = new AgentProcess(agent_name, host, port);
const agentProcess = new AgentProcess(agent_name, port);
agentProcess.start(load_memory, init_message, agent_count);
agent_count++;
agent_processes[settings.profile.name] = agentProcess;

View file

@ -40,7 +40,7 @@ export function logoutAgent(agentName) {
}
// Initialize the server
export function createMindServer(host = 'localhost', port = 8080) {
export function createMindServer(host_public = false, port = 8080) {
const app = express();
server = http.createServer(app);
io = new Server(server);
@ -149,6 +149,7 @@ export function createMindServer(host = 'localhost', port = 8080) {
});
});
let host = host_public ? '0.0.0.0' : 'localhost';
server.listen(port, host, () => {
console.log(`MindServer running on port ${port}`);
});

View file

@ -2,9 +2,8 @@ import { spawn } from 'child_process';
import { logoutAgent } from '../mindcraft/mindserver.js';
export class AgentProcess {
constructor(name, host, port) {
constructor(name, port) {
this.name = name;
this.host = host;
this.port = port;
}
@ -19,7 +18,6 @@ export class AgentProcess {
args.push('-l', load_memory);
if (init_message)
args.push('-m', init_message);
args.push('-h', this.host);
args.push('-p', this.port);
const agentProcess = spawn('node', args, {
@ -45,7 +43,7 @@ export class AgentProcess {
return;
}
console.log('Restarting agent...');
this.start(true, 'Agent process restarted.', count_id, this.host, this.port);
this.start(true, 'Agent process restarted.', count_id, this.port);
last_restart = Date.now();
}
});

View file

@ -4,7 +4,7 @@ import yargs from 'yargs';
const args = process.argv.slice(2);
if (args.length < 1) {
console.log('Usage: node init_agent.js <agent_name> [profile] [load_memory] [init_message]');
console.log('Usage: node init_agent.js -n <agent_name> -p <port> -l <load_memory> -m <init_message> -c <count_id>');
process.exit(1);
}
@ -30,11 +30,6 @@ const argv = yargs(args)
default: 0,
description: 'identifying count for multi-agent scenarios',
})
.option('host', {
alias: 'h',
type: 'string',
description: 'host of mindserver'
})
.option('port', {
alias: 'p',
type: 'number',
@ -45,7 +40,7 @@ const argv = yargs(args)
(async () => {
try {
console.log('Connecting to MindServer');
await serverProxy.connect(argv.name, argv.host, argv.port);
await serverProxy.connect(argv.name, argv.port);
console.log('Starting agent');
const agent = new Agent();
serverProxy.setAgent(agent);