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

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

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

View file

@ -56,7 +56,10 @@ next to it. `npm run page -- -o /tmp/page.html` writes the page players get if y
development page only (`<!-- @include-dev agent -->`): players never download it. Its top-level names development page only (`<!-- @include-dev agent -->`): 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` 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 and break for players (`tests/build.test.js` checks). Tests load the players' page; a test of the
facade asks for `load({ agent: true })`. See docs/adr/0004-dev-only-code.md. 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/`. - **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`. - **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 - **Data tables** (cities, cables, networks): one entry per line, and keep id-keyed objects such as

View file

@ -6,6 +6,7 @@ All notable changes to this project are documented here. The project follows
## [Unreleased] ## [Unreleased]
- 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 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 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. - 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.

View file

@ -21,7 +21,7 @@ Read these before larger changes:
```bash ```bash
npm ci # once: installs jsdom for the tests 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 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-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`) node scripts/i18n-add.js FILE.json # add/change/remove translations (see `add-strings`)

View file

@ -52,11 +52,11 @@ and remembers the one you pick under Settings or on the title screen.
```sh ```sh
npm ci 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 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 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 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; --http for HTTP) 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 ## Community

View file

@ -49,7 +49,9 @@ hoisted across files, and top-level statements run in path order. Find code by n
`src/agent/` is the agent facade (`window.TUBES`): the typed commands, reads and screens the MCP server plays `src/agent/` is the agent facade (`window.TUBES`): the typed commands, reads and screens the MCP server plays
through. It is assembled into the **development page** only (`npm run dev`, the MCP server, tests that ask for it); through. It is assembled into the **development page** only (`npm run dev`, the MCP server, tests that ask for it);
the page players get never has it ([ADR 0004](adr/0004-dev-only-code.md)). Its top-level names all start with the page players get never has it ([ADR 0004](adr/0004-dev-only-code.md)). Its top-level names all start with
`api`/`API_`, and nothing outside `src/agent/` may use them. `api`/`API_`, and nothing outside `src/agent/` may use them. Where it must reach into the game (agent mode in the
player's tab locks the clock and draws its badge and Settings section), the game offers `HOOKS` and the flag
`UI.clockLocked` (`50-state.js`), empty and false in the page players get, and `runClock(dt)` (`99-loop.js`).
Rules for the source (checked by `tests/build.test.js` and the assembler): files are named Rules for the source (checked by `tests/build.test.js` and the assembler): files are named
`NN-lower-case.js`/`.css`, end with a newline and never close their `<script>`/`<style>`; top-level code `NN-lower-case.js`/`.css`, end with a newline and never close their `<script>`/`<style>`; top-level code
@ -69,11 +71,12 @@ Development runs on `npm run dev` (assembles the development page on every reque
| `scripts/lib/page.js` | Assembles the page from `src/` (also from a git ref with `--ref`, for performance baselines) | | `scripts/lib/page.js` | Assembles the page from `src/` (also from a git ref with `--ref`, for performance baselines) |
| `scripts/lib/compile-labels.js` | Shrinks labels to short ids in the shipped page and dictionaries | | `scripts/lib/compile-labels.js` | Shrinks labels to short ids in the shipped page and dictionaries |
| `scripts/build.js` | Builds `_site/` for GitHub Pages: copies `site/`, writes the page, stamps `__VERSION__`/`__BUILD_DATE__`, bakes release notes, writes `version.json` | | `scripts/build.js` | Builds `_site/` for GitHub Pages: copies `site/`, writes the page, stamps `__VERSION__`/`__BUILD_DATE__`, bakes release notes, writes `version.json` |
| `scripts/dev.js` | `npm run dev`: development server, no dependencies | | `scripts/dev.js` | `npm run dev`: development server (loopback unless `--host`), serving the development page and hosting the agent relay |
| `scripts/test.js` | `npm test`: runs every `tests/*.test.js` | | `scripts/test.js` | `npm test`: runs every `tests/*.test.js` |
| `scripts/release-notes.js` | Extracts a version's CHANGELOG bullets | | `scripts/release-notes.js` | Extracts a version's CHANGELOG bullets |
| `scripts/perf-bench.js`, `perf-browser.js`, `perf-stats.js`, `perf-fixture.js` | Big-network benchmark, base vs head, headless and in Chromium as a desktop and a throttled phone, with a significance test per row (posted on every PR by `perf.yml` + `perf-comment.yml`), and the generator of its save, `tests/fixtures/big-network.json` | | `scripts/perf-bench.js`, `perf-browser.js`, `perf-stats.js`, `perf-fixture.js` | Big-network benchmark, base vs head, headless and in Chromium as a desktop and a throttled phone, with a significance test per row (posted on every PR by `perf.yml` + `perf-comment.yml`), and the generator of its save, `tests/fixtures/big-network.json` |
| `scripts/mcp.js`, `scripts/lib/mcp-game.js`, `scripts/lib/mcp-headless.js`, `src/agent/` | The game as a local MCP server, on the official SDK over stdio or HTTP: typed tools to play, inspect and debug it from an AI client ([MCP.md](MCP.md)) | | `scripts/mcp.js`, `scripts/lib/mcp-game.js`, `scripts/lib/mcp-headless.js`, `src/agent/` | The game as a local MCP server, on the official SDK over stdio or HTTP: typed tools to play, inspect and debug it from an AI client, headless or in the player's own tab ([MCP.md](MCP.md)) |
| `scripts/agent/relay.js`, `scripts/lib/mcp-browser.js`, `scripts/lib/relay-client.js` | The agent relay `npm run dev` hosts at `/agent`, and the MCP server's side of it: how a tool reaches the game in the player's tab |
| `scripts/i18n-check.js`, `scripts/i18n-add.js`, `scripts/lib/dict.js` | Translation coverage and dictionary order; adding, renaming and removing entries | | `scripts/i18n-check.js`, `scripts/i18n-add.js`, `scripts/lib/dict.js` | Translation coverage and dictionary order; adding, renaming and removing entries |
| `scripts/legacy/` | The splitter that made `src/` from the old `site/index.html` (and gave its text labels), and `port-branch.js`, which carries older branches over | | `scripts/legacy/` | The splitter that made `src/` from the old `site/index.html` (and gave its text labels), and `port-branch.js`, which carries older branches over |
| `tests/harness.js` | Loads the assembled page in jsdom with a seeded `Math.random` and a fake canvas: the players' page, or the development page with `{agent: true}` | | `tests/harness.js` | Loads the assembled page in jsdom with a seeded `Math.random` and a fake canvas: the players' page, or the development page with `{agent: true}` |

View file

@ -1,20 +1,55 @@
# Series of Tubes as an MCP server # Series of Tubes as an MCP server
`scripts/mcp.js` lets an AI client (Claude Code, Claude Desktop, any MCP client) play, inspect and debug the game `scripts/mcp.js` lets an AI client (Claude Code, Claude Desktop, any MCP client) play, inspect and debug the game
through typed tools. It runs on your machine, over stdio or over HTTP, and loads the game from this checkout's through typed tools, over stdio or HTTP, in one of two sessions:
`src/`, the way the tests do: one page in jsdom, seeded, with no animation loop. Nothing is hosted and the game page
does not change, so it stays within [ADR 0001](adr/0001-github-pages-only.md): it is a local tool, like `npm run dev`, - **Headless** (`node scripts/mcp.js`): a game of its own, loaded from this checkout's `src/` the way the tests load
not a server for the game. The protocol is the official SDK's (`@modelcontextprotocol/server`, a dev dependency). it: one page in jsdom, seeded, with no animation loop. For playing and debugging when nobody is watching: fresh
starts, bug-report saves, scenarios and puzzles, and fast-forwarding time.
- **Browser** (`node scripts/mcp.js --browser`): the game in your own browser tab, through a local relay, so you can
watch and take part. Toasts fire, panels open, the map moves. The game, its saves, its settings and any window you
open stay yours.
Both run the same tools on the same code: the agent facade in the game page (`src/agent/`, `window.TUBES`), which does
nothing until a tool calls it. It is part of the development page only, never of the page players get
([ADR 0004](adr/0004-dev-only-code.md)). Nothing is hosted, so this stays within
[ADR 0001](adr/0001-github-pages-only.md): it is a local tool, like `npm run dev`. On the public site there is no relay
and no agent mode. The protocol is the official SDK's (`@modelcontextprotocol/server`, a dev dependency).
## Set it up ## Set it up
### Headless
```sh ```sh
npm ci npm ci
claude mcp add seriesoftubes -- node /path/to/seriesoftubes/scripts/mcp.js claude mcp add seriesoftubes -- node /path/to/seriesoftubes/scripts/mcp.js
``` ```
Other clients take the same command (`node /path/to/seriesoftubes/scripts/mcp.js`) in their MCP server settings. Other clients take the same command (`node /path/to/seriesoftubes/scripts/mcp.js`) in their MCP server settings.
`npm run mcp` starts it by hand; clients should use the `node` command, because `npm run` prints a line of its own first. Use `node` directly: `npm run` prints a line of its own to stdout, which is the protocol channel.
A game is always loaded: a fresh On-call game in Frankfurt until you start or load another. Every game is seeded, so
the same seed and the same moves give the same game. `--seed N` sets the first game's seed.
### Browser
1. `npm run dev`. It hosts the agent relay on its own port, at `/agent`.
2. Open the game at `http://localhost:8080`, start or load the game you want the agent to play, and turn on
**Settings → Agent API → "Let an AI agent drive this game"**. That connects the page to the relay; there are no
tokens and no ports to configure. The section only exists while the page is served over plain `http://` to an
address (`localhost`, `127.0.0.1`, or the IP the dev server is bound to).
3. Point your MCP client at `node /path/to/seriesoftubes/scripts/mcp.js --browser` (add `--relay-port N` if the dev
server runs on another port, `--relay-host ADDR` if it is bound elsewhere).
The order does not matter. The server answers the MCP handshake at once, then waits up to 90 s (`--page-wait-ms`) for
a page on the relay. When one connects it checks that the page was built from the code on disk, and over stdio stops
with a message if the tab is older (reload it). A call the page has not answered after 30 s comes back as an error
(`--call-ms`); a page that goes away answers its calls at once. One tab drives the relay at a time: the newest one wins.
`npm run dev` binds loopback by default. `npm run dev -- --host 0.0.0.0` (to try the game on a phone, say) binds every
interface, the relay with it, and says so: then anything that can reach the address can drive a game whose player
turned agent mode on. Whatever the bind address, the relay only takes connections made to an IP address or
`localhost`, and refuses a page from another site, so a website in your browser cannot reach it.
### Over HTTP ### Over HTTP
@ -39,23 +74,36 @@ claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp
write files under `DIR` and nowhere else (symbolic links that lead out are refused). write files under `DIR` and nowhere else (symbolic links that lead out are refused).
- **One game for every client.** Calls run one at a time, in the order they arrive; `new_game` or `load_save` from - **One game for every client.** Calls run one at a time, in the order they arrive; `new_game` or `load_save` from
any client replaces the game for all of them. any client replaces the game for all of them.
- **Either session.** `--http` works headless and with `--browser` alike: then a client elsewhere drives the game
in the player's tab, while the relay stays where `npm run dev` put it.
A game is always loaded: a fresh On-call game in Frankfurt until you start or load another. Every game is seeded, so ## The clock
the same seed and the same moves give the same game.
Every session has one of two clocks, and `schema` (section `mode`) says which:
- **The agent's clock**: nothing happens between calls. `advance {days}` runs the days, one `dayTick()` each, as the
game loop runs them, and stops early when a window asks a question or the network goes bankrupt. Headless, this is
the default. In the browser the player picks it in Settings ("The agent moves it"), and the days run on screen.
- **A running clock**: one simulated day passes every so often whatever the agent does, and nothing can stop it, not
even an open window. The agent decides while it runs, and `wait {days}` returns once that many days have passed (or
earlier, when a window asks a question). Headless: `--clock realtime --pace MS` (default 60000 ms a day). In the
browser the player picks a pace from 30 s to 5 min a day; the clock holds while no tool is connected.
`advance` with a running clock and `wait` with the agent's are errors that say which one to use.
## Tools ## Tools
| Tool | What it does | | Tool | What it does |
|---|---| |---|---|
| `new_game` | Start a network in any home city with a preset (`soft` for Best Effort, `freeze`, `oncall`, `bgp`, `sandbox`), a seed, your own ASN, and the sandbox's chaos dial | | `new_game` | Headless only. Start a network in any home city with a preset (`soft` for Best Effort, `freeze`, `oncall`, `bgp`, `sandbox`), a seed, your own ASN, and the sandbox's chaos dial |
| `load_save`, `export_save` | Load an exported save (a path or JSON text, migrated as the game does) or write one the real game can import | | `load_save`, `export_save` | Headless only. Load an exported save (a path or JSON text, migrated as the game does) or write one the real game can import |
| `status` | Date, cash, revenue and costs by kind, level, tier and why it is not Tier 1, the goal, traffic, reach, POPs, incidents | | `status` | Date, cash, revenue and costs by kind, level, tier and why it is not Tier 1, the goal, traffic, reach, POPs, incidents |
| `advance` | Run N days through `dayTick()`. Stops when a window opens or the network goes bankrupt. Returns the log, new incidents, cash and the time each day took | | `advance`, `wait` | Move time with the agent's clock, or let it pass with a running one. They return the log, new incidents and cash; `advance` also the time each day took |
| `network`, `city`, `find` | The world: policies and what a network asks for, its PoPs, cone and price; a city's exchanges, transit sellers, cables; search by name, id or ASN | | `network`, `city`, `find` | The world: policies and what a network asks for, its PoPs, cone and price; a city's exchanges, transit sellers, cables; search by name, id or ASN |
| `traceroute` | The looking glass: which exit wins to a network and why, with the AS path | | `traceroute` | The looking glass: which exit wins to a network and why, with the AS path |
| `peering_check` | Would this network peer with you over a PNI or at an exchange, and the game's reason if not | | `peering_check` | Would this network peer with you over a PNI or at an exchange, and the game's reason if not |
| `hot_spots` | The fullest links, transit ports and PNIs, the transit bill by carrier, and the biggest traffic still on transit with the way off it | | `hot_spots` | The fullest links, transit ports and PNIs, the transit bill by carrier, and the biggest traffic still on transit with the way off it |
| `schema` | The typed contract: every action with its arguments, their domains and what it does; what is not available and why; a field-by-field reference of `state` and `results` | | `schema` | The typed contract: the session (`mode`: headless or browser, the clock, what is held back), every action with its arguments, their domains and what it does; what is not available and why; a field-by-field reference of `state` and `results` |
| `catalog` | The reference tables the arguments point at (cities, networks, ports, optics, interns…), plus the conference calendar with its keys and the RouteScript recipes with their scripts | | `catalog` | The reference tables the arguments point at (cities, networks, ports, optics, interns…), plus the conference calendar with its keys and the RouteScript recipes with their scripts |
| `state`, `results`, `ui` | The saved game itself (`S`), the last traffic computation (`R`) and the view state, as JSON, whole or by path (`pops.fra`, `loanOffers`, `links.<id>`) | | `state`, `results`, `ui` | The saved game itself (`S`), the last traffic computation (`R`) and the view state, as JSON, whole or by path (`pops.fra`, `loanOffers`, `links.<id>`) |
| `actions`, `act` | Every action with its arguments, and running one | | `actions`, `act` | Every action with its arguments, and running one |
@ -81,32 +129,63 @@ what happened:
`click` presses a button as a player's click does, with the button's own arguments, so a confirmation arms first `click` presses a button as a player's click does, with the button's own arguments, so a confirmation arms first
and windows step on as they do in the game. Lists the game acts on when they change are listed with their options and windows step on as they do in the game. Lists the game acts on when they change are listed with their options
and clicked with a value. Neither tool reaches files, save slots, settings, the title screen or the game speed: time and clicked with a value. Neither tool reaches files, save slots, settings, the title screen or the game speed.
moves only with `advance`. There is no tool that evaluates code in the page. There is no tool that evaluates code in the page, and nothing but tool names and JSON arguments crosses the relay.
## In the player's browser
The browser mode plays by the player's rules on top of the headless ones:
- **The game is the player's.** There is no `new_game`, `load_save` or `export_save`, and the actions that start,
retry or leave a scenario, puzzle or architect run are refused. Whichever tab is connected is the game.
- **So is the clock**, set in Settings (see above). There is no tool for it.
- **And their windows.** A window the player opened (Settings, the menu, a sheet) is never a question, never closed
and never replaced: the agent plays behind it. `screen` shows it with `playerWindow`, and its buttons are the
player's to press. A sheet the agent opens meanwhile is shown to it and closed again. Only a question the game asks
in answer to the agent's own move takes the screen, as it would after a click.
- **And their settings**: no preference can be changed.
- **The dice stay hidden**: `state` never returns the seed or the days of the next failure, event or scripted attack;
`schema` marks them `withheld`, with the reason.
## Looking into a bug report ## Looking into a bug report
1. `load_save` with the save attached to the issue. 1. `load_save` (headless) with the save attached to the issue.
2. `status` and `hot_spots` for the picture, `traceroute` and `peering_check` for one network's traffic, `state` 2. `status` and `hot_spots` for the picture, `traceroute` and `peering_check` for one network's traffic, `state`
and `results` for the numbers behind them. and `results` for the numbers behind them.
3. `advance` a few days and read `timing.slowestDays` for lag, or the log for what went wrong. 3. `advance` a few days and read `timing.slowestDays` for lag, or the log for what went wrong.
## Troubleshooting the browser mode
- **"no game page answered"**: the tab is not connected. Settings → Agent API → on. No Agent API section in Settings?
The page is not the development page served locally: open it from `npm run dev`, at an address such as
`http://localhost:8080` or `http://127.0.0.1:8080`, not under a DNS name, which the relay refuses.
- **"the game page in the browser disagrees with the code on disk"**: the tab is older than the checkout (perhaps
after a `git pull`). Reload it: `npm run dev` assembles the page on every request.
- **A second tab took over**: one page per relay; the newest tab wins and the old one stops dialing.
## Code ## Code
- `scripts/mcp.js`: the server on the SDK: the tools registered from `TOOLS`, stdio or Streamable HTTP, the Host, - `scripts/mcp.js`: the server on the SDK: the tools registered from `TOOLS` for the session's mode, stdio or
Origin and token checks, the one-at-a-time queue. Streamable HTTP, the Host, Origin and token checks, the one-at-a-time queue, and the options.
- `tests/mcp-http.test.js`: the HTTP transport, its checks, the token and the save directory. - `scripts/lib/mcp-game.js`: the headless session (one game page) and the tool list, each tool with its input schema
- `scripts/lib/mcp-game.js`: the session (one game page: the development page, which has the facade) and the tool and the modes it works in.
list with input schemas. - `scripts/lib/mcp-headless.js`: runs inside the headless page only: starting, loading and exporting games, and the
- `src/agent/`: the facade (`window.TUBES.call(tool, args)`), in the page's own scope: every action's class, server's clock.
arguments, domains, price and description (`20-commands.js`), the `state`/`results` field reference (`30-docs.js`), - `scripts/lib/mcp-browser.js`, `scripts/lib/relay-client.js`: the browser session: the relay's tool side, the wait
the reads, screens, dispatch and time. It is part of the development page only, never of the page players get for a page and the check that it serves this checkout's contract.
([ADR 0004](adr/0004-dev-only-code.md)). - `scripts/agent/relay.js`: the relay, hosted by `scripts/dev.js` on its own port.
- `scripts/lib/mcp-headless.js`: added to the server's own page to start, load and export games. - `src/agent/`: the facade in the page, in the development page only: every action's class, arguments, domains,
- `tests/agent-api.test.js`: the facade is inert until called, and the page players get has none of it. price and description (`20-commands.js`), the `state`/`results` field reference and what is withheld
- `tests/mcp.test.js`: the protocol, a game played through the tools, determinism, saves, and what stays out of reach. (`30-docs.js`), the reads, the screens, dispatch and the clocks (`70-time.js`); agent mode's switch, clock and
- `tests/mcp-commands.test.js`: every action classified and its arguments real, outcomes, quotes, typed text, Settings (`75-mode.js`), the page's side of the relay (`80-relay.js`) and the clock where frames do not run
multi-step builds, confirmations, the reads and the screens. (`85-ticker.js`). The game itself only offers `HOOKS` and `UI.clockLocked` (`src/game/50-state.js`).
- `tests/mcp.test.js`: the protocol over stdio, a game played through the tools, determinism, saves, both clocks, and
what stays out of reach. `tests/mcp-http.test.js`: the HTTP transport, its checks, the token and the save directory.
`tests/mcp-commands.test.js`: every action classified and its arguments real, outcomes, quotes, typed text,
multi-step builds, confirmations, the reads and the screens. `tests/agent-api.test.js`: the facade is inert until
called, and the page players get has none of it. `tests/agent-relay.test.js`, `tests/agent-settings.test.js`: the
relay, the browser mode and its rules, and the Settings. `tests/mcp-parity.test.js`: one scripted session gives the
same outcomes headless and through the relay.
The tools read the game's internals (`S`, `R`, `ACT`, `NETS`…), which are not a stable API: a refactor in `src/` can The tools read the game's internals (`S`, `R`, `ACT`, `NETS`…), which are not a stable API: a refactor in `src/` can
break a tool, and the tests are there to catch that in CI. A new action in `ACT` needs an entry in break a tool, and the tests are there to catch that in CI. A new action in `ACT` needs an entry in

3
package-lock.json generated
View file

@ -12,7 +12,8 @@
"@modelcontextprotocol/node": "2.1.2", "@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/server": "2.4.0", "@modelcontextprotocol/server": "2.4.0",
"jsdom": "24.1.3", "jsdom": "24.1.3",
"playwright-core": "1.56.0" "playwright-core": "1.56.0",
"ws": "8.22.0"
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=20"

View file

@ -19,7 +19,8 @@
"page": "node scripts/lib/page.js", "page": "node scripts/lib/page.js",
"serve": "npm run build && npx --yes serve@14.2.4 _site", "serve": "npm run build && npx --yes serve@14.2.4 _site",
"perf": "node scripts/perf-bench.js", "perf": "node scripts/perf-bench.js",
"mcp": "node scripts/mcp.js" "mcp": "node scripts/mcp.js",
"mcp:browser": "node scripts/mcp.js --browser"
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=20"
@ -28,6 +29,7 @@
"@modelcontextprotocol/node": "2.1.2", "@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/server": "2.4.0", "@modelcontextprotocol/server": "2.4.0",
"jsdom": "24.1.3", "jsdom": "24.1.3",
"playwright-core": "1.56.0" "playwright-core": "1.56.0",
"ws": "8.22.0"
} }
} }

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

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

