Agent mode: an AI agent plays in the player's own tab, with the agent's clock or a running one

The MCP server gains a second session, --browser: the game in the player's tab, reached through the
agent relay npm run dev hosts at /agent (loopback unless --host; Host and Origin checked, no token).
The player turns it on in Settings → Agent API, a section only the development page has, and picks the
clock: a pace of 30 s to 5 min a day that nobody can pause, or the agent's own. Headless gets the
running clock too (--clock realtime --pace MS) and both get a wait tool.

All of it lives in src/agent/ (development page only). The game offers HOOKS, UI.clockLocked,
setSpeed() and runClock(dt), the frame's day block moved out unchanged, and nothing more: the page
players get grows by under 1 KB gzipped and runs exactly as before.
This commit is contained in:
Wolfgang Nagele 2026-11-03 15:30:04 -05:00
parent 2526dd458d
commit 7438fd1065
53 changed files with 1827 additions and 170 deletions

113
scripts/agent/relay.js Normal file
View file

@ -0,0 +1,113 @@
#!/usr/bin/env node
// The agent relay: a WebSocket router between the game page and tool clients. The page (src/agent/80-relay.js, agent
// mode in Settings) connects as the one "page"; tools (the MCP server, a script) connect as "tool" peers and send
// {kind:'call', id, tool, args}, which the relay routes to the page and back as {kind:'result', id, ...}. It holds no
// game state and knows no game logic: a dumb router (every client states its role; there is no token), so the whole
// player/operator boundary stays in the page's facade and in the driver.
//
// The relay rides the page's own HTTP server, on the same port, at the path AGENT_PATH: there is no second port, and
// the page infers its endpoint from where it was loaded (location.host). `npm run dev` hosts it in-process
// (scripts/dev.js); `createRelay({ server })` is the whole file, shared by the dev server and the tests.
//
// Security: no token. The bind address is the dev server's --host, loopback unless the operator chooses otherwise;
// what can reach that address may drive a game whose player turned agent mode on. What no bind address opens up: a
// website in the player's browser dialing the relay. Browsers send Origin on every WebSocket handshake and Node
// clients do not, and an Origin that does not name this very host (the page's own server) is refused below.
// Same-origin alone would let DNS rebinding through (evil.example re-pointed at 127.0.0.1 is "same-origin" with
// itself), so the Host must also be an address, never a name: an IP literal, localhost or *.localhost. Every client
// still states its role before anything routes, and one page at a time: a new page replaces the old one (a reload).
const { WebSocketServer } = require('ws');
const AUTH_MS = 5000; // a client must state its role within this, or the socket closes
const AGENT_PATH = '/agent'; // the relay's path on the page's own HTTP port
// `server`: the http.Server that serves the game page. The WebSocket rides it, same port.
// Host header → whether it names this machine by address (IP literal, localhost) rather than by a
// DNS name someone else controls.
function hostOk(h) {
if (typeof h !== 'string' || !h) return false;
let name;
try { name = new URL(`http://${h}`).hostname.toLowerCase(); } catch { return false; }
return name === 'localhost' || name.endsWith('.localhost') || /^\[[0-9a-f:.]+\]$/.test(name) || /^\d{1,3}(\.\d{1,3}){3}$/.test(name);
}
function createRelay({ server } = {}) {
if (!server) throw new Error('createRelay needs the http.Server that serves the page');
const wss = new WebSocketServer({ server, path: AGENT_PATH });
let page = null; // the one connected game page
const tools = new Set(); // connected tool clients
const pending = new Map(); // relay-scoped call id → {tool, id, page}
let seq = 0;
const send = (ws, o) => { if (ws.readyState === 1) ws.send(JSON.stringify(o)); };
// Presence goes both ways: tools learn whether a page is connected, the page learns how many
// tools are — agent mode holds the game's clock while none are (src/game/98-agent.js).
const presence = () => {
const p = !!(page && page.readyState === 1);
const n = [...tools].filter((t) => t.readyState === 1).length;
for (const t of tools) send(t, { kind: 'presence', page: p });
if (page) send(page, { kind: 'presence', tools: n });
};
wss.on('connection', (ws, req) => {
// Browsers send Origin on every WebSocket handshake, Node clients (our tools) never do.
// Same-origin only, host against Host: a foreign site must not dial the loopback relay
// and drive (or replace) the game — this closes that hole at no cost to either side.
if (!hostOk(req.headers.host)) { ws.close(4004, 'bad host'); return; }
const origin = req.headers.origin;
if (origin) {
let host = null;
try { host = new URL(origin).host; } catch { host = null; }
if (!host || host !== req.headers.host) { ws.close(4004, 'bad origin'); return; }
}
let role = null;
const authTimer = setTimeout(() => { if (!role) ws.close(4003, 'no auth'); }, AUTH_MS);
const dead = () => {
clearTimeout(authTimer);
if (ws === page) {
page = null;
// Answer the calls this page was sent with, so no tool waits out its timeout: the
// call is lost (reload, tab closed, replaced), not pending — say so, at once.
for (const [id, p] of [...pending]) if (p.page === ws) {
pending.delete(id);
send(p.tool, { kind: 'result', id: p.id, error: 'the game page disconnected before answering (reload or another tab took over)' });
}
}
tools.delete(ws);
for (const [id, p] of [...pending]) if (p.tool === ws) pending.delete(id);
presence(); // tools left: the page must know, to hold its clock
};
ws.on('message', (data) => {
let m; try { m = JSON.parse(String(data)); } catch { return; }
if (!m || typeof m !== 'object') return;
if (!role) {
if (m.kind !== 'auth' || (m.role !== 'page' && m.role !== 'tool')) { ws.close(4001, 'bad role'); return; }
role = m.role; clearTimeout(authTimer);
if (role === 'page') { if (page && page.readyState === 1) page.close(4000, 'replaced'); page = ws; presence(); }
else { tools.add(ws); presence(); }
return;
}
if (role === 'tool' && m.kind === 'call' && m.id !== undefined && typeof m.tool === 'string') {
if (!page || page.readyState !== 1) { send(ws, { kind: 'result', id: m.id, error: 'no game page connected: open the game in a browser with the relay on in Settings' }); return; }
const id = 'r' + (++seq);
pending.set(id, { tool: ws, id: m.id, page });
send(page, { kind: 'call', id, tool: m.tool, args: m.args || {} });
return;
}
if (role === 'page' && m.kind === 'result' && m.id !== undefined) {
const p = pending.get(m.id); if (!p) return;
pending.delete(m.id);
send(p.tool, { kind: 'result', id: p.id, dayBefore: m.dayBefore, dayAfter: m.dayAfter, value: m.value, error: m.error });
}
});
ws.on('close', dead);
ws.on('error', () => dead());
});
return {
wss, path: AGENT_PATH,
close() { for (const c of [page, ...tools]) { try { c.close(4002, 'relay shutdown'); } catch {} } try { wss.close(); } catch {} },
};
}
module.exports = { createRelay };

