The game as a local MCP server: play, inspect and debug it from an AI client
scripts/mcp.js speaks MCP over stdio and loads the game from src/ in jsdom, seeded, like the tests. Tools: new_game, load_save, export_save, status, advance (with per-day timings), network, city, find, traceroute, peering_check, hot_spots, actions, act, screen, panel, click, open_link. Actions go through ACT as buttons do; files, slots, settings and the clock stay out of reach, and nothing evaluates code in the page. Nothing is hosted and the page is unchanged. See docs/MCP.md.
This commit is contained in:
parent
935c08839f
commit
37def9dd6b
9 changed files with 733 additions and 1 deletions
167
scripts/lib/mcp-game.js
Normal file
167
scripts/lib/mcp-game.js
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
// The game behind the MCP server (scripts/mcp.js): one game page from src/, loaded in jsdom like the tests load it
|
||||
// (tests/harness.js: seeded, no animation loop), with scripts/lib/mcp-page.js added to read and drive it.
|
||||
// TOOLS is the list the server offers; each run() gets the session and the tool's arguments and returns JSON.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('../../tests/harness');
|
||||
|
||||
const PAGE_JS = fs.readFileSync(path.join(__dirname, 'mcp-page.js'), 'utf8');
|
||||
const ACT_DIR = path.join(__dirname, '..', '..', 'src', 'game', '90-actions');
|
||||
|
||||
// The arguments each action takes, read from its source (`buyTransit:({city,net,tier})=>`): in the page the
|
||||
// actions are wrapped for puzzle mode, so their own parameter lists are not visible there.
|
||||
let ACT_ARGS = null;
|
||||
function actArgs() {
|
||||
if (ACT_ARGS) return ACT_ARGS;
|
||||
ACT_ARGS = {};
|
||||
const re = /(?:^|[\s,{])([A-Za-z]\w*):\s*(?:async\s*)?\(\s*\{([^}]*)\}\s*\)\s*=>/g;
|
||||
for (const f of fs.readdirSync(ACT_DIR).filter((f) => f.endsWith('.js')).sort()) {
|
||||
const src = fs.readFileSync(path.join(ACT_DIR, f), 'utf8');
|
||||
for (const m of src.matchAll(re)) if (!ACT_ARGS[m[1]]) ACT_ARGS[m[1]] = m[2].split(',').map((a) => a.split('=')[0].trim()).filter(Boolean);
|
||||
}
|
||||
return ACT_ARGS;
|
||||
}
|
||||
const MAX_INLINE_SAVE = 200000;
|
||||
|
||||
function createSession(opts = {}) {
|
||||
let game = null;
|
||||
const boot = () => {
|
||||
const g = load({ seed: opts.seed || 12345, file: opts.file });
|
||||
g.ev(PAGE_JS);
|
||||
g.call = (fn, ...args) => {
|
||||
g.dom.window.__mcpArgs = JSON.parse(JSON.stringify(args));
|
||||
return JSON.parse(g.ev(`JSON.stringify(__mcp.${fn}(...window.__mcpArgs))`) || 'null');
|
||||
};
|
||||
g.call('newGame', { city: 'fra', name: 'Scratch Networks', preset: 'oncall' });
|
||||
return g;
|
||||
};
|
||||
const session = {
|
||||
get game() { return game || (game = boot()); },
|
||||
call(fn, ...args) { return session.game.call(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(__mcp.loadSave(window.__mcpSave))')); },
|
||||
errors() { return game ? game.errors.slice() : []; },
|
||||
};
|
||||
return session;
|
||||
}
|
||||
|
||||
const str = (description, extra = {}) => ({ type: 'string', description, ...extra });
|
||||
const num = (description, extra = {}) => ({ type: 'number', description, ...extra });
|
||||
const obj = (properties = {}, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
|
||||
|
||||
const TOOLS = [
|
||||
{
|
||||
name: 'new_game',
|
||||
description: 'Start a new network, replacing the current one. Presets: freeze (Change Freeze, gentle), oncall (On-call, the classic game), bgp (BGP at 3 a.m., harsh), sandbox (endless money, every level, no chaos). Seeded, so the same seed and the same moves give the same game.',
|
||||
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: ['freeze', 'oncall', 'bgp', 'sandbox'] }), seed: num('Random seed, default 12345.') }),
|
||||
run: (s, a) => s.call('newGame', a),
|
||||
},
|
||||
{
|
||||
name: 'load_save',
|
||||
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) => {
|
||||
if (!a.path === !a.json) throw new Error('Give either path or json.');
|
||||
const txt = a.path ? fs.readFileSync(path.resolve(a.path), 'utf8') : a.json;
|
||||
return s.loadSave(txt);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'export_save',
|
||||
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) => {
|
||||
const txt = s.call('exportSave', require('../../package.json').version);
|
||||
if (a.path) { fs.writeFileSync(path.resolve(a.path), txt); return { wrote: path.resolve(a.path), bytes: Buffer.byteLength(txt) }; }
|
||||
if (txt.length > MAX_INLINE_SAVE) throw new Error(`The save is ${txt.length} characters; give a path to write it to.`);
|
||||
return JSON.parse(txt);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'status',
|
||||
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: (s) => s.call('status'),
|
||||
},
|
||||
{
|
||||
name: 'advance',
|
||||
description: 'Run the game forward day by day, as the game loop does. Stops early when a window opens that needs an answer (then answer it with screen and click) or the network goes bankrupt. Returns what happened: log, toasts, new incidents, cash, and how long each simulated day took.',
|
||||
inputSchema: obj({ days: num('Days to run, 1 to 3650. Default 1.') }),
|
||||
run: (s, a) => s.call('advance', a.days),
|
||||
},
|
||||
{
|
||||
name: 'network',
|
||||
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: (s, a) => s.call('network', a.network),
|
||||
},
|
||||
{
|
||||
name: 'city',
|
||||
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: (s, a) => s.call('city', a.city),
|
||||
},
|
||||
{
|
||||
name: 'find',
|
||||
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: (s, a) => s.call('find', a.query, a.kind),
|
||||
},
|
||||
{
|
||||
name: 'traceroute',
|
||||
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: (s, a) => s.call('trace', a.from, a.to),
|
||||
},
|
||||
{
|
||||
name: 'peering_check',
|
||||
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: (s, a) => s.call('peering', a.network, a.city, a.via),
|
||||
},
|
||||
{
|
||||
name: 'hot_spots',
|
||||
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: (s, a) => s.call('hotSpots', a.limit || 10),
|
||||
},
|
||||
{
|
||||
name: 'actions',
|
||||
description: 'Every game action act can run, with the arguments it takes, e.g. buildPop(city), buyTransit(city,net,tier), buyIx(city,tier), pni(city,net,tier). Port tiers: 0 = 10G, 1 = 100G, 2 = 400G, 3 = 800G. Exchanges are given as city=<exchange id>.',
|
||||
inputSchema: obj(),
|
||||
run: (s) => { const a = actArgs(); return s.call('actions').map((k) => (a[k] ? `${k}(${a[k].join(',')})` : k)); },
|
||||
},
|
||||
{
|
||||
name: 'act',
|
||||
description: 'Do something in the game, as a button would: run one action with its arguments (see actions). Returns the game\'s messages, the change in cash, and what is on screen now: an open window (a quote, a choice) with its numbered buttons, or the side panel.',
|
||||
inputSchema: obj({ action: str('Action name, e.g. buildPop.'), args: { type: 'object', description: 'Its arguments, e.g. {"city":"ams"}.' } }, ['action']),
|
||||
run: (s, a) => s.call('run', a.action, a.args || {}),
|
||||
},
|
||||
{
|
||||
name: 'screen',
|
||||
description: 'What the player sees now: the open window, or else the side panel, as text with numbered buttons for click.',
|
||||
inputSchema: obj(),
|
||||
run: (s) => s.call('screen'),
|
||||
},
|
||||
{
|
||||
name: 'panel',
|
||||
description: 'Open the side panel of a city or a link, or a network in the network list, 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 or hot_spots).'), network: str('Network id or name.'), tab: str('Tab id, as the tab buttons name it.') }),
|
||||
run: (s, a) => s.call('panel', a),
|
||||
},
|
||||
{
|
||||
name: 'click',
|
||||
description: 'Press a numbered button from the last screen, panel or act result.',
|
||||
inputSchema: obj({ button: num('The button\'s n.') }, ['button']),
|
||||
run: (s, a) => s.call('click', a.button),
|
||||
},
|
||||
{
|
||||
name: 'open_link',
|
||||
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. Then pick the route and size with click (buildLink takes the tier).',
|
||||
inputSchema: obj({ from: str('One of your POPs.'), to: str('Any city.') }, ['from', 'to']),
|
||||
run: (s, a) => s.call('openLink', a.from, a.to),
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = { createSession, TOOLS };
|
||||
273
scripts/lib/mcp-page.js
Normal file
273
scripts/lib/mcp-page.js
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
// Runs inside the game page (see scripts/lib/mcp-game.js), in the game's own global scope, so it reads S, R, NET,
|
||||
// CITY… directly. Every function takes and returns plain JSON. It only reads the game, except act(), click(),
|
||||
// panel(), advance() and the game loaders, which go through the same ACT actions and dayTick() the page uses.
|
||||
(() => {
|
||||
const BLOCK = /^(DIV|P|H1|H2|H3|H4|SECTION|LI|UL|OL|TR|TABLE|NAV|HEADER|FOOTER|BUTTON|LABEL|DETAILS|SUMMARY)$/;
|
||||
// Text as a player would read it: one line per block, no runs of spaces. jsdom has no innerText.
|
||||
const text = (x, max = 8000) => {
|
||||
let el = x;
|
||||
if (typeof x === 'string') { el = document.createElement('div'); el.innerHTML = x; }
|
||||
if (!el) return '';
|
||||
const out = [];
|
||||
const walk = (n) => {
|
||||
if (n.nodeType === 3) { out.push(n.nodeValue); return; }
|
||||
if (n.nodeType !== 1 || n.hidden || /^(SCRIPT|STYLE|SVG|CANVAS)$/i.test(n.tagName)) return;
|
||||
if (n.tagName === 'BR') { out.push('\n'); return; }
|
||||
// Blocks get their own line; inline tags a space, so "Revenue<b>$2k</b>" does not read as one word.
|
||||
const sep = BLOCK.test(n.tagName) ? '\n' : ' ';
|
||||
out.push(sep);
|
||||
for (const c of n.childNodes) walk(c);
|
||||
out.push(sep);
|
||||
};
|
||||
walk(el);
|
||||
const s = out.join('').split('\n').map((l) => l.replace(/\s+/g, ' ').replace(/ ([.,;:!?)])/g, '$1').replace(/\( /g, '(').trim()).filter(Boolean).join('\n');
|
||||
return s.length > max ? s.slice(0, max) + '\n…' : s;
|
||||
};
|
||||
const r1 = (v) => (typeof v === 'number' && isFinite(v) ? Math.round(v * 10) / 10 : v);
|
||||
const fail = (msg) => { throw new Error(msg); };
|
||||
const norm = (s) => String(s || '').toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').trim();
|
||||
|
||||
// ---------- finding things by id or by name ----------
|
||||
const best = (list, q, keys) => {
|
||||
const n = norm(q);
|
||||
if (!n) return null;
|
||||
for (const test of [(v) => v === n, (v) => v.startsWith(n), (v) => v.includes(n)]) {
|
||||
const hit = list.find((x) => keys(x).some((k) => test(norm(k))));
|
||||
if (hit) return hit;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const netOf = (q) => NET[q] || best(NETS, q, (n) => [n.id, n.name, 'as' + n.asn, String(n.asn)]) || fail(`No network matches "${q}". Try find.`);
|
||||
const cityOf = (q) => CITY[q] || best(CITIES, q, (c) => [c.id, c.name]) || fail(`No city matches "${q}". Try find.`);
|
||||
const allIx = () => {
|
||||
const o = [];
|
||||
for (const c of CITIES) for (const x of ixStatic(c.id)) o.push(x);
|
||||
for (const c of Object.keys(S.myIx || {})) if (!o.includes(c)) o.push(c);
|
||||
return o;
|
||||
};
|
||||
const ixOf = (q) => (XIXM[q] || (CITY[q] && CITY[q].ix) || (S.myIx && S.myIx[q]) ? q : best(allIx(), q, (x) => [x, ixName(x)])) || fail(`No exchange matches "${q}".`);
|
||||
const cityName = (c) => (CITY[c] ? CITY[c].name : c);
|
||||
const incText = (i) => text(i.msg || incTitle(i), 400);
|
||||
|
||||
// ---------- toasts: what the game tells the player ----------
|
||||
let toasts = [];
|
||||
const t0 = toast;
|
||||
toast = function (h, kind) { toasts.push((kind ? kind + ': ' : '') + text(String(h), 600)); return t0.apply(this, arguments); };
|
||||
const takeToasts = () => { const t = toasts; toasts = []; return t; };
|
||||
|
||||
// ---------- what is on screen ----------
|
||||
let last = [];
|
||||
const buttons = (root) => [...root.querySelectorAll('[data-act]')].map((b) => {
|
||||
let args = {};
|
||||
try { args = JSON.parse(b.dataset.args || '{}'); } catch (e) {}
|
||||
return { label: text(b, 200).replace(/\n/g, ' ') || b.getAttribute('aria-label') || b.dataset.act, act: b.dataset.act, args, disabled: !!b.disabled };
|
||||
});
|
||||
const screen = (where) => {
|
||||
const modal = !$('modal').hidden;
|
||||
if (modal && !where) {
|
||||
last = buttons($('modal'));
|
||||
return { where: 'modal', text: text($('modal')), buttons: last.map((b, i) => ({ n: i, ...b })) };
|
||||
}
|
||||
const p = where === 'left' ? $('leftBody') : $('panel');
|
||||
last = p ? buttons(p) : [];
|
||||
return { where: where === 'left' ? 'network list' : 'panel', modalOpen: modal, selected: UI.sel, tab: UI.tab, text: p ? text(p) : '', buttons: last.map((b, i) => ({ n: i, ...b })) };
|
||||
};
|
||||
|
||||
// ---------- starting and loading ----------
|
||||
const settle = () => { UI.started = true; UI.pitched = true; UI.speed = 0; if (UI.pendGame) ACT.pitchSkip(); closeModal(); compute(); renderAll(); takeToasts(); };
|
||||
const newGame = ({ city = 'fra', name, preset = 'oncall', seed }) => {
|
||||
const c = cityOf(city).id;
|
||||
if (!homeOk(c)) fail(`${cityName(c)} cannot be a home city.`);
|
||||
if (!['freeze', 'oncall', 'bgp', 'sandbox'].includes(preset)) fail('preset is one of freeze, oncall, bgp, sandbox');
|
||||
if (seed !== undefined && window.__reseed) window.__reseed(Math.max(1, Math.floor(+seed) || 1));
|
||||
if (UI.pendGame) UI.pendGame = null;
|
||||
UI.pitched = true;
|
||||
const nm = String(name || randomNetworkName()).slice(0, 24);
|
||||
beginGame(nm, c, preset === 'sandbox' ? { mode: 'sandbox', rules: { chaos: 'none' } } : { mode: 'normal', preset });
|
||||
settle();
|
||||
return status();
|
||||
};
|
||||
const loadSave = (txt) => {
|
||||
const r = parseSave(txt);
|
||||
if (r.err) fail(text(r.err));
|
||||
S = migrate(JSON.parse(JSON.stringify(r.s)));
|
||||
settle();
|
||||
return { savedBy: r.ver, ...status() };
|
||||
};
|
||||
const exportSave = (version) => JSON.stringify({ app: 'series-of-tubes', version: /^\d/.test(APP_VERSION) ? APP_VERSION : version, exported: new Date().toISOString(), S: packSave(S) });
|
||||
|
||||
// ---------- reading the network ----------
|
||||
const status = () => {
|
||||
const goal = GOALS.find((g) => S.done[g.id] === undefined);
|
||||
const t1 = isTier1();
|
||||
return {
|
||||
name: S.name, asn: S.asn, home: cityName(S.home), mode: S.mode, rules: S.rules && S.rules.preset,
|
||||
day: S.day, date: dateStr(S.day), cash: Math.round(S.cash), level: S.lvl || 0,
|
||||
tier: tierLabel(), whyNotTier1: t1 ? null : text(t1Why()),
|
||||
goal: goal ? { title: text(goal.t), what: text(goal.d) } : null,
|
||||
monthly: { revenue: Math.round(R.revMo), cost: Math.round(R.costMo), profit: Math.round(R.revMo - R.costMo),
|
||||
revenueBy: Object.fromEntries(Object.entries(R.rev || {}).map(([k, v]) => [k, Math.round(v)]).filter(([, v]) => v)),
|
||||
costBy: Object.fromEntries(Object.entries(R.cost || {}).map(([k, v]) => [k, Math.round(v)]).filter(([, v]) => v)) },
|
||||
traffic: { demandGbps: r1(R.demand), servedGbps: r1(R.served), reach: r1((R.reach || 0) * 100) + '%', peeringSessions: R.sessions },
|
||||
counts: { pops: Object.keys(S.pops).length, links: S.links.length, transitPorts: S.transit.length, exchangePorts: Object.keys(S.ixp).length,
|
||||
pnis: S.pni.length, cacheBoxes: S.caches.length, customers: S.biz.length, offers: S.offers.length },
|
||||
pops: Object.keys(S.pops).map(cityName),
|
||||
incidents: S.inc.map((i) => ({ id: i.id, type: i.type, what: incText(i), until: i.until !== undefined ? dateStr(i.until) : undefined, rushRepairCost: i.cost || undefined })),
|
||||
lost: !!S.lost, won: !!S.won,
|
||||
};
|
||||
};
|
||||
|
||||
const network = (q) => {
|
||||
const n = netOf(q), id = n.id, eg = R.netEg && R.netEg[id];
|
||||
return {
|
||||
id, name: n.name, asn: n.asn, type: TYPE_L[n.type], policy: n.pol,
|
||||
requirements: { minIxGbps: n.minIx, minPniGbps: n.minPni, paidFeePerMonth: n.paidFee, freeFromLevel: n.freeLv },
|
||||
trafficShare: r1(NSH[id] * 100) + '%', transitPerGbps: n.price ? r1(n.price * S.priceMul) : null,
|
||||
homeMarkets: n.cc ? [].concat(n.cc) : [], pops: n.pops.map(cityName),
|
||||
exchanges: n.ix === 'ALL' ? 'most exchanges where it has a PoP' : (n.ix || []).map((x) => ixName(x)),
|
||||
upstreams: (n.up || []).map((u) => NET[u] ? NET[u].name : u), customerCone: (DOWN[id] || []).length,
|
||||
neededForTier1: t1Need().some((x) => x.id === id), mergedInto: merged(id) ? (MERGERS.find((m) => m.id === id) || {}).into : undefined,
|
||||
about: text(n.blurb),
|
||||
you: {
|
||||
reachable: !!(R.reachable && R.reachable[id]), demandGbps: r1((R.demTo && R.demTo[id]) || 0),
|
||||
egressGbps: eg ? Object.fromEntries(Object.entries(eg).map(([k, v]) => [k, r1(v)])) : null,
|
||||
pnis: S.pni.filter((p) => p.net === id).map((p) => ({ id: p.id, city: cityName(p.city), port: pniPN(p), count: p.n || 1, ready: pniOn(p) })),
|
||||
exchangeSessions: Object.keys(S.ixp).filter((x) => ixSessions(x).has(id)).map(ixName),
|
||||
howToPeer: text(offTransitHint(id, S.home)),
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const city = (q) => {
|
||||
const C = cityOf(q), c = C.id, P = S.pops[c];
|
||||
const cab = CABLE_PAIRS.filter((p) => p.a === c || p.b === c).map((p) => ({ cable: CAB[p.cid] ? CAB[p.cid].name : p.cid, to: cityName(p.a === c ? p.b : p.a), km: p.km }));
|
||||
const here = NETS.filter((n) => n.pops.includes(c) && !n.tail).sort((a, b) => b.share - a.share);
|
||||
return {
|
||||
id: c, name: C.name, country: C.cc, region: C.reg, about: C.note ? text(C.note) : undefined, dataCenter: C.dc,
|
||||
canBeHome: homeOk(c),
|
||||
exchanges: ixIdsIn(c).map((x) => ({ id: x, name: ixName(x), members: ixMembers(x).length, yourPort: S.ixp[x] !== undefined })),
|
||||
transit: NETS.filter((n) => sellsAt(n, c)).map((n) => ({ id: n.id, name: n.name, type: TYPE_L[n.type], perGbps: r1(transitPerG(n, c, false) * S.priceMul) })).sort((a, b) => a.perGbps - b.perGbps),
|
||||
networksHere: here.length, biggestNetworksHere: here.slice(0, 15).map((n) => n.name), cables: cab,
|
||||
you: P ? { demandGbps: r1((R.cityDem || {})[c] || 0), servedGbps: r1((R.citySrv || {})[c] || 0), routers: P.routers, down: P.down > S.day ? dateStr(P.down) : false,
|
||||
broadband: !!P.bb, links: S.links.filter((l) => l.a === c || l.b === c).length } : null,
|
||||
};
|
||||
};
|
||||
|
||||
const find = (q, kind) => {
|
||||
const n = norm(q), hit = (...k) => k.some((v) => norm(v).includes(n)), out = {};
|
||||
if (!n) fail('Give a word to search for.');
|
||||
if (!kind || kind === 'city') out.cities = CITIES.filter((c) => hit(c.id, c.name)).slice(0, 20).map((c) => ({ id: c.id, name: c.name, country: c.cc }));
|
||||
if (!kind || kind === 'network') out.networks = NETS.filter((x) => hit(x.id, x.name, String(x.asn))).slice(0, 20).map((x) => ({ id: x.id, name: x.name, asn: x.asn, type: TYPE_L[x.type] }));
|
||||
if (!kind || kind === 'cable') out.cables = Object.values(CAB).filter((x) => hit(x.id, x.name)).slice(0, 20).map((x) => ({ id: x.id, name: x.name, lands: [...new Set(x.pairs.flatMap((p) => [p[0], p[1]]))].map(cityName) }));
|
||||
if (!kind || kind === 'exchange') out.exchanges = allIx().filter((x) => hit(x, ixName(x))).slice(0, 20).map((x) => ({ id: x, name: ixName(x), city: cityName(ixCity(x)) }));
|
||||
return out;
|
||||
};
|
||||
|
||||
const trace = (from, to) => {
|
||||
const src = cityOf(from).id;
|
||||
if (!S.pops[src]) fail(`You have no POP in ${cityName(src)}. Yours: ${Object.keys(S.pops).map(cityName).join(', ')}.`);
|
||||
let target = null;
|
||||
if (typeof to === 'string' && /^city:/i.test(to)) target = { city: cityOf(to.slice(5)).id };
|
||||
else { try { target = { net: netOf(to).id }; } catch (e) { target = { city: cityOf(to).id }; } }
|
||||
if (target.city && !S.pops[target.city]) fail(`A traceroute to a city goes to one of your POPs: ${Object.keys(S.pops).map(cityName).join(', ')}.`);
|
||||
const r = traceroute(src, target);
|
||||
return { text: r.text, why: text(r.why || ''), asPath: r.asPath || null };
|
||||
};
|
||||
|
||||
const peering = (q, where, via) => {
|
||||
const n = netOf(q), id = n.id, out = [];
|
||||
if (!via || via === 'pni') for (const c of (where ? [cityOf(where).id] : Object.keys(S.pops).filter((c) => n.pops.includes(c)))) {
|
||||
const r = peerOk(id, 'pni', c);
|
||||
out.push({ via: 'pni', city: cityName(c), ok: !!r.ok, why: r.why ? text(r.why) : undefined, feePerMonth: r.fee, free: r.free, minimumPort: PORT[pniMin(id)].n });
|
||||
}
|
||||
if (!via || via === 'ix') for (const x of Object.keys(S.ixp).filter((x) => ixMembers(x).includes(id) && (!where || ixCity(x) === cityOf(where).id))) {
|
||||
const r = peerOk(id, 'ix', x);
|
||||
out.push({ via: 'ix', exchange: ixName(x), ok: !!r.ok, why: r.why ? text(r.why) : undefined, session: ixSessions(x).has(id) });
|
||||
}
|
||||
return { network: n.name, policy: n.pol, hint: text(offTransitHint(id, where ? cityOf(where).id : S.home)),
|
||||
checks: out, note: out.length ? undefined : 'No POP or exchange port of yours is where this network is. Build one first: see network.' };
|
||||
};
|
||||
|
||||
const hotSpots = (limit = 10) => {
|
||||
const top = (a) => a.sort((x, y) => y.util - x.util).slice(0, limit);
|
||||
const pct = (u, c) => (c > 0 ? r1((u / c) * 100) : null);
|
||||
const links = S.links.map((l) => { const cap = capOf(l), u = (R.load || {})[l.id] || 0; return { id: l.id, between: cityName(l.a) + ' – ' + cityName(l.b), kind: l.kind, capacity: capName(l), usedGbps: r1(u), util: pct(u, cap), down: linkDown(l) }; });
|
||||
const transit = S.transit.map((t) => { const cap = lagCap(PORT[t.tier].g, t.n), u = (R.useT || {})[t.id] || 0, q = (R.p95 && R.p95[t.id]) || u;
|
||||
return { id: t.id, city: cityName(t.city), carrier: NET[t.net].name, port: lagName(t.tier, t.n), usedGbps: r1(u), util: pct(u, cap), billPerMonth: Math.round(transitMo(t, q)) }; });
|
||||
const pnis = S.pni.filter(pniOn).map((p) => { const cap = pniG(p) * (p.n || 1), u = (R.usePni || {})[p.id] || 0; return { id: p.id, network: NET[p.net].name, city: cityName(p.city), port: pniPN(p), usedGbps: r1(u), util: pct(u, cap) }; });
|
||||
const viaTransit = NETS.filter((n) => R.netEg && R.netEg[n.id] && R.netEg[n.id].t > 0.05).sort((a, b) => R.netEg[b.id].t - R.netEg[a.id].t).slice(0, limit)
|
||||
.map((n) => ({ id: n.id, network: n.name, overTransitGbps: r1(R.netEg[n.id].t), howToPeer: text(offTransitHint(n.id, S.home)) }));
|
||||
const bill = {};
|
||||
for (const t of transit) bill[t.carrier] = (bill[t.carrier] || 0) + t.billPerMonth;
|
||||
return { links: top(links), transitPorts: top(transit), pnis: top(pnis), transitBillByCarrier: bill, biggestTrafficStillOnTransit: viaTransit };
|
||||
};
|
||||
|
||||
// ---------- doing things ----------
|
||||
// Actions the server never runs: files, storage slots, settings and the title screen are not the game's, and time
|
||||
// only moves through advance.
|
||||
const DENY = new Set(['animSet', 'cont', 'exportSave', 'importGo', 'importPick', 'install', 'langSet', 'menu', 'mute', 'newgame', 'phonePlay', 'phoneSpeed',
|
||||
'prefSet', 'pzShare', 'resetAsk', 'settings', 'settingsClose', 'share', 'shareDl', 'shareGo', 'slotBack', 'slotDel', 'slotDelGo', 'slotExport', 'slotMenu',
|
||||
'slotRetry', 'slotSpace', 'slotSwitch', 'slotTake', 'soundSet', 'speed', 'start', 'toTitle', 'traceCopy', 'updateLater', 'updateNow', 'vpSet', 'wsShare']);
|
||||
const run = (name, args) => {
|
||||
if (DENY.has(name)) fail(`${name} is not available here${name === 'speed' ? ': use advance to move time' : name === 'start' || name === 'newgame' ? ': use new_game' : ''}.`);
|
||||
const fn = ACT[name];
|
||||
if (typeof fn !== 'function') fail(`There is no action "${name}". See the actions list.`);
|
||||
takeToasts();
|
||||
const cash = S.cash;
|
||||
fn(args && typeof args === 'object' ? args : {});
|
||||
return { toasts: takeToasts(), cashChange: Math.round(S.cash - cash), screen: screen() };
|
||||
};
|
||||
const click = (n) => {
|
||||
const b = last[n];
|
||||
if (!b) fail(`No button ${n} on the last screen. Call screen first.`);
|
||||
if (b.disabled) fail(`"${b.label}" is greyed out.`);
|
||||
return { clicked: b.label, ...run(b.act, b.args) };
|
||||
};
|
||||
const panel = ({ city: c, link, network: q, tab }) => {
|
||||
if (c) UI.sel = { type: 'city', id: cityOf(c).id };
|
||||
else if (link) { if (!S.links.some((l) => l.id === link)) fail(`No link ${link}. See status or hot_spots for link ids.`); UI.sel = { type: 'link', id: link }; }
|
||||
else if (q) ACT.netFocus({ id: netOf(q).id });
|
||||
if (tab) UI.tab = tab;
|
||||
renderAll();
|
||||
return screen(q ? 'left' : 'panel');
|
||||
};
|
||||
const openLink = (a, b) => {
|
||||
const x = cityOf(a).id, y = cityOf(b).id;
|
||||
if (!S.pops[x]) fail(`A link starts at one of your POPs: ${Object.keys(S.pops).map(cityName).join(', ')}.`);
|
||||
takeToasts();
|
||||
openLinkModal(x, y);
|
||||
return { toasts: takeToasts(), screen: screen() };
|
||||
};
|
||||
const actions = () => Object.keys(ACT).filter((k) => !DENY.has(k)).sort();
|
||||
|
||||
// ---------- time ----------
|
||||
const advance = (days = 1) => {
|
||||
days = Math.max(1, Math.min(3650, Math.floor(+days) || 1));
|
||||
if (!$('modal').hidden) fail('A window is open. Answer it first (screen, click), the game does not run days behind it.');
|
||||
const start = S.day, cash = S.cash, inc0 = new Set(S.inc.map((i) => i.id)), times = [];
|
||||
takeToasts();
|
||||
let ran = 0, stop = null;
|
||||
while (ran < days) {
|
||||
if (S.lost) { stop = 'bankrupt'; break; }
|
||||
const t = performance.now();
|
||||
dayTick();
|
||||
times.push({ day: S.day, ms: r1(performance.now() - t) });
|
||||
ran++;
|
||||
if (!$('modal').hidden) { stop = 'a window opened'; break; }
|
||||
}
|
||||
renderAll();
|
||||
// The log keeps what mattered; toasts that only repeat a log line are left out.
|
||||
const entries = (S.log || []).filter((e) => e.d > start).slice(-60), logged = entries.map((e) => norm(text(e.t, 400)));
|
||||
const log = entries.map((e) => `${dateStr(e.d)}: ${text(e.t, 400)}`);
|
||||
const total = times.reduce((a, x) => a + x.ms, 0);
|
||||
return {
|
||||
from: dateStr(start), to: dateStr(S.day), daysRun: ran, stoppedBecause: stop, cash: Math.round(S.cash), cashChange: Math.round(S.cash - cash),
|
||||
newIncidents: S.inc.filter((i) => !inc0.has(i.id)).map(incText),
|
||||
log, toasts: [...new Set(takeToasts())].filter((t) => { const f = norm(t.replace(/^\w+: /, '').split('\n')[0]); return !logged.some((l) => l.startsWith(f)); }).slice(-40),
|
||||
timing: { totalMs: r1(total), perDayMs: r1(total / (ran || 1)), slowestDays: times.slice().sort((a, b) => b.ms - a.ms).slice(0, 5).map((x) => ({ date: dateStr(x.day), ms: x.ms })) },
|
||||
screen: stop === 'a window opened' ? screen() : undefined,
|
||||
};
|
||||
};
|
||||
|
||||
window.__mcp = { newGame, loadSave, exportSave, status, network, city, find, trace, peering, hotSpots, run, click, panel, openLink, actions, advance, screen };
|
||||
})();
|
||||
Loading…
Add table
Add a link
Reference in a new issue