View file

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

View file

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

View file

@ -1,9 +1,11 @@
// The game behind the MCP server (scripts/mcp.js): one game page of its own, the development page from src/ (with the // The game behind the MCP server (scripts/mcp.js), in one of two places. Headless (createSession): one game page of its
// agent facade, src/agent/), loaded in jsdom as the tests load it (tests/harness.js: seeded, no animation loop), with // own, the development page from src/ (with the agent facade, src/agent/), loaded in jsdom as the tests load it
// scripts/lib/mcp-headless.js added to start, load and export games. Every other tool is the page's own facade // (tests/harness.js: seeded, no animation loop), with scripts/lib/mcp-headless.js added to start, load and export games.
// (TUBES.call), so the server plays the game the way the page itself would be played. // In the browser (scripts/lib/mcp-browser.js): the game in the player's tab, over the agent relay. Either way every
// other tool is the page's own facade (TUBES.call), so both play the same game the same way.
// //
// TOOLS is the list the server offers; each run() gets the session and the tool's arguments and returns JSON. // TOOLS is the list the server offers; each says which sessions it works in (modes), and run() gets the session and
// the tool's arguments and returns JSON, or a promise of it (the browser answers over a socket).
const fs = require('node:fs'); const fs = require('node:fs');
const path = require('node:path'); const path = require('node:path');
const { load } = require('../../tests/harness'); const { load } = require('../../tests/harness');
@ -25,12 +27,15 @@ function actArgs() {
return ACT_ARGS; return ACT_ARGS;
} }
const MAX_INLINE_SAVE = 200000; 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. // One call into a jsdom page's facade, as JSON both ways: nothing but plain data crosses.
function pageCall(g, tool, args = {}) { function pageCall(g, tool, args = {}, ctx) {
const w = g.dom.window; const w = g.dom.window;
w.__mcpTool = tool; w.__mcpArgs = JSON.parse(JSON.stringify(args)); 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))') || '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 // Where load_save and export_save may touch files. stdio (saveDir undefined): anywhere, as the operator's own client
@ -46,42 +51,79 @@ function savePath(s, p, write) {
return real; return real;
} }
// opts.seed, opts.file as tests/harness.js takes them (a file must be a development page: it carries the facade). // opts.clock: 'agent' (time moves with advance) or 'realtime' (the session runs a day every opts.paceMs, and tools can
// opts.saveDir: see savePath. // 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 = {}) { 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 boot = () => {
const g = load({ seed: opts.seed || 12345, file: opts.file, agent: true }); const g = load({ seed: opts.seed || 12345, file: opts.file, agent: true });
g.ev(HEADLESS_JS); 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 = (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' }); 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; return g;
}; };
const session = { const session = {
saveDir: opts.saveDir, mode: 'headless', clock, paceMs: clock === 'realtime' ? paceMs : 0, saveDir: opts.saveDir,
get game() { return game || (game = boot()); }, get game() { return game || (game = boot()); },
// The page's own tools (TUBES.call). // The page's own tools (TUBES.call), answered at once.
call(name, args) { return pageCall(session.game, name, args); }, 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); }, headless(fn, ...args) { return session.game.headless(fn, ...args); },
// Text into the page without building a giant eval string (saves run to megabytes). // Text into the page without building a giant eval string (saves run to megabytes).
loadSave(txt) { session.game.dom.window.__mcpSave = txt; return JSON.parse(session.game.ev('JSON.stringify(__mcpHeadless.loadSave(window.__mcpSave))')); }, 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() : []; }, errors() { return game ? game.errors.slice() : []; },
close() { if (timer) clearInterval(timer); timer = null; },
}; };
return session; 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 str = (description, extra = {}) => ({ type: 'string', description, ...extra });
const num = (description, extra = {}) => ({ type: 'number', description, ...extra }); const num = (description, extra = {}) => ({ type: 'number', description, ...extra });
const bool = (description) => ({ type: 'boolean', description }); const bool = (description) => ({ type: 'boolean', description });
const obj = (properties = {}, required = []) => ({ type: 'object', properties, required, additionalProperties: false }); 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 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. // A page tool, passed straight through: the MCP tool's arguments are the facade's.
const page = (name) => (s, a) => s.call(name, a); const page = (name) => (s, a) => s.tool(name, a);
// wait: a running clock's days, read off the page until enough have passed (or something needs an answer).
async function waitDays(s, a) {
const days = Math.max(1, Math.min(365, Math.floor(+a.days) || 1)), maxMs = Math.max(1, Math.min(600, +a.maxSeconds || 120)) * 1000;
const c0 = await s.tool('clock', {});
if (c0.mode !== 'realtime') throw new Error('The clock here is yours and stands still between calls: use advance to move it.');
const t0 = Date.now(), poll = Math.max(10, Math.min(250, (c0.paceMs || 1000) / 4));
let c = c0, stop = null;
if (!c0.running) stop = 'the clock is not running (no game, a puzzle, or the network is bankrupt)';
while (!stop) {
await sleep(poll);
c = await s.tool('clock', {});
if (c.day >= c0.day + days) break;
if (c.lost) stop = 'bankrupt';
else if (c.question && !c0.question) stop = 'a window opened';
else if (Date.now() - t0 >= maxMs) stop = 'maxSeconds passed';
}
const since = await s.tool('since', { day: c0.day, cash: c0.cash, inc: c0.incidents });
return { ...since, daysAsked: days, stoppedBecause: stop, waitedSeconds: Math.round((Date.now() - t0) / 100) / 10 };
}
const TOOLS = [ 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).', 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.'), 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.'), preset: str('Rules preset', { enum: ['soft', 'freeze', 'oncall', 'bgp', 'sandbox'] }), seed: num('Random seed, default 12345.'),
@ -89,7 +131,7 @@ const TOOLS = [
run: (s, a) => s.headless('newGame', a), 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.', 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.') }), inputSchema: obj({ path: str('Path to a .json save file.'), json: str('The save itself, as JSON text.') }),
run: (s, a) => { run: (s, a) => {
@ -99,7 +141,7 @@ const TOOLS = [
}, },
}, },
{ {
name: 'export_save', name: 'export_save', modes: HEADLESS,
description: 'Export the current game as a save file the real game can import (Menu → Import save). Writes it to path, or returns it when it is small.', 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.') }), inputSchema: obj({ path: str('Where to write the .json file.') }),
run: (s, a) => { run: (s, a) => {
@ -110,124 +152,132 @@ const TOOLS = [
}, },
}, },
{ {
name: 'status', name: 'status', modes: BOTH,
description: 'The network at a glance: date, cash, monthly revenue and costs by kind, level, tier and why it is not Tier 1 yet, the current goal, traffic, reach, counts, POPs and open incidents.', 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(), inputSchema: obj(),
run: page('status'), run: page('status'),
}, },
{ {
name: 'advance', name: 'advance', modes: BOTH,
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.', 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.') }), inputSchema: obj({ days: num('Days to run, 1 to 3650. Default 1.') }),
run: page('advance'), 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.', 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']), inputSchema: obj({ network: str('Id (dtk), name (Doitsche Telekomm) or ASN.') }, ['network']),
run: page('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.', 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']), inputSchema: obj({ city: str('Id (fra) or name (Frankfurt).') }, ['city']),
run: page('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.', 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']), inputSchema: obj({ query: str('Part of a name, an id or an ASN.'), kind: str('Only this kind', { enum: ['city', 'network', 'cable', 'exchange'] }) }, ['query']),
run: page('find'), 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:).', description: 'The game\'s looking glass: the path traffic takes from one of your POPs to a network (which exit wins and why, with the AS path) or to another of your POPs (prefix it city:).',
inputSchema: obj({ from: str('One of your POPs: id or name.'), to: str('A network (id, name or ASN), or city:<one of your POPs>.') }, ['from', 'to']), inputSchema: obj({ from: str('One of your POPs: id or name.'), to: str('A network (id, name or ASN), or city:<one of your POPs>.') }, ['from', 'to']),
run: page('traceroute'), 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…).', 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']), inputSchema: obj({ network: str('Id, name or ASN.'), city: str('Only this city.'), via: str('Only this way', { enum: ['pni', 'ix'] }) }, ['network']),
run: page('peering_check'), 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.', 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.') }), inputSchema: obj({ limit: num('How many of each, default 10.') }),
run: page('hot_spots'), run: page('hot_spots'),
}, },
{ {
name: 'schema', name: 'schema', modes: BOTH,
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.', 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 }) }), inputSchema: obj({ section: str('One part only', { enum: SECTIONS }) }),
run: page('schema'), run: (s, a) => then(s.tool('schema', a), (v) => (!a.section ? { ...v, mode: { ...v.mode, ...s.info() } } : a.section === 'mode' ? { ...v, ...s.info() } : v)),
}, },
{ {
name: 'catalog', name: 'catalog', modes: BOTH,
description: 'The game\'s reference tables, which the argument domains point at: CITIES, NETS, CABLES, PORT, LT, OPT, DF_SYS, FAB, INTERNS, OPSK, CHARTERS, SCN, BANKS… plus three made for you: conferences (the upcoming calendar with the keys confGo and confSponsor take), TE_RECIPES (each RouteScript recipe with its script, ready for teDeploy) and BADGES (as the badge wall shows them). Omit name for the list of tables with their sizes.', 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.') }), inputSchema: obj({ name: str('One table; omit for the list.') }),
run: page('catalog'), run: page('catalog'),
}, },
{ {
name: 'state', 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. Give a path (pops.fra, links, loanOffers, biz.3, links.<id>): the whole state of a big network is hundreds of KB.', description: 'The saved game itself as JSON, the same object the game saves: offers, loan offers, links, ports, PNIs, customers, the intern, events… with their ids. schema section "state" documents each field; in the player\'s browser the dice (the seed, the days of the next failure and event) are held back. Give a path (pops.fra, links, loanOffers, biz.3, links.<id>): the whole state of a big network is hundreds of KB.',
inputSchema: obj({ path: str('Dotted path: a key, an array index or an entity id per step.') }), inputSchema: obj({ path: str('Dotted path: a key, an array index or an entity id per step.') }),
run: page('state'), 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).', 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.') }), inputSchema: obj({ path: str('Dotted path.') }),
run: page('results'), 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.', 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(), inputSchema: obj(),
run: page('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=<exchange id>. schema has each one\'s argument domains and what it does.', description: 'Every action act can run, with its arguments (? marks an optional one), e.g. buildPop(city), buyTransit(city,net,tier), buildLink(a,b,tier,cable?,route?,premiumCrossing?). Port tiers: 0 = 10G, 1 = 100G, 2 = 400G, 3 = 800G. Exchanges are given as city=<exchange id>. schema has each one\'s argument domains and what it does.',
inputSchema: obj(), inputSchema: obj(),
run: (s) => { run: (s) => then(s.tool('actions', {}), ({ typed, drafts }) => {
const { typed, drafts } = s.call('actions', {}), a = actArgs(); const a = actArgs();
return [...Object.entries(typed).map(([k, sig]) => `${k}(${sig})`), ...drafts.map((k) => (a[k] ? `${k}(${a[k].join(',')})` : k))].sort(); return [...Object.entries(typed).map(([k, sig]) => `${k}(${sig})`), ...drafts.map((k) => (a[k] ? `${k}(${a[k].join(',')})` : k))].sort();
}, }),
}, },
{ {
name: 'act', 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.', 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"}.' }, 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.') }), dryRun: bool('Price it and check it can be done: {setup, monthly, days, blocked}. Nothing happens.') }),
run: page('act'), 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.', 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).') }), inputSchema: obj({ where: str('Which surface', { enum: WHERE }), offset: num('Start the text here (from textMore).') }),
run: page('screen'), 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.', 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.'), 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'] }) }), left: str('A tab of the left drawer', { enum: ['goals', 'deals', 'noc', 'nets'] }) }),
run: page('panel'), 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.', 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']), inputSchema: obj({ button: num('The button\'s n.'), value: str('For a list: the option to pick.') }, ['button']),
run: page('click'), 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.', 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']), inputSchema: obj({ from: str('One of your POPs.'), to: str('Any city.') }, ['from', 'to']),
run: page('open_link'), run: page('open_link'),
}, },
]; ];
module.exports = { createSession, TOOLS, actArgs, savePath }; const toolsFor = (mode) => TOOLS.filter((t) => t.modes.includes(mode));
module.exports = { createSession, TOOLS, toolsFor, actArgs, pageCall, savePath, CLOCKS, DEFAULT_PACE_MS };

View file

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

View file

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

View file

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

View file

@ -3851,19 +3851,30 @@
"security_and_china.tier_scrubbing_center_online_in_city":"<b>{tier}-Scrubbing-Center in {city} online.</b><br>Angriffe bis {g} werden herausgefiltert, und du kannst DDoS-Schutz verkaufen.", "security_and_china.tier_scrubbing_center_online_in_city":"<b>{tier}-Scrubbing-Center in {city} online.</b><br>Angriffe bis {g} werden herausgefiltert, und du kannst DDoS-Schutz verkaufen.",
"security_and_china.tier_scrubbing_unlocks_at_customer":"<b>{tier}-Scrubbing wird ab Kundenlevel {lv} freigeschaltet.</b>", "security_and_china.tier_scrubbing_unlocks_at_customer":"<b>{tier}-Scrubbing wird ab Kundenlevel {lv} freigeschaltet.</b>",
"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.", "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.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.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.customers_and_alerts":"Kunden und Warnungen",
"settings.display_and_sound":"Anzeige und Ton", "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.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.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_on_outages_that_hurt":"Bei echten Ausfällen pausieren",
"settings.pause_when_a_customer_is_furious":"Bei wütenden Kunden pausieren", "settings.pause_when_a_customer_is_furious":"Bei wütenden Kunden pausieren",
"settings.quiet_notifications":"Leise Benachrichtigungen", "settings.quiet_notifications":"Leise Benachrichtigungen",
"settings.saved_on_this_device":"Auf diesem Gerät gespeichert.", "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.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.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.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.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.n_in_r_regions":"{n} in {r} Regionen",
"share_card.not_this_time":"diesmal nicht", "share_card.not_this_time":"diesmal nicht",

