diff --git a/.claude/skills/edit-the-game/SKILL.md b/.claude/skills/edit-the-game/SKILL.md index 7dc75dd..aca2564 100644 --- a/.claude/skills/edit-the-game/SKILL.md +++ b/.claude/skills/edit-the-game/SKILL.md @@ -14,6 +14,7 @@ load, so splitting code across files costs nothing at runtime. Why it works this src/index.html the shell: , static markup, ``, `` src/styles/NN-*.css CSS, in order (phones last) src/game/NN-area/NN-*.js the game script, in order (see the map in docs/ARCHITECTURE.md) +src/agent/NN-*.js the agent facade the MCP server drives: in the development page only site/ static files copied as they are (dictionaries, icons, service worker) ``` @@ -34,7 +35,8 @@ npm test -- tests/peering.test.js # one suite ``` A browser error points at a line of the assembled page; the dev server prints the `src/` file and line -next to it. `npm run page -- -o /tmp/page.html` writes the assembled page if you want to look at it. +next to it. `npm run page -- -o /tmp/page.html` writes the page players get if you want to look at it; +`npm run page -- --source --dev -o /tmp/page.html` the development page `npm run dev` serves. ## Where new code goes @@ -48,9 +50,16 @@ next to it. `npm run page -- -o /tmp/page.html` writes the assembled page if you - **Actions:** add `name:(args)=>{…},` to the matching `src/game/90-actions/*.js`. Only `10-interface.js` declares `const ACT={`; the others are `Object.assign(ACT,{ … });`. A new area can get a new `NN-area.js` file of that second form. The MCP server types every action: a new one also gets - an entry in `scripts/lib/mcp-commands.js` (a game command with its argument domains, a view, a draft - or a session action) or in the server's `DENY` list in `scripts/lib/mcp-page.js`; - `tests/mcp-commands.test.js` fails until it has one. + an entry in `src/agent/20-commands.js` (a game command with its argument domains, a view, a draft, + a session action, or `API_DENY`); `tests/mcp-commands.test.js` fails until it has one. +- **Agent code** (`src/agent/`, the facade the MCP server plays through) is assembled into the + development page only (``): players never download it. Its top-level names + start with `api`/`API_`, and **nothing in `src/game/` may name them**: that would work in `npm run dev` + and break for players (`tests/build.test.js` checks). Tests load the players' page; a test of the + facade asks for `load({ agent: true })`. Where agent code must change what the game does (agent mode + locks the clock, adds a Settings section and a HUD badge), the game calls `HOOKS.x?.()` and reads + `UI.clockLocked` (`50-state.js`), and agent code fills them in: add a hook there rather than an `if` for + the agent in a game file. See docs/adr/0004-dev-only-code.md. - **Panels and modals:** `93-ui/` (HUD, side panels), `94-dashboard/` (NOC dashboard, bank), `95-modals/`. - **Styles:** the matching `src/styles/*.css`; phone rules go in `60-phone.css`. - **Data tables** (cities, cables, networks): one entry per line, and keep id-keyed objects such as diff --git a/.claude/skills/github-pages/SKILL.md b/.claude/skills/github-pages/SKILL.md index 205db5b..c0ed652 100644 --- a/.claude/skills/github-pages/SKILL.md +++ b/.claude/skills/github-pages/SKILL.md @@ -31,6 +31,10 @@ one, redesign the feature. - **Limits:** about 1 GB for the whole site, 100 MB per file. - **Paths:** the site lives at the domain root (`site/CNAME`), so `/` paths are fine; unknown paths get `404.html`. +- **Local tools are not hosting.** `npm run dev` and the MCP server (`npm run mcp`, also over `--http`) + run on a developer's own machine against a checkout; nothing they serve is deployed, and the game + never depends on them. Their code stays out of `_site/` (`src/agent/` is development-only, see + `docs/adr/0004-dev-only-code.md`). ## How it deploys diff --git a/.claude/skills/write-tests/SKILL.md b/.claude/skills/write-tests/SKILL.md index efe406c..42937b9 100644 --- a/.claude/skills/write-tests/SKILL.md +++ b/.claude/skills/write-tests/SKILL.md @@ -7,7 +7,8 @@ description: Write deterministic jsdom tests for Series of Tubes features and fi Tests use `node:test` and `tests/harness.js`, which assembles the game page from `src/` (once per test file) and loads it in jsdom with the animation loop off, a seeded `Math.random` and a recording fake canvas. -Code runs inside the page through `ev()`. +Code runs inside the page through `ev()`. `load()` is the page players get; tests of the agent facade +(`src/agent/`, `window.TUBES`) ask for the development page with `load({ agent: true })`. ## Pattern diff --git a/CHANGELOG.md b/CHANGELOG.md index cf3c82a..fc05708 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ All notable changes to this project are documented here. The project follows - DE-Kicks ports stop getting dearer once they cost four times the list price. Before, the yearly price harmonisation kept compounding, so a long game ended up paying $100k a month for one port at Frankfurt or Mumbai. - An exchange port, a transit port or a PNI can now be stepped down one size from its panel, so shrinking a port no longer means leaving and rejoining (a PNI cannot while an augment is on order). - The traceroute can follow the metrics, the lowest latency or the quietest links, like a customer circuit. +- If you run the game on your own computer, an AI agent can now play it in your browser while you watch. Turn the Agent API on in Settings (the section only appears in a copy of the game you run with npm run dev, never on seriesoftub.es) and point an AI client at the game's MCP server: every move happens live on your screen, and docs/MCP.md in the repository explains the setup. You choose the clock: a pace from one simulated day every 30 seconds to 5 minutes, which nobody can pause and which waits while no agent is connected, or the agent moves time itself. Your game, your settings and the windows you open stay yours. - Every capital in Africa is on the map, which puts every capital of the world in the game: 33 new cities from Porto-Novo, Bamako and Niamey to Khartoum, Juba, Mogadishu, Brazzaville, Tripoli, Rabat and Pretoria. Each country brings its real telcos, Nigeria gets its wholesale backbone up to Abuja, and the island capitals of the Comoros, São Tomé and Equatorial Guinea sit on their real cables. - Every capital in South, East and Southeast Asia and the Pacific is on the map: Thimphu, Kathmandu, Bandar Seri Begawan, Phnom Penh, Vientiane, Ulaanbaatar, Naypyidaw, Pyongyang, Dili, Hanoi and Wellington, with the island capitals Tarawa, Palikir, Yaren, Funafuti and Port Vila. Each country brings its real telcos, North Korea reaches the world only through China and Russia, and the islands hang on their real cables. - Every capital in the Middle East, the Caucasus and Central Asia is on the map, from Yerevan and Baku to Kabul, Tehran, Baghdad, Jerusalem, Amman, Kuwait City, Beirut, Damascus, Sanaa and Manama, with Ankara and Islamabad. Each country brings its real telcos, and Bahrain is an island on the Gulf's cables. diff --git a/CLAUDE.md b/CLAUDE.md index e383fa1..439c4a1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,7 +5,8 @@ https://seriesoftub.es, hosted on GitHub Pages. The game is one static page with Its source is many small files in `src/` (`src/styles/*.css`, `src/game/**/*.js`, the shell `src/index.html`); the build pastes them together, in path order, into a single `index.html`, the same one-file page players have always loaded. Static files (dictionaries, icons, service worker) -live in `site/`. +live in `site/`. `src/agent/` (the facade the MCP server plays through) goes into the development page only, +never into the page players get, and nothing in `src/game/` may use it (`docs/adr/0004-dev-only-code.md`). Read these before larger changes: @@ -20,7 +21,7 @@ Read these before larger changes: ```bash npm ci # once: installs jsdom for the tests -npm run dev # play while developing: http://localhost:8080, reloads on save +npm run dev # play while developing: http://localhost:8080, reloads on save (--host to share) npm test # node:test + jsdom, every tests/*.test.js, must stay green node scripts/i18n-check.js # must report "0 missing, 0 unused, 0 broken" (and sorted dictionaries) node scripts/i18n-add.js FILE.json # add/change/remove translations (see `add-strings`) @@ -28,7 +29,7 @@ npm run build # builds _site/ for GitHub Pages (assembles src/, s npm run serve # build and serve the production site locally npm run perf -- --base-ref origin/main # big-network benchmark vs main (see `performance`) npm run perf -- --base-ref origin/main --browser # the same, also in real Chromium (desktop and phone) -npm run mcp # the game as a local MCP server for AI clients (docs/MCP.md) +npm run mcp # the game as a local MCP server for AI clients, stdio or --http (docs/MCP.md) ``` ## Hard rules diff --git a/README.md b/README.md index cc6e3fb..ec085fa 100644 --- a/README.md +++ b/README.md @@ -52,11 +52,11 @@ and remembers the one you pick under Settings or on the title screen. ```sh npm ci -npm run dev # development server: assembles src/ on every request, reloads on save +npm run dev # development server on localhost (--host to share): assembles src/ on every request, reloads on save npm test # headless tests: boot, geography, a year of play, every incident, every panel npm run build # writes the site for GitHub Pages to _site/, with version and date stamped in npm run i18n:check # lists text missing from (or stale in) the translations -npm run mcp # the game as an MCP server, so an AI client can play and debug it (docs/MCP.md) +npm run mcp # the game as an MCP server, so an AI client can play and debug it, headless or in your tab (docs/MCP.md) ``` ## Community diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9729449..75127a5 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -11,8 +11,10 @@ src/ the game page, in pieces i18n/en.js the English for every label → inlined at the top of the page's `; return html.replace('', `${hint}${RELOAD}`); } -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' }); @@ -48,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']) { diff --git a/scripts/i18n-check.js b/scripts/i18n-check.js index 8d8e657..fd21bb2 100644 --- a/scripts/i18n-check.js +++ b/scripts/i18n-check.js @@ -16,7 +16,8 @@ const D = require('./lib/dict'); const { CALL } = require('./legacy/labels'); const SITE = path.join(__dirname, '..', 'site'); -const page = () => require('./lib/page').assemble().html; +// The development page: it has every label, the agent's (src/agent/) too. +const page = () => require('./lib/page').assemble({ dev: true }).html; const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/; // The labels the game uses, with problems in how they are used. diff --git a/scripts/lib/fuzz-page.js b/scripts/lib/fuzz-page.js index 4586d55..d2a6f35 100644 --- a/scripts/lib/fuzz-page.js +++ b/scripts/lib/fuzz-page.js @@ -1,4 +1,4 @@ -// Runs inside a game page (scripts/route-fuzz.js loads two: main's and this checkout's), next to scripts/lib/mcp-page.js. +// Runs inside a game page (scripts/route-fuzz.js loads two: main's and this checkout's). // The driver picks every move with its own seeded random numbers and sends the same calls to both pages, so the pages // stay in lockstep; this file only offers what a player could do now (buttons on screen, POPs, cities) and digests what // routing gave, as strings the driver compares. diff --git a/scripts/lib/mcp-browser.js b/scripts/lib/mcp-browser.js new file mode 100644 index 0000000..f70e9aa --- /dev/null +++ b/scripts/lib/mcp-browser.js @@ -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 }; diff --git a/scripts/lib/mcp-game.js b/scripts/lib/mcp-game.js index fbf0983..0de39b8 100644 --- a/scripts/lib/mcp-game.js +++ b/scripts/lib/mcp-game.js @@ -1,12 +1,16 @@ -// 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-commands.js (the typed command tables) and -// 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. +// 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 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'); -const PAGE_JS = ['mcp-commands.js', 'mcp-page.js'].map((f) => fs.readFileSync(path.join(__dirname, f), 'utf8')); +const HEADLESS_JS = fs.readFileSync(path.join(__dirname, 'mcp-headless.js'), 'utf8'); const ACT_DIR = path.join(__dirname, '..', '..', 'src', 'game', '90-actions'); // The arguments of the actions the command tables do not type (the drafts), read from their source @@ -23,189 +27,257 @@ 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 = {}, ctx) { + const w = g.dom.window; + 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 +// asks. Over HTTP the client may be another machine: nowhere (null), or only under one directory, symlinks included. +function savePath(s, p, write) { + if (s.saveDir === undefined) return path.resolve(p); + if (s.saveDir === null) throw new Error('This server takes saves as JSON only: give json instead of path (the server can allow a directory with --save-dir).'); + const root = s.saveDir, full = path.resolve(root, String(p)); + let real; + try { real = write ? path.join(fs.realpathSync(path.dirname(full)), path.basename(full)) : fs.realpathSync(full); } catch (e) { throw new Error(`${p}: no such file or directory under the save directory`); } + if (!real.startsWith(root + path.sep)) throw new Error(`${p} is outside the save directory.`); + if (write && fs.existsSync(real) && fs.lstatSync(real).isSymbolicLink()) throw new Error(`${p} is a symbolic link: write to a plain file.`); + return real; +} + +// 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 }); - for (const js of PAGE_JS) g.ev(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' }); + 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 = { + mode: 'headless', clock, paceMs: clock === 'realtime' ? paceMs : 0, saveDir: opts.saveDir, get game() { return game || (game = boot()); }, - call(fn, ...args) { return session.game.call(fn, ...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(__mcp.loadSave(window.__mcpSave))')); }, + 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.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.'), asn: num('Your own AS number, as the title screen takes it. Default: a free one.'), chaos: str('Sandbox only: how often things break. Default none.', { enum: ['none', 'calm', 'normal', 'spicy'] }) }), - run: (s, a) => s.call('newGame', a), + 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) => { 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; + const txt = a.path ? fs.readFileSync(savePath(s, a.path, false), 'utf8') : a.json; return s.loadSave(txt); }, }, { - 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) => { - 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) }; } + const txt = s.headless('exportSave', require('../../package.json').version); + if (a.path) { const f = savePath(s, a.path, true); fs.writeFileSync(f, txt); return { wrote: f, 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', + 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: (s) => s.call('status'), + 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: (s, a) => s.call('advance', a.days), + 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: (s, a) => s.call('network', a.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: (s, a) => s.call('city', a.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: (s, a) => s.call('find', a.query, a.kind), + 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:.') }, ['from', 'to']), - run: (s, a) => s.call('trace', a.from, a.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: (s, a) => s.call('peering', a.network, a.city, a.via), + 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: (s, a) => s.call('hotSpots', a.limit || 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: (s, a) => s.call('schema', a.section), + 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: (s, a) => s.call('catalog', a.name), + 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.): 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.): 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: (s, a) => s.call('state', a.path), + 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: (s, a) => s.call('results', a.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: (s) => s.call('ui'), + 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=. 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: (s, a) => { - const name = a.action || a.command; - if (!name) throw new Error('Give action, e.g. {"action":"buildPop","args":{"city":"ams"}}.'); - return s.call('run', name, a.args || {}, { dryRun: !!a.dryRun }); - }, + 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: (s, a) => s.call('screen', a.where, a.offset), + 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: (s, a) => s.call('panel', a), + 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: (s, a) => s.call('click', a.button, a.value), + 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: (s, a) => s.call('openLink', a.from, a.to), + run: page('open_link'), }, ]; -module.exports = { createSession, TOOLS, actArgs }; +const toolsFor = (mode) => TOOLS.filter((t) => t.modes.includes(mode)); + +module.exports = { createSession, TOOLS, toolsFor, actArgs, pageCall, savePath, CLOCKS, DEFAULT_PACE_MS }; diff --git a/scripts/lib/mcp-headless.js b/scripts/lib/mcp-headless.js new file mode 100644 index 0000000..8a77698 --- /dev/null +++ b/scripts/lib/mcp-headless.js @@ -0,0 +1,36 @@ +// Runs inside the MCP server's own game page (scripts/lib/mcp-game.js), in the game's global scope, after the page has +// loaded: the half of a session only that page has. It starts, loads and exports games, which in a player's browser +// are the player's alone, so it is not part of any page. Everything else a tool does goes through the page's own +// facade (window.TUBES, src/agent/). +(() => { + // Out of the way of the game: no sheet of a previous game, no title screen or pitch, the clock left to the server. + const settle = () => { UI.started = true; UI.pitched = true; UI.speed = 0; if (UI.pendGame) ACT.pitchSkip(); closeModal(); API_SHEET = null; compute(); renderAll(); }; + const newGame = ({ city = 'fra', name, preset = 'oncall', seed, asn, chaos } = {}) => { + const c = apiCityOf(city).id; + if (!homeOk(c)) apiFail(`${apiCityName(c)} cannot be a home city.`); + if (!['soft', 'freeze', 'oncall', 'bgp', 'sandbox'].includes(preset)) apiFail('preset is one of soft, freeze, oncall, bgp, sandbox'); + if (asn !== undefined && !asnOk(+asn)) apiFail(`AS${asn} cannot be yours: it is reserved, private or another network's. Leave asn out for a free one.`); + if (chaos !== undefined && preset !== 'sandbox') apiFail('chaos is the sandbox\'s dial: give preset "sandbox" with it.'); + if (chaos !== undefined && !own(CHAOS, chaos)) apiFail(`chaos is one of ${Object.keys(CHAOS).join(', ')}.`); + 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), was = UI.asnTxt; + // beginGame takes the ASN typed on the title screen. + UI.asnTxt = asn !== undefined ? String(+asn) : ''; + try { beginGame(nm, c, preset === 'sandbox' ? { mode: 'sandbox', rules: { chaos: chaos || 'none' } } : { mode: 'normal', preset }); } finally { UI.asnTxt = was; } + settle(); + return apiStatus(); + }; + const loadSave = (txt) => { + const r = parseSave(txt); + if (r.err) apiFail(apiText(r.err)); + S = migrate(JSON.parse(JSON.stringify(r.s))); + settle(); + 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) }); + // 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 }; +})(); diff --git a/scripts/lib/mcp-page.js b/scripts/lib/mcp-page.js deleted file mode 100644 index 2eb6717..0000000 --- a/scripts/lib/mcp-page.js +++ /dev/null @@ -1,487 +0,0 @@ -// 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 run(), click(), -// panel(), advance() and the game loaders, which go through the same ACT actions and dayTick() the page uses. -// The command tables run() checks arguments against come from scripts/lib/mcp-commands.js, evaluated first. -(() => { - const { API_DOMAINS, API_CMD, API_VIEW, API_BOUND, API_SESSION, API_STATE_DOC, API_RESULTS_DOC, API_TABLES, API_MADE, - API_UI_HIDDEN, apiDomCheck, apiDomValues, apiPath, apiJson } = window.__mcpCmds; - const BLOCK = /^(DIV|P|H1|H2|H3|H4|SECTION|LI|UL|OL|TR|TABLE|NAV|HEADER|FOOTER|BUTTON|LABEL|DETAILS|SUMMARY)$/; - const MAX_TEXT = 8000; - // Text as a player would read it: one line per block, no runs of spaces. jsdom has no innerText. - const fullText = (x) => { - 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; } - // A dropdown reads as its choice: hundreds of options would crowd out the rest (the catalog lists them). - if (n.tagName === 'SELECT') { const o = n.options[n.selectedIndex]; out.push(' ', o ? o.text : '', ' '); return; } - // Blocks get their own line; inline tags a space, so "Revenue$2k" 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); - return out.join('').split('\n').map((l) => l.replace(/\s+/g, ' ').replace(/ ([.,;:!?)])/g, '$1').replace(/\( /g, '(').trim()).filter(Boolean).join('\n'); - }; - const text = (x, max = MAX_TEXT) => { const s = fullText(x); 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(); - const parse = (s) => { try { return JSON.parse(s || '{}'); } catch (e) { return {}; } }; - - // ---------- 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 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: text(String(h), 600) }); return t0.apply(this, arguments); }; - const takeToasts = () => { const t = toasts; toasts = []; return t; }; - const toastLines = (t) => t.map((x) => (x.kind ? x.kind + ': ' : '') + x.text); - - // ---------- what is on screen ---------- - // The surfaces a player can read, by the name screen() takes. The left drawer has tabs (goals, deals, noc, nets). - const ROOT = { modal: 'modal', bank: 'bankBox', dash: 'dash', panel: 'panel', left: 'leftBody', puzzle: 'pzBox' }; - const shown = (w) => { const el = $(ROOT[w]); return !!el && !el.hidden; }; - const modalOpen = () => shown('modal'); - let last = []; - const controls = (root) => { - const out = []; - for (const b of root.querySelectorAll('[data-act],select[data-chg]')) { - if (b.dataset.act) out.push({ label: text(b, 200).replace(/\n/g, ' ') || b.getAttribute('aria-label') || b.dataset.act, act: b.dataset.act, args: parse(b.dataset.args), disabled: !!b.disabled }); - // A list the game acts on when its value changes (the change handler in src/game/96-map/95-clicks.js): click - // it with a value. - else out.push({ label: b.getAttribute('aria-label') || (b.closest('label') && text(b.closest('label'), 120).split('\n')[0]) || b.dataset.chg, - select: b.dataset.chg, value: b.value, options: [...b.options].map((o) => ({ value: o.value, label: o.textContent.trim() })), disabled: !!b.disabled }); - } - return out; - }; - const screen = (where, offset = 0) => { - if (where === null) where = undefined; - if (where !== undefined && !ROOT[where]) fail(`where is one of ${Object.keys(ROOT).join(', ')}.`); - const open = Object.keys(ROOT).filter((w) => w !== 'left' && shown(w)); - const w = where || ['modal', 'bank', 'dash', 'panel', 'puzzle'].find(shown) || 'panel'; - const root = $(ROOT[w]); - last = root ? controls(root) : []; - const all = root ? fullText(root) : '', from = Math.max(0, Math.floor(+offset) || 0), more = all.length - from - MAX_TEXT; - const out = { where: w, open, selected: UI.sel, tab: UI.tab }; - if (w === 'left') out.leftTab = UI.left || 'goals'; - if (w === 'modal') { const d = decision(); out.question = !!d; } - out.text = all.slice(from, from + MAX_TEXT); - if (from) out.textFrom = from; - if (more > 0) out.textMore = `${more} more characters: call screen with where "${w}" and offset ${from + MAX_TEXT}`; - out.buttons = last.map((b, i) => ({ n: i, ...b })); - return out; - }; - - // ---------- windows: the agent's own sheets, and the game's questions ---------- - // A window the agent opened itself (a view, a draft, the link window, a sheet it clicked inside) is something to read - // and click through. A window the game opened in answer to a game command, or during a day, is a question when one - // of its buttons runs a game command other than closeModal (a De-Kicks quote, a retention offer); then other game - // commands wait until it is answered or closed, as clicks outside an open window do in the game. - let sheet = null; - const card = () => $('modalCard').firstChild; - const markSheet = () => { sheet = modalOpen() ? card() : null; }; - const isSheet = () => modalOpen() && !!sheet && card() === sheet; - const decision = () => { - if (!modalOpen() || isSheet()) return null; - const b = [...$('modal').querySelectorAll('[data-act]')].filter((x) => x.dataset.act !== 'closeModal' && API_CMD[x.dataset.act]); - if (!b.length) return null; - return { text: text($('modal'), 1500), options: b.map((x) => ({ command: x.dataset.act, args: parse(x.dataset.args), label: text(x, 120).replace(/\n/g, ' ') })) }; - }; - - // ---------- starting and loading ---------- - const settle = () => { UI.started = true; UI.pitched = true; UI.speed = 0; if (UI.pendGame) ACT.pitchSkip(); closeModal(); sheet = null; compute(); renderAll(); takeToasts(); }; - const newGame = ({ city = 'fra', name, preset = 'oncall', seed, asn, chaos }) => { - const c = cityOf(city).id; - if (!homeOk(c)) fail(`${cityName(c)} cannot be a home city.`); - if (!['soft', 'freeze', 'oncall', 'bgp', 'sandbox'].includes(preset)) fail('preset is one of soft, freeze, oncall, bgp, sandbox'); - if (asn !== undefined && !asnOk(+asn)) fail(`AS${asn} cannot be yours: it is reserved, private or another network's. Leave asn out for a free one.`); - if (chaos !== undefined && preset !== 'sandbox') fail('chaos is the sandbox\'s dial: give preset "sandbox" with it.'); - if (chaos !== undefined && !own(CHAOS, chaos)) fail(`chaos is one of ${Object.keys(CHAOS).join(', ')}.`); - 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), was = UI.asnTxt; - // beginGame takes the ASN typed on the title screen. - UI.asnTxt = asn !== undefined ? String(+asn) : ''; - try { beginGame(nm, c, preset === 'sandbox' ? { mode: 'sandbox', rules: { chaos: chaos || 'none' } } : { mode: 'normal', preset }); } finally { UI.asnTxt = was; } - 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 }; - }; - - // ---------- the contract: commands, arguments, reference tables, raw state ---------- - // 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 WHY = { - time: 'use advance to move time', start: 'use new_game', files: 'use load_save or export_save', - slots: 'saved networks in browser storage are not part of this game', prefs: 'device and player settings are not part of the game', - browser: 'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)', - }; - const DENY_WHY = { - speed: 'time', phonePlay: 'time', phoneSpeed: 'time', - start: 'start', newgame: 'start', cont: 'start', toTitle: 'start', resetAsk: 'start', - exportSave: 'files', importGo: 'files', importPick: 'files', slotExport: 'files', - slotBack: 'slots', slotDel: 'slots', slotDelGo: 'slots', slotMenu: 'slots', slotRetry: 'slots', slotSpace: 'slots', slotSwitch: 'slots', slotTake: 'slots', - animSet: 'prefs', langSet: 'prefs', menu: 'prefs', mute: 'prefs', prefSet: 'prefs', settings: 'prefs', settingsClose: 'prefs', soundSet: 'prefs', vpSet: 'prefs', - install: 'browser', share: 'browser', shareDl: 'browser', shareGo: 'browser', traceCopy: 'browser', updateLater: 'browser', updateNow: 'browser', wsShare: 'browser', pzShare: 'browser', - }; - const denied = (name) => (Object.prototype.hasOwnProperty.call(DENY_WHY, name) ? WHY[DENY_WHY[name]] : null); - const kindOf = (name) => (API_CMD[name] ? 'game' : API_VIEW[name] ? 'view' : API_BOUND[name] ? 'draft' : API_SESSION[name] ? 'session' : null); - const specOf = (name) => API_CMD[name] || API_VIEW[name] || API_SESSION[name] || null; - const classes = () => ({ game: Object.keys(API_CMD), view: Object.keys(API_VIEW), draft: Object.keys(API_BOUND), session: Object.keys(API_SESSION), denied: Object.keys(DENY_WHY) }); - - // One argument as the schema states it. Table domains name their catalog table rather than list every id. - const argDoc = ([name, dom, req]) => { - const a = { name, required: req !== false }, d = API_DOMAINS[dom]; - if (!d) { a.type = dom; return a; } - a.domain = dom; - if (d.table) a.from = d.table; - else { const v = apiDomValues(dom); if (Array.isArray(v)) a.values = v; else if (v && v.from !== undefined) a.range = v; } - return a; - }; - const schema = (section) => { - const cmd = (s) => ({ args: (s.args || []).map(argDoc), doc: s.doc }); - const doc = { - clock: 'Time moves only with advance: one dayTick() per simulated day, as the game loop runs it. Nothing runs between calls.', - commands: Object.fromEntries(Object.entries(API_CMD).map(([n, s]) => [n, { ...cmd(s), dryRun: !!s.quote, - ...(s.decides ? { decides: true } : {}), ...(s.confirm ? { confirm: s.confirm } : {}), ...(s.open ? { opens: s.open } : {}), ...(s.reads ? { report: true } : {}) }])), - view: Object.fromEntries(Object.entries(API_VIEW).map(([n, s]) => [n, cmd(s)])), - session: Object.fromEntries(Object.entries(API_SESSION).map(([n, s]) => [n, cmd(s)])), - drafts: API_BOUND, - denied: Object.fromEntries(Object.keys(DENY_WHY).sort().map((n) => [n, denied(n)])), - domains: Object.fromEntries(Object.entries(API_DOMAINS).map(([n, d]) => { const v = apiDomValues(n); - return [n, { kind: d.kind === 'fn' ? 'custom' : d.kind, ...(d.table ? { from: d.table } : {}), - ...(!d.table && Array.isArray(v) ? { values: v } : v && v.from !== undefined ? { range: v } : v && v.of ? { of: v.of } : {}) }]; })), - state: API_STATE_DOC, results: API_RESULTS_DOC, - }; - if (section === undefined || section === null || section === '') return doc; - if (!(section in doc)) fail(`No section "${section}". Sections: ${Object.keys(doc).join(', ')}.`); - return doc[section]; - }; - const catalog = (name) => { - if (name === undefined || name === null || name === '') { - return { tables: [...Object.keys(API_TABLES), ...Object.keys(API_MADE)].sort().map((k) => { const t = k in API_MADE ? API_MADE[k]() : API_TABLES[k]; - return { name: k, n: Array.isArray(t) ? t.length : t && typeof t === 'object' ? Object.keys(t).length : 1 }; }) }; - } - if (name in API_MADE) return apiJson(API_MADE[name]()); - if (name in API_TABLES) return apiJson(API_TABLES[name]); - fail(`No table "${name}". Call catalog without a name for the list.`); - }; - const state = (path) => { if (!S) return null; const v = apiJson(apiPath(S, path)); return v === undefined ? null : v; }; - const results = (path) => { const v = apiJson(apiPath(R, path)); return v === undefined ? null : v; }; - const ui = () => { const o = {}; for (const k of Object.keys(UI)) if (!API_UI_HIDDEN[k]) o[k] = apiJson(UI[k]); return o; }; - const actions = () => { - const sig = (s) => (s.args || []).map((a) => a[0] + (a[2] === false ? '?' : '')).join(','); - const typed = {}; - for (const t of [API_CMD, API_VIEW, API_SESSION]) for (const [n, s] of Object.entries(t)) typed[n] = sig(s); - return { typed, drafts: Object.keys(API_BOUND) }; - }; - - // ---------- doing things ---------- - // Arguments: shape and domain only. Anything beyond that is the game's to answer. - const validate = (spec, args) => { - const problems = [], out = {}; - for (const [name, dom, req] of spec.args || []) { - const v = args[name]; - if (v === undefined) { if (req !== false) problems.push(`${name} is required`); continue; } - if (apiDomCheck(dom, v).ok) { out[name] = v; continue; } - const vs = apiDomValues(dom), d = API_DOMAINS[dom]; - problems.push(`${name}: ${JSON.stringify(v)} is not a ${dom}${d && d.table && d.kind === 'id' ? ` (see catalog ${d.table} or find)` : Array.isArray(vs) ? ` (one of ${vs.slice(0, 12).join(', ')}${vs.length > 12 ? '…' : ''})` : vs && typeof vs === 'object' && vs.from !== undefined ? ` (${vs.from}..${vs.to})` : ''}`); - } - for (const k of Object.keys(args)) if (!(spec.args || []).some((a) => a[0] === k)) problems.push(`${k} is not an argument of this action`); - return { ok: !problems.length, problems, args: out }; - }; - // The fingerprint tells "did nothing" from "did something quietly": cash, day, the entity counts, the small - // settings maps, and the paths a command declares in watch. R is left out: it is rebuilt after every action. - const FP_LEN = ['links', 'transit', 'pni', 'caches', 'biz', 'offers', 'nni', 'loans', 'loanOffers', 'inc', 'scrubs']; - const FP_KEYS = ['pops', 'ixp', 'peers', 'myIx', 'done', 'ach', 'merged', 'confReg']; - const FP_JSON = ['name', 'pairMet', 'rs', 'ixn', 'ixSite', 'ixPref', 'spares', 'te', 'cnLic', 'hw', 'scrubMode', 'ppol', 'ops', 'core', 'ddosAuto', 'popStd', 'demo', 'charter', 'monkey', 'seatOff', 'pz', 'ar', 'dk', 'ev']; - const fp = (watch, args) => { - if (!S) return null; - const f = { cash: S.cash, day: S.day, lvl: S.lvl || 1, won: !!S.won, lost: !!S.lost }; - for (const k of FP_LEN) f[k] = (S[k] || []).length; - for (const k of FP_KEYS) f[k] = Object.keys(S[k] || {}).length; - for (const k of FP_JSON) f[k] = JSON.stringify(apiJson(S[k]) ?? null); - for (const p of watch || []) f['@' + p] = JSON.stringify(apiJson(apiPath(S, String(p).replace(/#(\w+)/g, (m, k) => (args && args[k] !== undefined ? args[k] : m)))) ?? null); - return JSON.stringify(f); - }; - // spend() is the game's money gate and a top-level function, so every action reaches it by its global name. - const meter = () => { const real = window.spend; let paid = 0; window.spend = (c) => { const ok = real(c); if (ok) paid += c; return ok; }; return () => { window.spend = real; return paid; }; }; - - // One action, run as the game runs it, and reported: what the game said (toasts), what it charged at the money gate - // (goal rewards that land in the same call are not a price), whether anything changed, and what is on screen now. - // typed: through the command table (bind the UI, type into fields, pass the confirmation); otherwise as a button - // click does it, with the button's own arguments. - const dispatch = (name, kind, spec, args, typed) => { - const mine = isSheet() || (typed && kind === 'game' && !!spec.open); - takeToasts(); - const ref = S, cash = S ? S.cash : 0, f0 = fp(spec && spec.watch, args), paid = meter(); - let threw = null, report; - try { - if (typed && kind === 'game') { - if (spec.open) { ACT[spec.open]({}); markSheet(); } - // The custom metric's field lives in the link's panel. - if (name === 'metricSet' && !$('metIn')) { UI.sel = { type: 'link', id: args.id }; renderAll(); } - const gone = (spec.dom || []).filter((f) => !$(f)); - if (gone.length) throw new Error(`the field it types into (${gone.join(', ')}) is not on screen${name === 'metricSet' ? ': set the link\'s metric to custom first (setMetric v "custom")' : ''}`); - if (spec.bind) spec.bind(args); - const a = spec.pass ? spec.pass(args) : args; - ACT[name](a); - if (spec.confirm === 'double') ACT[name](a); - if (spec.reads === 'modal' && modalOpen()) { report = text($('modal')); closeModal(); } - } else ACT[name](args); - } catch (e) { threw = e; } - const charged = paid(); - if (threw) { takeToasts(); fail(`${name} failed: ${threw && threw.message || threw}`); } - if (!modalOpen()) sheet = null; - else if (mine || kind !== 'game') markSheet(); - else sheet = null; - const said = takeToasts(), d = decision(); - const outcome = d ? 'decision' : S !== ref || fp(spec && spec.watch, args) !== f0 || report !== undefined ? 'applied' - : said.some((t) => t.kind === 'bad') ? 'rejected' : kind === 'view' || kind === 'draft' ? 'shown' : 'no_effect'; - return { action: name, outcome, toasts: toastLines(said), charged, cashChange: Math.round((S ? S.cash : 0) - cash), - ...(report !== undefined ? { report } : {}), ...(d ? { decision: d } : {}), screen: screen() }; - }; - // While the game waits for an answer, game commands other than its options report the question instead. - const waiting = (name) => { - const d = decision(); - return d && name !== 'closeModal' && !d.options.some((o) => o.command === name) - ? { action: name, outcome: 'decision', reason: 'A window is waiting for an answer: run one of its options, or closeModal.', decision: d, screen: screen() } : null; - }; - const quote = (name, spec, args) => { - const ui0 = {}; - for (const k of spec.bindsUI || []) ui0[k] = UI[k]; - const f0 = fp(spec.watch, args); - // A dry run must not use up the dice: some helpers draw (a PNI's lead time), and a draw here would move the seeded - // game. They get the middle of the range instead, so a drawn figure in a quote is a typical one. - const dice = Math.random; - Math.random = () => 0.5; - let q = {}; - try { - if (spec.bind && !spec.dom) spec.bind(args); - if (spec.quote) q = spec.quote(args) || {}; - } catch (e) { fail(`${name}: the price could not be worked out: ${e && e.message || e}`); } finally { Math.random = dice; for (const k of Object.keys(ui0)) UI[k] = ui0[k]; } - return { action: name, outcome: 'quote', quote: { setup: 0, monthly: 0, ...q, blocked: (q.blocked || []).map((b) => text(String(b), 400)) }, consistent: fp(spec.watch, args) === f0, - ...(spec.quote ? {} : { note: 'This command has no price of its own: it costs nothing up front.' }) }; - }; - const run = (name, args, opts = {}) => { - name = String(name || ''); - if (name.startsWith('view.')) name = name.slice(5); - const no = denied(name); - if (no) fail(`${name} is not available here: ${no}.`); - const kind = kindOf(name); - if (!kind || typeof ACT[name] !== 'function') fail(`There is no action "${name}". See actions or schema.`); - args = args && typeof args === 'object' && !Array.isArray(args) ? args : {}; - const spec = specOf(name); - if (spec) { const v = validate(spec, args); if (!v.ok) fail(`${name}: ${v.problems.join('; ')}. See schema for its arguments.`); args = v.args; } - if (kind === 'game') { - if (S && S.lost && name !== 'closeModal') return { action: name, outcome: 'stopped', reason: 'The network went bankrupt: start or load another game.' }; - const w = waiting(name); - if (w) return w; - if (opts.dryRun) return quote(name, spec, args); - } else if (opts.dryRun) fail(`${name} has no price: only game commands (see schema commands) dry-run.`); - return dispatch(name, kind, spec, args, true); - }; - const click = (n, value) => { - 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.`); - const name = b.select || b.act, args = b.select ? { v: value === undefined ? undefined : String(value) } : b.args; - if (b.select && !b.options.some((o) => o.value === args.v)) fail(`"${b.label}" is a list: click it with a value, one of ${b.options.map((o) => JSON.stringify(o.value)).join(', ')}.`); - const no = denied(name); - if (no) fail(`${name} is not available here: ${no}.`); - const kind = kindOf(name); - if (!kind || typeof ACT[name] !== 'function') fail(`"${b.label}" runs ${name}, which is not an action.`); - if (kind === 'game') { const w = waiting(name); if (w) return { clicked: b.label, ...w }; } - return { clicked: b.label, ...dispatch(name, kind, specOf(name), args, false) }; - }; - const panel = ({ city: c, link, network: q, tab, left }) => { - if (left !== undefined) { if (!['goals', 'deals', 'noc', 'nets'].includes(left)) fail('left is one of goals, deals, noc, nets.'); ACT.leftTab({ t: left }); return screen('left'); } - 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); - markSheet(); - return { toasts: toastLines(takeToasts()), screen: screen() }; - }; - - // ---------- time ---------- - const advance = (days = 1) => { - days = Math.max(1, Math.min(3650, Math.floor(+days) || 1)); - if (modalOpen()) fail('A window is open. Answer it first (screen, click, or act closeModal), the game does not run days behind it.'); - sheet = null; - 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 (modalOpen()) { 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), d = stop === 'a window opened' ? decision() : null; - 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(toastLines(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 })) }, - ...(d ? { decision: d } : {}), - 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, - schema, catalog, state, results, ui, classes }; -})(); diff --git a/scripts/lib/page.js b/scripts/lib/page.js index 880af5c..b905f26 100644 --- a/scripts/lib/page.js +++ b/scripts/lib/page.js @@ -3,8 +3,14 @@ // The result is the same single, self-contained index.html the game has always shipped: one request, // no module loader, no runtime cost. See docs/ARCHITECTURE.md ("Source layout") and docs/adr/. // +// A line `` is the same, but only in the development page (dev: true): the +// tools' side of the game (src/agent/, the agent facade the MCP server drives) for npm run dev, the +// MCP server's own page and the tests that ask for it. Everywhere else the line is dropped whole, so +// the page players get is exactly what it would be without it (docs/adr/0004-dev-only-code.md). +// // node scripts/lib/page.js [-o FILE] the page as it ships (stdout by default) -// node scripts/lib/page.js --source [-o FILE] assembled only, labels as in src/ (what tests and npm run dev use) +// node scripts/lib/page.js --source [-o FILE] assembled only, labels as in src/ (what tests use) +// node scripts/lib/page.js --source --dev [-o FILE] the development page: with src/agent/ (what npm run dev serves) // node scripts/lib/page.js --ref origin/main -o FILE the page as it ships at a git ref // // --ref uses that commit's own assembler, so it keeps working when this file changes; refs from before @@ -15,7 +21,7 @@ const path = require('node:path'); const { execFileSync } = require('node:child_process'); const ROOT = path.join(__dirname, '..', '..'); -const INCLUDE = /^$/; +const INCLUDE = /^$/; // Every file under dir, as paths relative to dir with '/' separators, in a stable order // (plain code-unit comparison, so the order never depends on the machine's locale). @@ -45,7 +51,8 @@ function partials(src, dir) { } // The assembled page as a string, plus a map of which output line came from which source file. -function assemble({ src = path.join(ROOT, 'src') } = {}) { +// dev: also the @include-dev parts (the development page); without it, their lines are left out entirely. +function assemble({ src = path.join(ROOT, 'src'), dev = false } = {}) { const shell = fs.readFileSync(path.join(src, 'index.html'), 'utf8'); const out = [], map = []; let line = 1; @@ -57,7 +64,8 @@ function assemble({ src = path.join(ROOT, 'src') } = {}) { line++; return; } - for (const p of partials(src, m[1])) { + if (m[1] && !dev) return; + for (const p of partials(src, m[2])) { const n = p.text.split('\n').length - 1; map.push({ file: p.file, from: line, to: line + n - 1 }); out.push(p.text); @@ -104,7 +112,7 @@ module.exports = { assemble, assembleRef, shipped, pageFile, locate, listFiles, if (require.main === module) { const args = process.argv.slice(2); const opt = (k) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : null; }; - const html = opt('--ref') ? assembleRef(opt('--ref')) : args.includes('--source') ? assemble().html : shipped().html; + const html = opt('--ref') ? assembleRef(opt('--ref')) : args.includes('--source') ? assemble({ dev: args.includes('--dev') }).html : shipped().html; const out = opt('-o'); if (out) { fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true }); fs.writeFileSync(out, html); } else process.stdout.write(html); diff --git a/scripts/lib/relay-client.js b/scripts/lib/relay-client.js new file mode 100644 index 0000000..410857b --- /dev/null +++ b/scripts/lib/relay-client.js @@ -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 }; diff --git a/scripts/mcp.js b/scripts/mcp.js index 75f9d4b..41d8ac5 100644 --- a/scripts/mcp.js +++ b/scripts/mcp.js @@ -1,70 +1,239 @@ #!/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 runs locally over stdio and loads the game from this checkout's src/ (scripts/lib/mcp-game.js); nothing is -// hosted, and the game page itself does not change. Register it with a client, for example: +// 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, 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 +// claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp // -// Protocol: JSON-RPC 2.0, one message per line on stdin and stdout (MCP stdio transport). stdout carries only -// protocol messages; anything else goes to stderr. -const readline = require('node:readline'); -const { createSession, TOOLS } = require('./lib/mcp-game'); +// stdout carries only protocol messages in stdio mode; anything else goes to stderr. +const crypto = require('node:crypto'); +const fs = require('node:fs'); +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, toolsFor, CLOCKS, DEFAULT_PACE_MS } = require('./lib/mcp-game'); const { version } = require('../package.json'); -const VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05']; -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 session = createSession(); -const send = (msg) => process.stdout.write(JSON.stringify(msg) + '\n'); -const reply = (id, result) => send({ jsonrpc: '2.0', id, result }); -const error = (id, code, message) => send({ jsonrpc: '2.0', id, error: { code, message } }); +const usage = () => `Usage: node scripts/mcp.js [options] -function handle(msg) { - const { id, method, params = {} } = msg; - const isRequest = id !== undefined && id !== null; - switch (method) { - case 'initialize': - return reply(id, { - protocolVersion: VERSIONS.includes(params.protocolVersion) ? params.protocolVersion : VERSIONS[0], - capabilities: { tools: { listChanged: false } }, - serverInfo: { name: 'seriesoftubes', title: 'Series of Tubes', version }, - instructions: INSTRUCTIONS, - }); - case 'ping': - return reply(id, {}); - case 'tools/list': - return reply(id, { tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })) }); - case 'tools/call': { - const tool = TOOLS.find((t) => t.name === params.name); - if (!tool) return error(id, -32602, `Unknown tool: ${params.name}`); - try { - const out = tool.run(session, params.arguments || {}); - const errs = session.errors(); - return reply(id, { content: [{ type: 'text', text: JSON.stringify(out, null, 1) }], ...(errs.length ? { _meta: { pageErrors: errs.slice(-5) } } : {}) }); - } catch (e) { - return reply(id, { content: [{ type: 'text', text: String(e && e.message || e) }], isError: true }); - } - } - default: - if (method && method.startsWith('notifications/')) return undefined; - if (isRequest) return error(id, -32601, `Method not found: ${method}`); - return undefined; + (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 " (or set SOT_MCP_TOKEN) + --allow-host NAME HTTP: also accept this Host name (repeatable), e.g. for a tunnel or a LAN name + --save-dir DIR HTTP: load_save and export_save may read and write files under DIR (otherwise no files) + --help`; + +// Valueless flags are true; repeated ones collect; --kebab-case becomes camelCase. +function parseArgs(argv) { + const out = {}; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (!a.startsWith('--')) continue; + const k = a.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase()), v = argv[i + 1]; + const val = v === undefined || v.startsWith('--') ? true : (i++, v); + out[k] = k in out ? [].concat(out[k], val) : val; } + return out; } -if (require.main === module) { - // The game page logs nothing to stdout, but a stray console.log anywhere must not break the protocol. +// Tool calls run one at a time, in the order they arrived, from every client: one game, one move at a time. +function serial() { + let chain = Promise.resolve(); + return (f) => { const p = chain.then(f); chain = p.catch(() => {}); return p; }; +} + +// 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(), 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: 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 || {}); + const errs = session.errors(); + return { content: [{ type: 'text', text: JSON.stringify(out, null, 1) }], ...(errs.length ? { _meta: { pageErrors: errs.slice(-5) } } : {}) }; + } catch (e) { + return { content: [{ type: 'text', text: String(e && e.message || e) }], isError: true }; + } + })); + } + return server; + }; +} + +// --http [HOST:]PORT, with IPv6 hosts in brackets ([::1]:7777). +function parseListen(v) { + const s = String(v === true ? '' : v); + const m = /^(?:\[([^\]]+)\]|([^:]+)):(\d+)$/.exec(s) || /^()()(\d+)$/.exec(s); + // Port 0 picks a free one (the banner says which). + if (!m || +m[3] > 65535) throw new Error(`--http takes [HOST:]PORT, e.g. 7777 or 0.0.0.0:7777, not "${s}"`); + return { host: m[1] || m[2] || '127.0.0.1', port: +m[3] }; +} +const isLoopback = (h) => h === 'localhost' || h === '::1' || /^127\.\d+\.\d+\.\d+$/.test(h); +const isWildcard = (h) => h === '0.0.0.0' || h === '::'; +const bracket = (h) => (h.includes(':') && !h.startsWith('[') ? `[${h}]` : h); + +// The names a request's Host may carry: this machine by loopback, the address the server is bound to (every local +// address when bound to all of them), and names the operator allowed. Anything else is a name someone else's DNS +// points here (DNS rebinding) and is refused. +function allowedHosts(host, extra = []) { + const out = new Set([...localhostAllowedHostnames(), ...extra.map(String)]); + if (isWildcard(host)) for (const list of Object.values(os.networkInterfaces())) for (const a of list || []) out.add(bracket(a.address.split('%')[0])); + else out.add(bracket(host)); + return [...out]; +} + +// Constant-time token check (hashing first makes the lengths equal, so the length does not leak either). +const sameToken = (a, b) => crypto.timingSafeEqual(crypto.createHash('sha256').update(String(a)).digest(), crypto.createHash('sha256').update(String(b)).digest()); + +// The HTTP side: Host and Origin checked on every request (browsers cannot be talked into driving the game from a +// website), the token when there is one, then the SDK's Streamable HTTP handler. +function createHttpServer(factory, { host, allow = [], token = null } = {}) { + const { toNodeHandler } = require('@modelcontextprotocol/node'); + const handle = toNodeHandler(createMcpHandler(factory)); + const hosts = allowedHosts(host, allow), origins = localhostAllowedOrigins(); + const deny = (res, code, message, headers = {}) => { + res.writeHead(code, { 'content-type': 'application/json', ...headers }); + res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32000, message } })); + }; + const server = http.createServer((req, res) => { + const url = new URL(req.url, 'http://localhost'); + if (url.pathname !== MCP_PATH) return deny(res, 404, `The MCP endpoint is ${MCP_PATH}.`); + const h = validateHostHeader(req.headers.host, hosts); + if (!h.ok) return deny(res, 403, `Host not allowed: ${h.message}. Use an address of this machine, or start the server with --allow-host.`); + const o = validateOriginHeader(req.headers.origin, origins); + if (!o.ok) return deny(res, 403, 'Origin not allowed: a web page may not drive this server.'); + if (token) { + const m = /^Bearer\s+(.+)$/i.exec(req.headers.authorization || ''); + if (!m || !sameToken(m[1].trim(), token)) return deny(res, 401, 'A bearer token is required.', { 'www-authenticate': 'Bearer realm="seriesoftubes"' }); + } + handle(req, res); + }); + // advance over thousands of days on a big network takes minutes; Node's default would cut it off at five. + server.requestTimeout = 30 * 60 * 1000; + return server; +} + +function readToken(args) { + if (args.tokenFile) { + const t = fs.readFileSync(path.resolve(String(args.tokenFile)), 'utf8').trim(); + if (!t) throw new Error(`${args.tokenFile} is empty`); + return t; + } + return process.env.SOT_MCP_TOKEN ? String(process.env.SOT_MCP_TOKEN).trim() || null : null; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + if (args.help) { console.error(usage()); process.exit(0); } + const say = (m) => console.error(`[series-of-tubes] ${m}`); + 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 rl = readline.createInterface({ input: process.stdin }); - rl.on('line', (line) => { - if (!line.trim()) return; - let msg; - try { msg = JSON.parse(line); } catch (e) { return error(null, -32700, 'Parse error'); } - if (Array.isArray(msg)) { for (const m of msg) handle(m); return; } - handle(msg); + 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) { + const { serveStdio } = require('@modelcontextprotocol/server/stdio'); + 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; + try { listen = parseListen(args.http); token = readToken(args); } catch (e) { die(e.message); } + // Over HTTP the client may be another machine: files only under --save-dir, never anywhere on this one. + let saveDir = null; + if (args.saveDir !== undefined) { + 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 = 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, () => { + const ad = server.address(), at = `${bracket(ad.address)}:${ad.port}`; + 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.`); + 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 = () => { 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); }); } -module.exports = { handle, TOOLS }; +if (require.main === module) main(); + +module.exports = { serverFactory, createHttpServer, serial, parseArgs, parseListen, allowedHosts, instructions, INSTRUCTIONS, MCP_PATH }; diff --git a/site/i18n/de.js b/site/i18n/de.js index 36144e8..8080d82 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -3855,19 +3855,30 @@ "security_and_china.tier_scrubbing_center_online_in_city":"{tier}-Scrubbing-Center in {city} online.
Angriffe bis {g} werden herausgefiltert, und du kannst DDoS-Schutz verkaufen.", "security_and_china.tier_scrubbing_unlocks_at_customer":"{tier}-Scrubbing wird ab Kundenlevel {lv} freigeschaltet.", "security_and_china.you_counter_flooded_a_hospital_in":"Du hast mit deinem Gegenangriff ein Krankenhaus in einem Land geflutet, das du nicht aussprechen kannst.", +"settings.a_pace_runs_one_simulated_day":"Mit Tempo vergeht alle 30 Sekunden bis 5 Minuten ein simulierter Tag, und der Agent muss mithalten. Stellt der Agent die Uhr, steht sie still, bis er nach Tagen fragt.", +"settings.agent_api":"Agent-API", +"settings.agent_relay_connected":"Agenten-Relay verbunden: Jetzt kann ein Tool dieses Spiel in diesem Tab spielen.", +"settings.agent_s_clock":"Uhr des Agenten", "settings.an_early_heads_up_below_60":"Eine frühe Warnung unter 60 % Zufriedenheit, lange bevor sie wütend sind.", "settings.auto_follows_your_device_s_reduce":"Auto folgt der Einstellung „Bewegung reduzieren“ deines Geräts. Aus friert die Karte ein: keine wandernden Pakete, kein Pulsieren, kein schwebender Text.", "settings.customers_and_alerts":"Kunden und Warnungen", "settings.display_and_sound":"Anzeige und Ton", "settings.for_reporting_layout_bugs_shows_what":"Zum Melden von Layout-Fehlern: zeigt, was dein Bildschirm dem Spiel mitteilt.", +"settings.let_an_ai_agent_drive_this_game":"Eine KI soll dieses Spiel spielen", +"settings.n_min":"{n} Min.", +"settings.n_sec":"{n} s", "settings.only_trouble_and_milestones_pop_up":"Nur Ärger und Meilensteine poppen auf; alles andere landet still im NOC-Log. In Best Effort standardmäßig an.", +"settings.pace_t_per_day":"{t} pro simulierten Tag", "settings.pause_on_outages_that_hurt":"Bei echten Ausfällen pausieren", "settings.pause_when_a_customer_is_furious":"Bei wütenden Kunden pausieren", "settings.quiet_notifications":"Leise Benachrichtigungen", "settings.saved_on_this_device":"Auf diesem Gerät gespeichert.", "settings.stops_the_game_when_a_failure":"Hält das Spiel an, wenn ein Ausfall dich echten Traffic kostet, nicht wenn der Traffic von selbst umgeleitet wird.", +"settings.the_agent_moves_it":"Der Agent stellt sie", +"settings.the_clock_while_an_agent_plays":"Die Uhr, während ein Agent spielt", "settings.the_game_stops_so_you_can":"Das Spiel hält an, damit du ihren Dienst reparieren kannst, bevor sie kündigen. Am nützlichsten bei hoher Geschwindigkeit.", "settings.warn_when_a_customer_gets_unhappy":"Bei unzufriedenen Kunden warnen", +"settings.while_agent_mode_is_on_the":"Solange der Agenten-Modus an ist, gehört die Uhr nicht dir. Mit Tempo läuft sie von selbst und lässt sich von Hand nicht anhalten, auch nicht durch ein offenes Fenster (deins eingeschlossen), und sie wartet, solange kein Agent verbunden ist. Oder der Agent stellt sie, und nichts passiert, bis er nach Tagen fragt. Die Seite verbindet sich mit dem lokalen Agenten-Relay (npm run dev bringt eins mit), damit Tools wie der MCP-Server dieses Spiel spielen können, während du zusiehst.", "share_card.build_the_internet_one_tube_at":"Bau das Internet, eine Röhre nach der anderen", "share_card.n_in_r_regions":"{n} in {r} Regionen", "share_card.not_this_time":"diesmal nicht", diff --git a/site/i18n/es.js b/site/i18n/es.js index baba114..8a40405 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -3853,19 +3853,30 @@ "security_and_china.tier_scrubbing_center_online_in_city":"Centro de depuración {tier} en línea en {city}.
Se limpian ataques de hasta {g}, y puedes vender protección DDoS.", "security_and_china.tier_scrubbing_unlocks_at_customer":"La depuración {tier} se desbloquea en el nivel de cliente {lv}.", "security_and_china.you_counter_flooded_a_hospital_in":"Contrainundaste un hospital en un país que no sabes pronunciar.", +"settings.a_pace_runs_one_simulated_day":"Con un ritmo pasa un día simulado cada 30 segundos a 5 minutos, y el agente tiene que seguirlo. Si lo mueve el agente, el reloj se queda quieto hasta que pide días.", +"settings.agent_api":"API de agentes", +"settings.agent_relay_connected":"Relay de agentes conectado: ahora una herramienta puede jugar esta partida en esta pestaña.", +"settings.agent_s_clock":"Reloj del agente", "settings.an_early_heads_up_below_60":"Un aviso temprano por debajo del 60 % de felicidad, mucho antes de que estén furiosos.", "settings.auto_follows_your_device_s_reduce":"Auto sigue el ajuste de reducir movimiento de tu dispositivo. Desactivado congela el mapa: sin paquetes en movimiento, pulsos ni texto flotante.", "settings.customers_and_alerts":"Clientes y alertas", "settings.display_and_sound":"Pantalla y sonido", "settings.for_reporting_layout_bugs_shows_what":"Para informar de fallos de diseño: muestra lo que tu pantalla le dice al juego.", +"settings.let_an_ai_agent_drive_this_game":"Deja que un agente de IA juegue", +"settings.n_min":"{n} min", +"settings.n_sec":"{n} s", "settings.only_trouble_and_milestones_pop_up":"Solo aparecen los problemas y los hitos; todo lo demás va en silencio al registro del NOC. Activado por defecto en Best Effort.", +"settings.pace_t_per_day":"{t} por día simulado", "settings.pause_on_outages_that_hurt":"Pausar con caídas que duelen", "settings.pause_when_a_customer_is_furious":"Pausar cuando un cliente está furioso", "settings.quiet_notifications":"Notificaciones discretas", "settings.saved_on_this_device":"Guardado en este dispositivo.", "settings.stops_the_game_when_a_failure":"Detiene el juego cuando un fallo te cuesta tráfico real, no cuando se reencamina solo.", +"settings.the_agent_moves_it":"Lo mueve el agente", +"settings.the_clock_while_an_agent_plays":"El reloj mientras juega un agente", "settings.the_game_stops_so_you_can":"El juego se detiene para que arregles su servicio antes de que cancelen. Muy útil a alta velocidad.", "settings.warn_when_a_customer_gets_unhappy":"Avisar cuando un cliente se descontenta", +"settings.while_agent_mode_is_on_the":"Mientras el modo agente está activo, el reloj no es tuyo. Con un ritmo, corre solo y no se puede pausar a mano, ni siquiera con una ventana abierta (las tuyas incluidas), y espera mientras no haya ningún agente conectado. O lo mueve el agente, y no pasa nada hasta que pide días. La página se conecta al relay local de agentes (npm run dev trae uno), para que herramientas como el servidor MCP jueguen esta partida mientras miras.", "share_card.build_the_internet_one_tube_at":"Construye internet, un tubo a la vez", "share_card.n_in_r_regions":"{n} en {r} regiones", "share_card.not_this_time":"esta vez no", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index 263018f..17f3c36 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -3853,19 +3853,30 @@ "security_and_china.tier_scrubbing_center_online_in_city":"Centre de scrubbing {tier} en ligne à {city}.
Les attaques jusqu’à {g} sont nettoyées, et tu peux vendre de la protection DDoS.", "security_and_china.tier_scrubbing_unlocks_at_customer":"Le scrubbing {tier} se débloque au niveau client {lv}.", "security_and_china.you_counter_flooded_a_hospital_in":"Tu as contre-floodé un hôpital dans un pays dont tu ne sais même pas prononcer le nom.", +"settings.a_pace_runs_one_simulated_day":"Avec un rythme, un jour simulé passe toutes les 30 secondes à 5 minutes, et l'agent doit suivre. Avancée par l'agent, l'horloge reste immobile tant qu'il ne demande pas de jours.", +"settings.agent_api":"API agent", +"settings.agent_relay_connected":"Relais pour agents connecté : un outil peut maintenant jouer cette partie dans cet onglet.", +"settings.agent_s_clock":"Horloge de l'agent", "settings.an_early_heads_up_below_60":"Une alerte précoce sous 60 % de satisfaction, bien avant qu’il soit furieux.", "settings.auto_follows_your_device_s_reduce":"Auto suit le réglage « réduire les animations » de ton appareil. Inactif fige la carte : plus de paquets en mouvement, de pulsations ni de texte flottant.", "settings.customers_and_alerts":"Clients et alertes", "settings.display_and_sound":"Affichage et son", "settings.for_reporting_layout_bugs_shows_what":"Pour signaler des bugs de mise en page : montre ce que ton écran dit au jeu.", +"settings.let_an_ai_agent_drive_this_game":"Laisser un agent IA jouer", +"settings.n_min":"{n} min", +"settings.n_sec":"{n} s", "settings.only_trouble_and_milestones_pop_up":"Seuls les problèmes et les étapes s'affichent ; tout le reste va discrètement dans le journal du NOC. Activé par défaut en Best Effort.", +"settings.pace_t_per_day":"{t} par jour simulé", "settings.pause_on_outages_that_hurt":"Pause sur les pannes qui font mal", "settings.pause_when_a_customer_is_furious":"Pause quand un client est furieux", "settings.quiet_notifications":"Notifications discrètes", "settings.saved_on_this_device":"Sauvegardées sur cet appareil.", "settings.stops_the_game_when_a_failure":"Arrête le jeu quand une panne te coûte du vrai trafic, pas quand elle se reroute toute seule.", +"settings.the_agent_moves_it":"L'agent l'avance", +"settings.the_clock_while_an_agent_plays":"L'horloge pendant qu'un agent joue", "settings.the_game_stops_so_you_can":"Le jeu s’arrête pour que tu répares leur service avant qu’ils résilient. Surtout utile à grande vitesse.", "settings.warn_when_a_customer_gets_unhappy":"Prévenir quand un client devient mécontent", +"settings.while_agent_mode_is_on_the":"Tant que le mode agent est actif, l'horloge n'est plus à toi. Avec un rythme, elle tourne toute seule et ne peut pas être mise en pause à la main, pas même par une fenêtre ouverte (les tiennes comprises), et elle attend tant qu'aucun agent n'est connecté. Ou bien c'est l'agent qui l'avance, et rien ne se passe tant qu'il ne demande pas de jours. La page se connecte au relais local pour agents (npm run dev en lance un), pour que des outils comme le serveur MCP jouent cette partie pendant que tu regardes.", "share_card.build_the_internet_one_tube_at":"Construis Internet, un tube à la fois", "share_card.n_in_r_regions":"{n} dans {r} régions", "share_card.not_this_time":"pas cette fois", diff --git a/site/i18n/it.js b/site/i18n/it.js index 7fe478b..c4728d3 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -3853,19 +3853,30 @@ "security_and_china.tier_scrubbing_center_online_in_city":"Centro di scrubbing {tier} attivo a {city}.
Gli attacchi fino a {g} vengono ripuliti, e puoi vendere protezione DDoS.", "security_and_china.tier_scrubbing_unlocks_at_customer":"Lo scrubbing {tier} si sblocca al livello cliente {lv}.", "security_and_china.you_counter_flooded_a_hospital_in":"Hai contro-floodato un ospedale in un paese che non sai pronunciare.", +"settings.a_pace_runs_one_simulated_day":"Con un ritmo passa un giorno simulato ogni 30 secondi fino a 5 minuti, e l'agente deve stare al passo. Se lo muove l'agente, l'orologio resta fermo finché non chiede dei giorni.", +"settings.agent_api":"API per agenti", +"settings.agent_relay_connected":"Relay per agenti collegato: ora uno strumento può giocare questa partita in questa scheda.", +"settings.agent_s_clock":"Orologio dell'agente", "settings.an_early_heads_up_below_60":"Un avviso in anticipo sotto il 60% di soddisfazione, molto prima che siano furiosi.", "settings.auto_follows_your_device_s_reduce":"Auto segue l’impostazione “riduci movimento” del tuo dispositivo. Off congela la mappa: niente pacchetti in movimento, pulsazioni o testo fluttuante.", "settings.customers_and_alerts":"Clienti e avvisi", "settings.display_and_sound":"Schermo e audio", "settings.for_reporting_layout_bugs_shows_what":"Per segnalare bug di layout: mostra cosa lo schermo dice al gioco.", +"settings.let_an_ai_agent_drive_this_game":"Lascia giocare un agente IA", +"settings.n_min":"{n} min", +"settings.n_sec":"{n} s", "settings.only_trouble_and_milestones_pop_up":"Compaiono solo i problemi e i traguardi; tutto il resto finisce in silenzio nel registro del NOC. Attivo di default in Best Effort.", +"settings.pace_t_per_day":"{t} per giorno simulato", "settings.pause_on_outages_that_hurt":"Pausa sui guasti che fanno male", "settings.pause_when_a_customer_is_furious":"Pausa quando un cliente è furioso", "settings.quiet_notifications":"Notifiche discrete", "settings.saved_on_this_device":"Salvate su questo dispositivo.", "settings.stops_the_game_when_a_failure":"Ferma il gioco quando un guasto ti costa traffico vero, non quando si reinstrada da solo.", +"settings.the_agent_moves_it":"Lo muove l'agente", +"settings.the_clock_while_an_agent_plays":"L'orologio mentre gioca un agente", "settings.the_game_stops_so_you_can":"Il gioco si ferma così puoi sistemare il servizio prima che disdicano. Utilissimo ad alta velocità.", "settings.warn_when_a_customer_gets_unhappy":"Avvisa quando un cliente diventa scontento", +"settings.while_agent_mode_is_on_the":"Finché la modalità agente è attiva, l'orologio non è tuo. Con un ritmo va da solo e non si può fermare a mano, nemmeno con una finestra aperta (comprese le tue), e aspetta finché non è collegato nessun agente. Oppure lo muove l'agente, e non succede nulla finché non chiede dei giorni. La pagina si collega al relay locale per agenti (npm run dev ne avvia uno), così strumenti come il server MCP possono giocare questa partita mentre guardi.", "share_card.build_the_internet_one_tube_at":"Costruisci internet, un tubo alla volta", "share_card.n_in_r_regions":"{n} in {r} regioni", "share_card.not_this_time":"non stavolta", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 64f78e1..58390fc 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -3853,19 +3853,30 @@ "security_and_china.tier_scrubbing_center_online_in_city":"Centro de scrubbing {tier} no ar em {city}.
Ataques de até {g} são limpos, e você pode vender proteção DDoS.", "security_and_china.tier_scrubbing_unlocks_at_customer":"Scrubbing {tier} desbloqueia no nível de cliente {lv}.", "security_and_china.you_counter_flooded_a_hospital_in":"Você contra-floodou um hospital num país que você nem sabe pronunciar.", +"settings.a_pace_runs_one_simulated_day":"Com um ritmo passa um dia simulado a cada 30 segundos a 5 minutos, e o agente tem de acompanhar. Movido pelo agente, o relógio fica parado até ele pedir dias.", +"settings.agent_api":"API para agentes", +"settings.agent_relay_connected":"Relay de agentes ligado: agora uma ferramenta pode jogar este jogo nesta aba.", +"settings.agent_s_clock":"Relógio do agente", "settings.an_early_heads_up_below_60":"Um aviso antecipado abaixo de 60% de satisfação, bem antes de ficarem furiosos.", "settings.auto_follows_your_device_s_reduce":"Auto segue a configuração de reduzir movimento do seu aparelho. Desligado congela o mapa: sem pacotes andando, pulsos ou texto flutuante.", "settings.customers_and_alerts":"Clientes e alertas", "settings.display_and_sound":"Tela e som", "settings.for_reporting_layout_bugs_shows_what":"Para reportar bugs de layout: mostra o que sua tela informa ao jogo.", +"settings.let_an_ai_agent_drive_this_game":"Deixa um agente de IA jogar", +"settings.n_min":"{n} min", +"settings.n_sec":"{n} s", "settings.only_trouble_and_milestones_pop_up":"Só aparecem problemas e marcos; todo o resto vai em silêncio para o registro do NOC. Ligado por padrão no Best Effort.", +"settings.pace_t_per_day":"{t} por dia simulado", "settings.pause_on_outages_that_hurt":"Pausar em falhas que doem", "settings.pause_when_a_customer_is_furious":"Pausar quando um cliente estiver furioso", "settings.quiet_notifications":"Notificações discretas", "settings.saved_on_this_device":"Salvo neste dispositivo.", "settings.stops_the_game_when_a_failure":"Para o jogo quando uma falha custa tráfego de verdade, não quando ela se reroteia sozinha.", +"settings.the_agent_moves_it":"O agente move-o", +"settings.the_clock_while_an_agent_plays":"O relógio enquanto um agente joga", "settings.the_game_stops_so_you_can":"O jogo para para você consertar o serviço antes que cancelem. Muito útil em alta velocidade.", "settings.warn_when_a_customer_gets_unhappy":"Avisar quando um cliente ficar insatisfeito", +"settings.while_agent_mode_is_on_the":"Enquanto o modo agente estiver ligado, o relógio não é teu. Com um ritmo, corre sozinho e não pode ser parado à mão, nem por uma janela aberta (as tuas incluídas), e espera enquanto nenhum agente estiver ligado. Ou é o agente que o move, e nada acontece até ele pedir dias. A página liga-se ao relay local de agentes (npm run dev traz um), para que ferramentas como o servidor MCP joguem este jogo enquanto vês.", "share_card.build_the_internet_one_tube_at":"Construa a internet, um tubo de cada vez", "share_card.n_in_r_regions":"{n} em {r} regiões", "share_card.not_this_time":"não foi dessa vez", diff --git a/src/agent/10-domains.js b/src/agent/10-domains.js new file mode 100644 index 0000000..01ff49a --- /dev/null +++ b/src/agent/10-domains.js @@ -0,0 +1,105 @@ +/* ================= AGENT API: argument domains ================= + The agent facade (window.TUBES, this folder) is how tools play the game: the MCP server (scripts/mcp.js) calls it in + its own jsdom page, or in the player's tab through the agent relay (80-relay.js). It is part of the development page + only (): the page players get has none of it, so nothing in src/game/ may name anything + defined here; the game offers HOOKS instead. Nothing here runs until a tool calls it or the player switches agent + mode on: these files define tables and functions, and 99-start.js wires agent mode in. + A domain is what an argument may be: an id in a catalog table, a key, an index, a small fixed list, or a check. */ +const API_DOMAINS={ + // Tables from the catalog: an id in a list, a key in an object, or an index into a list. + cityId:{table:'CITIES',kind:'id'}, + netId:{table:'NETS',kind:'id'}, + cableId:{table:'CABLES',kind:'id'}, + fabId:{table:'FAB',kind:'key'}, + opticId:{table:'OPT',kind:'key'}, + systemId:{table:'DF_SYS',kind:'key'}, + designId:{table:'SEA_DESIGNS',kind:'key'}, + upgradeId:{table:'SUB_UPGRADES',kind:'key'}, + bizTypeId:{table:'BIZ_T',kind:'key'}, + portTier:{table:'PORT',kind:'index'}, + linkTier:{table:'LT',kind:'index'}, + nniTier:{table:'NNI',kind:'index'}, + vxcTier:{table:'VXC',kind:'index'}, + routerModel:{table:'RG',kind:'index'}, + scrubTier:{table:'SCRUB_TIERS',kind:'index'}, + // Small fixed vocabularies the game itself checks by list membership. + // The link metric presets, plus "custom" for a hand-tuned number (ACT.setMetric). + metric:{kind:'enum',values:()=>[...Object.keys(MET),'custom']}, + egress:{table:'PREF',kind:'key'}, + routeMode:{table:'RT',kind:'key'}, + site:{kind:'enum',values:['a','b','ab']}, + step:{kind:'enum',values:[1,-1]}, + connKind:{kind:'enum',values:['t','p','ix','c','nni']}, + egressKind:{kind:'enum',values:['t','p','ix','c','nni','l2']}, + peerPolicy:{table:'PPOL',kind:'enum'}, + // The intern, their orders and the new-POP template (opsHire, opsToggle, opsParam…). + internId:{table:'INTERNS',kind:'key'}, + opsKey:{table:'OPSK',kind:'key'}, + opsPopKind:{kind:'enum',values:()=>OPS_POP.slice()}, + opsTplKey:{kind:'enum',values:()=>OPS_TPL.slice()}, + // The specialist's offers: a seat on a consortium cable, the charter, a vendor demo. + seatPairs:{kind:'enum',values:()=>SEAT_N.slice()}, + charterKey:{table:'CHARTERS',kind:'key'}, + // The link metric editor: a factor or an exact weight (metricMode, metricSet). + metricKind:{kind:'enum',values:['f','w']}, + // The NOC's auto-mitigation switches (ddosAuto). + ddosKey:{kind:'enum',values:['rtbh','scrub']}, + // Puzzle and architect builds: the tiers a puzzle may light, the router models it offers. + pztTier:{kind:'fn',ok:v=>PZ_TIERS.includes(+v)||AR_TIERS.includes(+v)}, + pzRouterModel:{table:'PZ_RG',kind:'index'}, + pzRouteMode:{kind:'enum',values:['normal','fast']}, + // The bulk PNI order takes one network or null for every network at every shared POP (ACT.pniAll). + pniAllNet:{kind:'fn',ok:v=>v===null||(typeof v==='string'&&!!NET[v])}, + dashTab:{kind:'enum',values:()=>DTABS.slice()}, + dashSortKey:{kind:'enum',values:['name','asn','type','traffic','cost','lost']}, + leftTab:{kind:'enum',values:['goals','deals','noc','nets']}, + netFilter:{kind:'enum',values:['all','out']}, + pniFilter:{kind:'enum',values:['all','t','worth','pni']}, + listPage:{kind:'enum',values:['conn','cust','nets','pni']}, + custSortKey:{kind:'enum',values:['mood','mo','name','city']}, + connFilter:{kind:'enum',values:['all','k']}, + connSortKey:{kind:'enum',values:['k','city','name','use','mo']}, + dfSource:{kind:'enum',values:['lease','build','cable']}, + cityIdArray:{kind:'array',of:'cityId'}, + // Anything a panel can reach: an exchange city, a rival exchange id, one of your own exchanges. + ixId:{kind:'fn',ok:v=>isIx(v)}, + // A PNI also takes tier:-1, the 1G courtesy port a network may offer (ACT.pni). + pniTier:{kind:'fn',ok:v=>v===-1||(Number.isInteger(v)&&v>=0&&vtypeof v==='string'&&upcomingConfs(75).some(c=>c.key===v)}, + // traceroute goes to your own POPs and to networks; traceModal parses a net:/city: prefix. + traceTo:{kind:'fn',ok:v=>typeof v==='string'&&(NET[v]||isCity(v))}, + // Entity ids (uid()) cannot be validated against a table: shape only. A wrong id is the game's + // to answer, honestly, with no_effect — never a refusal invented on this side of the wall. + entityId:{kind:'string'}, + scnId:{table:'SCN',kind:'id'}, + // A traceroute target in the modal's own terms. +}; + +/* Type names an arg can take instead of a domain: 'string' | 'boolean' | 'integer'. */ + +function apiDomCheck(dom,v){ + const d=API_DOMAINS[dom]; + // The game's own buttons ship truthiness as 0 and 1 (custOpen's {"sad":0}); accept the game's dialect. + if(dom==='boolean')return {ok:v===true||v===false||v===0||v===1}; + if(!d)return {ok:dom==='integer'?Number.isInteger(v):typeof v===dom}; // 'string' | 'integer' + if(d.kind==='array')return {ok:Array.isArray(v)&&v.every(x=>apiDomCheck(d.of,x).ok)}; + const t=d.table?API_CATALOG_TABLE(d.table):null; + if(d.kind==='id')return {ok:!!t&&t.some(x=>x&&x.id===v)}; + if(d.kind==='string')return {ok:typeof v==='string'}; + if(d.kind==='key'||d.kind==='enum'){ + const vs=d.kind==='key'?Object.keys(t||{}):(t||(typeof d.values==='function'?d.values():d.values)||[]); + return {ok:vs.includes(v)};} + if(d.kind==='index')return {ok:Number.isInteger(v)&&v>=0&&v<(t?t.length:0)}; + return {ok:!!d.ok&&d.ok(v)}; +} +function apiDomValues(dom){ + const d=API_DOMAINS[dom];if(!d)return null; + const t=d.table?API_CATALOG_TABLE(d.table):null; + if(d.kind==='array')return {of:d.of}; + if(d.kind==='id')return t?t.map(x=>x.id):[]; + if(d.kind==='key')return t?Object.keys(t):[]; + if(d.kind==='enum')return t||(typeof d.values==='function'?d.values():d.values)||[]; + if(d.kind==='index')return {from:0,to:(t?t.length:1)-1}; + return null; +} diff --git a/scripts/lib/mcp-commands.js b/src/agent/20-commands.js similarity index 67% rename from scripts/lib/mcp-commands.js rename to src/agent/20-commands.js index f612308..d7d1856 100644 --- a/scripts/lib/mcp-commands.js +++ b/src/agent/20-commands.js @@ -1,115 +1,13 @@ -// Runs inside the game page before scripts/lib/mcp-page.js, in the game's own global scope: the typed command -// tables the MCP server's act tool dispatches through. Data and small helpers only, no state. -// -// Every action in ACT is in exactly one class (tests/mcp-commands.test.js fails otherwise, so a new action forces a -// decision): CMD, a game command with typed arguments; VIEW, which changes only what is on screen; BOUND, which only -// drafts an input another command reads; SESSION, which starts, retries or leaves a game or dismisses a coaching -// screen; or the server's DENY list (scripts/lib/mcp-page.js). CMD fields: args [name, domain|'string'|'boolean'|'integer', required]; bind(args) writes the UI -// a panel would set (bindsUI: the UI keys it touches, restored after a dry run); open/dom: the window an input lives -// in and the fields that must exist before dispatch; pass(args) reshapes the args for the action (confirmations); -// confirm 'arg' (passed through) or 'double' (the game arms a button first); decides (may end in a question); reads -// 'modal' (the window's text is the report); watch (extra fingerprint paths, #name filled from args); quote (the dry -// run, priced with the game's own helpers); doc. -window.__mcpCmds = (() => { -const API_DOMAINS={ - // Tables from the catalog: an id in a list, a key in an object, or an index into a list. - cityId:{table:'CITIES',kind:'id'}, - netId:{table:'NETS',kind:'id'}, - cableId:{table:'CABLES',kind:'id'}, - fabId:{table:'FAB',kind:'key'}, - opticId:{table:'OPT',kind:'key'}, - systemId:{table:'DF_SYS',kind:'key'}, - designId:{table:'SEA_DESIGNS',kind:'key'}, - upgradeId:{table:'SUB_UPGRADES',kind:'key'}, - bizTypeId:{table:'BIZ_T',kind:'key'}, - portTier:{table:'PORT',kind:'index'}, - linkTier:{table:'LT',kind:'index'}, - nniTier:{table:'NNI',kind:'index'}, - vxcTier:{table:'VXC',kind:'index'}, - routerModel:{table:'RG',kind:'index'}, - scrubTier:{table:'SCRUB_TIERS',kind:'index'}, - // Small fixed vocabularies the game itself checks by list membership. - // The link metric presets, plus "custom" for a hand-tuned number (ACT.setMetric). - metric:{kind:'enum',values:()=>[...Object.keys(MET),'custom']}, - egress:{table:'PREF',kind:'key'}, - routeMode:{table:'RT',kind:'key'}, - site:{kind:'enum',values:['a','b','ab']}, - step:{kind:'enum',values:[1,-1]}, - connKind:{kind:'enum',values:['t','p','ix','c','nni']}, - egressKind:{kind:'enum',values:['t','p','ix','c','nni','l2']}, - peerPolicy:{table:'PPOL',kind:'enum'}, - // The intern, their orders and the new-POP template (opsHire, opsToggle, opsParam…). - internId:{table:'INTERNS',kind:'key'}, - opsKey:{table:'OPSK',kind:'key'}, - opsPopKind:{kind:'enum',values:()=>OPS_POP.slice()}, - opsTplKey:{kind:'enum',values:()=>OPS_TPL.slice()}, - // The specialist's offers: a seat on a consortium cable, the charter, a vendor demo. - seatPairs:{kind:'enum',values:()=>SEAT_N.slice()}, - charterKey:{table:'CHARTERS',kind:'key'}, - // The link metric editor: a factor or an exact weight (metricMode, metricSet). - metricKind:{kind:'enum',values:['f','w']}, - // The NOC's auto-mitigation switches (ddosAuto). - ddosKey:{kind:'enum',values:['rtbh','scrub']}, - // Puzzle and architect builds: the tiers a puzzle may light, the router models it offers. - pztTier:{kind:'fn',ok:v=>PZ_TIERS.includes(+v)||AR_TIERS.includes(+v)}, - pzRouterModel:{table:'PZ_RG',kind:'index'}, - pzRouteMode:{kind:'enum',values:['normal','fast']}, - // The bulk PNI order takes one network or null for every network at every shared POP (ACT.pniAll). - pniAllNet:{kind:'fn',ok:v=>v===null||(typeof v==='string'&&!!NET[v])}, - dashTab:{kind:'enum',values:()=>DTABS.slice()}, - dashSortKey:{kind:'enum',values:['name','asn','type','traffic','cost','lost']}, - leftTab:{kind:'enum',values:['goals','deals','noc','nets']}, - netFilter:{kind:'enum',values:['all','out']}, - pniFilter:{kind:'enum',values:['all','t','worth','pni']}, - listPage:{kind:'enum',values:['conn','cust','nets','pni']}, - custSortKey:{kind:'enum',values:['mood','mo','name','city']}, - connFilter:{kind:'enum',values:['all','k']}, - connSortKey:{kind:'enum',values:['k','city','name','use','mo']}, - dfSource:{kind:'enum',values:['lease','build','cable']}, - cityIdArray:{kind:'array',of:'cityId'}, - // Anything a panel can reach: an exchange city, a rival exchange id, one of your own exchanges. - ixId:{kind:'fn',ok:v=>isIx(v)}, - // A PNI also takes tier:-1, the 1G courtesy port a network may offer (ACT.pni). - pniTier:{kind:'fn',ok:v=>v===-1||(Number.isInteger(v)&&v>=0&&vtypeof v==='string'&&upcomingConfs(75).some(c=>c.key===v)}, - // traceroute goes to your own POPs and to networks; traceModal parses a net:/city: prefix. - traceTo:{kind:'fn',ok:v=>typeof v==='string'&&(NET[v]||isCity(v))}, - // Entity ids (uid()) cannot be validated against a table: shape only. A wrong id is the game's - // to answer, honestly, with no_effect — never a refusal invented on this side of the wall. - entityId:{kind:'string'}, - scnId:{table:'SCN',kind:'id'}, - // A traceroute target in the modal's own terms. -}; - -/* Type names an arg can take instead of a domain: 'string' | 'boolean' | 'integer'. */ - -function apiDomCheck(dom,v){ - const d=API_DOMAINS[dom]; - // The game's own buttons ship truthiness as 0 and 1 (custOpen's {"sad":0}); accept the game's dialect. - if(dom==='boolean')return {ok:v===true||v===false||v===0||v===1}; - if(!d)return {ok:dom==='integer'?Number.isInteger(v):typeof v===dom}; // 'string' | 'integer' - if(d.kind==='array')return {ok:Array.isArray(v)&&v.every(x=>apiDomCheck(d.of,x).ok)}; - const t=d.table?API_CATALOG_TABLE(d.table):null; - if(d.kind==='id')return {ok:!!t&&t.some(x=>x&&x.id===v)}; - if(d.kind==='string')return {ok:typeof v==='string'}; - if(d.kind==='key'||d.kind==='enum'){ - const vs=d.kind==='key'?Object.keys(t||{}):(t||(typeof d.values==='function'?d.values():d.values)||[]); - return {ok:vs.includes(v)};} - if(d.kind==='index')return {ok:Number.isInteger(v)&&v>=0&&v<(t?t.length:0)}; - return {ok:!!d.ok&&d.ok(v)}; -} -function apiDomValues(dom){ - const d=API_DOMAINS[dom];if(!d)return null; - const t=d.table?API_CATALOG_TABLE(d.table):null; - if(d.kind==='array')return {of:d.of}; - if(d.kind==='id')return t?t.map(x=>x.id):[]; - if(d.kind==='key')return t?Object.keys(t):[]; - if(d.kind==='enum')return t||(typeof d.values==='function'?d.values():d.values)||[]; - if(d.kind==='index')return {from:0,to:(t?t.length:1)-1}; - return null; -} - +/* ================= AGENT API: the command tables ================= + Every action in ACT is in exactly one class (tests/mcp-commands.test.js fails otherwise, so a new action forces a + decision): API_CMD, a game command with typed arguments; API_VIEW, which changes only what is on screen; API_BOUND, + which only drafts an input another command reads; API_SESSION, which starts, retries or leaves a game or dismisses a + coaching screen; or API_DENY, never run by a tool. CMD fields: args [name, domain|'string'|'boolean'|'integer', + required]; bind(args) writes the UI a panel would set (bindsUI: the UI keys it touches, restored after a dry run); + open/dom: the window an input lives in and the fields that must exist before dispatch; pass(args) reshapes the args + for the action (confirmations); confirm 'arg' (passed through) or 'double' (the game arms a button first); decides + (may end in a question); reads 'modal' (the window's text is the report); watch (extra fingerprint paths, #name + filled from args); quote (the dry run, priced with the game's own helpers); doc. */ const API_CMD={ downIx:{args:[['city','ixId']],watch:['ixp'],doc:'Step an exchange port down one size.'}, downT:{args:[['id','entityId']],watch:['transit.#id'],doc:'Step a transit port down one size (a LAG steps down together).'}, @@ -615,7 +513,9 @@ const API_BOUND={ }; /* Starting, retrying and leaving scenarios, puzzles and architect runs, and the screens a player dismisses. They run - as their buttons run them; new_game, load_save and export_save are the other half of the session (mcp-page.js). */ + as their buttons run them; new_game, load_save and export_save are the other half of the session, and exist only in + the MCP server's own page (scripts/lib/mcp-headless.js). In the player's tab the player owns the game, so the ones + that replace or leave it are refused there (API_PLAYER_OWNS). */ const API_SESSION={ startScn:{args:[['id','scnId']],doc:'Start a scenario (ids from catalog SCN), replacing the current game.'}, startWeekly:{args:[],doc:'Start this week\'s weekly scenario, replacing the current game. The week follows the real date.'}, @@ -628,200 +528,22 @@ const API_SESSION={ pitchSkip:{args:[],doc:'Skip the opening pitch; a game waiting behind it starts.'}, tutSkip:{args:[],doc:'Skip the tutorial coaching.'}, }; +// Session actions that would replace or leave the game in the player's tab: refused over the relay. +const API_OWN_WHY='the game in this tab is the player\'s: only the player starts, loads or leaves one'; +const API_PLAYER_OWNS={startScn:1,startWeekly:1,pzStart:1,pzWeekly:1,pzArStart:1,pzRetry:1,pzLeave:1}; -const API_STATE_DOC={ - v:{type:'integer',doc:'Save format version.'}, - name:{type:'string',doc:'Your network\'s name.'}, - asn:{type:'integer',doc:'Your AS number.'}, - home:{type:'string',doc:'The city you started in.'}, - day:{type:'integer',doc:'Days since the company was founded.'}, - cash:{type:'number',doc:'Cash on hand. Goes negative into the red; -100k is bankruptcy.'}, - priceMul:{type:'number',doc:'Multiplier on transit prices (weekly modifier).'}, - mode:{type:'string',doc:'normal | sandbox | scenario | puzzle.'}, - rules:{type:'map',doc:'The rules this network locked in at its door: preset (soft, freeze, oncall, bgp, sandbox or puzzle), the chaos dial, lead times, the market, and the Best Effort extras (sea, confs, broke, moods, pnis), which are only written where they differ from the classic game. They stay for the network\'s whole life.'}, - charter:{type:'string',doc:'The charter picked in the first month of a normal game: global | boutique.'}, - chartSet:{type:'boolean',doc:'The charter has been picked; false while the choice is still open.'}, - solWon:{type:'integer',doc:'The day the Speed of Light win landed (boutique charter), or 0.'}, - lvl:{type:'integer',doc:'Customer level (unlocks customer types).'}, - ltv:{type:'integer',doc:'Level at which Tier 1 vendors were visible (title-screen pick).'}, - t1v:{type:'integer',doc:'Level at which Tier 1 transit was offered.'}, - auV:{type:'integer',doc:'Australia content level gate.'}, - seen:{type:'array',doc:'Network ids the deals panel has already shown. Vestigial: written by newGame, read nowhere.'}, - pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site.'}, - links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables and fabric circuits (vxc), each with an entity id.'}, - transit:{type:'array',doc:'Transit ports: city, net, tier, LAG members, port history for 95th-percentile billing.'}, - ixp:{type:'map',doc:'IX ports by exchange city; tier per port (may exceed 1 with LAG members in ixn).'}, - rs:{type:'map',doc:'Route-server sessions by exchange city.'}, - ixn:{type:'map',doc:'LAG members on IX ports by exchange city.'}, - ixSite:{type:'map',doc:'Which building each IX port sits in (a, b or ab).'}, - ixPref:{type:'map',doc:'Egress preference per IX port.'}, - myIx:{type:'map',doc:'Exchanges you founded: name, members, join schedule, fabric step.'}, - peers:{type:'map',doc:'Peering sessions, keyed "net@ix".'}, - pairMet:{type:'map',doc:'Routing metric per city pair (prefer/avoid/backup/normal), keyed by pair.'}, - pni:{type:'array',doc:'Private interconnects: city, net, tier, ready day, augments (up), LAG, sacrificial flag.'}, - caches:{type:'array',doc:'CDN cache boxes: city, net, building.'}, - nni:{type:'array',doc:'Fabric ports: city, provider, tier.'}, - biz:{type:'array',doc:'Signed customers: type, cities, bandwidth, rate, mood, contract dates.'}, - offers:{type:'array',doc:'Pending customer offers, each expiring on a day.'}, - done:{type:'map',doc:'Goals landed, by goal id → day.'}, - ach:{type:'map',doc:'Badges earned this game, by badge id → day.'}, - inc:{type:'array',doc:'Open incidents: type, what they hit, until when, optional rush-repair price.'}, - ddosStarts:{type:'array',doc:'The days the attacks of the last week started; at most 14 a week.'}, - ev:{type:'map',doc:'Live world events: the running DDoS, route leaks, fabric failures, price shocks.'}, - stats:{type:'map',doc:'Counters: incidents survived, loans taken, sharks, conferences attended, peak traffic…'}, - log:{type:'array',doc:'The NOC notification feed, newest first, capped at 60; identical notices within a minute fold with a count.'}, - nextFail:{type:'integer',doc:'The day the next failure fires.'}, - nextEvent:{type:'integer',doc:'The day the next world event fires.'}, - rng:{type:'integer',doc:'The scenario seed; it predicts every future random draw.'}, - usedNames:{type:'array',doc:'Customer names already handed out.'}, - spares:{type:'map',doc:'Spare optics on the shelf, by optic id.'}, - scrubs:{type:'array',doc:'Scrubbing centres: city and tier.'}, - scrubMode:{type:'string',doc:'always | ondemand.'}, - cnLic:{type:'map',doc:'Mainland China licence: none | pending (with ready day) | ok.'}, - ppol:{type:'string',doc:'Your published peering policy: open | selective | closed.'}, - pdesk:{type:'map',doc:'This week\'s peering desk summary: sessions accepted and declined at which exchanges.'}, - pdeskRep:{type:'map',doc:'Last week\'s peering desk summary, as the NOC log reported it.'}, - ops:{type:'map',doc:'The NOC intern: who is hired, each standing order\'s on/off switch and settings, the monthly budget and what it spent, per-POP exceptions, the new-POP template and the weekly log.'}, - core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, - ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, - popStd:{type:'map',doc:'The standard POP: router model and count new POPs start with, or null for none.'}, - demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, - seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'}, - monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'}, - fleet:{type:'map',doc:'Cable-ship voyages by ship id: the cut it sails to, when it arrives, splices and comes home.'}, - achP:{type:'map',doc:'Which rule set each badge was earned under (oncall, freeze, bgp), by badge id.'}, - calV:{type:'integer',doc:'Calendar save-format marker: 1 once the real calendar (28-31-day months) applies.'}, - pz:{type:'map',doc:'The running puzzle: its id, cities, flows to deliver, budget and stars.'}, - ar:{type:'map',doc:'The running architect run: its HQ, brief index, gold sites, spend and the build it started from.'}, - loans:{type:'array',doc:'Active loans: bank, balance, APR, term, share (equity banks).'}, - loanOffers:{type:'array',doc:'Pending loan offers.'}, - loanStrikes:{type:'integer',doc:'How many loan offers you have let lapse.'}, - confReg:{type:'map',doc:'Conferences registered for, by key; "sp" when sponsoring.'}, - hw:{type:'map',doc:'Hardware market: price shocks and any price lock.'}, - capDeal:{type:'map',doc:'The pending capacity deal from a capacity conference.'}, - cam:{type:'map',doc:'Map camera position. View state that save() happens to store inside S.'}, - uiSpeed:{type:'number',doc:'The speed you left the game at. View state that save() stores inside S.'}, - won:{type:'boolean',doc:'You reached Tier 1.'}, - t1Now:{type:'boolean',doc:'Tier 1 right now, as of the last day; falling out of it is announced.'}, - lost:{type:'boolean',doc:'The bank repossessed the routers.'}, - neg:{type:'integer',doc:'Days in the red in a row.'}, - hist:{type:'array',doc:'Daily history for the graphs: demand, served, exit split, revenue, cost, cash.'}, - scn:{type:'map',doc:'The running scenario: id, rules, day limit, done/failed, and the day of the next scripted attack (nextDdos).'}, - dk:{type:'map',doc:'De-Kicks state: per-exchange multipliers, add-ons, retention, the live quote (q) and the remembered one (lastQ).'}, - grace:{type:'map',doc:'Courtesy transit after a merger wave, until a day.'}, - merged:{type:'map',doc:'Networks merged into others this game.'}, - tut:{type:'map',doc:'Tutorial progress.'}, - conf:{type:'map',doc:'The conference glow: region and until when; sp when you sponsored.'}, - phpDone:{type:'boolean',doc:'One-shot flag.'}, - krExit:{type:'map',doc:'Korea exit state.'}, - auNews:{type:'boolean',doc:'One-shot flag: the Australia news toast.'}, - richTold:{type:'boolean',doc:'One-shot flag: the cash milestone toast.'}, +/* Actions no tool runs, by reason: files, storage slots, settings and the title screen are not the game's, and time + moves only through advance (or the page's own clock). */ +const API_WHY={ + time:'use advance to move time, or wait when the clock runs on its own',start:'use new_game',files:'use load_save or export_save', + slots:'saved networks in browser storage are not part of this game',prefs:'device and player settings are not part of the game', + browser:'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)', }; - -const API_RESULTS_DOC={ - nt:{type:'map',doc:'Traffic per network through transit, by net id.'}, - tNet:{type:'map',doc:'Traffic per network you hand to each upstream, by "net@upstream".'}, - reachNT:{type:'number',doc:'Networks reachable without transit.'}, - teBlack:{type:'number',doc:'Traffic blackholed by RouteScript rules.'}, - teMoved:{type:'number',doc:'Traffic Auto-TE spilled onto alternate paths.'}, - egT:{type:'map',doc:'Egress split by exit kind (c/p/ix/t/l2) in Gbps.'}, - egDesc:{type:'map',doc:'RouteScript drains per exit.'}, - netEg:{type:'map',doc:'Per-network egress split: which exit carries which network.'}, - ef:{type:'map',doc:'LAZY per-link exit breakdown: what crosses each link, per network, built only when a panel asks. What is in here depends on which panels have rendered.'}, - l2:{type:'map',doc:'Layer-2 traffic per customer (L2VPN, SD-WAN, waves).'}, - l2lat:{type:'map',doc:'Latency per L2 customer.'}, - l2route:{type:'map',doc:'Which path an L2 customer\'s traffic takes.'}, - l2split:{type:'map',doc:'L2 traffic split per path.'}, - nodeLoad:{type:'map',doc:'Router forwarding load per city.'}, - nodeCap:{type:'map',doc:'Router forwarding capacity per city.'}, - div:{type:'map',doc:'Traffic diversity per customer (how split their paths are).'}, - gfwLost:{type:'number',doc:'Traffic lost to the Great Firewall.'}, - gfwCross:{type:'number',doc:'Traffic crossing into mainland China.'}, - p95:{type:'map',doc:'95th-percentile transit readings per port.'}, - peered:{type:'number',doc:'Share of traffic that stays on peering.'}, - peerShare:{type:'number',doc:'Fraction of traffic served by peers (mood driver).'}, - load:{type:'map',doc:'Load per link in Gbps.'}, - useT:{type:'map',doc:'Transit use per port id.'}, - useIx:{type:'map',doc:'IX use per exchange city.'}, - usePni:{type:'map',doc:'PNI use per port id.'}, - useCache:{type:'map',doc:'Cache use per box id.'}, - cityDem:{type:'map',doc:'Eyeball + customer demand per city.'}, - citySrv:{type:'map',doc:'Traffic served per city.'}, - cityEye:{type:'map',doc:'Eyeballs online per city.'}, - latF:{type:'map',doc:'Fraction of each city\'s traffic that goes far (over a threshold latency).'}, - latFar:{type:'map',doc:'The far exit each slow city sends traffic through.'}, - demTo:{type:'map',doc:'Your traffic destined to each network, in Gbps. The number CDN caches ask about.'}, - served:{type:'number',doc:'Total traffic served, in Gbps.'}, - demand:{type:'number',doc:'Total traffic demanded, in Gbps.'}, - reach:{type:'number',doc:'Fraction of the internet you can reach (0..1).'}, - sessions:{type:'number',doc:'Peering sessions up.'}, - revMo:{type:'number',doc:'Revenue per month.'}, - costMo:{type:'number',doc:'Cost per month.'}, - cost:{type:'map',doc:'Monthly cost by category (transit, pni, ix, links…).'}, - rev:{type:'map',doc:'Monthly revenue by source.'}, - reachable:{type:'map',doc:'Networks reachable per net id.'}, - cone:{type:'map',doc:'Which peer\'s customer cone carries each network you reach without transit of your own, by net id.'}, - ddos:{type:'array',doc:'Per live attack: the target, its size, which ports it fills, what Flowspec and each scrubbing centre cleaned, and what reaches the target.'}, - haul:{type:'array',doc:'Scrubbing detours: from the attacked city to each centre, one-way latency and how much they carry.'}, - tgtF:{type:'map',doc:'The share of a targeted customer\'s traffic that survives the attack, by customer id.'}, - bbF:{type:'map',doc:'The share of a city\'s broadband subscribers that survive an attack on them, by city id.'}, - fsUse:{type:'map',doc:'Flowspec rules in use per city: used of the routers\' rule capacity.'}, - bizDem:{type:'map',doc:'Business customers\' share of each city\'s demand, in Gbps (what RouteScript\'s protect customers serves first).'}, - bizSrv:{type:'map',doc:'Of that business demand, what was served, per city.'}, - graceNets:{type:'number',doc:'Networks reached over the courtesy route after a merger wave.'}, - cityBlocked:{type:'map',doc:'Set up per city by the traffic computation; nothing fills it at present.'}, - ddosHot:{type:'map',doc:'Cities whose ports a flood is filling, for the map\'s pulse. Keyed by city id.'}, +const API_DENY={ + speed:'time',phonePlay:'time',phoneSpeed:'time', + start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start', + exportSave:'files',importGo:'files',importPick:'files',slotExport:'files', + slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots', + animSet:'prefs',langSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',vpSet:'prefs', + install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser', }; - -/* One arg of a spec as the schema states it: the domain when there is one (catalog() resolves - it), the bare type otherwise, and the concrete value list or range where it is fixed. */ -function apiArgSpec([name,dom,req]){ - const a={name,required:req!==false}; - if(API_DOMAINS[dom])a.domain=dom;else a.type=dom; - const v=apiDomValues(dom); - if(Array.isArray(v))a.values=v;else if(v&&v.from!==undefined)a.range=v; - return a;} - -/* Dotted subtrees, no wildcards. An array walks by index (`biz.3`) or by entity id (`links[#id]`). */ -function apiPath(o,p){ - if(p===undefined||p===null||p==='')return o; - let v=o; - for(const k of String(p).split('.')){ - if(v==null)return undefined; - if(Array.isArray(v)){const i=Number(k); - v=(Number.isInteger(i)&&String(i)===k&&i>=0&&ix&&typeof x==='object'&&x.id===k);} - else if(v instanceof Set)v=[...v]; - else if(v instanceof Map)v=Object.fromEntries(v); - else if(typeof v==='object')v=v[k]; - else return undefined;} - return v;} - -function apiJson(v){ - if(v instanceof Set)return [...v].map(apiJson); - if(v instanceof Map)return apiJson(Object.fromEntries(v)); - if(v&&typeof v==='object')return Array.isArray(v)?v.map(apiJson):Object.fromEntries(Object.entries(v).map(([k,x])=>[k,apiJson(x)])); - if(typeof v==='function')return undefined; - return v;} - -/* The tables the argument domains point at. Everything is a static reference except three, - each computed for a reason: BADGES hides unearned secrets like the badge wall; conferences - carries the keys confGo/confSponsor need, which exist in no field of S; TE_RECIPES renders - each recipe's script, because the source is a function and some read the live network. The - recipes' relevance score is not exposed: judging which one fits is the agent's job. */ -const API_TABLES={CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; -const API_MADE={ - BADGES:()=>!S?[]:BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!hof()[b.id]; - return b.secret&&!on&&!ever?{id:b.id,i:'❔',t:'???',d:tr('badges.a_secret_badge'),r:b.r,secret:true}:{...b,ever};}), - conferences:()=>!S?[]:upcomingConfs(75).map(cf=>({key:cf.key,name:cf.n,city:cf.c,day:cf.day,capacity:!!cf.cap,cost:confCost(cf),sponsorCost:confSp(cf)?CONF_SP:null})), - TE_RECIPES:()=>!S?[]:TE_RECIPES.map(r=>({id:r.id,name:tr(r.n),description:tr(r.d),script:r.src().join('\n')})), -}; -function API_CATALOG_TABLE(name){return name in API_MADE?API_MADE[name]():API_TABLES[name];} - -/* UI minus the render caches and pointer scratch, which are inputs to nothing. - Everything a command binds (pending, route, via, dfSrc, dfSys, seaDesign, cnPrem, decom, - teDraft, confirm) stays, so an agent can see what it was given. */ -const API_UI_HIDDEN={_lh:1,_ph:1,_tb:1,_layer:1,layerAt:1,hover:1,drag:1,snap:1}; - -return {API_DOMAINS,API_CMD,API_VIEW,API_BOUND,API_SESSION,API_STATE_DOC,API_RESULTS_DOC,API_TABLES,API_MADE,API_UI_HIDDEN, - apiDomCheck,apiDomValues,apiArgSpec,apiPath,apiJson}; -})(); diff --git a/src/agent/30-docs.js b/src/agent/30-docs.js new file mode 100644 index 0000000..72af161 --- /dev/null +++ b/src/agent/30-docs.js @@ -0,0 +1,154 @@ +/* ================= AGENT API: what the state and the results hold ================= + One line per field of S and of R (tests/mcp-commands.test.js fails on a field without one). */ +const API_STATE_DOC={ + v:{type:'integer',doc:'Save format version.'}, + name:{type:'string',doc:'Your network\'s name.'}, + asn:{type:'integer',doc:'Your AS number.'}, + home:{type:'string',doc:'The city you started in.'}, + day:{type:'integer',doc:'Days since the company was founded.'}, + cash:{type:'number',doc:'Cash on hand. Goes negative into the red; -100k is bankruptcy.'}, + priceMul:{type:'number',doc:'Multiplier on transit prices (weekly modifier).'}, + mode:{type:'string',doc:'normal | sandbox | scenario | puzzle.'}, + rules:{type:'map',doc:'The rules this network locked in at its door: preset (soft, freeze, oncall, bgp, sandbox or puzzle), the chaos dial, lead times, the market, and the Best Effort extras (sea, confs, broke, moods, pnis), which are only written where they differ from the classic game. They stay for the network\'s whole life.'}, + charter:{type:'string',doc:'The charter picked in the first month of a normal game: global | boutique.'}, + chartSet:{type:'boolean',doc:'The charter has been picked; false while the choice is still open.'}, + solWon:{type:'integer',doc:'The day the Speed of Light win landed (boutique charter), or 0.'}, + lvl:{type:'integer',doc:'Customer level (unlocks customer types).'}, + ltv:{type:'integer',doc:'Level at which Tier 1 vendors were visible (title-screen pick).'}, + t1v:{type:'integer',doc:'Level at which Tier 1 transit was offered.'}, + auV:{type:'integer',doc:'Australia content level gate.'}, + seen:{type:'array',doc:'Network ids the deals panel has already shown. Vestigial: written by newGame, read nowhere.'}, + pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site.'}, + links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables and fabric circuits (vxc), each with an entity id.'}, + transit:{type:'array',doc:'Transit ports: city, net, tier, LAG members, port history for 95th-percentile billing.'}, + ixp:{type:'map',doc:'IX ports by exchange city; tier per port (may exceed 1 with LAG members in ixn).'}, + rs:{type:'map',doc:'Route-server sessions by exchange city.'}, + ixn:{type:'map',doc:'LAG members on IX ports by exchange city.'}, + ixSite:{type:'map',doc:'Which building each IX port sits in (a, b or ab).'}, + ixPref:{type:'map',doc:'Egress preference per IX port.'}, + myIx:{type:'map',doc:'Exchanges you founded: name, members, join schedule, fabric step.'}, + peers:{type:'map',doc:'Peering sessions, keyed "net@ix".'}, + pairMet:{type:'map',doc:'Routing metric per city pair (prefer/avoid/backup/normal), keyed by pair.'}, + pni:{type:'array',doc:'Private interconnects: city, net, tier, ready day, augments (up), LAG, sacrificial flag.'}, + caches:{type:'array',doc:'CDN cache boxes: city, net, building.'}, + nni:{type:'array',doc:'Fabric ports: city, provider, tier.'}, + biz:{type:'array',doc:'Signed customers: type, cities, bandwidth, rate, mood, contract dates.'}, + offers:{type:'array',doc:'Pending customer offers, each expiring on a day.'}, + done:{type:'map',doc:'Goals landed, by goal id → day.'}, + ach:{type:'map',doc:'Badges earned this game, by badge id → day.'}, + inc:{type:'array',doc:'Open incidents: type, what they hit, until when, optional rush-repair price.'}, + ddosStarts:{type:'array',doc:'The days the attacks of the last week started; at most 14 a week.'}, + ev:{type:'map',doc:'Live world events: the running DDoS, route leaks, fabric failures, price shocks.'}, + stats:{type:'map',doc:'Counters: incidents survived, loans taken, sharks, conferences attended, peak traffic…'}, + log:{type:'array',doc:'The NOC notification feed, newest first, capped at 60; identical notices within a minute fold with a count.'}, + nextFail:{type:'integer',doc:'The day the next failure fires.'}, + nextEvent:{type:'integer',doc:'The day the next world event fires.'}, + rng:{type:'integer',doc:'The scenario seed; it predicts every future random draw.'}, + usedNames:{type:'array',doc:'Customer names already handed out.'}, + spares:{type:'map',doc:'Spare optics on the shelf, by optic id.'}, + scrubs:{type:'array',doc:'Scrubbing centres: city and tier.'}, + scrubMode:{type:'string',doc:'always | ondemand.'}, + cnLic:{type:'map',doc:'Mainland China licence: none | pending (with ready day) | ok.'}, + ppol:{type:'string',doc:'Your published peering policy: open | selective | closed.'}, + pdesk:{type:'map',doc:'This week\'s peering desk summary: sessions accepted and declined at which exchanges.'}, + pdeskRep:{type:'map',doc:'Last week\'s peering desk summary, as the NOC log reported it.'}, + ops:{type:'map',doc:'The NOC intern: who is hired, each standing order\'s on/off switch and settings, the monthly budget and what it spent, per-POP exceptions, the new-POP template and the weekly log.'}, + core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, + ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, + popStd:{type:'map',doc:'The standard POP: router model and count new POPs start with, or null for none.'}, + demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, + seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'}, + monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'}, + fleet:{type:'map',doc:'Cable-ship voyages by ship id: the cut it sails to, when it arrives, splices and comes home.'}, + achP:{type:'map',doc:'Which rule set each badge was earned under (oncall, freeze, bgp), by badge id.'}, + calV:{type:'integer',doc:'Calendar save-format marker: 1 once the real calendar (28-31-day months) applies.'}, + pz:{type:'map',doc:'The running puzzle: its id, cities, flows to deliver, budget and stars.'}, + ar:{type:'map',doc:'The running architect run: its HQ, brief index, gold sites, spend and the build it started from.'}, + loans:{type:'array',doc:'Active loans: bank, balance, APR, term, share (equity banks).'}, + loanOffers:{type:'array',doc:'Pending loan offers.'}, + loanStrikes:{type:'integer',doc:'How many loan offers you have let lapse.'}, + confReg:{type:'map',doc:'Conferences registered for, by key; "sp" when sponsoring.'}, + hw:{type:'map',doc:'Hardware market: price shocks and any price lock.'}, + capDeal:{type:'map',doc:'The pending capacity deal from a capacity conference.'}, + cam:{type:'map',doc:'Map camera position. View state that save() happens to store inside S.'}, + uiSpeed:{type:'number',doc:'The speed you left the game at. View state that save() stores inside S.'}, + won:{type:'boolean',doc:'You reached Tier 1.'}, + t1Now:{type:'boolean',doc:'Tier 1 right now, as of the last day; falling out of it is announced.'}, + lost:{type:'boolean',doc:'The bank repossessed the routers.'}, + neg:{type:'integer',doc:'Days in the red in a row.'}, + hist:{type:'array',doc:'Daily history for the graphs: demand, served, exit split, revenue, cost, cash.'}, + scn:{type:'map',doc:'The running scenario: id, rules, day limit, done/failed, and the day of the next scripted attack (nextDdos).'}, + dk:{type:'map',doc:'De-Kicks state: per-exchange multipliers, add-ons, retention, the live quote (q) and the remembered one (lastQ).'}, + grace:{type:'map',doc:'Courtesy transit after a merger wave, until a day.'}, + merged:{type:'map',doc:'Networks merged into others this game.'}, + tut:{type:'map',doc:'Tutorial progress.'}, + conf:{type:'map',doc:'The conference glow: region and until when; sp when you sponsored.'}, + phpDone:{type:'boolean',doc:'One-shot flag.'}, + krExit:{type:'map',doc:'Korea exit state.'}, + auNews:{type:'boolean',doc:'One-shot flag: the Australia news toast.'}, + richTold:{type:'boolean',doc:'One-shot flag: the cash milestone toast.'}, +}; + +const API_RESULTS_DOC={ + nt:{type:'map',doc:'Traffic per network through transit, by net id.'}, + tNet:{type:'map',doc:'Traffic per network you hand to each upstream, by "net@upstream".'}, + reachNT:{type:'number',doc:'Networks reachable without transit.'}, + teBlack:{type:'number',doc:'Traffic blackholed by RouteScript rules.'}, + teMoved:{type:'number',doc:'Traffic Auto-TE spilled onto alternate paths.'}, + egT:{type:'map',doc:'Egress split by exit kind (c/p/ix/t/l2) in Gbps.'}, + egDesc:{type:'map',doc:'RouteScript drains per exit.'}, + netEg:{type:'map',doc:'Per-network egress split: which exit carries which network.'}, + ef:{type:'map',doc:'LAZY per-link exit breakdown: what crosses each link, per network, built only when a panel asks. What is in here depends on which panels have rendered.'}, + l2:{type:'map',doc:'Layer-2 traffic per customer (L2VPN, SD-WAN, waves).'}, + l2lat:{type:'map',doc:'Latency per L2 customer.'}, + l2route:{type:'map',doc:'Which path an L2 customer\'s traffic takes.'}, + l2split:{type:'map',doc:'L2 traffic split per path.'}, + nodeLoad:{type:'map',doc:'Router forwarding load per city.'}, + nodeCap:{type:'map',doc:'Router forwarding capacity per city.'}, + div:{type:'map',doc:'Traffic diversity per customer (how split their paths are).'}, + gfwLost:{type:'number',doc:'Traffic lost to the Great Firewall.'}, + gfwCross:{type:'number',doc:'Traffic crossing into mainland China.'}, + p95:{type:'map',doc:'95th-percentile transit readings per port.'}, + peered:{type:'number',doc:'Share of traffic that stays on peering.'}, + peerShare:{type:'number',doc:'Fraction of traffic served by peers (mood driver).'}, + load:{type:'map',doc:'Load per link in Gbps.'}, + useT:{type:'map',doc:'Transit use per port id.'}, + useIx:{type:'map',doc:'IX use per exchange city.'}, + usePni:{type:'map',doc:'PNI use per port id.'}, + useCache:{type:'map',doc:'Cache use per box id.'}, + cityDem:{type:'map',doc:'Eyeball + customer demand per city.'}, + citySrv:{type:'map',doc:'Traffic served per city.'}, + cityEye:{type:'map',doc:'Eyeballs online per city.'}, + latF:{type:'map',doc:'Fraction of each city\'s traffic that goes far (over a threshold latency).'}, + latFar:{type:'map',doc:'The far exit each slow city sends traffic through.'}, + demTo:{type:'map',doc:'Your traffic destined to each network, in Gbps. The number CDN caches ask about.'}, + served:{type:'number',doc:'Total traffic served, in Gbps.'}, + demand:{type:'number',doc:'Total traffic demanded, in Gbps.'}, + reach:{type:'number',doc:'Fraction of the internet you can reach (0..1).'}, + sessions:{type:'number',doc:'Peering sessions up.'}, + revMo:{type:'number',doc:'Revenue per month.'}, + costMo:{type:'number',doc:'Cost per month.'}, + cost:{type:'map',doc:'Monthly cost by category (transit, pni, ix, links…).'}, + rev:{type:'map',doc:'Monthly revenue by source.'}, + reachable:{type:'map',doc:'Networks reachable per net id.'}, + cone:{type:'map',doc:'Which peer\'s customer cone carries each network you reach without transit of your own, by net id.'}, + ddos:{type:'array',doc:'Per live attack: the target, its size, which ports it fills, what Flowspec and each scrubbing centre cleaned, and what reaches the target.'}, + haul:{type:'array',doc:'Scrubbing detours: from the attacked city to each centre, one-way latency and how much they carry.'}, + tgtF:{type:'map',doc:'The share of a targeted customer\'s traffic that survives the attack, by customer id.'}, + bbF:{type:'map',doc:'The share of a city\'s broadband subscribers that survive an attack on them, by city id.'}, + fsUse:{type:'map',doc:'Flowspec rules in use per city: used of the routers\' rule capacity.'}, + bizDem:{type:'map',doc:'Business customers\' share of each city\'s demand, in Gbps (what RouteScript\'s protect customers serves first).'}, + bizSrv:{type:'map',doc:'Of that business demand, what was served, per city.'}, + graceNets:{type:'number',doc:'Networks reached over the courtesy route after a merger wave.'}, + cityBlocked:{type:'map',doc:'Set up per city by the traffic computation; nothing fills it at present.'}, + ddosHot:{type:'map',doc:'Cities whose ports a flood is filling, for the map\'s pulse. Keyed by city id.'}, +}; + +/* The dice rather than the board: in the player's tab (over the relay) state never returns these, and schema says why. + The MCP server's own page returns them, for debugging. */ +const API_WITHHELD={ + rng:'the seed: it predicts every future random draw', + nextFail:'the day the next failure fires', + nextEvent:'the day the next world event fires', + 'scn.nextDdos':'the day of the next scripted attack in a scenario', +}; diff --git a/src/agent/40-read.js b/src/agent/40-read.js new file mode 100644 index 0000000..38afbe1 --- /dev/null +++ b/src/agent/40-read.js @@ -0,0 +1,230 @@ +/* ================= AGENT API: reading the game ================= + Every function takes and returns plain JSON and only reads the game. */ +/* Dotted subtrees, no wildcards. An array walks by index (`biz.3`) or by entity id (`links[#id]`). */ +function apiPath(o,p){ + if(p===undefined||p===null||p==='')return o; + let v=o; + for(const k of String(p).split('.')){ + if(v==null)return undefined; + if(Array.isArray(v)){const i=Number(k); + v=(Number.isInteger(i)&&String(i)===k&&i>=0&&ix&&typeof x==='object'&&x.id===k);} + else if(v instanceof Set)v=[...v]; + else if(v instanceof Map)v=Object.fromEntries(v); + else if(typeof v==='object')v=v[k]; + else return undefined;} + return v;} + +function apiJson(v){ + if(v instanceof Set)return [...v].map(apiJson); + if(v instanceof Map)return apiJson(Object.fromEntries(v)); + if(v&&typeof v==='object')return Array.isArray(v)?v.map(apiJson):Object.fromEntries(Object.entries(v).map(([k,x])=>[k,apiJson(x)])); + if(typeof v==='function')return undefined; + return v;} + +/* The tables the argument domains point at. Everything is a static reference except three, + each computed for a reason: BADGES hides unearned secrets like the badge wall; conferences + carries the keys confGo/confSponsor need, which exist in no field of S; TE_RECIPES renders + each recipe's script, because the source is a function and some read the live network. The + recipes' relevance score is not exposed: judging which one fits is the agent's job. */ +const API_TABLES={CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; +const API_MADE={ + BADGES:()=>!S?[]:BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!hof()[b.id]; + return b.secret&&!on&&!ever?{id:b.id,i:'❔',t:'???',d:tr('badges.a_secret_badge'),r:b.r,secret:true}:{...b,ever};}), + conferences:()=>!S?[]:upcomingConfs(75).map(cf=>({key:cf.key,name:cf.n,city:cf.c,day:cf.day,capacity:!!cf.cap,cost:confCost(cf),sponsorCost:confSp(cf)?CONF_SP:null})), + TE_RECIPES:()=>!S?[]:TE_RECIPES.map(r=>({id:r.id,name:tr(r.n),description:tr(r.d),script:r.src().join('\n')})), +}; +function API_CATALOG_TABLE(name){return name in API_MADE?API_MADE[name]():API_TABLES[name];} + +/* UI minus the render caches and pointer scratch, which are inputs to nothing. + Everything a command binds (pending, route, via, dfSrc, dfSys, seaDesign, cnPrem, decom, + teDraft, confirm) stays, so an agent can see what it was given. */ +const API_UI_HIDDEN={_lh:1,_ph:1,_tb:1,_layer:1,layerAt:1,hover:1,drag:1,snap:1}; + +/* ---------- text as a player reads it ---------- */ +const API_BLOCK=/^(DIV|P|H1|H2|H3|H4|SECTION|LI|UL|OL|TR|TABLE|NAV|HEADER|FOOTER|BUTTON|LABEL|DETAILS|SUMMARY)$/,API_MAX_TEXT=8000; +// One line per block, no runs of spaces. jsdom has no innerText, so this walks the nodes itself. +function apiFullText(x){ + 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;} + // A dropdown reads as its choice: hundreds of options would crowd out the rest (the catalog lists them). + if(n.tagName==='SELECT'){const o=n.options[n.selectedIndex];out.push(' ',o?o.text:'',' ');return;} + // Blocks get their own line; inline tags a space, so "Revenue$2k" does not read as one word. + const sep=API_BLOCK.test(n.tagName)?'\n':' '; + out.push(sep);for(const c of n.childNodes)walk(c);out.push(sep);}; + walk(el); + return out.join('').split('\n').map(l=>l.replace(/\s+/g,' ').replace(/ ([.,;:!?)])/g,'$1').replace(/\( /g,'(').trim()).filter(Boolean).join('\n');} +const apiText=(x,max=API_MAX_TEXT)=>{const s=apiFullText(x);return s.length>max?s.slice(0,max)+'\n…':s;}; +const apiR1=v=>typeof v==='number'&&isFinite(v)?Math.round(v*10)/10:v; +const apiFail=msg=>{throw new Error(msg);}; +const apiNorm=s=>String(s||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'').trim(); +const apiParse=s=>{try{return JSON.parse(s||'{}');}catch(e){return {};}}; + +/* ---------- finding things by id or by name ---------- */ +function apiBest(list,q,keys){const n=apiNorm(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(apiNorm(k))));if(hit)return hit;} + return null;} +const apiNetOf=q=>NET[q]||apiBest(NETS,q,n=>[n.id,n.name,'as'+n.asn,String(n.asn)])||apiFail(`No network matches "${q}". Try find.`); +const apiCityOf=q=>CITY[q]||apiBest(CITIES,q,c=>[c.id,c.name])||apiFail(`No city matches "${q}". Try find.`); +function apiAllIx(){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 apiCityName=c=>CITY[c]?CITY[c].name:c; +const apiIncText=i=>apiText(i.msg||incTitle(i),400); +const apiMyPops=()=>Object.keys(S.pops).map(apiCityName).join(', '); + +/* ---------- the network at a glance, and the world ---------- */ +function apiStatus(){ + const goal=GOALS.find(g=>S.done[g.id]===undefined),t1=isTier1(),k=o=>Object.fromEntries(Object.entries(o||{}).map(([a,v])=>[a,Math.round(v)]).filter(([,v])=>v)); + return { + name:S.name,asn:S.asn,home:apiCityName(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:apiText(t1Why()), + goal:goal?{title:apiText(goal.t),what:apiText(goal.d)}:null, + monthly:{revenue:Math.round(R.revMo),cost:Math.round(R.costMo),profit:Math.round(R.revMo-R.costMo),revenueBy:k(R.rev),costBy:k(R.cost)}, + traffic:{demandGbps:apiR1(R.demand),servedGbps:apiR1(R.served),reach:apiR1((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(apiCityName), + incidents:S.inc.map(i=>({id:i.id,type:i.type,what:apiIncText(i),until:i.until!==undefined?dateStr(i.until):undefined,rushRepairCost:i.cost||undefined})), + lost:!!S.lost,won:!!S.won, + };} + +function apiNetwork(q){ + const n=apiNetOf(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:apiR1(NSH[id]*100)+'%',transitPerGbps:n.price?apiR1(n.price*S.priceMul):null, + homeMarkets:n.cc?[].concat(n.cc):[],pops:n.pops.map(apiCityName), + 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:apiText(n.blurb), + you:{ + reachable:!!(R.reachable&&R.reachable[id]),demandGbps:apiR1((R.demTo&&R.demTo[id])||0), + egressGbps:eg?Object.fromEntries(Object.entries(eg).map(([k,v])=>[k,apiR1(v)])):null, + pnis:S.pni.filter(p=>p.net===id).map(p=>({id:p.id,city:apiCityName(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:apiText(offTransitHint(id,S.home)), + }, + };} + +function apiCity(q){ + const C=apiCityOf(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:apiCityName(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?apiText(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:apiR1(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:apiR1((R.cityDem||{})[c]||0),servedGbps:apiR1((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, + };} + +function apiFind(q,kind){ + const n=apiNorm(q),hit=(...k)=>k.some(v=>apiNorm(v).includes(n)),out={}; + if(!n)apiFail('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(apiCityName)})); + if(!kind||kind==='exchange')out.exchanges=apiAllIx().filter(x=>hit(x,ixName(x))).slice(0,20).map(x=>({id:x,name:ixName(x),city:apiCityName(ixCity(x))})); + return out;} + +function apiTrace(from,to){ + const src=apiCityOf(from).id; + if(!S.pops[src])apiFail(`You have no POP in ${apiCityName(src)}. Yours: ${apiMyPops()}.`); + let target=null; + if(typeof to==='string'&&/^city:/i.test(to))target={city:apiCityOf(to.slice(5)).id}; + else{try{target={net:apiNetOf(to).id};}catch(e){target={city:apiCityOf(to).id};}} + if(target.city&&!S.pops[target.city])apiFail(`A traceroute to a city goes to one of your POPs: ${apiMyPops()}.`); + const r=traceroute(src,target); + return {text:r.text,why:apiText(r.why||''),asPath:r.asPath||null};} + +function apiPeering(q,where,via){ + const n=apiNetOf(q),id=n.id,out=[]; + if(!via||via==='pni')for(const c of (where?[apiCityOf(where).id]:Object.keys(S.pops).filter(c=>n.pops.includes(c)))){ + const r=peerOk(id,'pni',c); + out.push({via:'pni',city:apiCityName(c),ok:!!r.ok,why:r.why?apiText(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)===apiCityOf(where).id))){ + const r=peerOk(id,'ix',x); + out.push({via:'ix',exchange:ixName(x),ok:!!r.ok,why:r.why?apiText(r.why):undefined,session:ixSessions(x).has(id)});} + return {network:n.name,policy:n.pol,hint:apiText(offTransitHint(id,where?apiCityOf(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.'};} + +function apiHotSpots(limit=10){ + const top=a=>a.sort((x,y)=>y.util-x.util).slice(0,limit),pct=(u,c)=>c>0?apiR1((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:apiCityName(l.a)+' – '+apiCityName(l.b),kind:l.kind,capacity:capName(l),usedGbps:apiR1(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:apiCityName(t.city),carrier:NET[t.net].name,port:lagName(t.tier,t.n),usedGbps:apiR1(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:apiCityName(p.city),port:pniPN(p),usedGbps:apiR1(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:apiR1(R.netEg[n.id].t),howToPeer:apiText(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};} + +/* ---------- the contract: commands, arguments, reference tables, raw state ---------- */ +const apiDenied=name=>own(API_DENY,name)?API_WHY[API_DENY[name]]:null; +const apiKind=name=>API_CMD[name]?'game':API_VIEW[name]?'view':API_BOUND[name]?'draft':API_SESSION[name]?'session':null; +const apiSpec=name=>API_CMD[name]||API_VIEW[name]||API_SESSION[name]||null; +const apiClasses=()=>({game:Object.keys(API_CMD),view:Object.keys(API_VIEW),draft:Object.keys(API_BOUND),session:Object.keys(API_SESSION),denied:Object.keys(API_DENY)}); + +// One argument as the schema states it. Table domains name their catalog table rather than list every id. +function apiArgDoc([name,dom,req]){ + const a={name,required:req!==false},d=API_DOMAINS[dom]; + if(!d){a.type=dom;return a;} + a.domain=dom; + if(d.table)a.from=d.table; + else{const v=apiDomValues(dom);if(Array.isArray(v))a.values=v;else if(v&&v.from!==undefined)a.range=v;} + return a;} +function apiSchema(section){ + const cmd=s=>({args:(s.args||[]).map(apiArgDoc),doc:s.doc}),relay=API_CTX.relay; + const doc={ + mode:apiMode(), + clock:apiClockDoc(), + commands:Object.fromEntries(Object.entries(API_CMD).map(([n,s])=>[n,{...cmd(s),dryRun:!!s.quote, + ...(s.decides?{decides:true}:{}),...(s.confirm?{confirm:s.confirm}:{}),...(s.open?{opens:s.open}:{}),...(s.reads?{report:true}:{})}])), + view:Object.fromEntries(Object.entries(API_VIEW).map(([n,s])=>[n,cmd(s)])), + session:Object.fromEntries(Object.entries(API_SESSION).map(([n,s])=>[n,{...cmd(s),...(relay&&API_PLAYER_OWNS[n]?{refused:API_OWN_WHY}:{})}])), + drafts:API_BOUND, + denied:Object.fromEntries(Object.keys(API_DENY).sort().map(n=>[n,apiDenied(n)])), + domains:Object.fromEntries(Object.entries(API_DOMAINS).map(([n,d])=>{const v=apiDomValues(n); + return [n,{kind:d.kind==='fn'?'custom':d.kind,...(d.table?{from:d.table}:{}), + ...(!d.table&&Array.isArray(v)?{values:v}:v&&v.from!==undefined?{range:v}:v&&v.of?{of:v.of}:{})}];})), + state:relay?Object.fromEntries(Object.entries(API_STATE_DOC).map(([k,d])=>[k,API_WITHHELD[k]?{...d,withheld:API_WITHHELD[k]}:d])):API_STATE_DOC, + results:API_RESULTS_DOC, + }; + if(section===undefined||section===null||section==='')return doc; + if(!(section in doc))apiFail(`No section "${section}". Sections: ${Object.keys(doc).join(', ')}.`); + return doc[section];} +function apiCatalog(name){ + if(name===undefined||name===null||name===''){ + return {tables:[...Object.keys(API_TABLES),...Object.keys(API_MADE)].sort().map(k=>{const t=k in API_MADE?API_MADE[k]():API_TABLES[k]; + return {name:k,n:Array.isArray(t)?t.length:t&&typeof t==='object'?Object.keys(t).length:1};})};} + if(name in API_MADE)return apiJson(API_MADE[name]()); + if(name in API_TABLES)return apiJson(API_TABLES[name]); + apiFail(`No table "${name}". Call catalog without a name for the list.`);} +// In the player's tab the dice are held back: a withheld field, or one inside the subtree asked for, is left out. +function apiState(path){ + if(!S)return null; + const p=path===undefined||path===null?'':String(path),v=apiJson(apiPath(S,p)); + if(v===undefined)return null; + if(!API_CTX.relay)return v; + for(const w of Object.keys(API_WITHHELD)){ + if(w===p||p.startsWith(w+'.'))return null; + if(p&&!w.startsWith(p+'.'))continue; + const ks=(p?w.slice(p.length+1):w).split('.');let o=v; + for(let i=0;i(s.args||[]).map(a=>a[0]+(a[2]===false?'?':'')).join(','),typed={}; + for(const t of [API_CMD,API_VIEW,API_SESSION])for(const [n,s] of Object.entries(t))typed[n]=sig(s); + return {typed,drafts:Object.keys(API_BOUND)};} diff --git a/src/agent/50-screen.js b/src/agent/50-screen.js new file mode 100644 index 0000000..42503c6 --- /dev/null +++ b/src/agent/50-screen.js @@ -0,0 +1,79 @@ +/* ================= AGENT API: what is on screen ================= + The surfaces a player can read, as text with numbered buttons, by the name screen takes. The left drawer has tabs + (goals, deals, noc, nets). */ +const API_ROOT={modal:'modal',bank:'bankBox',dash:'dash',panel:'panel',left:'leftBody',puzzle:'pzBox'}; +const apiShown=w=>{const el=$(API_ROOT[w]);return !!el&&!el.hidden;}; +const apiModalOpen=()=>apiShown('modal'); +// A window the player opened by hand (API_MODAL.hand, 75-mode.js) is theirs: a tool reads it but never answers, +// closes or replaces it, and it is never a question the game is waiting on. +const apiPlayerWin=()=>apiModalOpen()&&API_MODAL.hand; +// The buttons of the last screen a tool read, for click. Set by apiScreen. +let API_LAST=[]; +function apiControls(root,player){ + const out=[]; + for(const b of root.querySelectorAll('[data-act],select[data-chg]')){ + const o=b.dataset.act?{label:apiText(b,200).replace(/\n/g,' ')||b.getAttribute('aria-label')||b.dataset.act,act:b.dataset.act,args:apiParse(b.dataset.args),disabled:!!b.disabled} + // A list the game acts on when its value changes (the change handler in 96-map/95-clicks.js): click it with a value. + :{label:b.getAttribute('aria-label')||(b.closest('label')&&apiText(b.closest('label'),120).split('\n')[0])||b.dataset.chg, + select:b.dataset.chg,value:b.value,options:[...b.options].map(o=>({value:o.value,label:o.textContent.trim()})),disabled:!!b.disabled}; + if(player)o.player=true; + out.push(o);} + return out;} +function apiScreen(where,offset=0){ + if(where===null)where=undefined; + if(where!==undefined&&!API_ROOT[where])apiFail(`where is one of ${Object.keys(API_ROOT).join(', ')}.`); + const open=Object.keys(API_ROOT).filter(w=>w!=='left'&&apiShown(w)); + const w=where||['modal','bank','dash','panel','puzzle'].find(apiShown)||'panel'; + const root=$(API_ROOT[w]),player=w==='modal'&&apiPlayerWin(); + API_LAST=root?apiControls(root,player):[]; + const all=root?apiFullText(root):'',from=Math.max(0,Math.floor(+offset)||0),more=all.length-from-API_MAX_TEXT; + const out={where:w,open,selected:UI.sel,tab:UI.tab}; + if(w==='left')out.leftTab=UI.left||'goals'; + if(w==='modal'){out.question=!!apiDecision();if(player)out.playerWindow='the player opened this window: read it, but its buttons are theirs to press';} + out.text=all.slice(from,from+API_MAX_TEXT); + if(from)out.textFrom=from; + if(more>0)out.textMore=`${more} more characters: call screen with where "${w}" and offset ${from+API_MAX_TEXT}`; + out.buttons=API_LAST.map((b,i)=>({n:i,...b})); + return out;} + +/* ---------- windows: the tool's own sheets, and the game's questions ---------- + A window the tool opened itself (a view, a draft, the link window, a sheet it clicked inside) is something to read + and click through. A window the game opened in answer to a game command, or during a day, is a question when one + of its buttons runs a game command other than closeModal (a De-Kicks quote, a retention offer); then other game + commands wait until it is answered or closed, as clicks outside an open window do in the game. */ +let API_SHEET=null; +const apiCard=()=>$('modalCard').firstChild; +const apiMarkSheet=()=>{API_SHEET=apiModalOpen()&&!apiPlayerWin()?apiCard():null;}; +const apiIsSheet=()=>apiModalOpen()&&!!API_SHEET&&apiCard()===API_SHEET; +function apiDecision(){ + if(!apiModalOpen()||apiIsSheet()||apiPlayerWin())return null; + const b=[...$('modal').querySelectorAll('[data-act]')].filter(x=>x.dataset.act!=='closeModal'&&API_CMD[x.dataset.act]); + if(!b.length)return null; + return {text:apiText($('modal'),1500),options:b.map(x=>({command:x.dataset.act,args:apiParse(x.dataset.args),label:apiText(x,120).replace(/\n/g,' ')}))};} + +/* A player's window stays where it is: its very nodes are set aside while a tool's command runs, and put back after, + so typed text survives. Only a question the game asks in answer to the tool's move takes the screen, as it would + after a click. */ +function apiHold(){const m=$('modal'),c=$('modalCard'); + return {nodes:[...c.childNodes],cls:m.className,aria:c.getAttribute('aria-modal'),setOpen:UI.setOpen,pending:UI.pending};} +function apiRestore(h){const m=$('modal'),c=$('modalCard'); + if(!m.hidden&&m.className===h.cls&&c.childNodes.length===h.nodes.length&&h.nodes.every((n,i)=>c.childNodes[i]===n)){API_MODAL.hand=true;return;} + m.className=h.cls;if(h.aria!==null)c.setAttribute('aria-modal',h.aria);c.replaceChildren(...h.nodes); + if(m.hidden)markLayer();m.hidden=false;UI.setOpen=h.setOpen;UI.pending=h.pending;API_MODAL.hand=true;API_SHEET=null;} + +function apiPanel({city:c,link,network:q,tab,left}={}){ + if(left!==undefined){if(!['goals','deals','noc','nets'].includes(left))apiFail('left is one of goals, deals, noc, nets.');ACT.leftTab({t:left});return apiScreen('left');} + if(c)UI.sel={type:'city',id:apiCityOf(c).id}; + else if(link){if(!S.links.some(l=>l.id===link))apiFail(`No link ${link}. See status or hot_spots for link ids.`);UI.sel={type:'link',id:link};} + else if(q)ACT.netFocus({id:apiNetOf(q).id}); + if(tab)UI.tab=tab; + renderAll(); + return apiScreen(q?'left':'panel');} +function apiOpenLink(a,b){ + const x=apiCityOf(a).id,y=apiCityOf(b).id; + if(!S.pops[x])apiFail(`A link starts at one of your POPs: ${apiMyPops()}.`); + if(apiPlayerWin())apiFail('The player has a window open, and the link window would replace it. Use act buildLink, orderDf or orderCable, or wait until it is closed.'); + apiTake(); + openLinkModal(x,y); + apiMarkSheet(); + return {toasts:apiToastLines(apiTake()),screen:apiScreen()};} diff --git a/src/agent/60-dispatch.js b/src/agent/60-dispatch.js new file mode 100644 index 0000000..94957fd --- /dev/null +++ b/src/agent/60-dispatch.js @@ -0,0 +1,122 @@ +/* ================= AGENT API: doing things ================= + One action, run as the game runs it, and reported through the game's own channels: what it said (toast), what it + charged at the money gate (spend) and whether anything changed (a fingerprint of S). The API checks shape and domain + only; whether a move is allowed is the game's to answer. */ + +// Arguments: shape and domain only. Anything beyond that is the game's to answer. +function apiValidate(spec,args){ + const problems=[],out={}; + for(const [name,dom,req] of spec.args||[]){ + const v=args[name]; + if(v===undefined){if(req!==false)problems.push(`${name} is required`);continue;} + if(apiDomCheck(dom,v).ok){out[name]=v;continue;} + const vs=apiDomValues(dom),d=API_DOMAINS[dom]; + problems.push(`${name}: ${JSON.stringify(v)} is not a ${dom}${d&&d.table&&d.kind==='id'?` (see catalog ${d.table} or find)`:Array.isArray(vs)?` (one of ${vs.slice(0,12).join(', ')}${vs.length>12?'…':''})`:vs&&typeof vs==='object'&&vs.from!==undefined?` (${vs.from}..${vs.to})`:''}`);} + for(const k of Object.keys(args))if(!(spec.args||[]).some(a=>a[0]===k))problems.push(`${k} is not an argument of this action`); + return {ok:!problems.length,problems,args:out};} + +// The fingerprint tells "did nothing" from "did something quietly": cash, day, the entity counts, the small settings +// maps, and the paths a command declares in watch. R is left out: it is rebuilt after every action. +const API_FP_LEN=['links','transit','pni','caches','biz','offers','nni','loans','loanOffers','inc','scrubs']; +const API_FP_KEYS=['pops','ixp','peers','myIx','done','ach','merged','confReg']; +const API_FP_JSON=['name','pairMet','rs','ixn','ixSite','ixPref','spares','te','cnLic','hw','scrubMode','ppol','ops','core','ddosAuto','popStd','demo','charter','monkey','seatOff','pz','ar','dk','ev']; +function apiFp(watch,args){ + if(!S)return null; + const f={cash:S.cash,day:S.day,lvl:S.lvl||1,won:!!S.won,lost:!!S.lost}; + for(const k of API_FP_LEN)f[k]=(S[k]||[]).length; + for(const k of API_FP_KEYS)f[k]=Object.keys(S[k]||{}).length; + for(const k of API_FP_JSON)f[k]=JSON.stringify(apiJson(S[k])??null); + for(const p of watch||[])f['@'+p]=JSON.stringify(apiJson(apiPath(S,String(p).replace(/#(\w+)/g,(m,k)=>args&&args[k]!==undefined?args[k]:m)))??null); + return JSON.stringify(f);} +// spend() is the game's money gate and a top-level function, so every action reaches it by its global name. +function apiMeter(){const real=window.spend;let paid=0;window.spend=c=>{const ok=real(c);if(ok)paid+=c;return ok;};return ()=>{window.spend=real;return paid;};} + +/* typed: through the command table (bind the UI, type into fields, pass the confirmation); otherwise as a button click + does it, with the button's own arguments. */ +function apiDispatch(name,kind,spec,args,typed){ + const mine=apiIsSheet()||(typed&&kind==='game'&&!!spec.open),held=apiPlayerWin()?apiHold():null; + apiTake(); + const ref=S,cash=S?S.cash:0,f0=apiFp(spec&&spec.watch,args),paid=apiMeter(); + let threw=null,report; + try{ + if(typed&&kind==='game'){ + if(spec.open){ACT[spec.open]({});apiMarkSheet();} + // The custom metric's field lives in the link's panel. + if(name==='metricSet'&&!$('metIn')){UI.sel={type:'link',id:args.id};renderAll();} + const gone=(spec.dom||[]).filter(f=>!$(f)); + if(gone.length)throw new Error(`the field it types into (${gone.join(', ')}) is not on screen${name==='metricSet'?': set the link\'s metric to custom first (setMetric v "custom")':''}`); + if(spec.bind)spec.bind(args); + const a=spec.pass?spec.pass(args):args; + ACT[name](a); + if(spec.confirm==='double')ACT[name](a); + if(spec.reads==='modal'&&apiModalOpen()&&!apiPlayerWin()){report=apiText($('modal'));closeModal();} + }else ACT[name](args); + }catch(e){threw=e;} + const charged=paid(); + if(held&&(threw||!apiDecision())){ + // The tool's own sheet is read before the player's window goes back over it. + const shot=!threw&&apiModalOpen()&&!apiPlayerWin()?apiScreen('modal'):null; + apiRestore(held); + if(shot)shot.note='The player has a window open, so this one was shown to you and closed again.'; + held.shot=shot;} + if(threw){apiTake();apiFail(`${name} failed: ${threw&&threw.message||threw}`);} + if(!apiModalOpen()||apiPlayerWin())API_SHEET=null; + else if(mine||kind!=='game')apiMarkSheet(); + else API_SHEET=null; + const said=apiTake(),d=apiDecision(); + const outcome=d?'decision':S!==ref||apiFp(spec&&spec.watch,args)!==f0||report!==undefined?'applied' + :said.some(t=>t.kind==='bad')?'rejected':kind==='view'||kind==='draft'?'shown':'no_effect'; + return {action:name,outcome,toasts:apiToastLines(said),charged,cashChange:Math.round((S?S.cash:0)-cash), + ...(report!==undefined?{report}:{}),...(d?{decision:d}:{}),screen:held&&held.shot||apiScreen()};} +// While the game waits for an answer, game commands other than its options report the question instead. +function apiWaiting(name){ + const d=apiDecision(); + return d&&name!=='closeModal'&&!d.options.some(o=>o.command===name) + ?{action:name,outcome:'decision',reason:'A window is waiting for an answer: run one of its options, or closeModal.',decision:d,screen:apiScreen()}:null;} +function apiQuote(name,spec,args){ + const ui0={}; + for(const k of spec.bindsUI||[])ui0[k]=UI[k]; + const f0=apiFp(spec.watch,args); + // A dry run must not use up the dice: some helpers draw (a PNI's lead time), and a draw here would move the seeded + // game. They get the middle of the range instead, so a drawn figure in a quote is a typical one. + const dice=Math.random; + Math.random=()=>0.5; + let q={}; + try{ + if(spec.bind&&!spec.dom)spec.bind(args); + if(spec.quote)q=spec.quote(args)||{}; + }catch(e){apiFail(`${name}: the price could not be worked out: ${e&&e.message||e}`);}finally{Math.random=dice;for(const k of Object.keys(ui0))UI[k]=ui0[k];} + return {action:name,outcome:'quote',quote:{setup:0,monthly:0,...q,blocked:(q.blocked||[]).map(b=>apiText(String(b),400))},consistent:apiFp(spec.watch,args)===f0, + ...(spec.quote?{}:{note:'This command has no price of its own: it costs nothing up front.'})};} +// Checks shared by act and click: what no tool runs, and what only the player runs in their own tab. +function apiAllowed(name,what){ + const no=apiDenied(name); + if(no)apiFail(`${name} is not available here: ${no}.`); + if(API_CTX.relay&&API_PLAYER_OWNS[name])apiFail(`${name} is not available here: ${API_OWN_WHY}.`); + const kind=apiKind(name); + if(!kind||typeof ACT[name]!=='function')apiFail(what); + return kind;} +function apiRun(name,args,opts={}){ + name=String(name||''); + if(name.startsWith('view.'))name=name.slice(5); + const kind=apiAllowed(name,`There is no action "${name}". See actions or schema.`); + args=args&&typeof args==='object'&&!Array.isArray(args)?args:{}; + const spec=apiSpec(name); + if(spec){const v=apiValidate(spec,args);if(!v.ok)apiFail(`${name}: ${v.problems.join('; ')}. See schema for its arguments.`);args=v.args;} + if(kind==='game'){ + if(S&&S.lost&&name!=='closeModal')return {action:name,outcome:'stopped',reason:'The network went bankrupt: start or load another game.'}; + const w=apiWaiting(name); + if(w)return w; + if(opts.dryRun)return apiQuote(name,spec,args); + }else if(opts.dryRun)apiFail(`${name} has no price: only game commands (see schema commands) dry-run.`); + return apiDispatch(name,kind,spec,args,true);} +function apiClick(n,value){ + const b=API_LAST[n]; + if(!b)apiFail(`No button ${n} on the last screen. Call screen first.`); + if(b.disabled)apiFail(`"${b.label}" is greyed out.`); + if(b.player&&apiPlayerWin())apiFail(`"${b.label}" is in a window the player opened: it is theirs to press.`); + const name=b.select||b.act,args=b.select?{v:value===undefined?undefined:String(value)}:b.args; + if(b.select&&!b.options.some(o=>o.value===args.v))apiFail(`"${b.label}" is a list: click it with a value, one of ${b.options.map(o=>JSON.stringify(o.value)).join(', ')}.`); + const kind=apiAllowed(name,`"${b.label}" runs ${name}, which is not an action.`); + if(kind==='game'){const w=apiWaiting(name);if(w)return {clicked:b.label,...w};} + return {clicked:b.label,...apiDispatch(name,kind,apiSpec(name),args,false)};} diff --git a/src/agent/70-time.js b/src/agent/70-time.js new file mode 100644 index 0000000..fa7aee7 --- /dev/null +++ b/src/agent/70-time.js @@ -0,0 +1,67 @@ +/* ================= AGENT API: time ================= + Two clocks, in the MCP server's own page and in the player's tab alike. The agent's clock: nothing moves until a tool + asks for days with advance. A running clock: days pass at a fixed pace whatever the tool does, and the tool can only + wait and react. In the player's tab the player picks one in Settings (apiAgentMs(), 0 for the agent's clock); the MCP + server's own page is told by the server (API_CLK). */ +let API_CLK={mode:'agent',paceMs:0,running:false}; +const apiClockNow=()=>API_CTX.relay?(apiAgentMs()>0?{mode:'realtime',paceMs:apiAgentMs(),running:!!UI.speed}:{mode:'agent',paceMs:0,running:false}):API_CLK; +function apiMode(){const c=apiClockNow(); + return {backend:API_CTX.relay?'browser':'headless',clock:c.mode,...(c.mode==='realtime'?{paceMs:c.paceMs}:{}), + ...(API_CTX.relay?{withheld:API_WITHHELD,playerOwns:Object.keys(API_PLAYER_OWNS)}:{})};} +function apiClockDoc(){const c=apiClockNow(); + return c.mode==='agent'?'Time moves only with advance: one dayTick() per simulated day, as the game loop runs it. Nothing runs between calls.' + :`The clock runs on its own: one simulated day every ${apiR1(c.paceMs/1000)} s of real time, behind open windows too, and no tool can stop it${API_CTX.relay?' (it holds while no tool is connected)':''}. advance is not available; wait returns once days have passed.`;} +function apiClock(){const c=apiClockNow(); + return {mode:c.mode,paceMs:c.paceMs||undefined,running:c.mode==='realtime'?!!c.running:false, + day:S?S.day:null,date:S?dateStr(S.day):null,cash:S?S.cash:null,lost:!!(S&&S.lost),incidents:S?S.inc.map(i=>i.id):[],question:!!apiDecision()};} + +// What happened since a moment (the start of an advance, or a clock reading before wait): the log, new incidents, cash. +// The log keeps what mattered; toasts that only repeat a log line are left out. +function apiSince({day=0,cash=0,inc=[]}={},toasts=[]){ + const seen=new Set(inc),entries=(S.log||[]).filter(e=>e.d>day).slice(-60),logged=entries.map(e=>apiNorm(apiText(e.t,400))); + const d=apiDecision(); + return {from:dateStr(day),to:dateStr(S.day),daysRun:S.day-day,cash:Math.round(S.cash),cashChange:Math.round(S.cash-cash), + newIncidents:S.inc.filter(i=>!seen.has(i.id)).map(apiIncText), + log:entries.map(e=>`${dateStr(e.d)}: ${apiText(e.t,400)}`), + toasts:[...new Set(apiToastLines(toasts))].filter(t=>{const f=apiNorm(t.replace(/^\w+: /,'').split('\n')[0]);return !logged.some(l=>l.startsWith(f));}).slice(-40), + ...(d?{decision:d,screen:apiScreen()}:{})};} + +function apiAdvanceStart(days){ + if(!S)apiFail('No game is running.'); + const c=apiClockNow(); + if(c.mode!=='agent')apiFail(`The clock runs on its own here, one day every ${apiR1(c.paceMs/1000)} s: use wait to let days pass.`); + if(apiModalOpen()&&!apiPlayerWin())apiFail('A window is open. Answer it first (screen, click, or act closeModal), the game does not run days behind it.'); + API_SHEET=null; + apiTake(); + return {days:Math.max(1,Math.min(3650,Math.floor(+days)||1)),start:S.day,cash:S.cash,inc:S.inc.map(i=>i.id),times:[],ran:0,stop:null};} +// One day of the run; false once it is over. +function apiAdvanceDay(a){ + if(a.ran>=a.days)return false; + if(S.lost){a.stop='bankrupt';return false;} + const t=performance.now(); + dayTick(); + a.times.push({day:S.day,ms:apiR1(performance.now()-t)});a.ran++; + if(apiModalOpen()&&!apiPlayerWin()){a.stop='a window opened';return false;} + return a.ranx+t.ms,0),out=apiSince({day:a.start,cash:a.cash,inc:a.inc},apiTake()); + if(a.stop!=='a window opened'){delete out.decision;delete out.screen;} + return {from:out.from,to:out.to,daysRun:a.ran,stoppedBecause:a.stop,cash:out.cash,cashChange:out.cashChange,newIncidents:out.newIncidents,log:out.log,toasts:out.toasts, + timing:{totalMs:apiR1(total),perDayMs:apiR1(total/(a.ran||1)),slowestDays:a.times.slice().sort((x,y)=>y.ms-x.ms).slice(0,5).map(x=>({date:dateStr(x.day),ms:x.ms}))}, + ...(out.decision?{decision:out.decision,screen:out.screen}:{})};} +function apiAdvance(days){const a=apiAdvanceStart(days);while(apiAdvanceDay(a));return apiAdvanceEnd(a);} +/* In the player's tab the days run where the player can watch them: a frame's worth of days, then the page draws. + A hidden tab draws nothing (and its timers are throttled), so there they run straight through. A day the route + worker is still routing finishes first. */ +const apiSleep=ms=>new Promise(r=>setTimeout(r,ms)); +async function apiAdvanceLive(days){ + const a=apiAdvanceStart(days);let t=performance.now(); + for(;;){ + while(RW.job)await apiSleep(20); + if(!apiAdvanceDay(a))break; + if(document.visibilityState!=='hidden'&&performance.now()-t>30){renderHUD();UI.panelsDue=true;await apiSleep(0);t=performance.now();}} + return apiAdvanceEnd(a);} + +// One day of a running clock in the MCP server's own page (the server keeps the time); the player's tab runs its own loop. +function apiTick(){if(!S||S.lost||pzOn()||!rule('clock'))return false;dayTick();renderAll();return true;} diff --git a/src/agent/75-mode.js b/src/agent/75-mode.js new file mode 100644 index 0000000..0924eb7 --- /dev/null +++ b/src/agent/75-mode.js @@ -0,0 +1,86 @@ +/* ================= AGENT MODE: the player's switch and clock ================= + In the player's own tab (the development page, served locally), the player can let an agent drive: the page dials + the agent relay (80-relay.js) and answers tool calls through TUBES.call. While it does, the clock is not the + player's (UI.clockLocked): either a fixed pace, one simulated day every 30 s to 5 min, that nobody can pause and + that holds while no tool is connected; or the agent's clock, which stands still until the agent asks for days. + The game itself knows none of this: it calls HOOKS (50-state.js), which this file fills in, and reads + UI.clockLocked. Settings of its own, in their own storage key, so the game's preferences stay as they are. */ +const API_AGENT_MS=[0,30000,60000,120000,300000],API_AGENT_KEY='sot-agent'; +const API_AGENT_PREFS=(()=>{let j={};try{j=JSON.parse(localStorage.getItem(API_AGENT_KEY)||'{}')||{};}catch(e){} + return {on:j.on===true,ms:API_AGENT_MS.includes(j.ms)?j.ms:60000};})(); +/* Only where a relay can be: plain http (an https page cannot open ws://) to an address, never a DNS name, which the + relay refuses (DNS rebinding). The public site is https and a name, so it never shows the switch. The test + harness's made-up origin opts in, and a test page loaded from the public address does not. */ +const apiAgentLocal=(p,h)=>p==='http:'&&(h==='localhost'||/\.localhost$/.test(h)||/^\[[0-9a-f:.]+\]$/i.test(h)||/^\d{1,3}(\.\d{1,3}){3}$/.test(h)); +const API_AGENT_OK=apiAgentLocal(location.protocol,location.hostname)||!!window.__TUBES_TEST__&&location.hostname==='tests.invalid'; +const apiAgentMs=()=>API_AGENT_PREFS.ms; +const apiMsLabel=ms=>ms>=60000?tr('settings.n_min',{n:Math.round(ms/60000)}):tr('settings.n_sec',{n:Math.round(ms/1000)}); +const apiAgentMsLabel=()=>apiAgentMs()>0?apiMsLabel(apiAgentMs()):tr('settings.agent_s_clock'); + +/* The speed a locked clock runs at: the pace while a tool is connected, else held (0); always 0 on the agent's clock, + where only advance moves days; and only in a game with a clock (the rule the pause buttons follow). */ +function apiAgentSpeed(){const r=API_RELAY;return r.on&&r.tools>0&&apiAgentMs()>0&&S&&rule('clock')?DAY_MS/apiAgentMs():0;} + +// k: 'on' (true/false) or 'ms' (one of API_AGENT_MS). Anything else is ignored, never coerced. +function apiAgentSet(k,v){ + if(k==='on')API_AGENT_PREFS.on=v===true||v==='1'||v===1; + else if(k==='ms'){if(!API_AGENT_MS.includes(+v))return;API_AGENT_PREFS.ms=+v;} + else return; + try{localStorage.setItem(API_AGENT_KEY,JSON.stringify(API_AGENT_PREFS));}catch(e){} + apiAgentSync();} + +/* Locks or frees the clock to match the switch, and keeps the speed where it belongs. Switching on leaves the save's + speed alone (save() does not overwrite it while the clock is locked), so switching off puts back the one the player + left the game at. Safe to run any number of times. */ +function apiAgentSync(){ + const on=!RW_IN&&API_AGENT_OK&&API_AGENT_PREFS.on; + if(on!==UI.clockLocked){ + if(on&&S&&[0,0.5,1,2,4,8].includes(UI.speed))S.uiSpeed=UI.speed; + UI.clockLocked=on; + if(!on)UI.speed=S&&[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:(UI.lastSpeed||1);} + if(on)UI.speed=apiAgentSpeed(); + apiRelaySync(); + apiTickerSync(); + renderHUD();renderTabbar();} + +/* What the game draws for a locked clock: the badge in the HUD in place of the speed buttons, and on phones the two + tab bar slots of play and speed, disabled, the second one reading the pace. */ +function apiAgentHud(){ + const p=$('spPace');if(!p)return; + p.hidden=!UI.clockLocked; + if(UI.clockLocked)p.textContent=apiAgentMs()>0?tr('settings.pace_t_per_day',{t:apiAgentMsLabel()}):apiAgentMsLabel();} +function apiAgentTabbar(){ + return ``+ + ``;} + +/* The Settings section. Its buttons are the agent's own (data-agent-set, answered below), not game actions, so no + tool can find them on a screen and switch the agent off, or on. */ +function apiAgentSettings(){ + if(!API_AGENT_OK)return ''; + const b=(v,l,on)=>``; + const line=(lab,btns,note)=>`
${lab}
${btns}