View file

@ -1,15 +1,22 @@
#!/usr/bin/env node
// Development server: http://localhost:8080 (PORT=… to change). The page is assembled from src/ on every
// request, static files come straight from site/, and the browser reloads itself when you save a file.
// Development server: http://127.0.0.1:8080 (--host/--port, or HOST=/PORT=, to change). The page is assembled from
// src/ on every request, static files come straight from site/, and the browser reloads itself when you save a file.
// The page is not version-stamped, so the game runs in dev mode (IS_DEV) like a local copy always has, and it is
// the development page: with the agent facade (src/agent/, window.TUBES) that the page players get has not.
// No dependencies: plain node:http. For the production build as GitHub Pages will serve it: npm run serve.
// The agent relay rides this same server, same port, path /agent: agent mode in the game's Settings dials it, and
// tools (node scripts/mcp.js --browser) drive the page this server serves.
// Binds loopback by default; --host binds wherever the operator chooses, the relay with it. Plain node:http and the
// relay's ws. For the production build as GitHub Pages will serve it: npm run serve.
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const { assemble, ROOT } = require('./lib/page');
const { createRelay } = require('./agent/relay');
const PORT = +process.env.PORT || 8080;
// --host/--port; a bare --host binds loopback (never undefined, which would listen on every interface).
const argOf = (k) => { const i = process.argv.indexOf(k); return i >= 0 && process.argv[i + 1] && !process.argv[i + 1].startsWith('--') ? process.argv[i + 1] : null; };
const HOST = argOf('--host') || process.env.HOST || '127.0.0.1';
const PORT = (() => { const p = +argOf('--port'); return Number.isInteger(p) && p > 0 && p < 65536 ? p : (+process.env.PORT || 8080); })();
const SITE = path.join(ROOT, 'site');
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css', '.json': 'application/json',
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml',
@ -24,7 +31,7 @@ function page() {
return html.replace('</body>', `${hint}${RELOAD}</body>`);
}
http.createServer((req, res) => {
const server = http.createServer((req, res) => {
const url = new URL(req.url, 'http://localhost');
if (url.pathname === '/__dev') {
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
@ -49,7 +56,20 @@ http.createServer((req, res) => {
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
res.end(String(e && e.stack || e));
}
}).listen(PORT, () => console.log(`Series of Tubes (dev): http://localhost:${PORT}/ — edits in src/ and site/ reload the page`));
});
const relay = createRelay({ server });
server.on('error', (e) => { console.error(`error: could not listen on ${HOST}:${PORT}: ${e.message}`); process.exit(1); });
server.listen(PORT, HOST, () => {
// The banner reports the socket's real address, not the flag it was asked for.
const ad = server.address(), at = `${ad.family === 'IPv6' ? `[${ad.address}]` : ad.address}:${ad.port}`;
const local = /^(127\.|::1$|localhost$)/.test(ad.address);
console.log(`Series of Tubes (dev): http://${at}/ — edits in src/ and site/ reload the page`);
console.error(`[series-of-tubes] agent relay on ws://${at}${relay.path} (no token)${local ? '' : `: bound to ${ad.address}, so anything that can reach this address can drive a game whose player turned agent mode on`}`);
console.error('[series-of-tubes] to let an agent play: Settings → Agent API in the game, then node scripts/mcp.js --browser');
});
const shutdown = () => { relay.close(); process.exit(0); };
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
let timer = null;
for (const dir of ['src', 'site']) {

View file

@ -0,0 +1,64 @@
// The MCP server's browser session: the game in the player's tab, over the agent relay (scripts/lib/relay-client.js),
// never a game of this process. The page owns the game (start, saves, seed), the clock (its Settings) and its windows;
// the tools are the page's own facade (src/agent/, TUBES.call), called with ctx.relay, so the same tools play
// the same way as the headless session (scripts/lib/mcp-game.js), with the player's rules on top.
const { load } = require('../../tests/harness');
const { pageCall } = require('./mcp-game');
const { createRelaySession } = require('./relay-client');
// Days the player watches take their time: an advance may run for minutes on a big network.
const ADVANCE_MS = 10 * 60 * 1000;
// The sections of the contract a tab and this checkout must agree on. mode and clock are the live session's own.
const CONTRACT = ['commands', 'view', 'session', 'drafts', 'denied', 'domains', 'state', 'results'];
// This checkout's contract, as a tab built from it would serve it over the relay.
let LOCAL = null;
function localSchema() {
if (LOCAL) return LOCAL;
const g = load({ agent: true });
LOCAL = pageCall(g, 'schema', {}, { relay: true });
if (g.errors.length) throw new Error(`the page assembled from src/ reported errors: ${g.errors.join('; ')}`);
g.dom.window.close();
return LOCAL;
}
// The sections in which a live tab's contract differs from this checkout's: a stale tab keeps names but may have
// changed arguments, domains or docs, so the comparison is deep.
const drift = (live, local = localSchema()) => CONTRACT.filter((k) => JSON.stringify(live && live[k]) !== JSON.stringify(local[k]));
function createBrowserSession(opts = {}) {
const relay = createRelaySession(opts);
const session = {
mode: 'browser', relay,
async tool(name, args = {}) {
const r = await relay.call(name, args, { ms: name === 'advance' ? Math.max(relay.config.callMs, ADVANCE_MS) : undefined });
if (r.refused) throw new Error(r.refused);
return r.value;
},
call(name, args) { return session.tool(name, args); },
headless() { throw new Error('Not in the player\'s browser: the game there is the player\'s to start, load and save.'); },
loadSave() { return session.headless(); },
info() { return { transport: 'relay', relay: relay.url }; },
errors() { return []; },
close() { return relay.close(); },
// Wait for a page on the relay (up to waitMs), then check that it serves this checkout's contract.
// Resolves {ok:true}, or {ok:false, why} for the server to say and stop on.
async ready({ waitMs = 90000, onWait } = {}) {
const deadline = Date.now() + waitMs;
let said = false, why = 'no answer';
for (;;) {
const r = await relay.call('schema', {});
if (!r.refused && r.value) {
const d = drift(r.value);
return d.length ? { ok: false, stale: d, why: `the game page in the browser disagrees with the code on disk (${d.join(', ')})` } : { ok: true };
}
why = r.refused || why;
if (Date.now() >= deadline) return { ok: false, why: `no game page answered on the relay (${relay.url}): ${why}` };
if (!said && onWait) { said = true; onWait(); }
await new Promise((res) => setTimeout(res, 1000));
}
},
};
return session;
}
module.exports = { createBrowserSession, drift, localSchema, CONTRACT };

View file

@ -1,9 +1,11 @@
// The game behind the MCP server (scripts/mcp.js): one game page of its own, the development page from src/ (with the
// agent facade, src/agent/), loaded in jsdom as the tests load it (tests/harness.js: seeded, no animation loop), with
// scripts/lib/mcp-headless.js added to start, load and export games. Every other tool is the page's own facade
// (TUBES.call), so the server plays the game the way the page itself would be played.
// The game behind the MCP server (scripts/mcp.js), in one of two places. Headless (createSession): one game page of its
// own, the development page from src/ (with the agent facade, src/agent/), loaded in jsdom as the tests load it
// (tests/harness.js: seeded, no animation loop), with scripts/lib/mcp-headless.js added to start, load and export games.
// In the browser (scripts/lib/mcp-browser.js): the game in the player's tab, over the agent relay. Either way every
// other tool is the page's own facade (TUBES.call), so both play the same game the same way.
//
// TOOLS is the list the server offers; each run() gets the session and the tool's arguments and returns JSON.
// TOOLS is the list the server offers; each says which sessions it works in (modes), and run() gets the session and
// the tool's arguments and returns JSON, or a promise of it (the browser answers over a socket).
const fs = require('node:fs');
const path = require('node:path');
const { load } = require('../../tests/harness');
@ -25,12 +27,15 @@ function actArgs() {
return ACT_ARGS;
}
const MAX_INLINE_SAVE = 200000;
const CLOCKS = ['agent', 'realtime'];
const DEFAULT_PACE_MS = 60000;
// One call into a jsdom page's facade, as JSON both ways: nothing but plain data crosses.
function pageCall(g, tool, args = {}) {
function pageCall(g, tool, args = {}, ctx) {
const w = g.dom.window;
w.__mcpTool = tool; w.__mcpArgs = JSON.parse(JSON.stringify(args));
return JSON.parse(g.ev('JSON.stringify(TUBES.call(__mcpTool,__mcpArgs))') || 'null');
w.__mcpTool = tool; w.__mcpArgs = JSON.parse(JSON.stringify(args)); w.__mcpCtx = ctx || null;
return JSON.parse(g.ev('JSON.stringify(TUBES.call(__mcpTool,__mcpArgs,__mcpCtx))') || 'null');
}
// Where load_save and export_save may touch files. stdio (saveDir undefined): anywhere, as the operator's own client
@ -46,42 +51,79 @@ function savePath(s, p, write) {
return real;
}
// opts.seed, opts.file as tests/harness.js takes them (a file must be a development page: it carries the facade).
// opts.saveDir: see savePath.
// opts.clock: 'agent' (time moves with advance) or 'realtime' (the session runs a day every opts.paceMs, and tools can
// only wait). opts.seed, opts.file as tests/harness.js takes them (a file must be a development page: it carries the
// facade). opts.saveDir: see savePath.
function createSession(opts = {}) {
let game = null;
const clock = CLOCKS.includes(opts.clock) ? opts.clock : 'agent';
const paceMs = Math.max(10, Math.floor(+opts.paceMs) || DEFAULT_PACE_MS);
let game = null, timer = null;
const boot = () => {
const g = load({ seed: opts.seed || 12345, file: opts.file, agent: true });
g.ev(HEADLESS_JS);
g.headless = (fn, ...args) => { g.dom.window.__mcpArgs = JSON.parse(JSON.stringify(args)); return JSON.parse(g.ev(`JSON.stringify(__mcpHeadless.${fn}(...window.__mcpArgs))`) || 'null'); };
g.headless('setClock', clock, paceMs, clock === 'realtime');
g.headless('newGame', { city: 'fra', name: 'Scratch Networks', preset: 'oncall' });
// A running clock: the server keeps the time, one day per pace, whatever the tools do (as the player's tab does).
if (clock === 'realtime') {
timer = setInterval(() => { try { g.ev('apiTick()'); } catch (e) { g.errors.push(String(e && e.message || e)); } }, paceMs);
if (timer.unref) timer.unref();
}
return g;
};
const session = {
saveDir: opts.saveDir,
mode: 'headless', clock, paceMs: clock === 'realtime' ? paceMs : 0, saveDir: opts.saveDir,
get game() { return game || (game = boot()); },
// The page's own tools (TUBES.call).
call(name, args) { return pageCall(session.game, name, args); },
// The page's own tools (TUBES.call), answered at once.
tool(name, args) { return pageCall(session.game, name, args); },
call(name, args) { return session.tool(name, args); },
headless(fn, ...args) { return session.game.headless(fn, ...args); },
// Text into the page without building a giant eval string (saves run to megabytes).
loadSave(txt) { session.game.dom.window.__mcpSave = txt; return JSON.parse(session.game.ev('JSON.stringify(__mcpHeadless.loadSave(window.__mcpSave))')); },
info() { return { transport: 'jsdom', clock, ...(clock === 'realtime' ? { paceMs } : {}) }; },
errors() { return game ? game.errors.slice() : []; },
close() { if (timer) clearInterval(timer); timer = null; },
};
return session;
}
// A value or a promise of one, the same way: headless tools answer at once, the browser's over a socket.
const then = (v, f) => (v && typeof v.then === 'function' ? v.then(f) : f(v));
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const str = (description, extra = {}) => ({ type: 'string', description, ...extra });
const num = (description, extra = {}) => ({ type: 'number', description, ...extra });
const bool = (description) => ({ type: 'boolean', description });
const obj = (properties = {}, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
const SECTIONS = ['clock', 'commands', 'view', 'session', 'drafts', 'denied', 'domains', 'state', 'results'];
const SECTIONS = ['mode', 'clock', 'commands', 'view', 'session', 'drafts', 'denied', 'domains', 'state', 'results'];
const WHERE = ['modal', 'bank', 'dash', 'panel', 'left', 'puzzle'];
const BOTH = ['headless', 'browser'], HEADLESS = ['headless'];
// A page tool, passed straight through: the MCP tool's arguments are the facade's.
const page = (name) => (s, a) => s.call(name, a);
const page = (name) => (s, a) => s.tool(name, a);
// wait: a running clock's days, read off the page until enough have passed (or something needs an answer).
async function waitDays(s, a) {
const days = Math.max(1, Math.min(365, Math.floor(+a.days) || 1)), maxMs = Math.max(1, Math.min(600, +a.maxSeconds || 120)) * 1000;
const c0 = await s.tool('clock', {});
if (c0.mode !== 'realtime') throw new Error('The clock here is yours and stands still between calls: use advance to move it.');
const t0 = Date.now(), poll = Math.max(10, Math.min(250, (c0.paceMs || 1000) / 4));
let c = c0, stop = null;
if (!c0.running) stop = 'the clock is not running (no game, a puzzle, or the network is bankrupt)';
while (!stop) {
await sleep(poll);
c = await s.tool('clock', {});
if (c.day >= c0.day + days) break;
if (c.lost) stop = 'bankrupt';
else if (c.question && !c0.question) stop = 'a window opened';
else if (Date.now() - t0 >= maxMs) stop = 'maxSeconds passed';
}
const since = await s.tool('since', { day: c0.day, cash: c0.cash, inc: c0.incidents });
return { ...since, daysAsked: days, stoppedBecause: stop, waitedSeconds: Math.round((Date.now() - t0) / 100) / 10 };
}
const TOOLS = [
{
name: 'new_game',
name: 'new_game', modes: HEADLESS,
description: 'Start a new network, replacing the current one. Presets: soft (Best Effort, the gentlest: no DDoS, no cable ships, no conferences, instant PNIs, patient customers, a rescue loan instead of game over), freeze (Change Freeze, gentle), oncall (On-call, the classic game), bgp (BGP at 3 a.m., harsh), sandbox (endless money, every level; chaos sets how often things break, default none). Seeded, so the same seed and the same moves give the same game. Scenarios, puzzles and architect runs start with act (startScn, pzStart, pzArStart).',
inputSchema: obj({ city: str('Home city: id (fra) or name (Frankfurt). Default Frankfurt.'), name: str('Network name (24 characters at most). Default: a random pun.'),
preset: str('Rules preset', { enum: ['soft', 'freeze', 'oncall', 'bgp', 'sandbox'] }), seed: num('Random seed, default 12345.'),
@ -89,7 +131,7 @@ const TOOLS = [
run: (s, a) => s.headless('newGame', a),
},
{
name: 'load_save',
name: 'load_save', modes: HEADLESS,
description: 'Load a saved game: a file exported from the game (Menu → Export save, the series-of-tubes-*.json from a bug report) or a raw save, as a path or as JSON text. Old saves are migrated exactly as the game does.',
inputSchema: obj({ path: str('Path to a .json save file.'), json: str('The save itself, as JSON text.') }),
run: (s, a) => {
@ -99,7 +141,7 @@ const TOOLS = [
},
},
{
name: 'export_save',
name: 'export_save', modes: HEADLESS,
description: 'Export the current game as a save file the real game can import (Menu → Import save). Writes it to path, or returns it when it is small.',
inputSchema: obj({ path: str('Where to write the .json file.') }),
run: (s, a) => {
@ -110,124 +152,132 @@ const TOOLS = [
},
},
{
name: 'status',
name: 'status', modes: BOTH,
description: 'The network at a glance: date, cash, monthly revenue and costs by kind, level, tier and why it is not Tier 1 yet, the current goal, traffic, reach, counts, POPs and open incidents.',
inputSchema: obj(),
run: page('status'),
},
{
name: 'advance',
description: 'Run the game forward day by day, as the game loop does. Stops early when a window opens (then read it with screen and answer it with click or act; decision says when it is a question with options) or the network goes bankrupt. Returns what happened: log, toasts, new incidents, cash, and how long each simulated day took.',
name: 'advance', modes: BOTH,
description: 'With the agent\'s clock (schema mode.clock "agent"): run the game forward day by day, as the game loop does. Stops early when a window opens (then read it with screen and answer it with click or act; decision says when it is a question with options) or the network goes bankrupt. Returns what happened: log, toasts, new incidents, cash, and how long each simulated day took. With a running clock it is an error: use wait.',
inputSchema: obj({ days: num('Days to run, 1 to 3650. Default 1.') }),
run: page('advance'),
},
{
name: 'network',
name: 'wait', modes: BOTH,
description: 'With a running clock (schema mode.clock "realtime"): days pass on their own at a fixed pace and nobody can stop them. wait returns once that many have passed, or earlier when a window asks a question, the network goes bankrupt or maxSeconds of real time are up. Returns what happened meanwhile: log, new incidents, cash. With the agent\'s clock it is an error: use advance.',
inputSchema: obj({ days: num('Days to wait for, 1 to 365. Default 1.'), maxSeconds: num('Give up after this much real time, 1 to 600. Default 120.') }),
run: (s, a) => waitDays(s, a),
},
{
name: 'network', modes: BOTH,
description: 'Everything about one network (a carrier, eyeball network, CDN…): type, peering policy and what it asks for, traffic share, transit price, PoPs, exchanges, upstreams and customer cone, whether Tier 1 needs it, and for you: demand, how its traffic leaves you (egress by kind), your PNIs and sessions with it, and how to move it to peering.',
inputSchema: obj({ network: str('Id (dtk), name (Doitsche Telekomm) or ASN.') }, ['network']),
run: page('network'),
},
{
name: 'city',
name: 'city', modes: BOTH,
description: 'One city: country, exchanges and their member counts, data center, who sells transit there and at what price, the networks present, the cables that land there, and your POP if you have one.',
inputSchema: obj({ city: str('Id (fra) or name (Frankfurt).') }, ['city']),
run: page('city'),
},
{
name: 'find',
name: 'find', modes: BOTH,
description: 'Search cities, networks, cables and exchanges by name, id or ASN. Use it to get the ids other tools and actions take.',
inputSchema: obj({ query: str('Part of a name, an id or an ASN.'), kind: str('Only this kind', { enum: ['city', 'network', 'cable', 'exchange'] }) }, ['query']),
run: page('find'),
},
{
name: 'traceroute',
name: 'traceroute', modes: BOTH,
description: 'The game\'s looking glass: the path traffic takes from one of your POPs to a network (which exit wins and why, with the AS path) or to another of your POPs (prefix it city:).',
inputSchema: obj({ from: str('One of your POPs: id or name.'), to: str('A network (id, name or ASN), or city:<one of your POPs>.') }, ['from', 'to']),
run: page('traceroute'),
},
{
name: 'peering_check',
name: 'peering_check', modes: BOTH,
description: 'Would this network peer with you, and if not, why not? Checks a PNI at each of your POPs where it is, and a session at each exchange you are on where it is a member, with the game\'s own reasons (traffic it wants, paid peering, the Tier 1 club…).',
inputSchema: obj({ network: str('Id, name or ASN.'), city: str('Only this city.'), via: str('Only this way', { enum: ['pni', 'ix'] }) }, ['network']),
run: page('peering_check'),
},
{
name: 'hot_spots',
name: 'hot_spots', modes: BOTH,
description: 'Where it hurts: the fullest links, transit ports and PNIs, the transit bill by carrier, and the networks with the most traffic still over transit, each with the cheapest way to peer with it.',
inputSchema: obj({ limit: num('How many of each, default 10.') }),
run: page('hot_spots'),
},
{
name: 'schema',
description: 'The typed contract act checks against: every game command with its arguments, their domains and a description, which ones dry-run, decide or confirm; view commands; session actions (scenarios, puzzles, runs); drafts (inputs another command reads); what is not available and why; the argument domains; and a field-by-field reference of state and results. Give section for one part.',
name: 'schema', modes: BOTH,
description: 'The typed contract act checks against: which session this is (mode: headless or the player\'s browser, and whose clock), every game command with its arguments, their domains and a description, which ones dry-run, decide or confirm; view commands; session actions (scenarios, puzzles, runs); drafts (inputs another command reads); what is not available and why; the argument domains; and a field-by-field reference of state and results. Give section for one part.',
inputSchema: obj({ section: str('One part only', { enum: SECTIONS }) }),
run: page('schema'),
run: (s, a) => then(s.tool('schema', a), (v) => (!a.section ? { ...v, mode: { ...v.mode, ...s.info() } } : a.section === 'mode' ? { ...v, ...s.info() } : v)),
},
{
name: 'catalog',
name: 'catalog', modes: BOTH,
description: 'The game\'s reference tables, which the argument domains point at: CITIES, NETS, CABLES, PORT, LT, OPT, DF_SYS, FAB, INTERNS, OPSK, CHARTERS, SCN, BANKS… plus three made for you: conferences (the upcoming calendar with the keys confGo and confSponsor take), TE_RECIPES (each RouteScript recipe with its script, ready for teDeploy) and BADGES (as the badge wall shows them). Omit name for the list of tables with their sizes.',
inputSchema: obj({ name: str('One table; omit for the list.') }),
run: page('catalog'),
},
{
name: 'state',
description: 'The saved game itself as JSON, the same object the game saves: offers, loan offers, links, ports, PNIs, customers, the intern, events… with their ids. schema section "state" documents each field. Give a path (pops.fra, links, loanOffers, biz.3, links.<id>): the whole state of a big network is hundreds of KB.',
name: 'state', modes: BOTH,
description: 'The saved game itself as JSON, the same object the game saves: offers, loan offers, links, ports, PNIs, customers, the intern, events… with their ids. schema section "state" documents each field; in the player\'s browser the dice (the seed, the days of the next failure and event) are held back. Give a path (pops.fra, links, loanOffers, biz.3, links.<id>): the whole state of a big network is hundreds of KB.',
inputSchema: obj({ path: str('Dotted path: a key, an array index or an entity id per step.') }),
run: page('state'),
},
{
name: 'results',
name: 'results', modes: BOTH,
description: 'The game\'s last traffic computation (R), rebuilt after every action and every day: load per link, use per port, demand and served per city, egress per network, monthly cost and revenue by kind, latency, reach. schema section "results" documents each field. Give a path (load, cost, netEg.ggl).',
inputSchema: obj({ path: str('Dotted path.') }),
run: page('results'),
},
{
name: 'ui',
name: 'ui', modes: BOTH,
description: 'The view state actions read and write (the selection, the pending link pair, the drafts of the link, fiber and cable windows, the RouteScript draft, confirmations), without render caches. For working out why an action did what it did.',
inputSchema: obj(),
run: page('ui'),
},
{
name: 'actions',
name: 'actions', modes: BOTH,
description: 'Every action act can run, with its arguments (? marks an optional one), e.g. buildPop(city), buyTransit(city,net,tier), buildLink(a,b,tier,cable?,route?,premiumCrossing?). Port tiers: 0 = 10G, 1 = 100G, 2 = 400G, 3 = 800G. Exchanges are given as city=<exchange id>. schema has each one\'s argument domains and what it does.',
inputSchema: obj(),
run: (s) => {
const { typed, drafts } = s.call('actions', {}), a = actArgs();
run: (s) => then(s.tool('actions', {}), ({ typed, drafts }) => {
const a = actArgs();
return [...Object.entries(typed).map(([k, sig]) => `${k}(${sig})`), ...drafts.map((k) => (a[k] ? `${k}(${a[k].join(',')})` : k))].sort();
},
}),
},
{
name: 'act',
description: 'Do something in the game: run one action with its arguments (see actions and schema). Arguments are checked first (a wrong id or value is an error that lists what fits); the action then runs as the game runs it: windows that take typed text are filled in (renameGo, teDeploy, teCheck, metricSet), multi-step builds take their choices as arguments (buildLink, orderDf, orderCable, decomGo), and confirmations are given (rmLink, cancelTransit…). outcome says what happened: applied (something changed), rejected (the game said no, see toasts), no_effect (nothing changed and nothing was said), shown (a view or draft: only the screen changed), decision (a window asks a question: answer with one of decision.options or closeModal; other game commands wait), quote (dryRun), stopped (bankrupt). charged is what the money gate took; cashChange also counts goal rewards. With dryRun, a game command is priced with the game\'s own helpers and nothing happens.',
name: 'act', modes: BOTH,
description: 'Do something in the game: run one action with its arguments (see actions and schema). Arguments are checked first (a wrong id or value is an error that lists what fits); the action then runs as the game runs it: windows that take typed text are filled in (renameGo, teDeploy, teCheck, metricSet), multi-step builds take their choices as arguments (buildLink, orderDf, orderCable, decomGo), and confirmations are given (rmLink, cancelTransit…). outcome says what happened: applied (something changed), rejected (the game said no, see toasts), no_effect (nothing changed and nothing was said), shown (a view or draft: only the screen changed), decision (a window asks a question: answer with one of decision.options or closeModal; other game commands wait), quote (dryRun), stopped (bankrupt). charged is what the money gate took; cashChange also counts goal rewards. With dryRun, a game command is priced with the game\'s own helpers and nothing happens. In the player\'s browser, a window the player opened stays theirs: you play behind it.',
inputSchema: obj({ action: str('Action name, e.g. buildPop (view. prefixes are accepted).'), command: str('Same as action.'), args: { type: 'object', description: 'Its arguments, e.g. {"city":"ams"}.' },
dryRun: bool('Price it and check it can be done: {setup, monthly, days, blocked}. Nothing happens.') }),
run: page('act'),
},
{
name: 'screen',
name: 'screen', modes: BOTH,
description: 'What the player sees, as text with numbered buttons for click: the open window, else the bank or the NOC dashboard when open, else the side panel, else the puzzle box. where picks one: modal, bank, dash, panel, left (the left drawer: goals, deals, noc or nets) or puzzle. open lists what is showing. Long text comes in pages: textMore says the offset of the next one. Lists the game acts on when they change come with their options; click them with a value.',
inputSchema: obj({ where: str('Which surface', { enum: WHERE }), offset: num('Start the text here (from textMore).') }),
run: page('screen'),
},
{
name: 'panel',
name: 'panel', modes: BOTH,
description: 'Open the side panel of a city or a link, a network in the network list, or a tab of the left drawer (goals, deals: offers and loans, noc, nets), optionally on a tab (a city has cust, up, peer, infra…), and show it as text with numbered buttons.',
inputSchema: obj({ city: str('City id or name.'), link: str('Link id (from status, hot_spots or state links).'), network: str('Network id or name.'), tab: str('Tab id, as the tab buttons name it.'),
left: str('A tab of the left drawer', { enum: ['goals', 'deals', 'noc', 'nets'] }) }),
run: page('panel'),
},
{
name: 'click',
name: 'click', modes: BOTH,
description: 'Press a numbered button from the last screen, panel or act result, as a player\'s click does: with the button\'s own arguments, so confirmations arm first and windows step on as in the game. For a list (it has options), give value.',
inputSchema: obj({ button: num('The button\'s n.'), value: str('For a list: the option to pick.') }, ['button']),
run: page('click'),
},
{
name: 'open_link',
name: 'open_link', modes: BOTH,
description: 'Open the build window for a link (a leased wave, dark fiber or your own cable) from one of your POPs to any city, to compare the routes and sizes it offers; then click through it. act buildLink, orderDf and orderCable do the same in one call.',
inputSchema: obj({ from: str('One of your POPs.'), to: str('Any city.') }, ['from', 'to']),
run: page('open_link'),
},
];
module.exports = { createSession, TOOLS, actArgs, savePath };
const toolsFor = (mode) => TOOLS.filter((t) => t.modes.includes(mode));
module.exports = { createSession, TOOLS, toolsFor, actArgs, pageCall, savePath, CLOCKS, DEFAULT_PACE_MS };

View file

@ -30,5 +30,7 @@
return { savedBy: r.ver, ...apiStatus() };
};
const exportSave = (version) => JSON.stringify({ app: 'series-of-tubes', version: /^\d/.test(APP_VERSION) ? APP_VERSION : version, exported: new Date().toISOString(), S: packSave(S) });
window.__mcpHeadless = { newGame, loadSave, exportSave };
// The server's clock: the agent's (advance), or a running one it ticks itself (apiTick) at paceMs.
const setClock = (mode, paceMs, running) => { API_CLK = { mode, paceMs: mode === 'realtime' ? paceMs : 0, running: !!running }; };
window.__mcpHeadless = { newGame, loadSave, exportSave, setClock };
})();

View file

@ -0,0 +1,72 @@
// The tool side of the agent relay (scripts/agent/relay.js), for the MCP server's browser session
// (scripts/lib/mcp-browser.js). The game runs in the player's browser, never in this process, connected to the relay
// from Settings. The relay rides the server that serves the page, same port, path /agent (npm run dev, 8080 unless
// told otherwise), so host and port say where the page is served, nothing else. A call travels
// tool → relay → page → TUBES.call and back.
const WebSocket = require('ws');
// A healthy page answers in milliseconds, and a page that goes away has its calls answered at once (by the relay, or
// by the close handler below), so this only catches a page that hangs. Days the player watches take longer: a call
// can ask for more time of its own.
const CALL_MS = 30000;
function createRelaySession(opts = {}) {
const cfg = {
host: typeof opts.host === 'string' && opts.host ? opts.host : '127.0.0.1',
port: +opts.port || 8080, // the port the game page is served on: the relay rides it
callMs: +opts.callMs > 0 ? +opts.callMs : CALL_MS,
};
const url = `ws://${cfg.host.includes(':') && !cfg.host.startsWith('[') ? `[${cfg.host}]` : cfg.host}:${cfg.port}/agent`;
let ws = null, connecting = null, id = 0, page = false;
const pending = new Map();
function connect() {
if (ws && ws.readyState === 1) return Promise.resolve();
if (connecting) return connecting;
connecting = new Promise((res, rej) => {
const w = new WebSocket(url);
let done = false;
const finish = (e) => { if (done) return; done = true; connecting = null; e ? rej(e) : res(); };
w.on('open', () => { w.send(JSON.stringify({ kind: 'auth', role: 'tool' })); finish(); });
w.on('error', (e) => finish(new Error(`relay ${url}: ${e.message}`)));
w.on('close', () => {
if (ws === w) { ws = null; page = false; }
// The socket died with calls in flight: answer them here too, so no tool waits out its timeout on a
// connection that is already gone (the relay answers for a dead page).
for (const [k, p] of [...pending]) { pending.delete(k); clearTimeout(p.t); p.res({ error: `relay ${url}: connection closed before the game page answered` }); }
if (!done) finish(new Error(`relay ${url}: connection closed`));
});
w.on('message', (d) => {
let m; try { m = JSON.parse(String(d)); } catch { return; }
if (!m || typeof m !== 'object') return;
if (m.kind === 'presence') { page = !!m.page; return; }
if (m.kind === 'result' && m.id !== undefined) { const p = pending.get(m.id); if (p) { pending.delete(m.id); clearTimeout(p.t); p.res(m); } }
});
ws = w;
});
return connecting;
}
// One call: {refused} when it could not be answered (no relay, no page, a timeout) or the page's tool threw,
// else {value}. dayBefore/dayAfter: the game day the page saw around it.
async function call(tool, args = {}, o = {}) {
try { await connect(); } catch (e) { return { refused: e.message, value: null }; }
const k = 't' + (++id), ms = +o.ms > 0 ? +o.ms : cfg.callMs;
const m = await new Promise((res) => {
const t = setTimeout(() => { pending.delete(k); res({ error: `no answer from the game page in ${ms / 1000} s (is the tab stuck?)` }); }, ms);
pending.set(k, { res, t });
ws.send(JSON.stringify({ kind: 'call', id: k, tool, args }));
});
if (m.error) return { refused: m.error, value: null, dayBefore: m.dayBefore, dayAfter: m.dayAfter };
return { refused: null, value: m.value === undefined ? null : m.value, dayBefore: m.dayBefore, dayAfter: m.dayAfter };
}
return {
config: cfg, url, call, connect,
get page() { return page; },
async close() { try { ws && ws.close(1000); } catch {} },
};
}
module.exports = { createRelaySession, CALL_MS };

View file

@ -1,11 +1,14 @@
#!/usr/bin/env node
// Series of Tubes as an MCP server: an AI client can play, inspect and debug the game through typed tools.
// It loads the game from this checkout's src/ (scripts/lib/mcp-game.js) and speaks MCP through the official SDK
// Series of Tubes as an MCP server: an AI client can play, inspect and debug the game through typed tools, in one of
// two sessions: headless, a game of its own loaded from this checkout's src/ (scripts/lib/mcp-game.js), or the game in
// the player's browser tab over the agent relay (scripts/lib/mcp-browser.js). It speaks MCP through the official SDK
// (@modelcontextprotocol/server), over stdio or over HTTP. Nothing is hosted: this is a local tool, like npm run dev,
// and the game page players get does not change.
//
// node scripts/mcp.js # stdio, for a client that starts the server itself
// node scripts/mcp.js --http 7777 # Streamable HTTP on http://127.0.0.1:7777/mcp
// node scripts/mcp.js # stdio, headless, the agent's clock (advance)
// node scripts/mcp.js --clock realtime # a clock that runs on its own (--pace ms per day; wait)
// node scripts/mcp.js --browser # the player's tab, through the relay npm run dev hosts
// node scripts/mcp.js --http 7777 # Streamable HTTP on http://127.0.0.1:7777/mcp (with any of the above)
// node scripts/mcp.js --http 0.0.0.0:7777 # the same on every interface: anyone who can reach it can play
//
// claude mcp add seriesoftubes -- node /path/to/seriesoftubes/scripts/mcp.js
@ -18,17 +21,32 @@ const http = require('node:http');
const os = require('node:os');
const path = require('node:path');
const { McpServer, fromJsonSchema, createMcpHandler, validateHostHeader, validateOriginHeader, localhostAllowedHostnames, localhostAllowedOrigins } = require('@modelcontextprotocol/server');
const { createSession, TOOLS } = require('./lib/mcp-game');
const { createSession, toolsFor, CLOCKS, DEFAULT_PACE_MS } = require('./lib/mcp-game');
const { version } = require('../package.json');
const INSTRUCTIONS = `Series of Tubes is a cartoon game about building an internet backbone: POPs in cities, links between them, transit, exchanges, PNIs, customers. A game is always loaded (a fresh On-call game in Frankfurt until you start or load another).
Read with status, network, city, find, traceroute, peering_check and hot_spots, or raw with state, results and catalog; schema is the typed contract of every action. Change things with act (arguments are checked, outcome says what happened, dryRun prices a move first), or with screen, panel and click, which show the game's own panels and windows as text with numbered buttons. Time moves only with advance. Games are seeded: the same seed and moves give the same game.
const READ = 'Read with status, network, city, find, traceroute, peering_check and hot_spots, or raw with state, results and catalog; schema is the typed contract of every action, and its mode section says which session this is. Change things with act (arguments are checked, outcome says what happened, dryRun prices a move first), or with screen, panel and click, which show the game\'s own panels and windows as text with numbered buttons.';
const CLOCK = {
agent: 'Time moves only with advance.',
realtime: 'The clock runs on its own, a day at a fixed pace, and you cannot stop it: decide while it runs, and use wait to let days pass.',
};
const instructions = (mode, clock) => mode === 'browser'
? `Series of Tubes is a cartoon game about building an internet backbone: POPs in cities, links between them, transit, exchanges, PNIs, customers. You are playing the game in the player's own browser tab while they watch: the game, its saves and its settings are theirs, and so is any window they open (you play behind it). ${READ} The player picks the clock in Settings: either it runs on its own at a pace and you use wait, or it is yours and you use advance (schema mode.clock says which).`
: `Series of Tubes is a cartoon game about building an internet backbone: POPs in cities, links between them, transit, exchanges, PNIs, customers. A game is always loaded (a fresh On-call game in Frankfurt until you start or load another). ${READ} ${CLOCK[clock]} Games are seeded: the same seed and moves give the same game.
To look into a bug report: load_save with the attached save, then status, hot_spots, and advance with timings.`;
const INSTRUCTIONS = instructions('headless', 'agent');
const MCP_PATH = '/mcp';
const usage = () => `Usage: node scripts/mcp.js [options]
(no options) stdio: the client starts this process and talks over stdin and stdout
(no options) headless over stdio: a game of its own, from this checkout's src/; the client starts this process
--clock agent|realtime headless: who moves time (default agent: advance; realtime: a day every --pace ms, and wait)
--pace MS headless, realtime clock: real milliseconds per simulated day (default ${DEFAULT_PACE_MS})
--seed N headless: the random seed of the first game (default 12345)
--browser the game in the player's browser instead, over the agent relay (Settings → Agent API)
--relay-host HOST browser: where npm run dev serves the page; the relay rides it (default 127.0.0.1)
--relay-port N browser: the port it serves the page on (default 8080)
--page-wait-ms N browser: how long to wait for a game page to connect (default 90000)
--call-ms N browser: how long one tool call may wait for the page (default 30000)
--http [HOST:]PORT Streamable HTTP at http://HOST:PORT${MCP_PATH} instead (HOST defaults to 127.0.0.1)
--token-file FILE HTTP: require "Authorization: Bearer <the file's contents>" (or set SOT_MCP_TOKEN)
--allow-host NAME HTTP: also accept this Host name (repeatable), e.g. for a tunnel or a LAN name
@ -57,11 +75,11 @@ function serial() {
// One MCP server definition over the game session: the SDK asks for a fresh one per connection (stdio) or per request
// (HTTP); they all share the session and its queue.
function serverFactory(session) {
const queue = serial();
const schemas = new Map(TOOLS.map((t) => [t.name, fromJsonSchema(t.inputSchema)]));
const queue = serial(), tools = toolsFor(session.mode || 'headless'), text = instructions(session.mode || 'headless', session.clock || 'agent');
const schemas = new Map(tools.map((t) => [t.name, fromJsonSchema(t.inputSchema)]));
return () => {
const server = new McpServer({ name: 'seriesoftubes', title: 'Series of Tubes', version }, { capabilities: { tools: {} }, instructions: INSTRUCTIONS });
for (const tool of TOOLS) {
const server = new McpServer({ name: 'seriesoftubes', title: 'Series of Tubes', version }, { capabilities: { tools: {} }, instructions: text });
for (const tool of tools) {
server.registerTool(tool.name, { description: tool.description, inputSchema: schemas.get(tool.name) }, (args) => queue(async () => {
try {
const out = await tool.run(session, args || {});
@ -145,11 +163,24 @@ async function main() {
const die = (m) => { console.error(`error: ${m}`); process.exit(1); };
// The game page logs nothing to stdout, but a stray console.log anywhere must not break the stdio protocol.
console.log = console.info = (...a) => console.error(...a);
const flag = (k) => `--${k.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase())}`;
if (!args.http) for (const k of ['tokenFile', 'allowHost', 'saveDir']) if (args[k] !== undefined) die(`${flag(k)} is an --http option`);
if (args.browser) {
for (const k of ['clock', 'pace', 'seed', 'saveDir']) if (args[k] !== undefined) die(`${flag(k)} is the headless session's: in the browser the player owns the game and sets the clock in Settings`);
} else {
for (const k of ['relayHost', 'relayPort', 'pageWaitMs', 'callMs']) if (args[k] !== undefined) die(`${flag(k)} is a --browser option`);
if (args.clock !== undefined && !CLOCKS.includes(args.clock)) die(`--clock is one of ${CLOCKS.join(', ')}`);
}
if (!args.http) {
for (const k of ['tokenFile', 'allowHost', 'saveDir']) if (args[k] !== undefined) die(`--${k.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase())} is an --http option`);
const { serveStdio } = require('@modelcontextprotocol/server/stdio');
const session = createSession();
const session = open(args);
serveStdio(serverFactory(session));
const shutdown = () => { try { session.close(); } catch {} process.exit(0); };
process.stdin.on('close', shutdown);
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
// stdio has one client, which needs the page: without one, it is better told by the server stopping.
started(session, args, say, true);
return;
}
let listen, token;
@ -160,7 +191,7 @@ async function main() {
try { saveDir = fs.realpathSync(path.resolve(String(args.saveDir))); } catch (e) { die(`--save-dir ${args.saveDir}: ${e.message}`); }
if (!fs.statSync(saveDir).isDirectory()) die(`--save-dir ${args.saveDir} is not a directory`);
}
const session = createSession({ saveDir });
const session = open(args, { saveDir });
const server = createHttpServer(serverFactory(session), { host: listen.host, allow: [].concat(args.allowHost || []), token });
server.on('error', (e) => die(`could not listen on ${bracket(listen.host)}:${listen.port}: ${e.message}`));
server.listen(listen.port, listen.host, () => {
@ -168,13 +199,41 @@ async function main() {
say(`MCP server ${version} on http://${at}${MCP_PATH} (one game, shared by every client; calls run one at a time)`);
say(token ? 'a bearer token is required' : 'no token: anything that can reach this address may play');
if (!isLoopback(listen.host) && !token) say(`WARNING: bound to ${listen.host}, beyond this machine, without a token. Set SOT_MCP_TOKEN or --token-file to require one.`);
say(saveDir ? `load_save and export_save files: under ${saveDir}` : 'load_save and export_save take JSON only (no files: --save-dir DIR allows some)');
if (session.mode === 'headless') say(saveDir ? `load_save and export_save files: under ${saveDir}` : 'load_save and export_save take JSON only (no files: --save-dir DIR allows some)');
started(session, args, say, false);
});
const shutdown = () => server.close(() => process.exit(0));
const shutdown = () => { try { session.close(); } catch {} server.close(() => process.exit(0)); };
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
}
// The session the flags ask for: headless (with its clock), or the player's browser over the relay.
function open(args, extra = {}) {
if (args.browser) {
const { createBrowserSession } = require('./lib/mcp-browser');
return createBrowserSession({ host: args.relayHost, port: args.relayPort, callMs: args.callMs });
}
return createSession({ clock: args.clock, paceMs: args.pace, seed: +args.seed || undefined, ...extra });
}
// What the session is, said once it is up. In the browser the handshake is answered at once; the page may arrive
// later, and must be built from this checkout. Over stdio a missing or stale page stops the server (its one client
// is better told so); over HTTP the server stays up and says why its tools fail.
function started(session, args, say, stopOnFail) {
if (session.mode !== 'browser') {
say(`MCP server ${version}: headless, ${session.clock === 'realtime' ? `a running clock, a day every ${session.paceMs} ms` : 'the agent\'s clock'}`);
return;
}
say(`MCP server ${version}: the player's browser, over the relay ${session.relay.url}`);
session.ready({ waitMs: +args.pageWaitMs || 90000, onWait: () => say(`waiting for the game page on the relay (${session.relay.url})...`) }).then((r) => {
if (r.ok) { say('the game page serves this checkout\'s contract: ready'); return; }
say(r.why);
if (r.stale) say('Its tab is older than this checkout: reload the page in the browser (npm run dev assembles it from src/ on every request).');
else say('Turn agent mode on in the game (Settings → Agent API), which connects it to the relay. The page must come from npm run dev, which hosts the relay (the deployed seriesoftub.es has none), opened by address (http://localhost or http://127.0.0.1, or the IP it is bound to), not a DNS name, which the relay refuses.');
if (stopOnFail) process.exit(1);
});
}
if (require.main === module) main();
module.exports = { serverFactory, createHttpServer, serial, parseArgs, parseListen, allowedHosts, INSTRUCTIONS, MCP_PATH };
module.exports = { serverFactory, createHttpServer, serial, parseArgs, parseListen, allowedHosts, instructions, INSTRUCTIONS, MCP_PATH };