View file

@ -3849,19 +3849,30 @@
"security_and_china.tier_scrubbing_center_online_in_city":"<b>Centro de depuración {tier} en línea en {city}.</b><br>Se limpian ataques de hasta {g}, y puedes vender protección DDoS.", "security_and_china.tier_scrubbing_center_online_in_city":"<b>Centro de depuración {tier} en línea en {city}.</b><br>Se limpian ataques de hasta {g}, y puedes vender protección DDoS.",
"security_and_china.tier_scrubbing_unlocks_at_customer":"<b>La depuración {tier} se desbloquea en el nivel de cliente {lv}.</b>", "security_and_china.tier_scrubbing_unlocks_at_customer":"<b>La depuración {tier} se desbloquea en el nivel de cliente {lv}.</b>",
"security_and_china.you_counter_flooded_a_hospital_in":"Contrainundaste un hospital en un país que no sabes pronunciar.", "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.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.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.customers_and_alerts":"Clientes y alertas",
"settings.display_and_sound":"Pantalla y sonido", "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.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.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_on_outages_that_hurt":"Pausar con caídas que duelen",
"settings.pause_when_a_customer_is_furious":"Pausar cuando un cliente está furioso", "settings.pause_when_a_customer_is_furious":"Pausar cuando un cliente está furioso",
"settings.quiet_notifications":"Notificaciones discretas", "settings.quiet_notifications":"Notificaciones discretas",
"settings.saved_on_this_device":"Guardado en este dispositivo.", "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.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.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.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.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.n_in_r_regions":"{n} en {r} regiones",
"share_card.not_this_time":"esta vez no", "share_card.not_this_time":"esta vez no",

View file

@ -3849,19 +3849,30 @@
"security_and_china.tier_scrubbing_center_online_in_city":"<b>Centre de scrubbing {tier} en ligne à {city}.</b><br>Les attaques jusqu’à {g} sont nettoyées, et tu peux vendre de la protection DDoS.", "security_and_china.tier_scrubbing_center_online_in_city":"<b>Centre de scrubbing {tier} en ligne à {city}.</b><br>Les attaques jusqu’à {g} sont nettoyées, et tu peux vendre de la protection DDoS.",
"security_and_china.tier_scrubbing_unlocks_at_customer":"<b>Le scrubbing {tier} se débloque au niveau client {lv}.</b>", "security_and_china.tier_scrubbing_unlocks_at_customer":"<b>Le scrubbing {tier} se débloque au niveau client {lv}.</b>",
"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.", "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.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.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.customers_and_alerts":"Clients et alertes",
"settings.display_and_sound":"Affichage et son", "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.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.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_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.pause_when_a_customer_is_furious":"Pause quand un client est furieux",
"settings.quiet_notifications":"Notifications discrètes", "settings.quiet_notifications":"Notifications discrètes",
"settings.saved_on_this_device":"Sauvegardées sur cet appareil.", "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.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.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.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.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.n_in_r_regions":"{n} dans {r} régions",
"share_card.not_this_time":"pas cette fois", "share_card.not_this_time":"pas cette fois",

View file

@ -3849,19 +3849,30 @@
"security_and_china.tier_scrubbing_center_online_in_city":"<b>Centro di scrubbing {tier} attivo a {city}.</b><br>Gli attacchi fino a {g} vengono ripuliti, e puoi vendere protezione DDoS.", "security_and_china.tier_scrubbing_center_online_in_city":"<b>Centro di scrubbing {tier} attivo a {city}.</b><br>Gli attacchi fino a {g} vengono ripuliti, e puoi vendere protezione DDoS.",
"security_and_china.tier_scrubbing_unlocks_at_customer":"<b>Lo scrubbing {tier} si sblocca al livello cliente {lv}.</b>", "security_and_china.tier_scrubbing_unlocks_at_customer":"<b>Lo scrubbing {tier} si sblocca al livello cliente {lv}.</b>",
"security_and_china.you_counter_flooded_a_hospital_in":"Hai contro-floodato un ospedale in un paese che non sai pronunciare.", "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.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.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.customers_and_alerts":"Clienti e avvisi",
"settings.display_and_sound":"Schermo e audio", "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.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.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_on_outages_that_hurt":"Pausa sui guasti che fanno male",
"settings.pause_when_a_customer_is_furious":"Pausa quando un cliente è furioso", "settings.pause_when_a_customer_is_furious":"Pausa quando un cliente è furioso",
"settings.quiet_notifications":"Notifiche discrete", "settings.quiet_notifications":"Notifiche discrete",
"settings.saved_on_this_device":"Salvate su questo dispositivo.", "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.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.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.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.build_the_internet_one_tube_at":"Costruisci internet, un tubo alla volta",
"share_card.n_in_r_regions":"{n} in {r} regioni", "share_card.n_in_r_regions":"{n} in {r} regioni",
"share_card.not_this_time":"non stavolta", "share_card.not_this_time":"non stavolta",

View file

@ -3849,19 +3849,30 @@
"security_and_china.tier_scrubbing_center_online_in_city":"<b>Centro de scrubbing {tier} no ar em {city}.</b><br>Ataques de até {g} são limpos, e você pode vender proteção DDoS.", "security_and_china.tier_scrubbing_center_online_in_city":"<b>Centro de scrubbing {tier} no ar em {city}.</b><br>Ataques de até {g} são limpos, e você pode vender proteção DDoS.",
"security_and_china.tier_scrubbing_unlocks_at_customer":"<b>Scrubbing {tier} desbloqueia no nível de cliente {lv}.</b>", "security_and_china.tier_scrubbing_unlocks_at_customer":"<b>Scrubbing {tier} desbloqueia no nível de cliente {lv}.</b>",
"security_and_china.you_counter_flooded_a_hospital_in":"Você contra-floodou um hospital num país que você nem sabe pronunciar.", "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.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.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.customers_and_alerts":"Clientes e alertas",
"settings.display_and_sound":"Tela e som", "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.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.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_on_outages_that_hurt":"Pausar em falhas que doem",
"settings.pause_when_a_customer_is_furious":"Pausar quando um cliente estiver furioso", "settings.pause_when_a_customer_is_furious":"Pausar quando um cliente estiver furioso",
"settings.quiet_notifications":"Notificações discretas", "settings.quiet_notifications":"Notificações discretas",
"settings.saved_on_this_device":"Salvo neste dispositivo.", "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.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.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.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.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.n_in_r_regions":"{n} em {r} regiões",
"share_card.not_this_time":"não foi dessa vez", "share_card.not_this_time":"não foi dessa vez",

View file

@ -1,8 +1,9 @@
/* ================= AGENT API: argument domains ================= /* ================= 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 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. It is part of the development page only (<!-- @include-dev agent -->): the page players get has its own jsdom page, or in the player's tab through the agent relay (80-relay.js). It is part of the development page
none of it, so nothing in src/game/ may name anything defined here. Nothing here runs until a tool calls it: these only (<!-- @include-dev agent -->): the page players get has none of it, so nothing in src/game/ may name anything
files only define tables and functions. 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. */ 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={ const API_DOMAINS={
// Tables from the catalog: an id in a list, a key in an object, or an index into a list. // Tables from the catalog: an id in a list, a key in an object, or an index into a list.

View file

@ -510,7 +510,8 @@ const API_BOUND={
/* Starting, retrying and leaving scenarios, puzzles and architect runs, and the screens a player dismisses. They run /* 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, and exist only in 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). */ 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={ const API_SESSION={
startScn:{args:[['id','scnId']],doc:'Start a scenario (ids from catalog SCN), replacing the current game.'}, 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.'}, startWeekly:{args:[],doc:'Start this week\'s weekly scenario, replacing the current game. The week follows the real date.'},
@ -523,11 +524,14 @@ const API_SESSION={
pitchSkip:{args:[],doc:'Skip the opening pitch; a game waiting behind it starts.'}, pitchSkip:{args:[],doc:'Skip the opening pitch; a game waiting behind it starts.'},
tutSkip:{args:[],doc:'Skip the tutorial coaching.'}, 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};
/* Actions no tool runs, by reason: files, storage slots, settings and the title screen are not the game's, and time /* 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). */ moves only through advance (or the page's own clock). */
const API_WHY={ const API_WHY={
time:'use advance to move time',start:'use new_game',files:'use load_save or export_save', 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', 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)', browser:'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)',
}; };

View file

@ -143,3 +143,12 @@ const API_RESULTS_DOC={
cityBlocked:{type:'map',doc:'Set up per city by the traffic computation; nothing fills it at present.'}, 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.'}, 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',
};

View file

@ -183,19 +183,20 @@ function apiArgDoc([name,dom,req]){
else{const v=apiDomValues(dom);if(Array.isArray(v))a.values=v;else if(v&&v.from!==undefined)a.range=v;} else{const v=apiDomValues(dom);if(Array.isArray(v))a.values=v;else if(v&&v.from!==undefined)a.range=v;}
return a;} return a;}
function apiSchema(section){ function apiSchema(section){
const cmd=s=>({args:(s.args||[]).map(apiArgDoc),doc:s.doc}); const cmd=s=>({args:(s.args||[]).map(apiArgDoc),doc:s.doc}),relay=API_CTX.relay;
const doc={ const doc={
mode:apiMode(),
clock:apiClockDoc(), clock:apiClockDoc(),
commands:Object.fromEntries(Object.entries(API_CMD).map(([n,s])=>[n,{...cmd(s),dryRun:!!s.quote, 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}:{})}])), ...(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)])), 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)])), 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, drafts:API_BOUND,
denied:Object.fromEntries(Object.keys(API_DENY).sort().map(n=>[n,apiDenied(n)])), 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); 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}:{}), 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}:{})}];})), ...(!d.table&&Array.isArray(v)?{values:v}:v&&v.from!==undefined?{range:v}:v&&v.of?{of:v.of}:{})}];})),
state:API_STATE_DOC, 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, results:API_RESULTS_DOC,
}; };
if(section===undefined||section===null||section==='')return doc; if(section===undefined||section===null||section==='')return doc;
@ -208,7 +209,19 @@ function apiCatalog(name){
if(name in API_MADE)return apiJson(API_MADE[name]()); if(name in API_MADE)return apiJson(API_MADE[name]());
if(name in API_TABLES)return apiJson(API_TABLES[name]); if(name in API_TABLES)return apiJson(API_TABLES[name]);
apiFail(`No table "${name}". Call catalog without a name for the list.`);} apiFail(`No table "${name}". Call catalog without a name for the list.`);}
function apiState(path){if(!S)return null;const v=apiJson(apiPath(S,path));return v===undefined?null:v;} // 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<ks.length-1&&o&&typeof o==='object';i++)o=o[ks[i]];
if(o&&typeof o==='object')delete o[ks[ks.length-1]];}
return v;}
function apiResults(path){const v=apiJson(apiPath(R,path));return v===undefined?null:v;} function apiResults(path){const v=apiJson(apiPath(R,path));return v===undefined?null:v;}
function apiUi(){const o={};for(const k of Object.keys(UI))if(!API_UI_HIDDEN[k])o[k]=apiJson(UI[k]);return o;} function apiUi(){const o={};for(const k of Object.keys(UI))if(!API_UI_HIDDEN[k])o[k]=apiJson(UI[k]);return o;}
function apiActions(){ function apiActions(){

View file

@ -4,15 +4,19 @@
const API_ROOT={modal:'modal',bank:'bankBox',dash:'dash',panel:'panel',left:'leftBody',puzzle:'pzBox'}; 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 apiShown=w=>{const el=$(API_ROOT[w]);return !!el&&!el.hidden;};
const apiModalOpen=()=>apiShown('modal'); 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. // The buttons of the last screen a tool read, for click. Set by apiScreen.
let API_LAST=[]; let API_LAST=[];
function apiControls(root){ function apiControls(root,player){
const out=[]; const out=[];
for(const b of root.querySelectorAll('[data-act],select[data-chg]')){ 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} 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. // 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, :{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}; 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);} out.push(o);}
return out;} return out;}
function apiScreen(where,offset=0){ function apiScreen(where,offset=0){
@ -20,12 +24,12 @@ function apiScreen(where,offset=0){
if(where!==undefined&&!API_ROOT[where])apiFail(`where is one of ${Object.keys(API_ROOT).join(', ')}.`); 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 open=Object.keys(API_ROOT).filter(w=>w!=='left'&&apiShown(w));
const w=where||['modal','bank','dash','panel','puzzle'].find(apiShown)||'panel'; const w=where||['modal','bank','dash','panel','puzzle'].find(apiShown)||'panel';
const root=$(API_ROOT[w]); const root=$(API_ROOT[w]),player=w==='modal'&&apiPlayerWin();
API_LAST=root?apiControls(root):[]; 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 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}; const out={where:w,open,selected:UI.sel,tab:UI.tab};
if(w==='left')out.leftTab=UI.left||'goals'; if(w==='left')out.leftTab=UI.left||'goals';
if(w==='modal')out.question=!!apiDecision(); 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); out.text=all.slice(from,from+API_MAX_TEXT);
if(from)out.textFrom=from; if(from)out.textFrom=from;
if(more>0)out.textMore=`${more} more characters: call screen with where "${w}" and offset ${from+API_MAX_TEXT}`; if(more>0)out.textMore=`${more} more characters: call screen with where "${w}" and offset ${from+API_MAX_TEXT}`;
@ -39,14 +43,24 @@ function apiScreen(where,offset=0){
commands wait until it is answered or closed, as clicks outside an open window do in the game. */ commands wait until it is answered or closed, as clicks outside an open window do in the game. */
let API_SHEET=null; let API_SHEET=null;
const apiCard=()=>$('modalCard').firstChild; const apiCard=()=>$('modalCard').firstChild;
const apiMarkSheet=()=>{API_SHEET=apiModalOpen()?apiCard():null;}; const apiMarkSheet=()=>{API_SHEET=apiModalOpen()&&!apiPlayerWin()?apiCard():null;};
const apiIsSheet=()=>apiModalOpen()&&!!API_SHEET&&apiCard()===API_SHEET; const apiIsSheet=()=>apiModalOpen()&&!!API_SHEET&&apiCard()===API_SHEET;
function apiDecision(){ function apiDecision(){
if(!apiModalOpen()||apiIsSheet())return null; if(!apiModalOpen()||apiIsSheet()||apiPlayerWin())return null;
const b=[...$('modal').querySelectorAll('[data-act]')].filter(x=>x.dataset.act!=='closeModal'&&API_CMD[x.dataset.act]); const b=[...$('modal').querySelectorAll('[data-act]')].filter(x=>x.dataset.act!=='closeModal'&&API_CMD[x.dataset.act]);
if(!b.length)return null; 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,' ')}))};} 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}={}){ 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(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}; if(c)UI.sel={type:'city',id:apiCityOf(c).id};
@ -58,6 +72,7 @@ function apiPanel({city:c,link,network:q,tab,left}={}){
function apiOpenLink(a,b){ function apiOpenLink(a,b){
const x=apiCityOf(a).id,y=apiCityOf(b).id; const x=apiCityOf(a).id,y=apiCityOf(b).id;
if(!S.pops[x])apiFail(`A link starts at one of your POPs: ${apiMyPops()}.`); 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(); apiTake();
openLinkModal(x,y); openLinkModal(x,y);
apiMarkSheet(); apiMarkSheet();

View file

@ -34,7 +34,7 @@ function apiMeter(){const real=window.spend;let paid=0;window.spend=c=>{const ok
/* typed: through the command table (bind the UI, type into fields, pass the confirmation); otherwise as a button click /* 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. */ does it, with the button's own arguments. */
function apiDispatch(name,kind,spec,args,typed){ function apiDispatch(name,kind,spec,args,typed){
const mine=apiIsSheet()||(typed&&kind==='game'&&!!spec.open); const mine=apiIsSheet()||(typed&&kind==='game'&&!!spec.open),held=apiPlayerWin()?apiHold():null;
apiTake(); apiTake();
const ref=S,cash=S?S.cash:0,f0=apiFp(spec&&spec.watch,args),paid=apiMeter(); const ref=S,cash=S?S.cash:0,f0=apiFp(spec&&spec.watch,args),paid=apiMeter();
let threw=null,report; let threw=null,report;
@ -49,19 +49,25 @@ function apiDispatch(name,kind,spec,args,typed){
const a=spec.pass?spec.pass(args):args; const a=spec.pass?spec.pass(args):args;
ACT[name](a); ACT[name](a);
if(spec.confirm==='double')ACT[name](a); if(spec.confirm==='double')ACT[name](a);
if(spec.reads==='modal'&&apiModalOpen()){report=apiText($('modal'));closeModal();} if(spec.reads==='modal'&&apiModalOpen()&&!apiPlayerWin()){report=apiText($('modal'));closeModal();}
}else ACT[name](args); }else ACT[name](args);
}catch(e){threw=e;} }catch(e){threw=e;}
const charged=paid(); 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(threw){apiTake();apiFail(`${name} failed: ${threw&&threw.message||threw}`);}
if(!apiModalOpen())API_SHEET=null; if(!apiModalOpen()||apiPlayerWin())API_SHEET=null;
else if(mine||kind!=='game')apiMarkSheet(); else if(mine||kind!=='game')apiMarkSheet();
else API_SHEET=null; else API_SHEET=null;
const said=apiTake(),d=apiDecision(); const said=apiTake(),d=apiDecision();
const outcome=d?'decision':S!==ref||apiFp(spec&&spec.watch,args)!==f0||report!==undefined?'applied' 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'; :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), return {action:name,outcome,toasts:apiToastLines(said),charged,cashChange:Math.round((S?S.cash:0)-cash),
...(report!==undefined?{report}:{}),...(d?{decision:d}:{}),screen:apiScreen()};} ...(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. // While the game waits for an answer, game commands other than its options report the question instead.
function apiWaiting(name){ function apiWaiting(name){
const d=apiDecision(); const d=apiDecision();
@ -82,10 +88,11 @@ function apiQuote(name,spec,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];} }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, 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.'})};} ...(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. // Checks shared by act and click: what no tool runs, and what only the player runs in their own tab.
function apiAllowed(name,what){ function apiAllowed(name,what){
const no=apiDenied(name); const no=apiDenied(name);
if(no)apiFail(`${name} is not available here: ${no}.`); 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); const kind=apiKind(name);
if(!kind||typeof ACT[name]!=='function')apiFail(what); if(!kind||typeof ACT[name]!=='function')apiFail(what);
return kind;} return kind;}
@ -107,6 +114,7 @@ function apiClick(n,value){
const b=API_LAST[n]; const b=API_LAST[n];
if(!b)apiFail(`No button ${n} on the last screen. Call screen first.`); if(!b)apiFail(`No button ${n} on the last screen. Call screen first.`);
if(b.disabled)apiFail(`"${b.label}" is greyed out.`); 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; 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(', ')}.`); 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.`); const kind=apiAllowed(name,`"${b.label}" runs ${name}, which is not an action.`);

View file

@ -1,8 +1,21 @@
/* ================= AGENT API: time ================= /* ================= AGENT API: time =================
The agent's clock: nothing moves until a tool asks for days with advance, one dayTick() per simulated day. */ 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
const apiClockDoc=()=>'Time moves only with advance: one dayTick() per simulated day, as the game loop runs it. Nothing runs between calls.'; 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): the log, new incidents, cash. // 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. // The log keeps what mattered; toasts that only repeat a log line are left out.
function apiSince({day=0,cash=0,inc=[]}={},toasts=[]){ 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 seen=new Set(inc),entries=(S.log||[]).filter(e=>e.d>day).slice(-60),logged=entries.map(e=>apiNorm(apiText(e.t,400)));
@ -15,7 +28,9 @@ function apiSince({day=0,cash=0,inc=[]}={},toasts=[]){
function apiAdvanceStart(days){ function apiAdvanceStart(days){
if(!S)apiFail('No game is running.'); if(!S)apiFail('No game is running.');
if(apiModalOpen())apiFail('A window is open. Answer it first (screen, click, or act closeModal), the game does not run days behind it.'); 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; API_SHEET=null;
apiTake(); 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};} 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};}
@ -26,7 +41,7 @@ function apiAdvanceDay(a){
const t=performance.now(); const t=performance.now();
dayTick(); dayTick();
a.times.push({day:S.day,ms:apiR1(performance.now()-t)});a.ran++; a.times.push({day:S.day,ms:apiR1(performance.now()-t)});a.ran++;
if(apiModalOpen()){a.stop='a window opened';return false;} if(apiModalOpen()&&!apiPlayerWin()){a.stop='a window opened';return false;}
return a.ran<a.days;} return a.ran<a.days;}
function apiAdvanceEnd(a){ function apiAdvanceEnd(a){
renderAll(); renderAll();
@ -36,3 +51,17 @@ function apiAdvanceEnd(a){
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}))}, 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}:{})};} ...(out.decision?{decision:out.decision,screen:out.screen}:{})};}
function apiAdvance(days){const a=apiAdvanceStart(days);while(apiAdvanceDay(a));return apiAdvanceEnd(a);} 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;}