${note}

`; + return `

${tr('settings.agent_api')}

`+ + line(tr('settings.let_an_ai_agent_drive_this_game'),b('on:1',tr('common.on'),API_AGENT_PREFS.on)+b('on:0',tr('common.off'),!API_AGENT_PREFS.on),tr('settings.while_agent_mode_is_on_the'))+ + line(tr('settings.the_clock_while_an_agent_plays'),API_AGENT_MS.map(m=>b('ms:'+m,m?apiMsLabel(m):tr('settings.the_agent_moves_it'),apiAgentMs()===m)).join(''),tr('settings.a_pace_runs_one_simulated_day'));} +function apiAgentClick(e){ + const el=e.target&&e.target.closest&&e.target.closest('[data-agent-set]');if(!el||el.disabled)return; + const [k,v]=String(el.dataset.agentSet).split(':'); + apiAgentSet(k,k==='on'?v==='1':v);sfx('click');refreshSettings();} + +/* Who opened the window on screen: the player (a click, a key, a picker: window.event is the input being handled), or + the game itself (a day, a tool's call inside a relay message). A tool leaves the player's windows alone. */ +const API_MODAL={hand:false}; +const apiByHand=()=>{const e=window.event;return !!e&&/^(click|keydown|keyup|pointerup|touchend|change|input|submit)$/.test(e.type);}; + +// Wires agent mode into the page: the hooks, the badge and its style, the Settings buttons. Once, at load. +function apiAgentStart(){ + if(RW_IN)return; + Object.assign(HOOKS,{speed:apiAgentSpeed,hud:apiAgentHud,tabbar:apiAgentTabbar,settings:apiAgentSettings,modal:open=>{API_MODAL.hand=open&&apiByHand();}}); + const sp8=$('sp8'); + if(sp8&&!$('spPace')){const p=document.createElement('span');p.id='spPace';p.hidden=true;sp8.after(p);} + const st=document.createElement('style'); + st.textContent='.speed #spPace[hidden]{display:none}#spPace{border:2.5px solid var(--ink);background:var(--sun);border-radius:9px;height:32px;padding:0 8px;display:flex;align-items:center;font-family:var(--display);font-weight:800;font-size:12.5px;white-space:nowrap}'+ + '#tabbar button.pace .ic{font-size:13px;line-height:1.25}'; + document.head.appendChild(st); + document.addEventListener('click',apiAgentClick); + apiAgentSync();} diff --git a/src/agent/80-relay.js b/src/agent/80-relay.js new file mode 100644 index 0000000..b0cd1ff --- /dev/null +++ b/src/agent/80-relay.js @@ -0,0 +1,77 @@ +/* ================= AGENT RELAY: the in-page transport ================= + With agent mode on (75-mode.js), the page dials the agent relay (scripts/agent/relay.js, which npm run dev hosts on + its own port) and answers tool calls from connected tools (the MCP server, node scripts/mcp.js --browser) through + TUBES.call, so a human follows along on the real UI: toasts fire, panels render, the map moves. + + No endpoint to configure and no token: the relay rides the server that served the page, same port, path + API_RELAY_PATH, so the endpoint is where the page already is. The relay refuses a page from any other origin and a + Host that is a name, so no website can reach it through the player's browser; who else can reach it is the + operator's choice of bind address. No eval ever: a message is JSON with a tool name from TUBES.tools, a fixed list, + answered as the relay (ctx.relay): the player's game, clock, windows and settings stay theirs, and the dice stay + hidden. Nothing dials or polls while the switch is off. + + API_RELAY_HOST is a var because tests point it at their relay (under __TUBES_TEST__ nothing dials unless the test + opts in with __AGENT_RELAY_TEST__): a jsdom page is not loaded from the relay's server. */ +var API_RELAY_HOST=''; // tests: '127.0.0.1:'; live pages use their own host +const API_RELAY={ws:null,on:false,timer:null,tries:0,said:false,tools:0,host:null,queue:null}; +const API_RELAY_PATH='/agent'; +const apiRelayUrl=()=>`ws://${API_RELAY_HOST||location.host}${API_RELAY_PATH}`; + +/* The relay reports tool presence on every connect and disconnect: the clock holds while no tool is connected and + runs again the moment one arrives. A missing relay (dial failed, retry backoff) holds it too. */ +function apiRelayPresence(tools){ + API_RELAY.tools=tools|0; + if(!UI.clockLocked||!API_RELAY.on)return; + const run=apiAgentSpeed(); + if(run!==UI.speed){UI.speed=run;renderHUD();}} + +function apiRelaySync(){ + const want=!RW_IN&&UI.clockLocked&&(!window.__TUBES_TEST__||!!window.__AGENT_RELAY_TEST__); + // Nothing to do when the switch and the endpoint stand: tearing a healthy dial down for nothing drops the calls in + // flight and holds the clock for no reason. + if(API_RELAY_HOST===API_RELAY.host&&API_RELAY.on===want&&(want?!!(API_RELAY.ws||API_RELAY.timer):true))return; + clearTimeout(API_RELAY.timer);API_RELAY.timer=null;API_RELAY.tries=0; + if(API_RELAY.ws){const w=API_RELAY.ws;API_RELAY.ws=null;try{w.close();}catch(e){}} + API_RELAY.on=want;API_RELAY.host=API_RELAY_HOST; + apiRelayPresence(0); // off the relay: nobody driving, the clock holds + if(want)apiRelayDial();} + +// Dev reloads and relay restarts heal on their own, without a spinning reconnect. +function apiRelayRetry(){ + if(!API_RELAY.on)return; + const wait=Math.min(15000,500*Math.pow(2,Math.min(API_RELAY.tries++,5))); + API_RELAY.timer=setTimeout(()=>{API_RELAY.timer=null;apiRelayDial();},wait);} + +/* One call, answered in order: calls queue behind each other, so a move sent while days are still running waits for + them, as the tool sent it. A promise (days the player watches) is awaited; a throw is the tool's error. */ +function apiRelayAnswer(ws,m){ + const dayBefore=S?S.day:null,send=o=>{if(API_RELAY.ws===ws)ws.send(JSON.stringify({kind:'result',id:m.id,dayBefore,dayAfter:S?S.day:null,...o}));}; + const run=()=>Promise.resolve().then(()=>TUBES.call(m.tool,m.args||{},{relay:true})) + .then(value=>send({value}),er=>send({error:String(er&&er.message||er)})); + API_RELAY.queue=(API_RELAY.queue||Promise.resolve()).then(run);} + +function apiRelayDial(){ + if(!API_RELAY.on)return; + let ws; + try{ws=new WebSocket(apiRelayUrl());}catch(e){return apiRelayRetry();} + API_RELAY.ws=ws; + ws.onopen=()=>{ + if(API_RELAY.ws!==ws)return; + ws.send(JSON.stringify({kind:'auth',role:'page'})); + API_RELAY.tries=0; + if(!API_RELAY.said){API_RELAY.said=true;toast(tr('settings.agent_relay_connected'),'good');}}; + ws.onmessage=e=>{ + if(API_RELAY.ws!==ws)return; + let m;try{m=JSON.parse(e.data);}catch(_){return;} + if(!m||typeof m!=='object')return; + if(m.kind==='presence'){apiRelayPresence(m.tools);return;} + if(m.kind!=='call'||m.id===undefined)return; + // A call this page cannot make sense of is answered, never ignored: a silent drop would hang the tool that sent it. + if(typeof m.tool!=='string'||!TUBES.tools.includes(m.tool)){ws.send(JSON.stringify({kind:'result',id:m.id,error:`no tool "${m.tool}" here`}));return;} + apiRelayAnswer(ws,m);}; + // Replaced (4000): another tab took the relay, so this one yields instead of fighting it: redialing would just + // replace the new tab back, forever. Toggling agent mode dials again. + ws.onclose=e=>{if(API_RELAY.ws!==ws)return;API_RELAY.ws=null; + apiRelayPresence(0); // off the relay: the clock holds + if(e&&e.code===4000)API_RELAY.on=false;else apiRelayRetry();}; + ws.onerror=()=>{};} diff --git a/src/agent/85-ticker.js b/src/agent/85-ticker.js new file mode 100644 index 0000000..fca70e5 --- /dev/null +++ b/src/agent/85-ticker.js @@ -0,0 +1,24 @@ +/* ================= AGENT MODE: the clock where frames do not run ================= + A paced clock runs through the game's own loop (UI.speed is the pace, runClock() the days), but frames stop in a + hidden tab, and the frame runs no days behind an open window. Agent mode keeps time in both: a hidden tab is the + normal place for an agent to drive while the player does something else, and an agent that deliberates over a + window pays for it in days. This ticker covers exactly those moments, under the frame's other conditions, and + leaves every other moment to the frame. Hidden-tab timers are throttled (to 1 Hz, after five minutes to once a + minute in Chrome), so an unthrottled worker posts the ticks; a plain interval is the fallback without Worker. + The agent's clock (pace 0) needs no ticks: its days run when the agent asks. Never under __TUBES_TEST__: tests call + apiAgentTick() by hand. */ +const API_TICKER={on:false,worker:null,interval:null,last:0}; +// Days for the time since the last tick, if the frame is not running them now. +function apiAgentTick(now=performance.now()){ + const dt=API_TICKER.last?Math.max(0,Math.min(1000,now-API_TICKER.last)):0;API_TICKER.last=now; + const behind=document.visibilityState==='hidden'||!$('modal').hidden; + if(behind&&UI.clockLocked&&S&&!S.lost&&UI.speed&&!pzOn())runClock(dt);} +function apiTickerSync(){ + const want=UI.clockLocked&&apiAgentMs()>0&&!window.__TUBES_TEST__; + if(want===API_TICKER.on)return;API_TICKER.on=want;API_TICKER.last=0; + if(!want){if(API_TICKER.worker){try{API_TICKER.worker.terminate();}catch(e){}API_TICKER.worker=null;} + if(API_TICKER.interval){clearInterval(API_TICKER.interval);API_TICKER.interval=null;}return;} + try{const url=URL.createObjectURL(new Blob(['setInterval(()=>postMessage(0),250)'],{type:'text/javascript'})); + API_TICKER.worker=new Worker(url);URL.revokeObjectURL(url); + API_TICKER.worker.onmessage=()=>apiAgentTick();} + catch(e){API_TICKER.interval=setInterval(()=>apiAgentTick(),250);}} diff --git a/src/agent/90-facade.js b/src/agent/90-facade.js new file mode 100644 index 0000000..558d9b7 --- /dev/null +++ b/src/agent/90-facade.js @@ -0,0 +1,54 @@ +/* ================= AGENT API: the facade ================= + window.TUBES.call(tool, args) is the whole surface: one tool from API_TOOLS by name, with the MCP tool's own + arguments, answered as plain JSON (or a promise of it, for days that run where the player can watch). Nothing here + listens, polls or runs on the day loop: toast() is only listened to while a call runs. + ctx.relay: the call came over the relay into the player's tab (80-relay.js), where the player owns the game, its + clock and their windows, and the dice stay hidden. */ +let API_CTX={relay:false}; +const API_TOASTS={depth:0,list:[],real:null}; +function apiTake(){const t=API_TOASTS.list;API_TOASTS.list=[];return t;} +const apiToastLines=t=>t.map(x=>(x.kind?x.kind+': ':'')+x.text); +// toast() is a top-level function, so the game reaches it by its global name and this stands in for it. +function apiListen(on){ + if(on){if(API_TOASTS.depth++)return;const real=API_TOASTS.real=window.toast;API_TOASTS.list=[]; + window.toast=function(h,kind){API_TOASTS.list.push({kind:kind||'',text:apiText(String(h),600)});return real.apply(this,arguments);};} + else if(!--API_TOASTS.depth){window.toast=API_TOASTS.real;API_TOASTS.real=null;API_TOASTS.list=[];}} + +const API_TOOLS={ + status:()=>apiStatus(), + network:a=>apiNetwork(a.network), + city:a=>apiCity(a.city), + find:a=>apiFind(a.query,a.kind), + traceroute:a=>apiTrace(a.from,a.to), + peering_check:a=>apiPeering(a.network,a.city,a.via), + hot_spots:a=>apiHotSpots(a.limit||10), + schema:a=>apiSchema(a.section), + catalog:a=>apiCatalog(a.name), + state:a=>apiState(a.path), + results:a=>apiResults(a.path), + ui:()=>apiUi(), + actions:()=>apiActions(), + classes:()=>apiClasses(), + act:a=>{const name=a.action||a.command;if(!name)apiFail('Give action, e.g. {"action":"buildPop","args":{"city":"ams"}}.'); + return apiRun(name,a.args||{},{dryRun:!!a.dryRun});}, + screen:a=>apiScreen(a.where,a.offset), + panel:a=>apiPanel(a), + click:a=>apiClick(a.button,a.value), + open_link:a=>apiOpenLink(a.from,a.to), + advance:a=>API_CTX.relay?apiAdvanceLive(a.days):apiAdvance(a.days), + clock:()=>apiClock(), + since:a=>apiSince(a), +}; +function apiCall(tool,args,ctx){ + if(typeof tool!=='string'||!own(API_TOOLS,tool))apiFail(`No tool "${tool}".`); + if(!S&&!['schema','catalog','classes','actions','clock'].includes(tool))apiFail('No game is running.'); + const was=API_CTX;API_CTX={relay:!!(ctx&&ctx.relay)}; + apiListen(true); + let out; + try{out=API_TOOLS[tool](args&&typeof args==='object'&&!Array.isArray(args)?args:{});} + catch(e){apiListen(false);throw e;} + finally{API_CTX=was;} + if(out&&typeof out.then==='function')return out.finally(()=>apiListen(false)); + apiListen(false); + return out;} +window.TUBES={version:1,tools:Object.keys(API_TOOLS),call:apiCall}; diff --git a/src/agent/99-start.js b/src/agent/99-start.js new file mode 100644 index 0000000..7254460 --- /dev/null +++ b/src/agent/99-start.js @@ -0,0 +1,4 @@ +/* ================= AGENT API: start ================= + Last, once every file of the facade has loaded: agent mode wires itself in (75-mode.js). Everything before this only + defines tables and functions. */ +apiAgentStart(); diff --git a/src/game/50-state.js b/src/game/50-state.js index 53850bf..6375302 100644 --- a/src/game/50-state.js +++ b/src/game/50-state.js @@ -1,5 +1,9 @@ /* ================= STATE ================= */ let S=null, R=emptyR(); -const UI={sel:null,tab:'cust',left:'goals',speed:1,hover:null,drag:null,snap:null,pending:null,confirm:null,leftOpen:false,muted:false,startCity:'fra',hintOff:false}; +const UI={sel:null,tab:'cust',left:'goals',speed:1,hover:null,drag:null,snap:null,pending:null,confirm:null,leftOpen:false,muted:false,startCity:'fra',hintOff:false,clockLocked:false}; +/* Where tools that are not part of the game (the development page's agent, src/agent/) may hook in. Empty in the page + players get, and the game only ever calls into it with ?.(), so nothing changes there. clockLocked: the clock is not + the player's (an agent drives): no pause, no speed buttons, no auto-pause, and the speed is HOOKS.speed()'s. */ +const HOOKS={}; let uidN=1; const uid=()=>'i'+(Date.now()%1e7).toString(36)+(uidN++); function emptyR(){return {nt:{},cone:{},reachNT:0,teBlack:0,tNet:{},egT:{},netEg:{},l2lat:{},nodeLoad:{},nodeCap:{},div:{},l2:{},gfwLost:0,gfwCross:0,ef:{},egDesc:{},p95:{},peered:0,peerShare:0,load:{},useT:{},useIx:{},usePni:{},useCache:{},cityDem:{},citySrv:{},cityEye:{},latF:{},latFar:{},demTo:{},served:0,demand:0,reach:0,sessions:0,revMo:0,costMo:0,cost:{},rev:{},reachable:{},ddos:[],haul:[],tgtF:{},bbF:{},fsUse:{},ddosHot:{}};} diff --git a/src/game/60-features/20-scenarios.js b/src/game/60-features/20-scenarios.js index eedd60f..967cfb6 100644 --- a/src/game/60-features/20-scenarios.js +++ b/src/game/60-features/20-scenarios.js @@ -51,7 +51,7 @@ function beginGame(nm,city,o={}){if(needPitch()&&!UI.pitched){UI.pendGame=[nm,ci if(sc.cash)S.cash=sc.cash;if(sc.setup)sc.setup(); for(const m of S.scn.mods){if(m==='pricey')S.priceMul=1.3;if(m==='poor')S.cash=100000;if(m==='chaos')S.scn.rules.chaos=true;if(m==='boom')S.scn.rules.boom=true;if(m==='dk')S.scn.rules.dkAll=true;if(m==='sharks')S.scn.rules.sharks=true;}} // Every new network starts at ½ speed (#186), whatever the last one ran at: slow enough to look around, but things happen. - UI.speed=UI.lastSpeed=rule('clock')?0.5:0;UI.resumeSpeed=null; + UI.lastSpeed=rule('clock')?0.5:0;setSpeed(UI.lastSpeed);UI.resumeSpeed=null; track('game_new');UI.started=true;closeModal();compute();cam.x=CITY[city].x;cam.y=CITY[city].y;cam.z=innerWidth<760?1.1:1.4;selectCity(city); toast(S.scn?`${esc(S.scn.name)}
${o.scn.goal?esc(o.scn.goal)+'.':tr('common.serve_as_much_traffic_as_you')} ${tr('scenarios.you_have_n_days',{n:S.scn.days})}`:S.mode==='sandbox'?(chaosMul()?tr('scenarios.sandbox_mode_a_billion_dollars_chaos',{chaos:CHAOS[rule('chaos')].n}):tr('scenarios.sandbox_mode_a_billion_dollars_every')):tr('scenarios.welcome_name_the_ripe_ncc_assigned',{name:esc(nm),asn:S.asn,city:CITY[city].name}),'goal'); renderAll();save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle')tutorialStart();} diff --git a/src/game/60-features/92-puzzles.js b/src/game/60-features/92-puzzles.js index 9500c57..1acd952 100644 --- a/src/game/60-features/92-puzzles.js +++ b/src/game/60-features/92-puzzles.js @@ -132,7 +132,7 @@ function pzBegin(def){if(!def)return;pzMkStop();mkStop(); if(live)pzFlush();go();} function pzLeave(){pzMkStop();if(S&&S.ar)arStop(true);mkStop();const from=UI.pzFrom;pzToastsClear();document.body.classList.remove('pz');UI.sel=null;UI.pzHist=null;UI.pzFrom=null;UI.pzEv=null;closeModal();$('panel').hidden=true;$('pzBox').hidden=true;S=null;R=emptyR();UI.started=false; if(from==='game'){const sv=UI.pzKeep||loadSave();UI.pzKeep=null; - if(sv){try{S=migrate(sv);compute();UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} + if(sv){try{S=migrate(sv);compute();UI.started=true;setSpeed([0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);renderAll();return;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} // It cannot be loaded back: marked damaged (kept, so it can be exported), and the player is told. if(UI.slot&&(sv||UI.loadBad)){slotBroke(UI.slot);return;}} renderAll();showTitle();} diff --git a/src/game/90-actions/10-interface.js b/src/game/90-actions/10-interface.js index 17e2953..6f6056e 100644 --- a/src/game/90-actions/10-interface.js +++ b/src/game/90-actions/10-interface.js @@ -2,7 +2,7 @@ function spend(c){if(S.cash{const l=S.links.find(x=>x.id===id);if(!l||linkDown(l))return;linkCheckModal(l);}, - speed:({v})=>{v=+v;if(pzOn())return;if(![0,0.5,1,2,4,8].includes(v)||(S&&!rule('clock')&&v))return;if(v)UI.lastSpeed=v;UI.speed=v;renderHUD();}, + speed:({v})=>{v=+v;if(pzOn()||UI.clockLocked)return;if(![0,0.5,1,2,4,8].includes(v)||(S&&!rule('clock')&&v))return;if(v)UI.lastSpeed=v;UI.speed=v;renderHUD();}, help:()=>showHelp(), dash:()=>{if(!S||pzOn())return;const d=$('dash');d.hidden=!d.hidden;if(!d.hidden)renderDash();}, dashClose:()=>{$('dash').hidden=true;}, @@ -34,8 +34,8 @@ const ACT={ meetGo:({city})=>{if(!isCity(city))return;$('dash').hidden=true;ACT.focusCity({city});if(S.pops[city]){UI.tab='peer';renderPanel();}}, toggleLeft:()=>{UI.leftOpen=!UI.leftOpen;renderLeft();}, phoneTab:({t})=>{if(!['goals','deals','noc','nets'].includes(t))return;if($('modal').classList.contains('link-check'))closeModal();haptic(8);if(UI.leftOpen&&UI.left===t&&!UI.sel){UI.leftOpen=false;}else{UI.left=t;UI.leftOpen=true;UI.sel=null;renderPanel();}$('left').classList.remove('full');renderLeft();}, - phonePlay:()=>{if(pzOn())return;if(S&&!rule('clock'))return;haptic(10);if(UI.speed){UI.lastSpeed=UI.speed;UI.speed=0;}else UI.speed=UI.lastSpeed||1;renderHUD();}, - phoneSpeed:()=>{if(pzOn())return;if(S&&!rule('clock'))return;haptic(8);const cur=UI.speed||UI.lastSpeed||1,i=SPEEDS.indexOf(cur),n=SPEEDS[(i+1)%SPEEDS.length];UI.speed=n;UI.lastSpeed=n;renderHUD();}, + phonePlay:()=>{if(pzOn()||UI.clockLocked)return;if(S&&!rule('clock'))return;haptic(10);if(UI.speed){UI.lastSpeed=UI.speed;UI.speed=0;}else UI.speed=UI.lastSpeed||1;renderHUD();}, + phoneSpeed:()=>{if(pzOn()||UI.clockLocked)return;if(S&&!rule('clock'))return;haptic(8);const cur=UI.speed||UI.lastSpeed||1,i=SPEEDS.indexOf(cur),n=SPEEDS[(i+1)%SPEEDS.length];UI.speed=n;UI.lastSpeed=n;renderHUD();}, install:()=>{if(installEvt){installEvt.prompt();installEvt.userChoice.finally(()=>{installEvt=null;});return;} openModal(pitchHtml(false));}, pitchSkip:()=>{const p=UI.pendGame;UI.pendGame=null;UI.pitched=true;if(p)beginGame(...p);else closeModal();}, diff --git a/src/game/90-actions/89-game-and-settings.js b/src/game/90-actions/89-game-and-settings.js index 201f4f1..fb83f74 100644 --- a/src/game/90-actions/89-game-and-settings.js +++ b/src/game/90-actions/89-game-and-settings.js @@ -23,7 +23,7 @@ Object.assign(ACT,{ importPick:()=>{let f=$('importIn');if(!f){f=document.createElement('input');f.type='file';f.accept='.json,application/json';f.id='importIn';f.hidden=true;document.body.appendChild(f);f.addEventListener('change',()=>{importFile(f.files[0]);f.value='';});}f.click();}, importGo:()=>{const s0=UI.importing;if(!s0)return;UI.importing=null;const prev=S;let nx;try{nx=migrate(JSON.parse(JSON.stringify(s0)));}catch(e){nx=null;}if(nx&&pzOn())pzLeave();const was=S; // An import is a new network next to the others: the one playing here is saved and kept. - try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;UI.speed=S.uiSpeed===undefined?1:S.uiSpeed;if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');}, + try{if(!nx)throw 0;S=nx;compute();checkGoals();}catch(e){S=was;if(S)compute();renderAll();toast(tr('game_and_settings.import_failed_that_save_is_damaged'),'bad');sfx('err');return;}UI.confirm=null;$('bankBox').hidden=true;$('dash').hidden=true;UI.started=true;UI.sel=null;setSpeed(S.uiSpeed===undefined?1:S.uiSpeed);if(S.cam&&isFinite(S.cam.x))Object.assign(cam,S.cam);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;}}closeModal();$('modal').hidden=true;{const im=S;S=was;slotLeave();S=im;}slotNew();delete S.sv;compute();renderAll();save(true);toast(tr('game_and_settings.welcome_back_name_imported_and_saved',{name:esc(S.name)}),'good');sfx('coin');track('game_import');}, menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`
AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}

${esc(S.name)}

${saveFailing()?`

${saveFailMsg()}

`:`

${tr('game_and_settings.your_game_saves_itself_every_few')}

`}