86
src/agent/75-mode.js Normal file
View file

@ -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 `<button class="play${UI.speed?'':' paused'}" disabled aria-label="${UI.speed?tr('common.pause'):tr('common.play')}"><span class="ic" aria-hidden="true">${UI.speed?'❚❚':'▶'}</span>${UI.speed?tr('common.pause'):tr('common.play')}</button>`+
`<button class="pace" disabled aria-label="${tr('common.game_speed')}"><span class="ic" aria-hidden="true">${apiAgentMs()>0?apiAgentMsLabel():'🤖'}</span>${tr('common.speed')}</button>`;}
/* 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)=>`<button class="b ${on?'pink sm':'ghost sm'}" data-agent-set="${v}">${l}</button>`;
const line=(lab,btns,note)=>`<div class="setline"><span>${lab}</span><div class="seg">${btns}</div></div><p class="meta" style="margin:0 0 6px">${note}</p>`;
return `<h3 class="sub4">${tr('settings.agent_api')}</h3>`+
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();}

77
src/agent/80-relay.js Normal file
View file

@ -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:<port>'; 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=()=>{};}

24
src/agent/85-ticker.js Normal file
View file

@ -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);}}

View file

@ -1,7 +1,10 @@
/* ================= AGENT API: the facade ================= /* ================= 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 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. Nothing here listens, polls or runs on the day loop: toast() is only listened to arguments, answered as plain JSON (or a promise of it, for days that run where the player can watch). Nothing here
while a call runs. */ 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}; const API_TOASTS={depth:0,list:[],real:null};
function apiTake(){const t=API_TOASTS.list;API_TOASTS.list=[];return t;} function apiTake(){const t=API_TOASTS.list;API_TOASTS.list=[];return t;}
const apiToastLines=t=>t.map(x=>(x.kind?x.kind+': ':'')+x.text); const apiToastLines=t=>t.map(x=>(x.kind?x.kind+': ':'')+x.text);
@ -32,12 +35,20 @@ const API_TOOLS={
panel:a=>apiPanel(a), panel:a=>apiPanel(a),
click:a=>apiClick(a.button,a.value), click:a=>apiClick(a.button,a.value),
open_link:a=>apiOpenLink(a.from,a.to), open_link:a=>apiOpenLink(a.from,a.to),
advance:a=>apiAdvance(a.days), advance:a=>API_CTX.relay?apiAdvanceLive(a.days):apiAdvance(a.days),
clock:()=>apiClock(),
since:a=>apiSince(a),
}; };
function apiCall(tool,args){ function apiCall(tool,args,ctx){
if(typeof tool!=='string'||!own(API_TOOLS,tool))apiFail(`No tool "${tool}".`); if(typeof tool!=='string'||!own(API_TOOLS,tool))apiFail(`No tool "${tool}".`);
if(!S&&!['schema','catalog','classes','actions'].includes(tool))apiFail('No game is running.'); 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); apiListen(true);
try{return API_TOOLS[tool](args&&typeof args==='object'&&!Array.isArray(args)?args:{});} let out;
finally{apiListen(false);}} 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}; window.TUBES={version:1,tools:Object.keys(API_TOOLS),call:apiCall};

4
src/agent/99-start.js Normal file
View file

@ -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();

View file

@ -1,5 +1,9 @@
/* ================= STATE ================= */ /* ================= STATE ================= */
let S=null, R=emptyR(); 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++); 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:{}};} 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:{}};}

View file

@ -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(); 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;}} 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. // 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); 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?`<b>${esc(S.scn.name)}</b><br>${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'); toast(S.scn?`<b>${esc(S.scn.name)}</b><br>${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();} renderAll();save();if(!S.scn&&S.mode!=='sandbox'&&S.mode!=='puzzle')tutorialStart();}

View file

@ -132,7 +132,7 @@ function pzBegin(def){if(!def)return;pzMkStop();mkStop();
if(live)pzFlush();go();} 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; 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(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. // 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;}} if(UI.slot&&(sv||UI.loadBad)){slotBroke(UI.slot);return;}}
renderAll();showTitle();} renderAll();showTitle();}

View file

@ -2,7 +2,7 @@
function spend(c){if(S.cash<c){toast(tr('interface.not_enough_cash_wait_for_revenue'),'bad');sfx('err');return false;}S.cash-=c;sfx('build');return true;} function spend(c){if(S.cash<c){toast(tr('interface.not_enough_cash_wait_for_revenue'),'bad');sfx('err');return false;}S.cash-=c;sfx('build');return true;}
const ACT={ const ACT={
linkCheck:({id})=>{const l=S.links.find(x=>x.id===id);if(!l||linkDown(l))return;linkCheckModal(l);}, linkCheck:({id})=>{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(), help:()=>showHelp(),
dash:()=>{if(!S||pzOn())return;const d=$('dash');d.hidden=!d.hidden;if(!d.hidden)renderDash();}, dash:()=>{if(!S||pzOn())return;const d=$('dash');d.hidden=!d.hidden;if(!d.hidden)renderDash();},
dashClose:()=>{$('dash').hidden=true;}, 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();}}, 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();}, 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();}, 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();}, 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())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();}, 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;} install:()=>{if(installEvt){installEvt.prompt();installEvt.userChoice.finally(()=>{installEvt=null;});return;}
openModal(pitchHtml(false));}, openModal(pitchHtml(false));},
pitchSkip:()=>{const p=UI.pendGame;UI.pendGame=null;UI.pitched=true;if(p)beginGame(...p);else closeModal();}, pitchSkip:()=>{const p=UI.pendGame;UI.pendGame=null;UI.pitched=true;if(p)beginGame(...p);else closeModal();},

View file

@ -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();}, 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; 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. // 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(`<div style="display:flex;align-items:center"><div><div class="eyebrow">AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}</div><h2 style="font-size:28px">${esc(S.name)} <button class="thb rn" data-act="rename" aria-label="${tr('slots.rename_your_network')}">✏️</button></h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div> menu:()=>{if(!S||!UI.started){showTitle();return;}if(pzOn()){pzMenu();return;}openModal(`<div style="display:flex;align-items:center"><div><div class="eyebrow">AS${S.asn} · ${esc(dateStr(S.day))} · ${tierLabel()}</div><h2 style="font-size:28px">${esc(S.name)} <button class="thb rn" data-act="rename" aria-label="${tr('slots.rename_your_network')}">✏️</button></h2></div><button class="x" data-act="closeModal" aria-label="${tr('common.close')}">×</button></div>
${saveFailing()?`<p class="why">${saveFailMsg()}</p>`:`<p class="tagline">${tr('game_and_settings.your_game_saves_itself_every_few')}</p>`} ${saveFailing()?`<p class="why">${saveFailMsg()}</p>`:`<p class="tagline">${tr('game_and_settings.your_game_saves_itself_every_few')}</p>`}
<div class="menu-list"> <div class="menu-list">

View file

@ -29,6 +29,6 @@ Object.assign(ACT,{
// No game on screen: the map stays empty behind the title. // No game on screen: the map stays empty behind the title.
function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();} function gameClear(){S=null;R=emptyR();UI.started=false;UI.sel=null;UI.nm=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;renderAll();}
// Back from the title (or a puzzle) into a loaded network. // Back from the title (or a puzzle) into a loaded network.
function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1; function gameResume(){UI.started=true;UI.sel=null;UI.confirm=null;$('dash').hidden=true;$('bankBox').hidden=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);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}} 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;cam.z=innerWidth<760?1.1:1.4;}}
closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');} closeModal();renderAll();toast(tr('loop.welcome_back_name_your_network_is',{name:esc(S.name),date:dateStr(S.day)}),'good');}

View file

@ -8,7 +8,8 @@ function save(force,st){if(!st)st=pzOn()?UI.pzKeep:S;const id=UI.slot;
// Half a day (its routing still in the worker) is never saved: the day's end saves instead. // Half a day (its routing still in the worker) is never saved: the day's end saves instead.
if(RW.job&&st===S){UI.saveDue=true;UI.lastSave=performance.now();return;} if(RW.job&&st===S){UI.saveDue=true;UI.lastSave=performance.now();return;}
if(!st||st.lost||st.mode==='puzzle'||!id||SLOT.no.has(id))return; if(!st||st.lost||st.mode==='puzzle'||!id||SLOT.no.has(id))return;
if(st===S){S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};}const f=UI.saveFail,failed=f&&f.s===st; // A locked clock's speed is not the player's: the one they left the game at stays saved.
if(st===S){if(!UI.clockLocked)S.uiSpeed=UI.speed;S.cam={x:cam.x,y:cam.y,z:cam.z};}const f=UI.saveFail,failed=f&&f.s===st;
if(!force&&failed&&performance.now()-f.at<f.wait){UI.lastSave=performance.now();return;} if(!force&&failed&&performance.now()-f.at<f.wait){UI.lastSave=performance.now();return;}
UI.lastSave=performance.now(); UI.lastSave=performance.now();
// Set aside for a puzzle, it cannot change: once its save has landed (or is still compressing), there is nothing to do. // Set aside for a puzzle, it cannot change: once its save has landed (or is still compressing), there is nothing to do.

View file

@ -4,7 +4,8 @@ const SPEEDS=[0.5,1,2,4,8];
function renderTabbar(){const tb=$('tabbar');if(!tb||(pressing&&UI.ticking))return;if(!isPhone()||!S||!UI.started||pzOn()){tb.hidden=true;document.body.classList.toggle('sheet-open',pzOn()&&isPhone()&&!!UI.sel);return;}tb.hidden=false; function renderTabbar(){const tb=$('tabbar');if(!tb||(pressing&&UI.ticking))return;if(!isPhone()||!S||!UI.started||pzOn()){tb.hidden=true;document.body.classList.toggle('sheet-open',pzOn()&&isPhone()&&!!UI.sel);return;}tb.hidden=false;
const open=UI.leftOpen&&!UI.sel,cur=UI.left||'goals',ndone=GOALS.filter(g=>S.done[g.id]!==undefined).length; const open=UI.leftOpen&&!UI.sel,cur=UI.left||'goals',ndone=GOALS.filter(g=>S.done[g.id]!==undefined).length;
const tab=(k,ic,l,cnt,red)=>`<button class="${open&&cur===k?'on':''}" data-act="phoneTab" data-args='{"t":"${k}"}' aria-label="${esc(l)}"><span class="ic" aria-hidden="true">${ic}</span>${esc(l)}${cnt?(cnt===' '?`<span class="cnt red dot"></span>`:`<span class="cnt${red?' red':''}">${cnt}</span>`):''}</button>`; const tab=(k,ic,l,cnt,red)=>`<button class="${open&&cur===k?'on':''}" data-act="phoneTab" data-args='{"t":"${k}"}' aria-label="${esc(l)}"><span class="ic" aria-hidden="true">${ic}</span>${esc(l)}${cnt?(cnt===' '?`<span class="cnt red dot"></span>`:`<span class="cnt${red?' red':''}">${cnt}</span>`):''}</button>`;
const h=(rule('clock')?`<button class="play${UI.speed?'':' paused'}" data-act="phonePlay" aria-label="${UI.speed?tr('common.pause'):tr('common.play')}"><span class="ic" aria-hidden="true">${UI.speed?'❚❚':'▶'}</span>${UI.speed?tr('common.pause'):tr('common.play')}</button>`+ // A locked clock's two buttons come from whatever locked it (HOOKS.tabbar), in the same two slots, so the tabs stay put.
const h=(rule('clock')?UI.clockLocked&&HOOKS.tabbar?HOOKS.tabbar():`<button class="play${UI.speed?'':' paused'}" data-act="phonePlay" aria-label="${UI.speed?tr('common.pause'):tr('common.play')}"><span class="ic" aria-hidden="true">${UI.speed?'❚❚':'▶'}</span>${UI.speed?tr('common.pause'):tr('common.play')}</button>`+
`<button data-act="phoneSpeed" aria-label="${tr('common.game_speed')}"><span class="ic" aria-hidden="true">${UI.speed===0.5?'½':(UI.lastSpeed||UI.speed||1)}×</span>${tr('common.speed')}</button>`:'')+ `<button data-act="phoneSpeed" aria-label="${tr('common.game_speed')}"><span class="ic" aria-hidden="true">${UI.speed===0.5?'½':(UI.lastSpeed||UI.speed||1)}×</span>${tr('common.speed')}</button>`:'')+
(()=>{const P=scnProg();return tab('goals','🎯',tr('common.goals'),P&&!S.scn.done&&!S.scn.failed?`${Math.round(P.f*100)}%`:`${ndone}/${GOALS.length}`);})()+(()=>{const u=custStats().unhappy;return u?tab('deals','💼',tr('common.deals'),u,true):tab('deals','💼',tr('common.deals'),S.offers.length||'');})()+tab('noc','🚨','NOC',S.inc.length?' ':'',true)+tab('nets','🌐',tr('common.networks'),''); (()=>{const P=scnProg();return tab('goals','🎯',tr('common.goals'),P&&!S.scn.done&&!S.scn.failed?`${Math.round(P.f*100)}%`:`${ndone}/${GOALS.length}`);})()+(()=>{const u=custStats().unhappy;return u?tab('deals','💼',tr('common.deals'),u,true):tab('deals','💼',tr('common.deals'),S.offers.length||'');})()+tab('noc','🚨','NOC',S.inc.length?' ':'',true)+tab('nets','🌐',tr('common.networks'),'');
if(h!==UI._tb){UI._tb=h;tb.innerHTML=h;} if(h!==UI._tb){UI._tb=h;tb.innerHTML=h;}

View file

@ -3,7 +3,8 @@ function fitHud(){const h=$('hud');if(!h)return;h.classList.remove('fit1','fit2'
for(const c of ['fit1','fit2','fit3']){if(h.offsetHeight<=row()*1.5)break;h.classList.add(c);}} for(const c of ['fit1','fit2','fit3']){if(h.offsetHeight<=row()*1.5)break;h.classList.add(c);}}
function renderHUD(){ function renderHUD(){
// No clock (puzzles): there is no time to speed up, so the speed buttons go. // No clock (puzzles): there is no time to speed up, so the speed buttons go.
{const ck=!S||rule('clock');for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',UI.speed===v);b.hidden=!ck;}}} // A locked clock has no buttons: whoever locked it shows what it runs at (HOOKS.hud).
{const ck=!S||rule('clock'),lk=UI.clockLocked;for(const v of [0,0.5,1,2,4,8]){const b=$('sp'+v);if(b){b.classList.toggle('on',!lk&&UI.speed===v);b.hidden=lk||!ck;}}HOOKS.hud?.();}
$('muteBtn').style.opacity=UI.muted?.4:1; $('muteBtn').style.opacity=UI.muted?.4:1;
if(!S)return; if(!S)return;
if(pzOn()){$('hName').textContent=pzName(pzDef(S.pz.id)||S.pz);$('hAsn').textContent=tr('puzzles.puzzle');renderTabbar();return;} if(pzOn()){$('hName').textContent=pzName(pzDef(S.pz.id)||S.pz);$('hAsn').textContent=tr('puzzles.puzzle');renderTabbar();return;}

View file

@ -1,7 +1,7 @@
// Keyboard focus moves into the modal, so Enter or Space can't keep pressing a hidden button behind it. // Keyboard focus moves into the modal, so Enter or Space can't keep pressing a hidden button behind it.
// The link check on phones sits above the tab bar and is not modal, so the tabs stay usable. // The link check on phones sits above the tab bar and is not modal, so the tabs stay usable.
function openModal(html,cls=''){$('modal').className=cls;$('modalCard').setAttribute('aria-modal',cls==='link-check'&&isPhone()?'false':'true');if($('modal').hidden)markLayer();$('modalCard').innerHTML=html;$('modal').hidden=false;const a=document.activeElement;if(a&&a!==document.body&&!a.closest('#modal')){a.blur();const m=$('modalCard');m.tabIndex=-1;m.focus({preventScroll:true});}} function openModal(html,cls=''){HOOKS.modal?.(true);$('modal').className=cls;$('modalCard').setAttribute('aria-modal',cls==='link-check'&&isPhone()?'false':'true');if($('modal').hidden)markLayer();$('modalCard').innerHTML=html;$('modal').hidden=false;const a=document.activeElement;if(a&&a!==document.body&&!a.closest('#modal')){a.blur();const m=$('modalCard');m.tabIndex=-1;m.focus({preventScroll:true});}}
function closeModal(){if(!$('modal').hidden)markLayer();$('modal').hidden=true;UI.pending=null;} function closeModal(){if(!$('modal').hidden)markLayer();$('modal').hidden=true;UI.pending=null;HOOKS.modal?.(false);}
const NETWORK_NAMES=[ const NETWORK_NAMES=[
'Packet Pals','Shinternet','Post, Telegraph & Tubes','Peering Pressure','Best Effort Telecom', 'Packet Pals','Shinternet','Post, Telegraph & Tubes','Peering Pressure','Best Effort Telecom',
'Mostly Online','Buffering & Sons','Lord of the Pings','The Ping Dynasty', 'Mostly Online','Buffering & Sons','Lord of the Pings','The Ping Dynasty',

View file

@ -15,12 +15,14 @@ const pref=k=>typeof PREFS[k]==='boolean'?PREFS[k]:PREF_DEF[k];
// Quiet notifications: the player's choice once made, until then on in Best Effort only. // Quiet notifications: the player's choice once made, until then on in Best Effort only.
const quietOn=()=>typeof PREFS.quiet==='boolean'?PREFS.quiet:rulePreset()==='soft'; const quietOn=()=>typeof PREFS.quiet==='boolean'?PREFS.quiet:rulePreset()==='soft';
function setPref(k,v){if(!own(PREF_DEF,k))return;PREFS[k]=!!v;try{localStorage.setItem('sot-prefs',JSON.stringify(PREFS));}catch(e){}} function setPref(k,v){if(!own(PREF_DEF,k))return;PREFS[k]=!!v;try{localStorage.setItem('sot-prefs',JSON.stringify(PREFS));}catch(e){}}
// Stop the clock for something the player must see. Nothing happens if the game is already paused. // Stop the clock for something the player must see. Nothing happens if the game is already paused, or not the player's.
function autoPause(){if(!S||!UI.speed)return false;UI.resumeSpeed=UI.speed;UI.speed=0;renderHUD();return true;} function autoPause(){if(!S||!UI.speed||UI.clockLocked)return false;UI.resumeSpeed=UI.speed;UI.speed=0;renderHUD();return true;}
// Put the clock back at a speed (a new game, a loaded or resumed one): unless it is locked, then it runs as the lock says.
function setSpeed(v){UI.speed=UI.clockLocked&&HOOKS.speed?HOOKS.speed():v;}
const resumeAct=()=>({l:tr('common.resume'),act:'speed',args:{v:UI.resumeSpeed||1}}); const resumeAct=()=>({l:tr('common.resume'),act:'speed',args:{v:UI.resumeSpeed||1}});
function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`<div class="setline"><span>${lab}</span><div class="seg">${segBtns(act,cur,opts)}</div></div>${note?`<p class="meta" style="margin:0 0 6px">${note}</p>`:''}`; function settingsHtml(){const seg=(lab,act,cur,opts,note)=>`<div class="setline"><span>${lab}</span><div class="seg">${segBtns(act,cur,opts)}</div></div>${note?`<p class="meta" style="margin:0 0 6px">${note}</p>`:''}`;
const onoff=k=>[[k+':1',tr('common.on')],[k+':0',tr('common.off')]],cur=k=>k+':'+((k==='quiet'?quietOn():pref(k))?1:0); const onoff=k=>[[k+':1',tr('common.on')],[k+':0',tr('common.off')]],cur=k=>k+':'+((k==='quiet'?quietOn():pref(k))?1:0);
return `<div style="display:flex;align-items:center"><h2 style="font-size:26px">⚙️ ${tr('common.settings')}</h2><button class="x" data-act="settingsClose" aria-label="${tr('common.close')}">×</button></div><p class="tagline">${tr('settings.saved_on_this_device')}</p> return `<div style="display:flex;align-items:center"><h2 style="font-size:26px">⚙️ ${tr('common.settings')}</h2><button class="x" data-act="settingsClose" aria-label="${tr('common.close')}">×</button></div><p class="tagline">${tr('settings.saved_on_this_device')}</p>${HOOKS.settings?HOOKS.settings():''}
<h3 class="sub4">${tr('settings.customers_and_alerts')}</h3> <h3 class="sub4">${tr('settings.customers_and_alerts')}</h3>
${seg(tr('settings.pause_when_a_customer_is_furious'),'prefSet',cur('pauseFurious'),onoff('pauseFurious'),tr('settings.the_game_stops_so_you_can'))} ${seg(tr('settings.pause_when_a_customer_is_furious'),'prefSet',cur('pauseFurious'),onoff('pauseFurious'),tr('settings.the_game_stops_so_you_can'))}
${seg(tr('settings.warn_when_a_customer_gets_unhappy'),'prefSet',cur('warnUnhappy'),onoff('warnUnhappy'),tr('settings.an_early_heads_up_below_60'))} ${seg(tr('settings.warn_when_a_customer_gets_unhappy'),'prefSet',cur('warnUnhappy'),onoff('warnUnhappy'),tr('settings.an_early_heads_up_below_60'))}

View file

@ -40,5 +40,5 @@ cv.addEventListener('pointerup',endPtr);cv.addEventListener('pointercancel',canc
const ZMIN=0.35,ZMAX=16; const ZMIN=0.35,ZMAX=16;
function zoomAt(mx,my,f){const wx=cam.x+(mx-CW/2)/cam.z,wy=cam.y+(my-CH/2)/cam.z;cam.z=clamp(cam.z*f,ZMIN,ZMAX);cam.x=wx-(mx-CW/2)/cam.z;cam.y=wy-(my-CH/2)/cam.z;wrapCam();} function zoomAt(mx,my,f){const wx=cam.x+(mx-CW/2)/cam.z,wy=cam.y+(my-CH/2)/cam.z;cam.z=clamp(cam.z*f,ZMIN,ZMAX);cam.x=wx-(mx-CW/2)/cam.z;cam.y=wy-(my-CH/2)/cam.z;wrapCam();}
cv.addEventListener('wheel',e=>{e.preventDefault();zoomAt(e.clientX,e.clientY,Math.exp(-e.deltaY*0.0015));},{passive:false}); cv.addEventListener('wheel',e=>{e.preventDefault();zoomAt(e.clientX,e.clientY,Math.exp(-e.deltaY*0.0015));},{passive:false});
addEventListener('keydown',e=>{if(e.key==='Enter'&&e.target.id==='metIn'){ACT.metricSet({id:e.target.dataset.id});return;}if(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]'))return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.code==='Space'&&e.target.closest&&e.target.closest('button,a'))return;if(e.code==='Space'&&(!S||rule('clock'))&&!pzOn()){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='0')ACT.speed({v:0.5});if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}}); addEventListener('keydown',e=>{if(e.key==='Enter'&&e.target.id==='metIn'){ACT.metricSet({id:e.target.dataset.id});return;}if(e.target.closest&&e.target.closest('input,textarea,select,[contenteditable]'))return;if(e.ctrlKey||e.metaKey||e.altKey)return;if(e.code==='Space'&&e.target.closest&&e.target.closest('button,a'))return;if(e.code==='Space'&&(!S||rule('clock'))&&!pzOn()&&!UI.clockLocked){e.preventDefault();UI.speed=UI.speed?0:1;renderHUD();}if(e.key==='0')ACT.speed({v:0.5});if(e.key==='1')ACT.speed({v:1});if(e.key==='2')ACT.speed({v:2});if(e.key==='3')ACT.speed({v:4});if(e.key==='4')ACT.speed({v:8});if(e.key==='Escape'&&!$('bankBox').hidden){$('bankBox').hidden=true;return;}if(e.key==='Escape'&&!$('dash').hidden){$('dash').hidden=true;return;}if(e.key==='Escape'){if(!$('modal').hidden){if(S&&UI.started&&!S.lost)closeModal();}else{UI.sel=null;renderPanel();}}});

View file

@ -8,15 +8,18 @@ function frame(now){
if(S&&UI.started&&!S.lost&&now-(UI.lastSave||0)>5000)save(); if(S&&UI.started&&!S.lost&&now-(UI.lastSave||0)>5000)save();
// The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them. // The panels catch up on the frame after a day, so one frame does not carry both the day's simulation and them.
if(UI.panelsDue){UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();} if(UI.panelsDue){UI.panelsDue=false;if(!pressing){renderPanel();renderLeft();if(!$('dash').hidden)renderDash();renderBank();}renderHint();}
if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn()){acc+=dt*UI.speed;let n=0; if(S&&!S.lost&&$('modal').hidden&&UI.speed&&!pzOn())runClock(dt);
// With the route worker one day is in flight at a time; time does not pile up behind it.
if(rwOn()){if(!RW.w)rwStart();if(RW.job)acc=Math.min(acc,DAY_MS);else if(acc>=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);try{rwDay();}catch(e){tickErr(e);}}}
else{while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;}
if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}}}
if((UI.speed||pzOn())&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */ if((UI.speed||pzOn())&&!(S&&S.lost))animT+=dt; /* paused = frozen dots, waves and clouds */
const t=animOn()?animT:0; const t=animOn()?animT:0;
if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;} if(!(UI.mapHid=mapHidden())&&!mapStill(t,now)){try{draw(t);}catch(e){tickErr(e);}UI.drawnAt=now;}
} }
// dt of real time at UI.speed: the days it adds up to. The frame calls it; so may a clock that also runs where frames
// do not (src/agent/, a hidden tab), under the frame's own conditions otherwise.
function runClock(dt){acc+=dt*UI.speed;let n=0;
// With the route worker one day is in flight at a time; time does not pile up behind it.
if(rwOn()){if(!RW.w)rwStart();if(RW.job)acc=Math.min(acc,DAY_MS);else if(acc>=DAY_MS){acc=Math.min(acc-DAY_MS,DAY_MS);try{rwDay();}catch(e){tickErr(e);}}}
else{while(acc>=DAY_MS&&n<4&&UI.speed){acc-=DAY_MS;try{dayTick();}catch(e){tickErr(e);}n++;}
if(n){UI.ticking=true;renderHUD();UI.ticking=false;UI.panelsDue=true;}}}
/* On a phone the NOC dashboard (or the bank), scrolled past its top edge, covers the whole map. Drawing the map /* On a phone the NOC dashboard (or the bank), scrolled past its top edge, covers the whole map. Drawing the map
under it is work nobody sees, so it waits until the map shows again (and no payday money piles up meanwhile). */ under it is work nobody sees, so it waits until the map shows again (and no payday money piles up meanwhile). */
function mapHidden(){for(const id of ['dashCard','bankCard']){const c=$(id);if(c.parentNode.hidden)continue; function mapHidden(){for(const id of ['dashCard','bankCard']){const c=$(id);if(c.parentNode.hidden)continue;
@ -38,7 +41,7 @@ function boot(data){
if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();} if(data&&data.S){S=migrate(data.S);UI.started=true;if(data.cam)Object.assign(cam,data.cam);compute();renderAll();}
else{const sv=UI.slot?loadSave():null,stamp=sv&&sv.sv;if(sv)delete sv.sv; else{const sv=UI.slot?loadSave():null,stamp=sv&&sv.sv;if(sv)delete sv.sv;
let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}} let okSave=false;if(sv){try{S=migrate(sv);compute();okSave=true;}catch(e){console.error('[tubes] loading the network failed',e);S=null;UI.started=false;}}
if(okSave){slotIn(UI.slot,stamp);UI.started=true;UI.speed=[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:1; if(okSave){slotIn(UI.slot,stamp);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);else{const h=CITY[S.home];if(h){cam.x=h.x;cam.y=h.y;cam.z=innerWidth<760?1.1:1.4;}} 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;cam.z=innerWidth<760?1.1:1.4;}}
renderAll();if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);} renderAll();if(S.grace&&S.grace.until>S.day&&R.graceNets&&!S.grace.told){S.grace.told=1;toast(tr('loop.new_networks_on_the_map_this',{n:S.grace.until-S.day}),'goal',[{l:tr('common.open_noc'),act:'leftTab',args:{t:'noc'}}]);}
if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});} if(S.auNews){delete S.auNews;const c=Object.keys(S.pops).find(x=>CITY[x].au);toast(tr('loop.australia_got_more_australian'),'bad',[{l:tr('common.open'),act:'focusCity',args:{city:c}}],{a:'city',v:c});}

View file

@ -3850,19 +3850,30 @@
"security_and_china.tier_scrubbing_center_online_in_city":"<b>{tier} scrubbing center online in {city}.</b><br>Attacks up to {g} are cleaned, and you can sell DDoS protection.", "security_and_china.tier_scrubbing_center_online_in_city":"<b>{tier} scrubbing center online in {city}.</b><br>Attacks up to {g} are cleaned, and you can sell DDoS protection.",
"security_and_china.tier_scrubbing_unlocks_at_customer":"<b>{tier} scrubbing unlocks at customer level {lv}.</b>", "security_and_china.tier_scrubbing_unlocks_at_customer":"<b>{tier} scrubbing unlocks at customer level {lv}.</b>",
"security_and_china.you_counter_flooded_a_hospital_in":"You counter-flooded a hospital in a country you cannot pronounce.", "security_and_china.you_counter_flooded_a_hospital_in":"You counter-flooded a hospital in a country you cannot pronounce.",
"settings.a_pace_runs_one_simulated_day":"A pace runs one simulated day every 30 seconds to 5 minutes, and the agent has to keep up. Moved by the agent, the clock stands still until the agent asks for days.",
"settings.agent_api":"Agent API",
"settings.agent_relay_connected":"Agent relay connected: a tool can now drive this game in this tab.",
"settings.agent_s_clock":"Agent's clock",
"settings.an_early_heads_up_below_60":"An early heads-up below 60% happiness, long before they are furious.", "settings.an_early_heads_up_below_60":"An early heads-up below 60% happiness, long before they are furious.",
"settings.auto_follows_your_device_s_reduce":"Auto follows your device’s reduce-motion setting. Off freezes the map: no moving packets, pulses or floating text.", "settings.auto_follows_your_device_s_reduce":"Auto follows your device’s reduce-motion setting. Off freezes the map: no moving packets, pulses or floating text.",
"settings.customers_and_alerts":"Customers and alerts", "settings.customers_and_alerts":"Customers and alerts",
"settings.display_and_sound":"Display and sound", "settings.display_and_sound":"Display and sound",
"settings.for_reporting_layout_bugs_shows_what":"For reporting layout bugs: shows what your screen tells the game.", "settings.for_reporting_layout_bugs_shows_what":"For reporting layout bugs: shows what your screen tells the game.",
"settings.let_an_ai_agent_drive_this_game":"Let an AI agent drive this game",
"settings.n_min":"{n} min",
"settings.n_sec":"{n} s",
"settings.only_trouble_and_milestones_pop_up":"Only trouble and milestones pop up; everything else goes quietly into the NOC log. On by default in Best Effort.", "settings.only_trouble_and_milestones_pop_up":"Only trouble and milestones pop up; everything else goes quietly into the NOC log. On by default in Best Effort.",
"settings.pace_t_per_day":"{t} per simulated day",
"settings.pause_on_outages_that_hurt":"Pause on outages that hurt", "settings.pause_on_outages_that_hurt":"Pause on outages that hurt",
"settings.pause_when_a_customer_is_furious":"Pause when a customer is furious", "settings.pause_when_a_customer_is_furious":"Pause when a customer is furious",
"settings.quiet_notifications":"Quiet notifications", "settings.quiet_notifications":"Quiet notifications",
"settings.saved_on_this_device":"Saved on this device.", "settings.saved_on_this_device":"Saved on this device.",
"settings.stops_the_game_when_a_failure":"Stops the game when a failure costs you real traffic, not when it reroutes by itself.", "settings.stops_the_game_when_a_failure":"Stops the game when a failure costs you real traffic, not when it reroutes by itself.",
"settings.the_agent_moves_it":"The agent moves it",
"settings.the_clock_while_an_agent_plays":"The clock while an agent plays",
"settings.the_game_stops_so_you_can":"The game stops so you can fix their service before they cancel. Most useful at high speed.", "settings.the_game_stops_so_you_can":"The game stops so you can fix their service before they cancel. Most useful at high speed.",
"settings.warn_when_a_customer_gets_unhappy":"Warn when a customer gets unhappy", "settings.warn_when_a_customer_gets_unhappy":"Warn when a customer gets unhappy",
"settings.while_agent_mode_is_on_the":"While agent mode is on, the clock is not yours. With a pace it runs by itself and cannot be paused by hand, not even by an open window (yours included), and it waits while no agent is connected. Or the agent moves it, and nothing happens until it asks for days. The page connects to the local agent relay (npm run dev hosts one), so tools like the MCP server can drive this game while you watch.",
"share_card.build_the_internet_one_tube_at":"Build the internet, one tube at a time", "share_card.build_the_internet_one_tube_at":"Build the internet, one tube at a time",
"share_card.n_in_r_regions":"{n} in {r} regions", "share_card.n_in_r_regions":"{n} in {r} regions",
"share_card.not_this_time":"not this time", "share_card.not_this_time":"not this time",

View file

@ -9,15 +9,15 @@ const { load } = require('./harness');
const page = require('../scripts/lib/page'); const page = require('../scripts/lib/page');
// Names the agent files define at the top level: none may appear in the page players get. // Names the agent files define at the top level: none may appear in the page players get.
const AGENT_NAMES = ['TUBES', 'API_CMD', 'API_DOMAINS', 'apiCall', 'apiDispatch', 'apiSchema']; const AGENT_NAMES = ['TUBES', 'API_CMD', 'API_DOMAINS', 'API_RELAY', 'apiCall', 'apiDispatch', 'apiSchema', 'apiAgentStart'];
test('the facade is inert until called, and listens to the game only during a call', () => { test('the facade is inert until called, and listens to the game only during a call', () => {
const a = load({ agent: true }); const a = load({ agent: true });
assert.equal(a.ev('toast.name'), 'toast', 'loading the page leaves toast() alone'); assert.equal(a.ev('toast.name'), 'toast', 'loading the page leaves toast() alone');
assert.equal(a.ev('spend.name'), 'spend', 'and spend()'); assert.equal(a.ev('spend.name'), 'spend', 'and spend()');
assert.equal(a.ev('API_TOASTS.depth'), 0); assert.equal(a.ev('API_TOASTS.depth'), 0);
assert.deepEqual(JSON.parse(a.ev('JSON.stringify(TUBES.tools)')).sort(), ['act', 'actions', 'advance', 'catalog', 'city', 'classes', 'click', 'find', assert.deepEqual(JSON.parse(a.ev('JSON.stringify(TUBES.tools)')).sort(), ['act', 'actions', 'advance', 'catalog', 'city', 'classes', 'click', 'clock', 'find',
'hot_spots', 'network', 'open_link', 'panel', 'peering_check', 'results', 'schema', 'screen', 'state', 'status', 'traceroute', 'ui'].sort()); 'hot_spots', 'network', 'open_link', 'panel', 'peering_check', 'results', 'schema', 'screen', 'since', 'state', 'status', 'traceroute', 'ui'].sort());
// Before a game there is a contract to read, and nothing else. // Before a game there is a contract to read, and nothing else.
assert.ok(a.ev("TUBES.call('schema',{section:'commands'}).buildPop")); assert.ok(a.ev("TUBES.call('schema',{section:'commands'}).buildPop"));
assert.throws(() => a.ev("TUBES.call('status',{})"), /No game is running/); assert.throws(() => a.ev("TUBES.call('status',{})"), /No game is running/);
@ -36,6 +36,21 @@ test('the facade is inert until called, and listens to the game only during a ca
assert.deepEqual(a.errors, []); assert.deepEqual(a.errors, []);
}); });
test('headless and the player\'s tab share one contract; only the tab holds the dice back and names its owner', () => {
const a = load({ agent: true });
a.ev('ACT.start({});S.nextFail=S.day+30;compute()');
const here = a.ev("TUBES.call('schema',{})"), there = a.ev("TUBES.call('schema',{},{relay:true})");
for (const k of ['commands', 'view', 'drafts', 'denied', 'domains', 'results']) assert.deepEqual(here[k], there[k], k);
assert.equal(here.mode.backend, 'headless');
assert.equal(there.mode.backend, 'browser');
assert.ok(there.session.startScn.refused && !here.session.startScn.refused, 'starting a scenario is the player\'s in their tab');
assert.equal(a.ev("TUBES.call('state',{path:'nextFail'})"), a.ev('S.nextFail'), 'headless reads everything');
assert.equal(a.ev("TUBES.call('state',{path:'nextFail'},{relay:true})"), null, 'the tab holds it back');
assert.equal(a.ev("'rng' in TUBES.call('state',{},{relay:true})"), false);
assert.equal(a.ev("TUBES.call('state',{path:'cash'},{relay:true})"), a.ev('S.cash'));
assert.deepEqual(a.errors, []);
});
test('the page players get has no agent code; the development page has it', () => { test('the page players get has no agent code; the development page has it', () => {
const ship = page.assemble().html, dev = page.assemble({ dev: true }).html; const ship = page.assemble().html, dev = page.assemble({ dev: true }).html;
assert.ok(!ship.includes('@include-dev'), 'the marker line is dropped whole'); assert.ok(!ship.includes('@include-dev'), 'the marker line is dropped whole');
@ -51,6 +66,7 @@ test('the page players get has no agent code; the development page has it', () =
// The players' page is the game alone: no facade, and it boots and plays. // The players' page is the game alone: no facade, and it boots and plays.
const p = load(); const p = load();
assert.equal(p.ev('typeof TUBES+typeof apiCall+typeof API_CMD'), 'undefinedundefinedundefined'); assert.equal(p.ev('typeof TUBES+typeof apiCall+typeof API_CMD'), 'undefinedundefinedundefined');
assert.equal(p.ev('JSON.stringify(HOOKS)+UI.clockLocked'), '{}false', 'no hooks, and the clock is the player\'s');
p.ev("ACT.start({});ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});for(let i=0;i<5;i++)dayTick()"); p.ev("ACT.start({});ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});for(let i=0;i<5;i++)dayTick()");
assert.ok(p.ev('R.served') > 0); assert.ok(p.ev('R.served') > 0);
assert.deepEqual(p.errors, []); assert.deepEqual(p.errors, []);

528
tests/agent-relay.test.js Normal file
View file

@ -0,0 +1,528 @@
// The agent relay (scripts/agent/relay.js): a WebSocket router between the game page (src/agent/80-relay.js, agent
// mode in Settings) and tool clients. This drives the whole chain with a real page: the harness loads the game
// in jsdom, the page's own client dials the relay (a test opts in with __AGENT_RELAY_TEST__ and points it at the
// relay's port, because under __TUBES_TEST__ nothing dials on its own), and a raw WebSocket tool client, the relay
// client (scripts/lib/relay-client.js) and the MCP server in browser mode (scripts/mcp.js --browser) take turns driving
// it. No token anywhere: whatever can connect to the port may drive the game, by design.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { spawn } = require('node:child_process');
const http = require('node:http');
const WebSocket = require('ws');
const { load } = require('./harness');
const ROOT = path.join(__dirname, '..');
const { createRelay } = require('../scripts/agent/relay');
const { createRelaySession } = require('../scripts/lib/relay-client');
const SERVER = path.join(ROOT, 'scripts', 'mcp.js');
const PORT = 8799 + (process.pid % 500); // dodge a busy port across suites
const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'tubes-relay-'));
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
// The relay in-process, riding a real http.Server (the same createRelay the servers host): no child to leak, and
// 'listening' means the first dial cannot race the bind.
function startRelay(port = PORT) {
const srv = http.createServer((req, res) => { res.writeHead(404); res.end(); });
const relay = createRelay({ server: srv });
return {
relay, srv,
listening: () => new Promise((res, rej) => { srv.once('error', rej); srv.listen(port, '127.0.0.1', res); }),
close: () => new Promise((r) => { relay.close(); srv.close(() => r()); }),
};
}
// The game page: jsdom via the harness, agent mode on (opts.ms: the clock, 0 for the agent's). The page's own client
// connects to this relay's host:port as the page. The harness origin matches the relay host, so the page's WebSocket
// Origin is same-origin (the relay refuses a foreign one; a Node tool sends none).
function page(opts = {}) {
const a = load({ url: `http://127.0.0.1:${opts.port ?? PORT}/`, seed: opts.seed ?? 5, storage: { 'sot-agent': JSON.stringify({ on: true, ms: opts.ms ?? 60000 }) }, agent: true });
dial(a, opts.port);
return a;
}
const dial = (a, port = PORT) => a.ev(`window.__AGENT_RELAY_TEST__=true;API_RELAY_HOST='127.0.0.1:'+${port};apiAgentSync()`);
// Kill the page's dial and retry timer before a test ends, or its backoff keeps the process alive.
const stop = (...ps) => { for (const a of ps) if (a) a.ev("window.__AGENT_RELAY_TEST__=false;apiAgentSet('on',false)"); };
// A raw tool client, the way the MCP server speaks to the relay. `headers` fakes a browser's Origin (which Node's ws
// does not send) for the cross-site test.
function toolClient(port = PORT, headers) {
const ws = new WebSocket(`ws://127.0.0.1:${port}/agent`, headers ? { headers } : undefined);
const calls = new Map();
let seq = 0;
const events = [];
ws.on('message', (d) => {
const m = JSON.parse(String(d));
if (m.kind === 'presence') { events.push(m); return; }
if (m.kind === 'result' && calls.has(m.id)) { calls.get(m.id)(m); calls.delete(m.id); }
});
return {
ws, events,
open: () => new Promise((res, rej) => { ws.on('open', res); ws.on('error', rej); }),
auth: (role = 'tool') => ws.send(JSON.stringify({ kind: 'auth', role })),
call: (tool, args) => new Promise((res) => { // a timeout, never a hang
const id = 'c' + (++seq);
const t = setTimeout(() => { calls.delete(id); res({ error: `no answer for ${tool} (the page went silent?)` }); }, 20000);
calls.set(id, (m) => { clearTimeout(t); res(m); });
ws.send(JSON.stringify({ kind: 'call', id, tool, args: args || {} }));
}),
close: () => { try { ws.close(); } catch {} },
};
}
async function tool() { const t = toolClient(); await t.open(); t.auth('tool'); await wait(150); return t; }
async function withRelay(fn) {
const r = startRelay();
await r.listening();
try { return await fn(r); } finally { await r.close(); }
}
// The MCP server over stdio, as a client runs it.
function mcp(argv, onErr) {
const child = spawn(process.execPath, [SERVER, ...argv], { stdio: ['pipe', 'pipe', 'pipe'] });
let buf = '', id = 0, err = '';
const waiting = new Map();
child.stderr.on('data', (d) => { err += d; if (onErr) onErr(String(d)); });
child.stdout.on('data', (d) => {
buf += d;
let i;
while ((i = buf.indexOf('\n')) >= 0) {
const line = buf.slice(0, i); buf = buf.slice(i + 1);
let m; try { m = JSON.parse(line); } catch { continue; }
if (m.id !== undefined && waiting.has(m.id)) { waiting.get(m.id)(m); waiting.delete(m.id); }
}
});
const send = (o) => new Promise((res) => { const k = ++id; waiting.set(k, res); child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: k, ...o }) + '\n'); });
return {
child, send, stderr: () => err,
init: async () => { const r = await send({ method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '0' } } });
child.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n'); return r; },
call: async (name, args) => (await send({ method: 'tools/call', params: { name, arguments: args || {} } })).result,
json: async (name, args) => JSON.parse((await send({ method: 'tools/call', params: { name, arguments: args || {} } })).result.content[0].text),
kill: async () => { child.kill('SIGTERM'); await wait(200); child.kill('SIGKILL'); },
};
}
test('the relay binds loopback, gates on the role, and never needs a token', () => withRelay(async () => {
const silent = toolClient();
await silent.open();
assert.equal(await new Promise((res) => silent.ws.on('close', (code) => res(code))), 4003, 'a client that never states a role is closed');
const bogus = toolClient();
await bogus.open();
bogus.auth('hacker');
assert.equal(await new Promise((res) => bogus.ws.on('close', (code) => res(code))), 4001, 'a role that is neither page nor tool is refused');
const t = await tool();
assert.deepEqual(t.events.map((e) => e.page), [false], 'a fresh tool sees no page');
const r = await t.call('state', { path: 'cash' });
assert.match(r.error, /no game page connected/i);
t.close();
}));
test('a live page answers tool calls through the relay, from a fixed list of tools', () => withRelay(async () => {
const t = await tool();
const a = page();
try {
a.ev("ACT.start({});S.cash=500000;compute()");
await wait(600);
assert.ok(t.events.some((e) => e.page === true), 'the tools see the page join');
const q = await t.call('act', { action: 'buildPop', args: { city: 'ams' }, dryRun: true });
assert.equal(q.value.outcome, 'quote');
assert.equal(q.value.quote.setup, 20000);
assert.equal(a.ev('S.pops.ams'), undefined, 'nothing was dispatched in the page');
const r = await t.call('act', { action: 'buildPop', args: { city: 'ams' } });
assert.equal(r.value.outcome, 'applied');
assert.equal(r.value.charged, 20000);
assert.equal(a.ev('S.pops.ams && S.pops.ams.day'), 0, 'the page really changed');
assert.equal(r.dayBefore, 0);
assert.equal((await t.call('state', { path: 'cash' })).value, 480000);
assert.equal((await t.call('status')).value.pops.length, 2);
const nope = await t.call('act', { action: 'speed', args: { v: 0 } });
assert.match(nope.error, /not available here/);
// Unknown tools never reach the facade: its fixed list is the whole vocabulary.
const hack = await t.call('eval', { code: 'S.cash=1e9' });
assert.match(hack.error, /no tool "eval"/);
assert.equal(a.ev('S.cash'), 480000);
assert.equal(a.ev('API_TOASTS.depth===0&&API_TOASTS.real===null&&toast.name'), 'toast', 'toast() is the game\'s own again after every call');
} finally { stop(a); t.close(); }
}));
test('in the player\'s tab the player owns the game, their windows, their settings and the dice', () => withRelay(async () => {
const t = await tool();
const a = page({ ms: 0 });
try {
a.ev("ACT.start({});S.cash=1e7;S.nextFail=S.day+40;S.nextEvent=S.day+50;compute()");
await wait(500);
// The dice stay hidden, whole or by path, and the schema says so.
const st = (await t.call('state')).value;
for (const k of ['rng', 'nextFail', 'nextEvent']) assert.ok(!(k in st), `${k} is held back`);
assert.equal((await t.call('state', { path: 'nextFail' })).value, null);
assert.equal(st.cash, 1e7, 'the board itself is all there');
const mode = (await t.call('schema', { section: 'mode' })).value;
assert.equal(mode.backend, 'browser');
assert.equal(mode.clock, 'agent');
assert.ok(mode.withheld.nextFail);
assert.ok((await t.call('schema', { section: 'state' })).value.rng.withheld);
// Starting, loading or leaving a game is the player's.
for (const [action, args] of [['startScn', { id: a.ev('SCN[0].id') }], ['pzStart', { id: a.ev('PZ[0].id') }], ['startWeekly', {}]]) {
const r = await t.call('act', { action, args });
assert.match(r.error || '', /the player's/, action);
}
assert.equal(a.ev('S.mode'), 'normal');
// So are their settings, agent mode's own switch included: it is no game action, so no tool can find or press it.
assert.match((await t.call('act', { action: 'prefSet', args: { v: 'pauseFurious:0' } })).error, /not available here/);
assert.match((await t.call('act', { action: 'agentSet', args: {} })).error, /no action/);
assert.equal(a.ev('API_AGENT_PREFS.on'), true);
// A window the player opened by hand stays theirs: the agent plays behind it, and never closes or replaces it.
a.ev("(()=>{const b=document.createElement('button');b.dataset.act='settings';document.body.appendChild(b);b.click();b.remove();})()");
assert.equal(a.ev("$('modal').hidden"), false, 'the player has a window open');
assert.equal(a.ev('API_MODAL.hand'), true, 'marked as theirs');
const html = a.ev("$('modalCard').innerHTML");
const sc = (await t.call('screen')).value;
assert.equal(sc.where, 'modal');
assert.ok(sc.playerWindow, 'the screen says whose it is');
assert.equal(sc.question, false, 'and that it is no question');
const b = await t.call('act', { action: 'buildPop', args: { city: 'ams' } });
assert.equal(b.value.outcome, 'applied', 'the agent plays on behind it');
const v = await t.call('act', { action: 'opsOpen' });
assert.equal(v.value.screen.where, 'modal');
assert.match(v.value.screen.note || '', /shown to you and closed again/, 'its own sheet is shown, then the player\'s window comes back');
await t.call('act', { action: 'closeModal' });
assert.equal(a.ev("$('modal').hidden"), false, 'closeModal does not close the player\'s window');
assert.equal(a.ev("$('modalCard').innerHTML"), html, 'nor change it');
await t.call('screen', { where: 'modal' });
const c = await t.call('click', { button: 0 });
assert.match(c.error || '', /theirs to press/);
assert.match((await t.call('open_link', { from: 'fra', to: 'nyc' })).error || '', /would replace it/);
// Days run behind it (the agent's clock here), and it is still there after.
const adv = await t.call('advance', { days: 3 });
assert.equal(adv.value.daysRun, 3);
assert.equal(a.ev('S.day'), 3);
assert.equal(a.ev("$('modalCard').innerHTML"), html);
} finally { stop(a); t.close(); }
}));
test('the agent\'s clock moves only with advance; a running clock only with time, and wait reads it', () => withRelay(async () => {
const t = await tool();
const a = page({ ms: 0 });
try {
a.ev("ACT.start({});S.cash=1e7;compute()");
await wait(500);
assert.equal(a.ev('UI.speed'), 0, 'a tool is connected, but the agent\'s clock stands still');
a.ev('last=performance.now();for(let i=1;i<=20;i++)frame(last+i*250)');
assert.equal(a.ev('S.day'), 0, 'the loop runs no days');
const adv = await t.call('advance', { days: 20 });
assert.equal(adv.value.daysRun, 20, 'advance runs them, where the player sees them');
assert.equal(a.ev('S.day'), 20);
assert.match((await t.call('clock')).value.mode, /agent/);
// The player switches to a pace: the clock runs by itself, and advance is refused.
a.ev("apiAgentSet('ms',30000)");
assert.equal(a.ev('UI.speed'), a.ev('DAY_MS/30000'), 'a pace, and a tool connected: it runs, a day per 30 s');
assert.match((await t.call('advance', { days: 1 })).error, /use wait/);
const c = (await t.call('clock')).value;
assert.equal(c.mode, 'realtime');
assert.equal(c.running, true);
// The page's own loop moves days at the pace (the test plays the browser's frames, 2 s of them per day).
a.ev('API_AGENT_PREFS.ms=2000;apiAgentSync()');
a.ev('last=performance.now()');
const frames = setInterval(() => a.ev('frame(performance.now())'), 20);
try {
const { createBrowserSession } = require('../scripts/lib/mcp-browser');
const { TOOLS } = require('../scripts/lib/mcp-game');
const s = createBrowserSession({ port: PORT });
const w = await TOOLS.find((x) => x.name === 'wait').run(s, { days: 1, maxSeconds: 10 });
assert.ok(w.daysRun >= 1, `wait returns once a day has passed (${JSON.stringify(w)})`);
assert.equal(w.stoppedBecause, null);
await s.close();
} finally { clearInterval(frames); }
} finally { stop(a); t.close(); }
}));
test('the page client reconnects after the relay restarts, and stops when the player switches agent mode off', () => withRelay(async (r) => {
const t = await tool();
const a = page();
try {
a.ev("ACT.start({});S.cash=500000;compute()");
await wait(500);
assert.ok(t.events.some((e) => e.page === true));
await r.close();
await wait(300);
a.ev("apiAgentSet('on',false)");
const r2 = startRelay();
await r2.listening();
try {
await wait(1200); // past the first backoff retry
assert.equal(a.ev('API_RELAY.on'), false, 'the client is off');
a.ev("apiAgentSet('on',true)");
await wait(1200);
const t2 = await tool();
await wait(300);
assert.ok(t2.events.some((e) => e.page === true), 'the page reconnected after the relay came back');
assert.equal((await t2.call('state', { path: 'cash' })).value, 500000, 'and answers calls again');
t2.close();
} finally { stop(a); await r2.close(); }
} finally { stop(a); t.close(); }
}));
test('a paced clock holds while no tool is connected, and runs when one arrives', () => withRelay(async () => {
const a = page({ seed: 5 });
try {
a.ev("ACT.start({});S.nextFail=S.day+99;S.nextEvent=S.day+99;compute()");
await wait(500);
assert.equal(a.ev('UI.speed'), 0, 'no tool connected: the clock holds');
assert.equal(a.ev('UI.clockLocked'), true, 'agent mode stays on');
a.ev('last=performance.now();frame(last);frame(last+250);frame(last+500)');
assert.equal(a.ev('S.day'), 0, 'no day ran');
const t = await tool();
await wait(300);
assert.ok(a.ev('UI.speed') > 0, 'a tool connecting runs it');
t.close();
await wait(400);
assert.equal(a.ev('UI.speed'), 0, 'the tool leaving holds it again');
a.ev('S.uiSpeed=4;gameResume()');
assert.equal(a.ev('UI.speed'), 0, 'gameResume holds with no tool connected');
const t2 = await tool();
await wait(300);
assert.ok(a.ev('UI.speed') > 0, 'and a tool arriving runs it again');
// An unrelated preference change does not drop the connection or hold the clock.
a.ev('window.__w0=API_RELAY.ws');
a.ev("ACT.prefSet({v:'pauseFurious:0'})");
a.ev("apiAgentSet('ms',300000)");
assert.equal(a.ev('API_RELAY.ws===window.__w0'), true, 'the same socket survived both');
assert.equal(a.ev('UI.speed'), a.ev('DAY_MS/300000'), 'the clock never held for them, and runs at the new pace');
t2.close();
} finally { stop(a); }
}));
test('a second page replaces the first: one game per relay, the newest tab wins', () => withRelay(async () => {
const a = page({ seed: 5 });
a.ev("ACT.start({});S.cash=111000;compute()");
const b = page({ seed: 6 });
b.ev("ACT.start({});S.cash=222000;compute()");
await wait(700);
const t = await tool();
try {
assert.equal((await t.call('state', { path: 'cash' })).value, 222000, 'the newest page answers');
} finally { stop(a, b); t.close(); }
}));
test('the MCP server drives the player\'s page in browser mode, over stdio', () => withRelay(async () => {
const a = page({ seed: 9, ms: 0 });
a.ev("ACT.start({});S.cash=1000000;compute()");
await wait(500);
const m = mcp(['--browser', '--relay-host', 'localhost', '--relay-port', String(PORT)]);
try {
const init = await m.init();
assert.match(init.result.instructions, /player's own browser tab/);
const list = (await m.send({ method: 'tools/list' })).result.tools.map((x) => x.name);
for (const n of ['status', 'act', 'schema', 'state', 'advance', 'wait', 'screen', 'click']) assert.ok(list.includes(n), n);
for (const n of ['new_game', 'load_save', 'export_save']) assert.ok(!list.includes(n), `${n} is the headless session's`);
const mode = await m.json('schema', { section: 'mode' });
assert.equal(mode.backend, 'browser');
assert.equal(mode.transport, 'relay');
assert.equal(mode.relay, `ws://localhost:${PORT}/agent`, 'the mode says which relay: host, port and path');
assert.equal(await m.json('state', { path: 'cash' }), 1000000);
const r = await m.json('act', { action: 'buildPop', args: { city: 'ams' } });
assert.equal(r.outcome, 'applied');
assert.equal(r.charged, 20000);
assert.equal(a.ev('S.pops.ams && S.pops.ams.day'), 0, "the player's page really changed");
assert.equal((await m.json('advance', { days: 2 })).daysRun, 2);
assert.ok((await m.json('actions')).includes('buildLink(a,b,tier,cable?,route?,premiumCrossing?)'));
const no = await m.call('act', { action: 'startScn', args: { id: a.ev('SCN[0].id') } });
assert.equal(no.isError, true);
assert.match(no.content[0].text, /the player's/);
} finally { stop(a); await m.kill(); }
}));
test('a game page older than the code stops the server rather than mislead', () => withRelay(async () => {
const a = page({ seed: 3 });
a.ev("ACT.start({});compute()");
// A stale tab whose commands keep their names but change shape: only a deep compare of the sections catches it.
a.ev('const __c=TUBES.call;TUBES.call=(t,x,c)=>{const v=__c(t,x,c);if(t==="schema"&&!x.section)v.commands.buildPop.args=[{name:"city",required:true}];return v;};');
await wait(400);
const m = mcp(['--browser', '--relay-port', String(PORT), '--page-wait-ms', '8000']);
try {
const init = await m.init();
assert.ok(init.result.serverInfo, 'the handshake is answered at once');
const code = await new Promise((r) => m.child.on('exit', (c2) => r(c2)));
assert.equal(code, 1, 'the server exits with an error');
assert.match(m.stderr(), /disagrees with the code on disk \(commands\)/);
assert.match(m.stderr(), /reload the page/);
} finally { stop(a); await m.kill(); }
}));
test('the MCP server answers the handshake at once and waits for the game page', () => withRelay(async () => {
const gone = mcp(['--browser', '--relay-port', String(PORT), '--page-wait-ms', '1200']);
const code = await new Promise((r) => gone.child.on('exit', (c2) => r(c2)));
assert.equal(code, 1, 'exits 1 without a page');
assert.match(gone.stderr(), /waiting for the game page/);
assert.match(gone.stderr(), /no game page answered/);
assert.match(gone.stderr(), /Settings → Agent API/);
assert.doesNotMatch(gone.stderr(), /TypeError/);
const m = mcp(['--browser', '--relay-port', String(PORT), '--page-wait-ms', '20000']);
let a = null;
try {
const t0 = Date.now();
await m.init();
assert.ok(Date.now() - t0 < 3000, 'initialize does not wait for a browser tab');
const early = await m.call('status');
assert.equal(early.isError, true, 'a tool before the page arrives is an error, not a hang');
await wait(300);
assert.match(m.stderr(), /waiting for the game page/);
a = page({ seed: 4 });
a.ev("ACT.start({});S.cash=444000;compute()");
await wait(2500);
assert.match(m.stderr(), /ready/, 'the server proceeded once the page answered');
assert.equal(await m.json('state', { path: 'cash' }), 444000, 'and drives the late page');
} finally { stop(a); await m.kill(); }
}));
const free = () => new Promise((res, rej) => { const s = http.createServer(); s.on('error', rej); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => res(p)); }); });
test('dev.js binds loopback and parses --port; the page dials its own host', async () => {
const port = await free();
const child = spawn(process.execPath, [path.join(ROOT, 'scripts', 'dev.js'), '--port', String(port)], { stdio: ['ignore', 'ignore', 'pipe'] });
let serr = '';
child.stderr.on('data', (d) => { serr += d; });
let a = null;
try {
await wait(700);
assert.match(serr, new RegExp(`agent relay on ws://127\\.0\\.0\\.1:${port}/agent`), 'dev.js binds loopback and honours --port');
const t = toolClient(port);
await t.open(); t.auth('tool'); await wait(150);
assert.ok(t.events.some((e) => e.page === false), 'the relay answers on 127.0.0.1');
t.close();
a = load({ url: `http://127.0.0.1:${port}/`, agent: true, storage: { 'sot-agent': JSON.stringify({ on: true }) } });
assert.equal(a.ev('API_RELAY.on'), false, 'under __TUBES_TEST__ nothing dials on its own');
a.ev(`window.__AGENT_RELAY_TEST__=true;API_RELAY_HOST='';apiAgentSync()`);
assert.equal(a.ev('API_RELAY.on'), true);
assert.equal(a.ev('apiRelayUrl()'), `ws://127.0.0.1:${port}/agent`, 'its own host and port, the relay path');
} finally {
stop(a);
child.kill('SIGTERM'); await wait(150); child.kill('SIGKILL');
}
});
test('calls neither page nor relay can answer resolve as errors, not hangs', async () => {
const r = startRelay();
await r.listening();
const pages = [];
try {
const t = await tool();
const a = page();
pages.push(a);
a.ev('ACT.start({});S.cash=500000;compute()');
await wait(400);
// The page dies with a call in flight; it is silenced first, so the call is provably pending when it closes.
a.ev('API_RELAY.ws.onmessage=()=>{}');
const p = t.call('act', { action: 'buildPop', args: { city: 'ams' } });
await wait(100);
a.ev('API_RELAY.ws.close(1000)');
assert.match((await p).error || '', /disconnected before answering/i);
stop(a);
t.close();
// The relay dies under a call in flight: the client answers on its own behalf, at once.
const b = page({ seed: 12 });
pages.push(b);
b.ev('ACT.start({});S.cash=222000;compute()');
await wait(400);
b.ev('API_RELAY.ws.onmessage=()=>{}');
const s = createRelaySession({ host: '127.0.0.1', port: PORT });
const p2 = s.call('state', { path: 'cash' });
await wait(150);
await r.close();
assert.match((await p2).refused || '', /connection closed/i);
await s.close();
} finally {
for (const pg of pages) stop(pg);
await r.close();
}
});
test('a page that hangs on a call answers within --call-ms, not minutes later', () => withRelay(async () => {
const a = page({ seed: 4 });
try {
a.ev('ACT.start({});compute()');
await wait(400);
a.ev('API_RELAY.ws.onmessage=()=>{}'); // connected, alive, and never answering
const s = createRelaySession({ host: '127.0.0.1', port: PORT, callMs: 300 });
const t0 = Date.now();
const r = await s.call('state', { path: 'cash' });
assert.match(r.refused || '', /no answer from the game page in 0\.3 s/);
assert.ok(Date.now() - t0 < 2000, 'the configured timeout, not the default');
assert.equal(createRelaySession({}).config.callMs, 30000, 'the default is 30 s');
await s.close();
} finally { stop(a); }
}));
test('the relay refuses a cross-site Origin and takes a same-origin page or a token-less tool', () => withRelay(async () => {
const evil = toolClient(PORT, { Origin: 'http://evil.example' });
await evil.open();
assert.equal(await new Promise((res) => evil.ws.on('close', (code) => res(code))), 4004, 'refused before any role is granted');
// DNS rebinding: evil.example re-pointed at 127.0.0.1 is "same-origin" with itself, but the Host is a name.
const rebound = toolClient(PORT, { Host: `evil.example:${PORT}`, Origin: `http://evil.example:${PORT}` });
await rebound.open();
assert.equal(await new Promise((res) => rebound.ws.on('close', (code) => res(code))), 4004, 'a rebound DNS name is refused');
const named = toolClient(PORT, { Host: `evil.example:${PORT}` });
await named.open();
assert.equal(await new Promise((res) => named.ws.on('close', (code) => res(code))), 4004, 'with or without an Origin');
const same = toolClient(PORT, { Origin: `http://127.0.0.1:${PORT}` });
await same.open();
same.auth('page');
await wait(150);
const t = await tool();
await wait(100);
assert.ok(same.events.some((e) => e.tools === 1), 'the same-origin page connects and sees the tool');
t.close(); same.close();
}));
// Spawns a server script and resolves with the address its relay banner reports (server.address()).
function bannerOf(argv) {
const child = spawn(process.execPath, argv, { stdio: ['ignore', 'ignore', 'pipe'] });
let serr = '';
return new Promise((res) => {
const done = (v) => { clearTimeout(t); child.kill('SIGKILL'); res(v); };
const t = setTimeout(() => done({ addr: null, serr }), 5000);
child.stderr.on('data', (d) => { serr += d; const m = /agent relay on ws:\/\/(\S+)\/agent/.exec(serr); if (m) done({ addr: m[1], serr }); });
});
}
test('dev.js: a bare --host binds loopback, never every interface; binding wider is the operator\'s choice, and said', async () => {
const p1 = await free();
const dev = await bannerOf([path.join(ROOT, 'scripts', 'dev.js'), '--host', '--port', String(p1)]);
assert.equal(dev.addr, `127.0.0.1:${p1}`, `the socket is bound to loopback (${dev.serr})`);
const p2 = await free();
const wide = await bannerOf([path.join(ROOT, 'scripts', 'dev.js'), '--host', '0.0.0.0', '--port', String(p2)]);
assert.equal(wide.addr, `0.0.0.0:${p2}`, 'the banner is the real socket, not the flag echoed back');
assert.match(wide.serr, /bound to 0\.0\.0\.0, so anything that can reach this address can drive/);
});
test('browser mode over HTTP: a client connects to the server, the server to the player\'s page', () => withRelay(async () => {
const a = page({ seed: 11, ms: 0 });
a.ev("ACT.start({});S.cash=555000;compute()");
await wait(400);
const child = spawn(process.execPath, [SERVER, '--browser', '--relay-port', String(PORT), '--http', '127.0.0.1:0'], { stdio: ['ignore', 'ignore', 'pipe'] });
let err = '';
try {
const port = await new Promise((res, rej) => {
child.stderr.on('data', (d) => { err += d; const m = /on http:\/\/127\.0\.0\.1:(\d+)\/mcp/.exec(err); if (m) res(+m[1]); });
child.on('exit', () => rej(new Error(err)));
});
const post = (body) => new Promise((res, rej) => {
const data = JSON.stringify({ jsonrpc: '2.0', id: 1, ...body });
const req = http.request({ host: '127.0.0.1', port, path: '/mcp', method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', 'mcp-protocol-version': '2025-06-18', 'content-length': Buffer.byteLength(data) } }, (r) => {
let t = ''; r.setEncoding('utf8'); r.on('data', (d) => { t += d; });
r.on('end', () => { const line = t.split('\n').find((l) => l.startsWith('data: ')); res(JSON.parse(line ? line.slice(6) : t)); });
});
req.on('error', rej); req.end(data);
});
const init = await post({ method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '1' } } });
assert.match(init.result.instructions, /player's own browser tab/);
const r = await post({ method: 'tools/call', params: { name: 'state', arguments: { path: 'cash' } } });
assert.equal(JSON.parse(r.result.content[0].text), 555000, 'the player\'s game, through HTTP and the relay');
const no = await post({ method: 'tools/call', params: { name: 'new_game', arguments: {} } });
assert.ok(no.error || (no.result && no.result.isError), 'no new_game in the player\'s tab');
} finally { stop(a); child.kill('SIGTERM'); await wait(150); child.kill('SIGKILL'); }
}));

View file

@ -0,0 +1,166 @@
// Agent mode in the player's tab (src/agent/75-mode.js, 85-ticker.js): its own switch and clock in Settings, kept
// apart from the game's preferences; the gate that keeps it off the public site; the speed the save remembers across
// it; the badge that stands in for the speed buttons; and the clock that keeps running where frames do not.
const test = require('node:test');
const assert = require('node:assert/strict');
const { load } = require('./harness');
const prefs = (ms = 60000, on = true) => ({ 'sot-agent': JSON.stringify({ on, ms }) });
const agent = (o = {}) => load({ agent: true, storage: prefs(o.ms), ...o });
// Press one of agent mode's own Settings buttons, as the player does.
const press = (a, v) => a.ev(`(()=>{ACT.settings({});const b=document.querySelector('[data-agent-set="${v}"]');b.click();return true;})()`);
test('the clock buttons set the pace, or give the clock to the agent, and are remembered', () => {
const a = agent();
a.ev('ACT.start({});S.cash=1e9;compute()');
for (const m of [30000, 60000, 120000, 300000]) {
press(a, `ms:${m}`);
assert.equal(a.ev('apiAgentMs()'), m, `the ${m} ms button sets the pace`);
assert.equal(JSON.parse(a.ev(`localStorage.getItem('sot-agent')`)).ms, m, 'in agent mode\'s own storage');
assert.ok(a.ev(`document.querySelector('[data-agent-set="ms:${m}"]').classList.contains('pink')`), 'and shows as picked');
}
// 0: the agent's clock. It stands still: no speed, and the loop never runs a day by itself.
press(a, 'ms:0');
assert.equal(a.ev('apiAgentMs()'), 0);
assert.equal(a.ev('UI.speed'), 0, 'the agent\'s clock stands still');
a.ev('last=performance.now();for(let i=1;i<=40;i++)frame(last+i*250)');
assert.equal(a.ev('S.day'), 0, 'no day passes on its own');
assert.match(a.ev('settingsHtml()'), /The agent moves it/);
// Junk is ignored, never coerced.
a.ev("apiAgentSet('ms','nope');apiAgentSet('ms',true);apiAgentSet('ms',12345);apiAgentSet('nope',1)");
assert.equal(a.ev('apiAgentMs()'), 0);
// Its buttons are agent mode's own, not game actions: no tool finds them on a screen.
assert.equal(a.ev(`document.querySelectorAll('#modal [data-agent-set][data-act]').length`), 0);
assert.deepEqual(a.errors, []);
});
test('the game\'s preferences stay exactly as they are', () => {
const a = agent();
assert.deepEqual(Object.keys(a.ev('PREF_DEF')).sort(), ['pauseFurious', 'pauseIncident', 'quiet', 'warnUnhappy']);
a.ev("ACT.prefSet({v:'pauseFurious:0'})");
assert.equal(a.ev('PREFS.pauseFurious'), false);
a.ev("ACT.prefSet({v:'agent:1'})");
assert.equal(a.ev("'agent' in PREFS"), false, 'prefSet knows nothing of agent mode');
assert.equal(a.ev(`localStorage.getItem('sot-prefs')`), JSON.stringify({ pauseFurious: false }));
assert.deepEqual(a.errors, []);
});
test('agent mode only exists where a relay can be reached', () => {
const a = agent();
assert.equal(a.ev('API_AGENT_OK'), true);
assert.match(a.ev('settingsHtml()'), /Agent API/, 'the Settings sheet has the section');
// Plain http to an address: yes, wherever the operator bound the dev server. https (the public site cannot even
// open ws:// from its pages), and DNS names (the relay refuses them): no.
const gate = (p, h) => a.ev(`apiAgentLocal(${JSON.stringify(p)},${JSON.stringify(h)})`);
for (const h of ['127.0.0.1', 'localhost', 'tubes.localhost', '10.0.0.4', '192.168.1.5', '203.0.113.7', '[::1]']) assert.equal(gate('http:', h), true, h);
assert.equal(gate('https:', 'seriesoftub.es'), false, 'the public site has no relay behind it');
assert.equal(gate('http:', 'seriesoftub.es'), false);
assert.equal(gate('http:', 'example.com'), false);
assert.equal(gate('file:', ''), false);
assert.deepEqual(a.errors, []);
});
test('on the public site there is no agent mode, even with the preference set by hand', () => {
const a = load({ url: 'https://seriesoftub.es/', agent: true, storage: prefs() });
a.ev('ACT.start({});S.cash=1e9;compute()');
assert.equal(a.ev('API_AGENT_OK'), false);
assert.doesNotMatch(a.ev('settingsHtml()'), /Agent API/, 'no section in Settings');
assert.equal(a.ev('UI.clockLocked'), false, 'the clock is the player\'s');
assert.equal(a.ev('API_RELAY.on'), false, 'nothing dials');
a.ev('ACT.speed({v:2})');
assert.equal(a.ev('UI.speed'), 2, 'the speed buttons work');
assert.deepEqual(a.errors, []);
});
test('agent mode remembers the speed the player left the game at, not the agent\'s', () => {
const a = agent({ storage: prefs(60000, false) }); // agent mode off: the player is playing
a.ev('ACT.start({});S.cash=1e9;ACT.speed({v:2});compute();save(true)');
assert.equal(a.ev('S.uiSpeed'), 2, 'the save carries the player speed');
press(a, 'on:1');
assert.equal(a.ev('UI.clockLocked'), true);
assert.equal(a.ev('UI.speed'), 0, 'no tool is connected, so the clock holds');
for (const x of ['ACT.speed({v:4})', 'ACT.phonePlay()', 'ACT.phoneSpeed()', "dispatchEvent(new KeyboardEvent('keydown',{code:'Space',key:' '}))"]) {
a.ev(x);
assert.equal(a.ev('UI.speed'), 0, `${x} does nothing while an agent drives`);
}
assert.equal(a.ev('autoPause()'), false, 'nothing pauses a locked clock either');
a.ev('S.day=5;save(true)');
assert.equal(a.ev('S.uiSpeed'), 2, 'save() never stores the locked speed in its place');
a.ev('S.uiSpeed=4;gameResume()');
assert.equal(a.ev('UI.speed'), 0, 'resuming a game keeps the lock');
a.ev('S.uiSpeed=2');
press(a, 'on:0');
assert.equal(a.ev('UI.clockLocked'), false);
assert.equal(a.ev('UI.speed'), 2, 'switching off restores the speed the player left the game at');
a.ev('ACT.speed({v:4})');
assert.equal(a.ev('UI.speed'), 4, 'and the speed buttons are back');
assert.deepEqual(a.errors, []);
});
test('a paced clock runs behind an open window and in a hidden tab, and leaves the rest to the frame', () => {
const a = agent({ ms: 30000 });
a.ev('ACT.start({});S.cash=1e9;S.nextFail=S.day+999;S.nextEvent=S.day+999;compute()');
// As if a tool were connected: the pace runs.
a.ev('API_RELAY.on=true;apiRelayPresence(1)');
assert.equal(a.ev('UI.speed'), a.ev('DAY_MS/30000'));
// Visible, no window: the frame runs the days, the ticker none.
a.ev('API_TICKER.last=0;apiAgentTick(1000);for(let t=1250;t<=31000;t+=250)apiAgentTick(t)');
assert.equal(a.ev('S.day'), 0, 'the ticker leaves a visible, open map to the frame');
a.ev('last=0;for(let t=250;t<=30250;t+=250)frame(t)');
assert.equal(a.ev('S.day'), 1, 'which runs a day in 30 s');
// A window open: the frame stops, the ticker goes on.
a.ev('ACT.settings({})');
a.ev('last=40000;for(let t=40250;t<=70000;t+=250)frame(t)');
assert.equal(a.ev('S.day'), 1, 'no days in the frame behind a window');
a.ev('API_TICKER.last=0;apiAgentTick(70000);for(let t=70250;t<=100250;t+=250)apiAgentTick(t)');
assert.equal(a.ev('S.day'), 2, 'the ticker runs the day behind it');
a.ev('closeModal()');
// A hidden tab: frames stop altogether, the ticker goes on.
a.ev("Object.defineProperty(document,'visibilityState',{value:'hidden',configurable:true})");
a.ev('API_TICKER.last=0;apiAgentTick(200000);for(let t=200250;t<=230250;t+=250)apiAgentTick(t)');
assert.equal(a.ev('S.day'), 3, 'and in a hidden tab');
// Off: the ticker does nothing at all.
a.ev("apiAgentSet('on',false)");
a.ev('API_TICKER.last=0;apiAgentTick(300000);for(let t=300250;t<=400000;t+=250)apiAgentTick(t)');
assert.equal(a.ev('S.day'), 3);
assert.deepEqual(a.errors, []);
});
test('phones show the agent pace in the tab bar, where the speed button was', () => {
const a = agent();
a.ev('ACT.start({});S.cash=1e9;compute();window.innerWidth=360;window.innerHeight=740;renderTabbar()');
const pace = () => a.ev(`(()=>{const b=document.querySelector('#tabbar button.pace');return b?{dis:b.disabled,ic:b.querySelector('.ic').textContent}:null;})()`);
assert.equal(a.ev('isPhone()'), true);
assert.deepEqual({ ...pace() }, { dis: true, ic: '1 min' }, 'the locked speed button reads the pace');
assert.equal(a.ev(`document.querySelector('#tabbar button.play').disabled`), true, 'and play/pause is locked');
assert.equal(a.ev(`document.querySelectorAll('#tabbar [data-act="phonePlay"],#tabbar [data-act="phoneSpeed"]').length`), 0);
a.ev("apiAgentSet('ms',30000);renderTabbar()");
assert.equal(pace().ic, '30 s', 'and follows the pace the player picks');
a.ev("apiAgentSet('ms',0);renderTabbar()");
assert.equal(pace().ic, '🤖', 'the agent\'s clock has a badge of its own');
// The desktop and tablet HUD badge says the same, in place of the speed buttons.
a.ev('renderHUD()');
assert.equal(a.ev("$('spPace').hidden"), false);
assert.equal(a.ev("$('sp1').hidden"), true);
assert.equal(a.ev("$('spPace').textContent"), 'Agent\'s clock');
a.ev("apiAgentSet('ms',30000);renderHUD()");
assert.match(a.ev("$('spPace').textContent"), /30 s per simulated day/);
// Agent mode off: the ordinary buttons are back, and the badge goes.
a.ev("apiAgentSet('on',false);renderTabbar();renderHUD()");
assert.equal(pace(), null);
assert.match(a.ev(`document.querySelector('#tabbar [data-act="phoneSpeed"] .ic').textContent`), /×$/);
assert.equal(a.ev("$('spPace').hidden"), true);
assert.equal(a.ev("$('sp1').hidden"), false);
assert.deepEqual(a.errors, []);
});
test('the Settings sheet\'s agent section is complete in every language, on a phone too', () => {
for (const lang of ['en', 'de', 'es', 'fr', 'it', 'pt']) {
const a = load({ agent: true, storage: prefs(), ...(lang === 'en' ? {} : { lang }) });
a.ev('ACT.start({});window.innerWidth=360;window.innerHeight=740;ACT.settings({})');
const html = a.ev("$('modalCard').innerHTML");
assert.ok(html.includes('data-agent-set="ms:0"') && html.includes('data-agent-set="ms:300000"'), `${lang}: every clock button is there`);
assert.doesNotMatch(a.ev("$('modalCard').textContent"), /settings\./, `${lang}: no label shows untranslated`);
assert.deepEqual(a.errors, [], lang);
}
});

View file

@ -23,7 +23,10 @@ function load(opts = {}) {
if (!/getContext|Not implemented/.test(e.message)) errors.push(e.message); if (!/getContext|Not implemented/.test(e.message)) errors.push(e.message);
}); });
const dom = new JSDOM(html, { const dom = new JSDOM(html, {
url: 'https://tests.invalid/', // opts.url: the origin the page is "served" from. Tests that dial the agent relay pass the relay's own host, so
// the page's WebSocket Origin matches (the relay refuses a cross-site one); everything else stays on a made-up
// https origin nothing can reach.
url: opts.url || 'https://tests.invalid/',
runScripts: 'dangerously', runScripts: 'dangerously',
pretendToBeVisual: true, pretendToBeVisual: true,
virtualConsole: vc, virtualConsole: vc,

View file

@ -273,7 +273,7 @@ test('everything an action needs can be read: loan offers, conference keys, reci
assert.equal(T('state', { path: 'no.such.path' }), null); assert.equal(T('state', { path: 'no.such.path' }), null);
assert.ok('pending' in T('ui') && !('hover' in T('ui')), 'the view state, without render scratch'); assert.ok('pending' in T('ui') && !('hover' in T('ui')), 'the view state, without render scratch');
assert.throws(() => T('schema', { section: 'nope' }), /No section/); assert.throws(() => T('schema', { section: 'nope' }), /No section/);
assert.deepEqual(Object.keys(T('schema')).sort(), ['clock', 'commands', 'denied', 'domains', 'drafts', 'results', 'session', 'state', 'view']); assert.deepEqual(Object.keys(T('schema')).sort(), ['clock', 'commands', 'denied', 'domains', 'drafts', 'mode', 'results', 'session', 'state', 'view']);
const a = T('actions'); const a = T('actions');
for (const x of ['buildLink(a,b,tier,cable?,route?,premiumCrossing?)', 'orderDf(a,b,source,system)', 'teDeploy(script)', 'renameGo(name)', 'rtbh(id?)', 'startScn(id)', 'dfSrc(v)']) assert.ok(a.includes(x), x); for (const x of ['buildLink(a,b,tier,cable?,route?,premiumCrossing?)', 'orderDf(a,b,source,system)', 'teDeploy(script)', 'renameGo(name)', 'rtbh(id?)', 'startScn(id)', 'dfSrc(v)']) assert.ok(a.includes(x), x);
assert.deepEqual(s.errors(), []); assert.deepEqual(s.errors(), []);

83
tests/mcp-parity.test.js Normal file
View file

@ -0,0 +1,83 @@
// One MCP session, two places: the same scripted moves through the headless server's own page and through the agent
// relay into a page in a "browser" (a jsdom page connected to an in-process relay, the player's clock set to the
// agent's) must give the same outcomes, the same money and the same game. The facade is one piece of code; this checks
// that the transport, the async days and the player's rules change nothing a tool would see in a plain game.
const test = require('node:test');
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const http = require('node:http');
const { load } = require('./harness');
const { createRelay } = require('../scripts/agent/relay');
const { createSession, TOOLS } = require('../scripts/lib/mcp-game');
const { createBrowserSession } = require('../scripts/lib/mcp-browser');
const PORT = 9399 + (process.pid % 400);
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
const HEADLESS_JS = fs.readFileSync(path.join(__dirname, '..', 'scripts', 'lib', 'mcp-headless.js'), 'utf8');
const SCRIPT = [
['status'],
['act', { action: 'launchBB', args: { city: 'fra' } }],
['act', { action: 'buyTransit', args: { city: 'fra', net: 'cog', tier: 1 } }],
['act', { action: 'buildLink', args: { a: 'fra', b: 'ams', tier: 1 } }],
['act', { action: 'buildPop', args: { city: 'ams' } }],
['act', { action: 'buyTransit', args: { city: 'fra', net: 'nope', tier: 1 } }],
['act', { action: 'pni', args: { city: 'fra', net: 'lvl', tier: 1 }, dryRun: true }],
['act', { action: 'buyIx', args: { city: 'fra', tier: 1 } }],
['act', { action: 'buildPop', args: { city: 'par' } }],
['act', { action: 'dkAccept' }],
['advance', { days: 30 }],
['status'],
['hot_spots', { limit: 3 }],
['network', { network: 'ggl' }],
['traceroute', { from: 'fra', to: 'ggl' }],
['peering_check', { network: 'nfx' }],
['panel', { city: 'fra', tab: 'peer' }],
['act', { action: 'renameGo', args: { name: 'Twin Tubes' } }],
['actions'],
['advance', { days: 60 }],
['state', { path: 'pops' }],
['results', { path: 'served' }],
['status'],
];
// What differs by nature, not by game: how long a day took on this machine, and entity ids (uid() reads the clock).
const strip = (v) => JSON.parse(JSON.stringify(v, (k, x) => (k === 'timing' || k === 'id' ? undefined : x)));
async function play(s) {
const out = [];
for (const [name, args = {}] of SCRIPT) {
try { out.push([name, strip(await TOOLS.find((t) => t.name === name).run(s, args))]); } catch (e) { out.push([name, { error: String(e.message) }]); }
}
return out;
}
test('the same scripted session gives the same outcomes headless and through the relay', async () => {
const headless = createSession();
const here = await play(headless);
headless.close();
const srv = http.createServer((q, r) => { r.writeHead(404); r.end(); });
const relay = createRelay({ server: srv });
await new Promise((r) => srv.listen(PORT, '127.0.0.1', r));
// The player's tab: the same page and seed, the same first game, and the agent's clock in Settings.
const a = load({ url: `http://127.0.0.1:${PORT}/`, seed: 12345, agent: true, storage: { 'sot-agent': JSON.stringify({ on: true, ms: 0 }) } });
const s = createBrowserSession({ port: PORT });
try {
a.ev(HEADLESS_JS);
a.ev("__mcpHeadless.newGame({city:'fra',name:'Scratch Networks',preset:'oncall'})");
a.ev(`window.__AGENT_RELAY_TEST__=true;API_RELAY_HOST='127.0.0.1:${PORT}';apiAgentSync()`);
await wait(400);
assert.deepEqual(await s.ready({ waitMs: 5000 }), { ok: true }, 'the tab serves this checkout\'s contract');
const there = await play(s);
for (let i = 0; i < SCRIPT.length; i++) assert.deepEqual(there[i], here[i], `step ${i}: ${SCRIPT[i][0]} ${JSON.stringify(SCRIPT[i][1] || {})}`);
assert.ok(here.some(([n, v]) => n === 'act' && v.outcome === 'decision'), 'the script meets a question');
assert.ok(here.some(([, v]) => v.error), 'and an error');
assert.equal(a.ev('S.day'), 90);
assert.deepEqual(a.errors, []);
} finally {
a.ev("window.__AGENT_RELAY_TEST__=false;apiAgentSet('on',false)");
await s.close();
relay.close();
await new Promise((r) => srv.close(r));
}
});

View file

@ -163,3 +163,36 @@ test('only game actions: files, slots, settings and the clock stay out of reach'
assert.throws(() => T('act', { action: 'noSuchThing' }), /no action/); assert.throws(() => T('act', { action: 'noSuchThing' }), /no action/);
assert.throws(() => T('click', { button: 99 }), /No button 99/); assert.throws(() => T('click', { button: 99 }), /No button 99/);
}); });
test('a running clock: days pass on their own, advance is refused and wait reads them', async () => {
const s = createSession({ clock: 'realtime', paceMs: 30 }), T = tools(s);
try {
assert.equal(T('schema', { section: 'mode' }).clock, 'realtime');
assert.match(T('schema', { section: 'clock' }), /runs on its own/);
assert.throws(() => T('advance', { days: 1 }), /use wait/);
const w = await T('wait', { days: 3, maxSeconds: 10 });
assert.ok(w.daysRun >= 3, `three days passed by themselves (${w.daysRun})`);
assert.equal(w.stoppedBecause, null);
assert.ok(Array.isArray(w.log) && typeof w.cashChange === 'number');
assert.deepEqual(s.errors(), []);
} finally { s.close(); }
// The agent's clock stands still between calls, and wait says to use advance.
const s2 = createSession(), T2 = tools(s2);
const d0 = T2('status').day;
await new Promise((r) => setTimeout(r, 100));
assert.equal(T2('status').day, d0);
await assert.rejects(T2('wait', { days: 1 }), /use advance/);
});
test('--clock realtime over stdio: the instructions and the schema say whose clock it is', async () => {
const child = spawn(process.execPath, [path.join(__dirname, '..', 'scripts', 'mcp.js'), '--clock', 'realtime', '--pace', '50'], { stdio: ['pipe', 'pipe', 'pipe'] });
let buf = '';
const lines = [], waiters = [];
child.stdout.on('data', (d) => { buf += d; let i; while ((i = buf.indexOf('\n')) >= 0) { lines.push(JSON.parse(buf.slice(0, i))); buf = buf.slice(i + 1); waiters.splice(0).forEach((w) => w()); } });
const ask = async (msg) => { child.stdin.write(JSON.stringify({ jsonrpc: '2.0', ...msg }) + '\n'); const f = () => lines.find((l) => l.id === msg.id); while (!f()) await new Promise((r) => waiters.push(r)); return f(); };
try {
const init = await ask({ id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '1' } } });
assert.match(init.result.instructions, /runs on its own/);
const mode = JSON.parse((await ask({ id: 2, method: 'tools/call', params: { name: 'schema', arguments: { section: 'mode' } } })).result.content[0].text);
assert.deepEqual({ backend: mode.backend, clock: mode.clock, paceMs: mode.paceMs, transport: mode.transport }, { backend: 'headless', clock: 'realtime', paceMs: 50, transport: 'jsdom' });
} finally { child.kill(); }
});