diff --git a/.claude/skills/edit-the-game/SKILL.md b/.claude/skills/edit-the-game/SKILL.md index bfacf0e..7dc75dd 100644 --- a/.claude/skills/edit-the-game/SKILL.md +++ b/.claude/skills/edit-the-game/SKILL.md @@ -47,7 +47,10 @@ next to it. `npm run page -- -o /tmp/page.html` writes the assembled page if you anything runs after boot. When in doubt, put constants in an earlier file and logic in functions. - **Actions:** add `name:(args)=>{…},` to the matching `src/game/90-actions/*.js`. Only `10-interface.js` declares `const ACT={`; the others are `Object.assign(ACT,{ … });`. A new area can get - a new `NN-area.js` file of that second form. + a new `NN-area.js` file of that second form. The MCP server types every action: a new one also gets + an entry in `scripts/lib/mcp-commands.js` (a game command with its argument domains, a view, a draft + or a session action) or in the server's `DENY` list in `scripts/lib/mcp-page.js`; + `tests/mcp-commands.test.js` fails until it has one. - **Panels and modals:** `93-ui/` (HUD, side panels), `94-dashboard/` (NOC dashboard, bank), `95-modals/`. - **Styles:** the matching `src/styles/*.css`; phone rules go in `60-phone.css`. - **Data tables** (cities, cables, networks): one entry per line, and keep id-keyed objects such as diff --git a/CHANGELOG.md b/CHANGELOG.md index bf07b1a..d5c6874 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ All notable changes to this project are documented here. The project follows ## [Unreleased] +- Three new cities in northern Australia: Port Hedland, Townsville and Alice Springs (#255). Port Hedland lands a new cable up the coast to Darwin and a branch of Darwin's cable out to Singapore; Alice Springs has no sea at all. In the wet season, November to April, fiber cuts in the tropical north, Darwin included, take twice as long to reach. +- Traceroute no longer shows an "embedded cache in your rack" hop on paths that leave over transit, an exchange or a PNI. Only traffic that really ends at one of your cache boxes shows it now. - New keyboard shortcuts: the arrow keys and W A S D move the map, [ and ] step through your POPs, - and = zoom out and in, n opens the NOC dashboard, and ? lists every shortcut. A letter right after n opens one of the dashboard's tabs, such as n c for Connections, and Help links to the list too. ## [2.6.0] — 2026-11-03 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index cbae642..9729449 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -66,7 +66,7 @@ Development runs on `npm run dev` (assembles on every request, reloads on save); | `scripts/test.js` | `npm test`: runs every `tests/*.test.js` | | `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/mcp.js`, `scripts/lib/mcp-game.js`, `scripts/lib/mcp-page.js` | The game as a local MCP server: 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-commands.js`, `scripts/lib/mcp-page.js` | The game as a local MCP server: typed tools to play, inspect and debug it from an AI client ([MCP.md](MCP.md)) | | `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 | | `tests/harness.js` | Loads the assembled page in jsdom with a seeded `Math.random` and a fake canvas | diff --git a/docs/MCP.md b/docs/MCP.md index 0b4a52f..ffacde0 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -22,33 +22,61 @@ the same seed and the same moves give the same game. | Tool | What it does | |---|---| -| `new_game` | Start a network in any home city with a preset (`freeze`, `oncall`, `bgp`, `sandbox`) and a seed | +| `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 | | `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 | | `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 needs an answer or the network goes bankrupt. Returns the log, new incidents, cash and the time each day took | +| `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 | | `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 | | `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 | -| `actions`, `act` | Every game action with its arguments, and running one as a button would | -| `screen`, `panel`, `click`, `open_link` | The game's own windows and panels as text with numbered buttons; press one; open a link's build window | +| `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` | +| `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.`) | +| `actions`, `act` | Every action with its arguments, and running one | +| `screen`, `panel`, `click`, `open_link` | The game's own windows, panels, left drawer, NOC dashboard, bank and puzzle box as text with numbered buttons; press one; open a link's build window | -`act` and `click` run the same `ACT` actions the buttons dispatch, so the game's rules, prices and messages apply. -They never reach files, save slots, settings, the title screen or the game speed (time moves only with `advance`). -There is no tool that evaluates code in the page. +## Acting + +`act` checks the arguments against `schema` first: a wrong id or value is an error that says what would fit, and +nothing runs. The action then runs as the game runs it, with what a player would type and pick filled in: a rename, +a RouteScript, a custom metric, the route and size of a link, the source and line system of dark fiber, the design +of a cable, the POPs to close. Confirmations are given, so `rmLink` removes the link in one call. The result says +what happened: + +| `outcome` | Meaning | +|---|---| +| `applied` | Something changed. `charged` is what the game's money gate took; `cashChange` also counts goal rewards | +| `rejected` | The game said no; `toasts` has its words | +| `no_effect` | Nothing changed and nothing was said: usually a wrong id or a precondition | +| `shown` | A view or a draft: only the screen changed | +| `decision` | A window asks a question (a De-Kicks quote, a retention offer). Answer with one of `decision.options` or `closeModal`; other game commands wait until then | +| `quote` | With `dryRun`: `{setup, monthly, days, blocked}`, priced with the game's own helpers. Nothing happens, and no dice are rolled | +| `stopped` | The network is bankrupt | + +`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 clicked with a value. Neither tool reaches files, save slots, settings, the title screen or the game speed: time +moves only with `advance`. There is no tool that evaluates code in the page. ## Looking into a bug report 1. `load_save` with the save attached to the issue. -2. `status` and `hot_spots` for the picture, `traceroute` and `peering_check` for one network's traffic. +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. 3. `advance` a few days and read `timing.slowestDays` for lag, or the log for what went wrong. ## Code - `scripts/mcp.js`: the stdio transport (JSON-RPC 2.0, one message per line) and the protocol methods. - `scripts/lib/mcp-game.js`: the session (one game page) and the tool list with input schemas. +- `scripts/lib/mcp-commands.js`: runs inside the page: every action's class, arguments, domains, price and + description, and the `state`/`results` field reference. - `scripts/lib/mcp-page.js`: runs inside the page and reads or drives the game through its own globals. - `tests/mcp.test.js`: the protocol, a game played through the tools, determinism, saves, and what stays out of reach. +- `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. 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 `tests/mcp.test.js` is there to catch that in CI. +break a tool, and the tests are there to catch that in CI. A new action in `ACT` needs an entry in +`scripts/lib/mcp-commands.js` or the server's `DENY` list, or `tests/mcp-commands.test.js` fails. diff --git a/scripts/lib/mcp-commands.js b/scripts/lib/mcp-commands.js new file mode 100644 index 0000000..e21df6e --- /dev/null +++ b/scripts/lib/mcp-commands.js @@ -0,0 +1,816 @@ +// Runs inside the game page before scripts/lib/mcp-page.js, in the game's own global scope: the typed command +// tables the MCP server's act tool dispatches through. Data and small helpers only, no state. +// +// Every action in ACT is in exactly one class (tests/mcp-commands.test.js fails otherwise, so a new action forces a +// decision): CMD, a game command with typed arguments; VIEW, which changes only what is on screen; BOUND, which only +// drafts an input another command reads; SESSION, which starts, retries or leaves a game or dismisses a coaching +// screen; or the server's DENY list (scripts/lib/mcp-page.js). CMD fields: args [name, domain|'string'|'boolean'|'integer', required]; bind(args) writes the UI +// a panel would set (bindsUI: the UI keys it touches, restored after a dry run); open/dom: the window an input lives +// in and the fields that must exist before dispatch; pass(args) reshapes the args for the action (confirmations); +// confirm 'arg' (passed through) or 'double' (the game arms a button first); decides (may end in a question); reads +// 'modal' (the window's text is the report); watch (extra fingerprint paths, #name filled from args); quote (the dry +// run, priced with the game's own helpers); doc. +window.__mcpCmds = (() => { +const API_DOMAINS={ + // Tables from the catalog: an id in a list, a key in an object, or an index into a list. + cityId:{table:'CITIES',kind:'id'}, + netId:{table:'NETS',kind:'id'}, + cableId:{table:'CABLES',kind:'id'}, + fabId:{table:'FAB',kind:'key'}, + opticId:{table:'OPT',kind:'key'}, + systemId:{table:'DF_SYS',kind:'key'}, + designId:{table:'SEA_DESIGNS',kind:'key'}, + upgradeId:{table:'SUB_UPGRADES',kind:'key'}, + bizTypeId:{table:'BIZ_T',kind:'key'}, + portTier:{table:'PORT',kind:'index'}, + linkTier:{table:'LT',kind:'index'}, + nniTier:{table:'NNI',kind:'index'}, + vxcTier:{table:'VXC',kind:'index'}, + routerModel:{table:'RG',kind:'index'}, + scrubTier:{table:'SCRUB_TIERS',kind:'index'}, + // Small fixed vocabularies the game itself checks by list membership. + // The link metric presets, plus "custom" for a hand-tuned number (ACT.setMetric). + metric:{kind:'enum',values:()=>[...Object.keys(MET),'custom']}, + egress:{table:'PREF',kind:'key'}, + routeMode:{table:'RT',kind:'key'}, + site:{kind:'enum',values:['a','b','ab']}, + step:{kind:'enum',values:[1,-1]}, + connKind:{kind:'enum',values:['t','p','ix','c','nni']}, + egressKind:{kind:'enum',values:['t','p','ix','c','nni','l2']}, + peerPolicy:{table:'PPOL',kind:'enum'}, + // The intern, their orders and the new-POP template (opsHire, opsToggle, opsParam…). + internId:{table:'INTERNS',kind:'key'}, + opsKey:{table:'OPSK',kind:'key'}, + opsPopKind:{kind:'enum',values:()=>OPS_POP.slice()}, + opsTplKey:{kind:'enum',values:()=>OPS_TPL.slice()}, + // The specialist's offers: a seat on a consortium cable, the charter, a vendor demo. + seatPairs:{kind:'enum',values:()=>SEAT_N.slice()}, + charterKey:{table:'CHARTERS',kind:'key'}, + // The link metric editor: a factor or an exact weight (metricMode, metricSet). + metricKind:{kind:'enum',values:['f','w']}, + // The NOC's auto-mitigation switches (ddosAuto). + ddosKey:{kind:'enum',values:['rtbh','scrub']}, + // Puzzle and architect builds: the tiers a puzzle may light, the router models it offers. + pztTier:{kind:'fn',ok:v=>PZ_TIERS.includes(+v)||AR_TIERS.includes(+v)}, + pzRouterModel:{table:'PZ_RG',kind:'index'}, + pzRouteMode:{kind:'enum',values:['normal','fast']}, + // The bulk PNI order takes one network or null for every network at every shared POP (ACT.pniAll). + pniAllNet:{kind:'fn',ok:v=>v===null||(typeof v==='string'&&!!NET[v])}, + dashTab:{kind:'enum',values:()=>DTABS.slice()}, + dashSortKey:{kind:'enum',values:['name','asn','type','traffic','cost','lost']}, + leftTab:{kind:'enum',values:['goals','deals','noc','nets']}, + netFilter:{kind:'enum',values:['all','out']}, + pniFilter:{kind:'enum',values:['all','t','worth','pni']}, + listPage:{kind:'enum',values:['conn','cust','nets','pni']}, + custSortKey:{kind:'enum',values:['mood','mo','name','city']}, + connFilter:{kind:'enum',values:['all','k']}, + connSortKey:{kind:'enum',values:['k','city','name','use','mo']}, + dfSource:{kind:'enum',values:['lease','build','cable']}, + cityIdArray:{kind:'array',of:'cityId'}, + // Anything a panel can reach: an exchange city, a rival exchange id, one of your own exchanges. + ixId:{kind:'fn',ok:v=>isIx(v)}, + // A PNI also takes tier:-1, the 1G courtesy port a network may offer (ACT.pni). + pniTier:{kind:'fn',ok:v=>v===-1||(Number.isInteger(v)&&v>=0&&vtypeof v==='string'&&upcomingConfs(75).some(c=>c.key===v)}, + // traceroute goes to your own POPs and to networks; traceModal parses a net:/city: prefix. + traceTo:{kind:'fn',ok:v=>typeof v==='string'&&(NET[v]||isCity(v))}, + // Entity ids (uid()) cannot be validated against a table: shape only. A wrong id is the game's + // to answer, honestly, with no_effect — never a refusal invented on this side of the wall. + entityId:{kind:'string'}, + scnId:{table:'SCN',kind:'id'}, + // A traceroute target in the modal's own terms. +}; + +/* Type names an arg can take instead of a domain: 'string' | 'boolean' | 'integer'. */ + +function apiDomCheck(dom,v){ + const d=API_DOMAINS[dom]; + // The game's own buttons ship truthiness as 0 and 1 (custOpen's {"sad":0}); accept the game's dialect. + if(dom==='boolean')return {ok:v===true||v===false||v===0||v===1}; + if(!d)return {ok:dom==='integer'?Number.isInteger(v):typeof v===dom}; // 'string' | 'integer' + if(d.kind==='array')return {ok:Array.isArray(v)&&v.every(x=>apiDomCheck(d.of,x).ok)}; + const t=d.table?API_CATALOG_TABLE(d.table):null; + if(d.kind==='id')return {ok:!!t&&t.some(x=>x&&x.id===v)}; + if(d.kind==='string')return {ok:typeof v==='string'}; + if(d.kind==='key'||d.kind==='enum'){ + const vs=d.kind==='key'?Object.keys(t||{}):(t||(typeof d.values==='function'?d.values():d.values)||[]); + return {ok:vs.includes(v)};} + if(d.kind==='index')return {ok:Number.isInteger(v)&&v>=0&&v<(t?t.length:0)}; + return {ok:!!d.ok&&d.ok(v)}; +} +function apiDomValues(dom){ + const d=API_DOMAINS[dom];if(!d)return null; + const t=d.table?API_CATALOG_TABLE(d.table):null; + if(d.kind==='array')return {of:d.of}; + if(d.kind==='id')return t?t.map(x=>x.id):[]; + if(d.kind==='key')return t?Object.keys(t):[]; + if(d.kind==='enum')return t||(typeof d.values==='function'?d.values():d.values)||[]; + if(d.kind==='index')return {from:0,to:(t?t.length:1)-1}; + return null; +} + +const API_CMD={ +/* ---------- footprint: buildings, routers, POPs ---------- */ + buildPop:{args:[['city','cityId']], + quote:a=>({setup:popCost(a.city),blocked:cnCity(a.city)&&!cnOk()?[tr('pops_transit_ix.you_need_a_license_first_foreign')]:[]}), + doc:'Open a POP in a city you do not have one in. Costs popCost(city).'}, + launchBB:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>({setup:bbCost(a.city)}), + doc:'Launch broadband to the eyeballs of a city you have a POP in. The core revenue source; one per POP.'}, + ad:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>({setup:8000}), + doc:'A 30-day ad campaign that boosts eyeball growth in a broadband city.'}, + addRouter:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>{const p=S.pops[a.city];return {setup:p?routerCost(p.rgen||0,p.routers||1):0};}, + doc:'Add a router to a POP, up to RMAX. Cost rises with the model and the count.'}, + rmRouter:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>{const p=S.pops[a.city];return {setup:-((p&&tradeIn(p.rgen||0,1))||0),blocked:p&&portsUsed(a.city)>portsMax(a.city,undefined,p.routers-1)?[tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(a.city)),max:portsMax(a.city,undefined,p.routers-1)})]:[]};}, + doc:'Remove a router and sell it on eBuy for a trade-in. Refused while the rest cannot carry the ports.'}, + upRouter:{args:[['city','cityId'],['g','routerModel',false]],watch:['pops.#city'], + quote:a=>{const p=S.pops[a.city];if(!p)return {};const g=a.g===undefined?mainRG(RG[p.rgen||0].cls+1):+a.g; + return {setup:swapCost(a.city,g),blocked:[(!RG[g]||g===(p.rgen||0))?'no such model':modelFits(a.city,g)||''].filter(Boolean)};}, + doc:'Swap every router in a city for another model. Omit g for the next class up. One swap per day per city.'}, + addGen:{args:[['city','cityId']],watch:['pops.#city'],quote:a=>({setup:GEN_COST,monthly:GEN_MO}), + doc:'Install a generator, so a power cut does not take the POP out.'}, + addSite:{args:[['city','cityId']],watch:['pops.#city'],quote:a=>({setup:SITE2_COST,monthly:SITE2_MO}), + doc:'Add a second building in the city, so one dark data centre does not take everything down.'}, + rmSite:{args:[['city','cityId']],confirm:'double',watch:['pops.#city'], + doc:'Remove the second building. Every port, PNI and cache there moves back to site A.'}, + decomGo:{args:[['cities','cityIdArray']],bindsUI:['decom'],bind:a=>{UI.decom=new Set((a.cities||[]).filter(c=>S.pops[c]));}, + doc:'Close POPs: cancels their ports, links, peerings and customers. Refuses to close every POP you have. Irreversible.'}, +/* ---------- upstream (transit) ---------- */ + buyTransit:{args:[['city','cityId'],['net','netId'],['tier','portTier']], + quote:a=>({setup:PORT[a.tier].setup,monthly:PORT[a.tier].tmo}), + doc:'Order a transit port from a network that sells in that city. Billed monthly on the 95th percentile. A higher tier on an existing port upgrades it.'}, + lagT:{args:[['id','entityId'],['d','step']],watch:['transit.#id'], + quote:a=>{const t=S.transit.find(x=>x.id===a.id);return {setup:a.d>0&&t?PORT[t.tier].setup:0};}, + doc:'Add or remove one LAG member on a transit port, up to LAG_MAX. Adding charges another port setup.'}, + cancelTransit:{args:[['id','entityId']],confirm:'arg',pass:a=>({id:a.id,ok:1}), + doc:'Cancel a transit port.'}, + togglePrem:{args:[['id','entityId']],watch:['transit.#id'], + doc:'Turn the premium upstream product on or off, where the network sells one in that city.'}, + cleanPipe:{args:[['id','entityId']],watch:['transit.#id'], + quote:a=>{const t=S.transit.find(x=>x.id===a.id);return t?{monthly:cleanMo(t)}:{};}, + doc:'Add or remove the upstream DDoS-scrubbing add-on. Monthly.'}, +/* ---------- exchanges ---------- */ + buyIx:{args:[['city','ixId'],['tier','portTier'],['signed','boolean',false]],decides:true, + quote:a=>({setup:ixPortMo(a.city,a.tier),monthly:ixPortMo(a.city,a.tier),blocked:[portOk(ixCity(a.city),a.tier)?'':tr('actions.your_router_can_t_take_a',{port:PORT[a.tier].n})].filter(Boolean)}), + doc:'Take a port on an internet exchange. Monthly. At a De-Kicks exchange the first order returns a personalised quote to answer. A remote port (no POP) is possible at 10G over a fabric.'}, + lagIx:{args:[['city','ixId'],['d','step']],watch:['ixn'], + doc:'Add or remove one LAG member on an IX port. Not on your own exchange.'}, + cancelIx:{args:[['city','ixId']],confirm:'arg',pass:a=>({city:a.city,ok:1}),decides:true, + doc:'Leave an exchange; drops every peering session there. De-Kicks may answer with a retention offer.'}, + rs:{args:[['city','ixId']],watch:['rs'], + doc:'Toggle the route-server session, which peers you with everyone on the server at once.'}, + foundIx:{args:[['city','cityId']],watch:['myIx.#city'],quote:a=>({setup:MYIX_COST,monthly:MYIX_MO}), + doc:'Found your own exchange in a city with no IX. Networks join over the following days.'}, + myIxUp:{args:[['city','cityId']],watch:['myIx.#city'], + quote:a=>{const m=S.myIx[a.city];const f=m?(m.fab|0)+1:0,N=f{const t=a.tier===-1?0:a.tier,ex=S.pni.find(p=>p.city===a.city&&p.net===a.net),r=peerOk(a.net,'pni',a.city); + return {setup:a.tier===-1?PNI_G1_COST:(1500+PORT[t].setup/2)*((ex&&ex.n)||1),monthly:(a.tier===-1?Math.round(PORT[0].pni/2):PORT[t].pni)*((ex&&ex.n)||1),days:pniLead(a.net), + blocked:[r.ok?'':r.why,portOk(a.city,t)?'':tr('actions.your_router_can_t_take_a',{port:PORT[t].n}), + a.tier!==-1&&a.tier({id:a.id,ok:1}), + doc:'Cancel a PNI or its pending augment.'}, + lagP:{args:[['id','entityId'],['d','step']],watch:['pni.#id'], + doc:'Add or remove a LAG member on a PNI. Adding is an augment with a lead time.'}, + sacrif:{args:[['id','entityId']],watch:['pni.#id'], + doc:'Mark a PNI sacrificial, so attack traffic is steered into it.'}, + peerPol:{args:[['p','peerPolicy']],watch:['ppol'], + doc:'Set your published peering policy: open, selective or closed. It answers every peering request for you: open accepts everyone, selective takes small networks on the exchange and newcomers with an up-to-date PeeringDB, closed declines them all. The NOC log sums the week up.'}, +/* ---------- caches ---------- */ + cache:{args:[['city','cityId'],['net','netId']], + quote:a=>{const n=NET[a.net];return {monthly:n&&n.cache?CACHE_MO:0, + blocked:n&&n.cache&&(R.demTo[a.net]||0){UI.pending={a:a.a,b:a.b};UI.route=a.route||'';UI.via=a.cable||'';UI.cnPrem=!!a.premiumCrossing;}, + pass:a=>({tier:a.tier}), + quote:a=>{const A=a.a,B=a.b,tier=a.tier; + if(!waveOk(A,B,tier))return {blocked:[tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:waveNeed(tier)})]}; + const sib=pairLinks(A,B).filter(l=>l.kind!=='vxc'),jn=sib.length?routeJoin(A,B):null,border=cnCity(A)!==cnCity(B); + const mult=(sib.length&&!(jn&&jn.k===(landTrenches(A,B)[0]||{}).k)?DIVERSE:1)*(border?3*((a.premiumCrossing&&(A==='hkg'||B==='hkg'))?1.6:1):1); + const wr=waveRoute(A,B,mult,border);if(!wr)return {blocked:[tr('links.no_cable_available_for_that_route')]}; + const blocked=[],so=soldOut(A,B,tier,wr.cab); + if(so)blocked.push(tr('links.no_wave_capacity_on_this_route',{wave:LT[tier].n,why:tr(so.why),n:Math.max(1,so.until-S.day)})); + const w=subWaveWhy(tier,wr.km,wr.sub);if(w)blocked.push(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:w})); + return {setup:Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm)+(S.pops[B]?0:popCost(B)),monthly:Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm),blocked};}, + doc:'Lease a wave between two cities; opens a POP in b if there is none. A second wave on a pair costs 1.4x unless it joins an existing trench; cross-border into mainland China costs 3x. premiumCrossing applies only via Hong Kong.'}, + upLink:{args:[['id','entityId'],['tier','linkTier']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);if(!l)return {}; + const blocked=[waveOk(l.a,l.b,a.tier)?'':tr('links.a_wave_wave_needs_need_at',{wave:LT[a.tier].n,need:waveNeed(a.tier)})]; + const w=subWaveWhy(a.tier,l.km,l.sub);if(w)blocked.push(tr('links.no_wave_waves_on_this_cable',{wave:LT[a.tier].n,why:w})); + return {monthly:Math.round(waveMo(l.km,l.sub,a.tier)*(l.mult||1)),blocked:blocked.filter(Boolean)};}, + doc:'Upgrade a leased wave in place. Upward only, and only if the span and cable support it.'}, + rmLink:{args:[['id','entityId']],confirm:'double', + quote:a=>{const l=S.links.find(x=>x.id===a.id);return {setup:-((l&&cabBack(l))||0)};}, + doc:'Decommission a link. A cancelled own-cable build refunds part of the money. Irreversible.'}, + setMetric:{args:[['id','entityId'],['v','metric']],watch:['pairMet'], + doc:'Routing preference for the city pair this link belongs to (not the link): prefer, normal, avoid, backup, or custom (then metricMode and metricSet tune the number).'}, + setCarry:{args:[['id','entityId'],['on','boolean']],watch:['transit.#id'], + doc:'Turn a transit port\'s Carry here on or off: it pulls that carrier\'s traffic (and its customers\') across your network from POPs that have no port of that carrier. Prefer, Backup only and RouteScript still win.'}, + setStandby:{args:[['id','entityId'],['on','boolean']],watch:['links.#id'], + doc:'Hold a link in reserve: its capacity fills last.'}, +/* ---------- fabrics and VXCs ---------- */ + buyNni:{args:[['city','cityId'],['prov','fabId'],['tier','nniTier']], + quote:a=>({setup:NNI[a.tier]?NNI[a.tier].mo:undefined,monthly:NNI[a.tier]?NNI[a.tier].mo:undefined}), + doc:'Take a port on an interconnection fabric. Monthly. A higher tier upgrades unless the circuits on it already exceed the smaller port.'}, + rmNni:{args:[['city','cityId'],['prov','fabId']], + doc:'Give the fabric port back. Rejected while circuits still use it.'}, + buyVxc:{args:[['a','cityId'],['b','cityId'],['prov','fabId'],['t','vxcTier']], + quote:a=>({monthly:vxcMo(kmBetween(a.a,a.b),isSub(a.a,a.b),a.t)}), + doc:'Buy a virtual circuit between two fabric ports. Up in 59 seconds, which is the joke.'}, + upVxc:{args:[['id','entityId'],['t','vxcTier']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l&&l.kind==='vxc'?{monthly:vxcMo(l.km,l.sub,a.t)}:{};}, + doc:'Grow a circuit. Needs headroom at both ends.'}, + cancelVxc:{args:[['id','entityId']],confirm:'double', + doc:'Cancel a circuit; any remote IX ports it reached go with it.'}, + setPref:{args:[['kind','connKind'],['id','entityId'],['v','egress']],watch:['transit.#id','pni.#id'], + doc:'Egress preference for one exit: high sends more traffic that way, low keeps it for backup.'}, + siteSet:{args:[['k','connKind'],['id','entityId'],['s','site']],watch:['transit.#id','pni.#id'], + doc:'Put a transit port, PNI or IX port in building A, B or both. Choosing both with a single member adds a LAG member first, and charges for it.'}, +/* ---------- dark fiber and own cable ---------- */ + orderDf:{args:[['a','cityId'],['b','cityId'],['source','dfSource'],['system','systemId']], + bindsUI:['pending','dfSrc','dfSys'],bind:a=>{UI.pending={a:a.a,b:a.b};UI.dfSrc=a.source;UI.dfSys=a.system;}, + quote:a=>{const A=a.a,B=a.b,sc=isSub(A,B)?subDfCable(A,B):null,km=sc?sc.km:kmBetween(A,B); + const building=a.source==='build'&&lvl()>=3&&!sc,sys=DF_SYS[a.system]&&DF_SYS[a.system].lvl<=lvl()?a.system:'lite'; + const amps=ampCount(km),blocked=[]; + if(isSub(A,B)&&!sc)blocked.push(tr('fiber_modals.nobody_sells_dark_fiber_on_a')); + else if(uaePair(A,B))blocked.push(tr('fiber_modals.no_dark_fiber_inside_the_uae')); + else if(landX(A,B)&&cnCity(A)===cnCity(B))blocked.push(tr('fiber_modals.nobody_sells_one_fiber_pair_across')); + else if(!dfAllowed(A,B))blocked.push(tr('fiber_modals.dark_fiber_across_the_chinese_border')); + if(lvl()<2)blocked.push(tr('fiber_modals.dark_fiber_unlocks_at_customer_level')); + return {setup:(building?dfBuildCost(km):0)+DF_SYS[sys].cost+amps*AMP_COST+(S.pops[B]?0:popCost(B)), + monthly:(building?Math.round(km*0.15):dfLeaseMo(km))+amps*AMP_MO,days:building?dfBuildDays(km):30,blocked};}, + doc:'Get dark fiber: lease an IRU, dig your own (level 3+), or take a pair on a subsea cable. Then light it with a line system.'}, + orderCable:{args:[['a','cityId'],['b','cityId'],['design','designId',false],['terminal','boolean',false],['engineering','boolean',false]], + bindsUI:['pending','seaDesign','seaterminal','seaengineering'], + bind:a=>{UI.pending={a:a.a,b:a.b};UI.seaDesign=a.design||'standard';UI.seaterminal=!!a.terminal;UI.seaengineering=!!a.engineering;}, + quote:a=>{const why=ownCabWhy(a.a,a.b);if(why)return {blocked:[why]}; + const design=own(SEA_DESIGNS,a.design)?a.design:'standard',up={terminal:!!a.terminal,engineering:!!a.engineering}; + const q=seaQuote(a.a,a.b,design,up),lack=seaLack(q.km,up); + return {setup:q.cost+(S.pops[a.b]?0:popCost(a.b)),monthly:ownCabMo(q.km),days:q.days, + blocked:lack.map(k=>k==='design'?tr('own_cable.this_design_s_route_is_km',{km:q.km.toLocaleString()}) + :tr('own_cable.km_km_is_too_far_for',{km:q.km.toLocaleString(),what:lack.length>1?tr('own_cable.a_and_b',{a:tr(SUB_UPGRADES[lack[0]].n),b:tr(SUB_UPGRADES[lack[1]].n)}):tr(SUB_UPGRADES[lack[0]].n)}))};}, + doc:'Commission your own submarine cable. A ship sails; it takes months. The most expensive thing in the game.'}, + subUpgrade:{args:[['id','entityId'],['k','upgradeId']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:subUpgradeCost(l,a.k),days:SUB_UPGRADES[a.k].days}:{};}, + doc:'Add premium submarine terminals or extra optical engineering to your own subsea cable. Level 4+, once each.'}, + crews:{args:[['id','entityId'],['all','boolean',false]],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);if(!l)return {};const n=a.all?crewSteps(l):1;return {setup:n*crewCost(l),days:30*n};}, + doc:'Pay for more crews on a cable build: 30 days off per step. Only while more than a day of construction remains.'}, + addCh:{args:[['id','entityId'],['o','opticId']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:chCost(l,a.o),blocked:[chWhy(l,a.o)].filter(Boolean)}:{};}, + doc:'Light one channel on a dark-fiber span with a given optic; uses a spare from the shelf if you have one.'}, + rmCh:{args:[['id','entityId'],['o','opticId']],watch:['links.#id'], + doc:'Unplug a channel; the optic goes on the spares shelf.'}, + addPair:{args:[['id','entityId']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:pairCost(l)}:{};}, + doc:'Light another fiber pair on your own cable. ROADM system, finished construction, current pair full.'}, + upSys:{args:[['id','entityId']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:sysUpCost(l)}:{};}, + doc:'Upgrade the line system: Rainbow to ROADMaster to C+L. Every channel goes down for a day.'}, + regen:{args:[['id','entityId'],['d','step']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l&&a.d>0?{setup:REGEN_COST+Math.round((l.ch||[]).reduce((x,c)=>x+optCost(c),0)*REGEN_CH)}:{setup:0};}, + doc:'Add or remove a regeneration site on a terrestrial span, up to REGEN_MAX. Removing is refused if the optics then cannot reach.'}, + spares:{args:[['id','entityId']],watch:['links.#id'], + doc:'Toggle keeping spare optics on site for this span, so a card failure is fixed in hours instead of days.'}, +/* ---------- hardware ---------- */ + hwLock:{args:[],quote:a=>({setup:hwLockCost()}), + doc:'Lock router, optic and build prices for a year, shortages included. Costs twice as much while a shortage runs.'}, + buySpare:{args:[['o','opticId']], + quote:a=>({setup:optCost(a.o),blocked:[OPT[a.o]&&OPT[a.o].lvl>lvl()?tr('action_helpers.unlocks_at_customer_level_n',{n:OPT[a.o].lvl}):''].filter(Boolean)}), + doc:'Buy a spare optic for the shelf, up to 64 of a kind. The next channel of that type is then free of optic cost.'}, + sellSpare:{args:[['o','opticId']],quote:a=>({setup:-spareValue(a.o)}), + doc:'Sell a spare on eBuy for 40% of list.'}, + /* ---------- capacity broker ---------- */ + listFiber:{args:[['id','entityId'],['w','integer'],['p','integer',false]],watch:['links.#id'], + doc:'List spare capacity on a dark-fiber span with a capacity broker as a standing listing: w alien waves, and p (own cables only) your spare fiber pair. The broker sells them off over time as carriers on that route want capacity; a busy route sells in days, a road to nowhere maybe once.'}, + unlistFiber:{args:[['id','entityId']],watch:['links.#id'], + doc:'Take the listing down. What the broker already sold stays sold.'}, + setChCount:{args:[['id','entityId'],['o','opticId'],['n','integer']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:opticCountCost(l,a.o,a.n)}:{};}, + doc:'Set how many channels of one optic model a dark-fiber span carries, in one change. Added optics come from the spares shelf when you have them (regen cards still cost their share); removed ones go back to the shelf.'}, + /* ---------- customers ---------- */ + accept:{args:[['id','entityId']], + doc:'Sign a pending offer. Rejected without a POP in every city it needs, without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'}, + decline:{args:[['id','entityId']], + doc:'Throw an offer away.'}, + dropBiz:{args:[['id','entityId']],confirm:'double', + doc:'Terminate a signed customer. Rejected once an event contract\'s event has started.'}, + setRoute:{args:[['id','entityId'],['m','routeMode']],watch:['biz.#id'], + doc:'How a customer\'s traffic is routed: normal follows metrics, fast takes the lowest latency, scenic the quietest links.'}, +/* ---------- traffic engineering ---------- */ + buyTE:{args:[],quote:a=>({setup:TE_COST,monthly:TE_MO,blocked:coreTE()||(S&&S.te)?[]:[tr('core.auto_te_needs_an_rsvp_te_or')]}), + doc:'Buy the Auto-TE controller, which spills overflow onto alternate paths. Level 3+, and it needs an RSVP-TE-or-higher backbone.'}, + teToggle:{args:[],watch:['te'], + doc:'Turn Auto-TE on or off.'}, + teCheck:{args:[['script','string']],open:'teEdit',dom:['teSrc'],reads:'modal', + bind:a=>{$('teSrc').value=String(a.script);}, + doc:'Parse and dry-run a RouteScript without deploying it. The parse errors, or served traffic and transit cost before and after, come back as the report. No state change.'}, + teDeploy:{args:[['script','string']],open:'teEdit',dom:['teSrc'],watch:['te'], + bind:a=>{$('teSrc').value=String(a.script).slice(0,4000);}, + quote:a=>({setup:0}), + doc:'Deploy a RouteScript, up to 4000 characters. Rejected with the parse errors. A deploy that cuts traffic by more than 10% says so in messages.'}, + teClear:{args:[],watch:['te'], + doc:'Delete the script and fall back to plain Auto-TE.'}, + traceRun:{args:[['from','cityId'],['to','traceTo']],open:'trace',dom:['trFrom','trTo'],reads:'modal', + bind:a=>{$('trFrom').value=a.from;$('trTo').value=(NET[a.to]?'net:':'city:')+a.to;}, + doc:'Run a traceroute to a network or one of your own POPs. The hops come back as report text; they are not stored in the game state.'}, +/* ---------- money ---------- */ + takeLoan:{args:[['id','entityId']], + doc:'Accept a loan offer. Terms vary wildly by bank; the crypto one pays out 55-135% of face value. Equity banks take a share of the company.'}, + declineLoan:{args:[['id','entityId']], + doc:'Throw a loan offer away.'}, + repayLoan:{args:[['id','entityId']],confirm:'double', + quote:a=>{const l=S.loans.find(x=>x.id===a.id);return l?{setup:repayCost(l,BANKS[l.bank])}:{};}, + doc:'Repay a loan early, or buy an equity investor out.'}, +/* ---------- security, China, incidents ---------- */ + buildScrub:{args:[['city','cityId'],['tier','scrubTier',false]],watch:['scrubs'], + quote:a=>{const T=SCRUB_TIERS[a.tier||0];return {setup:T?T.cost:undefined,monthly:T?T.mo:undefined};}, + doc:'Build a scrubbing centre: 100G, 1T, 10T or 100T. Level-gated per tier; one per city.'}, + scrubUp:{args:[['city','cityId'],['tier','scrubTier']],watch:['scrubs'], + quote:a=>({setup:Math.round(SCRUB_TIERS[a.tier].cost*0.6)}), + doc:'Upgrade a scrubbing centre, at 60% of the tier price. Upward only.'}, + rmScrub:{args:[['city','cityId']],confirm:'double',watch:['scrubs'], + doc:'Tear a scrubbing centre down.'}, + scrubMode:{args:[],watch:['scrubMode'], + doc:'Switch scrubbing between always-on and on-demand.'}, + rtbh:{args:[['id','entityId',false]],watch:['ev'], + doc:'Announce a remote-triggered blackhole for the target under attack: it goes dark at your transits, most exchanges and about half your private peers, and everyone else is saved. Withdraw with unrtbh.'}, + unrtbh:{args:[['id','entityId',false]],watch:['ev'], + doc:'Withdraw the blackhole.'}, + ddosEngage:{args:[['id','entityId',false]],watch:['ev'], + doc:'Engage on-demand scrubbing now: start the diversion to the nearest active scrubbing centre instead of waiting for it to engage by itself.'}, + ddosAuto:{args:[['k','ddosKey']],watch:['ddosAuto'], + doc:'Flip a NOC auto-mitigation switch: rtbh blackholes the target of a flood on its own, scrub engages on-demand scrubbing.'}, + ddosTest:{args:[],watch:['ev'], + doc:'Sandbox only: send yourself a test flood, to try the tools on.'}, + hackback:{args:[['id','entityId',false]],watch:['ev'],quote:a=>({setup:20000}), + doc:'Fire the Hackback 3000(tm) at the botnet. 35% it ends the attack; otherwise a fine and a story.'}, + applyCn:{args:[],watch:['cnLic'],quote:a=>({setup:CN_LIC,days:45}), + doc:'File for a mainland China licence through a local partner. Required before a POP in mainland China. 45 days.'}, + fixInc:{args:[['id','entityId']],watch:['inc'], + quote:a=>{const i=S.inc.find(x=>x.id===a.id);return i&&i.cost>0?{setup:i.cost}:{};}, + doc:'Pay to rush a repair. A slow router reboot is cut to one day; anything else clears immediately.'}, +/* ---------- conferences ---------- */ + confGo:{args:[['key','confKey']],watch:['confReg'], + quote:a=>{const cf=upcomingConfs(75).find(x=>x.key===a.key);return cf?{setup:confCost(cf)}:{};}, + doc:'Register for an upcoming conference. Keys come from catalog(\'conferences\'). Peering gets easier in that region for 45 days. Capacity conferences need level 3.'}, + confSponsor:{args:[['key','confKey']],watch:['confReg'], + quote:a=>{const cf=upcomingConfs(75).find(x=>x.key===a.key);return cf&&confSp(cf)?{setup:CONF_SP-(S.confReg&&S.confReg[a.key]?CONF_COST:0)}:{};}, + doc:'Sponsor it instead: your logo on every lanyard, a bigger effect, a bigger bill. Only where sponsorships are offered; upgrades an existing registration for the difference.'}, +/* ---------- the NOC intern (standing orders) ---------- */ + opsHire:{args:[['id','internId']],quote:a=>({setup:INTERN_MO}),watch:['ops'], + doc:'Hire the NOC intern. They run your standing orders once a game day and cost a salary a month. Level 2+, and only in a game with a clock.'}, + opsFire:{args:[],confirm:'double',watch:['ops'], + doc:'Let the intern go. The standing orders stop; the rest of the month\'s salary is lost.'}, + opsToggle:{args:[['k','opsKey']],watch:['ops'], + doc:'Pause or resume one standing order. Keys come from catalog(\'OPSK\'); the sheet in the game shows what each one does.'}, + opsParam:{args:[['k','opsKey'],['p','string']],watch:['ops'], + doc:'Step one of a standing order\'s settings to its next value (the provider to prefer, the port size to order, the load ceiling…). The sheet steps the same way.'}, + opsCap:{args:[['k','opsKey']],watch:['ops'], + doc:'Step the monthly budget of an order that has one: 10k, 25k, 50k, 100k, 250k, no limit.'}, + opsFloor:{args:[],watch:['ops'], + doc:'Step the floor under your cash that the intern keeps clear when signing customers: 0, 50k, 250k, 1M, 5M.'}, + opsPop:{args:[['k','opsPopKind'],['city','cityId']],watch:['ops'], + doc:'Add or remove one POP as an exception to an order: the intern never touches the POPs you except.'}, + opsTpl:{args:[['k','opsTplKey']],watch:['ops'], + doc:'Toggle a piece of the one-tap new-POP template: broadband, a transit port, an IX port, the redundancy kit.'}, + opsNewPop:{args:[['city','cityId']],watch:['pops.#city'], + quote:a=>{const q=S&&S.ops?opsTplQuote(a.city):null;return q?{setup:q.cost}:{};}, + doc:'Open a city from the template in one go: the POP, then broadband, transit, an IX port and the redundancy kit as the template says — all or nothing on the price.'}, +/* ---------- the bulk PNI order ---------- */ + pniAll:{args:[['net','pniAllNet'],['tier','pniTier']], + quote:a=>{const b=pniBatch(a.net,a.tier);return b?{setup:b.cost,monthly:b.mo,blocked:(b.blocked||[]).map(q=>q.why).filter(Boolean)}:{};}, + watch:['pni'], + doc:'Order PNIs with one network (net) or every network (net:null) at all shared POPs: missing connections are added, smaller ones upgraded, each at its own minimum size. The quote is the batch total, lead times as for one PNI.'}, +/* ---------- backbone technology ---------- */ + coreUp:{args:[],watch:['core'], + quote:a=>{const n=S&&S.core?S.core.lv+1:1;return n<=4?{setup:CORE_COST[n],blocked:[(lvl()||1)({setup:CORE_LAB}), + doc:'Build the interop lab in the NOC: it tests your vendors against each other first and cuts interop incidents by 60%.'}, + coreSet:{args:[['v','integer']],watch:['core'], + doc:'Run the backbone at any level already paid for, 0 up to the highest bought.'}, +/* ---------- the specialist's offers ---------- */ + demoAsk:{args:[['k','string'],['id','string']],watch:['demo'], + doc:'Ask a vendor for a demo unit: a router, line system or optic one level above yours, delivered in about two weeks, at 60% over list until your level catches up. k and id name the thing (as the game\'s buttons pass them).'}, + seatBuy:{args:[['n','seatPairs']],decides:true,watch:['seatOff','links'], + quote:a=>{const o=S&&S.seatOff;if(!o||!SEAT_N.includes(a.n))return {};const miss=[o.a,o.b].filter(c=>!S.pops[c]); + return {setup:seatCost(o.km,a.n)+miss.reduce((x,c)=>x+popCost(c),0),days:seatDays(o.km)};}, + doc:'Take the consortium cable offer: own 1, 2 or 4 fiber pairs on a new subsea cable for your share of the build, and light them with your own optics. POPs open at both landings if you have none.'}, + seatNo:{args:[],watch:['seatOff'], + doc:'Decline the consortium cable offer.'}, + charter:{args:[['k','charterKey']],watch:['charter'], + doc:'Sign your first-month charter: global backbone (the classic game) or low-latency boutique (trading firms pay 40% more, and it has its own win). One choice per network, normal games only.'}, + mkBanana:{args:[],watch:['monkey'], + quote:a=>({setup:mkBananaCost()}), + doc:'Throw the chaos monkey a banana and it leaves early. Only while it is in your network; the price scales with your revenue.'}, +/* ---------- link tools ---------- */ + metricMode:{args:[['id','entityId'],['k','metricKind']],watch:['pairMet'], + doc:'Set the custom routing metric of a link\'s city pair as a factor (k:"f", the preset way) or an exact cost weight (k:"w"). Starts from the current preset\'s value; edit the number with metricSet.'}, + metricSet:{args:[['id','entityId'],['v','string']],dom:['metIn'],watch:['pairMet'], + bind:a=>{$('metIn').value=String(a.v);}, + doc:'Write the custom metric\'s number for the link\'s city pair, in the mode metricMode set. Select the link first (view.selLink), so the panel is showing the input.'}, + layShip:{args:[['id','entityId']],watch:['links.#id'], + quote:a=>{const l=S.links.find(x=>x.id===a.id),q=l&&layQuote(l);return q?{setup:q.cost}:{};}, + doc:'Book a second lay ship on your own cable before laying starts: it lays from the other end and halves that part of the build.'}, +/* ---------- standard POPs ---------- */ + popStdSet:{args:[['city','cityId']],watch:['popStd'], + doc:'Make a POP\'s routers the standard: every new POP starts with that model and that number of routers while it is still empty.'}, + popStdClear:{args:[],watch:['popStd'], + doc:'Stop setting a standard; new POPs go back to one basic router.'}, +/* ---------- utilities ---------- */ + utilityRouteServers:{args:[['city','cityId',false]],watch:['rs'], + doc:'Join the route server at every IX you have a port at. One call does what the button does.'}, + utilityKit:{args:[['city','cityId'],['cost','integer',false]],watch:['pops.#city','caches'], + quote:a=>{const q=S?utilityKit(a.city):null;return q?{setup:q.cost,monthly:q.mo}:{};}, + pass:a=>({city:a.city,cost:a.cost??((utilityKit(a.city)||{}).cost)}), + doc:'Install the POP redundancy kit in one go: generator, second building, a second router, and the cache boxes balanced between sites. Pass the quoted setup as cost; the game checks it still matches. Nothing to do reads as no_effect.'}, + utilityCaches:{args:[['city','cityId'],['quote','string',false]],watch:['caches'], + quote:a=>{const q=S?utilityCaches(a.city):null;return q?{key:q.key}:{};}, + pass:a=>({city:a.city,quote:a.quote??((utilityCaches(a.city)||{}).key)}), + doc:'Request a cache from each eligible provider at each site of the city, as many as demand asks for. Pass the quote\'s key back; the game checks the list has not moved under it.'}, + utilityPeers:{args:[['city','cityId',false]],watch:['peers'], + doc:'Request peering with every eligible peer across every IX you have joined.'}, +/* ---------- renaming ---------- */ + renameGo:{args:[['name','string']],open:'rename',dom:['rnIn'],watch:['name'], + bind:a=>{$('rnIn').value=String(a.name).slice(0,24);}, + doc:'Rename your network. act opens the menu\'s rename sheet and types the name in; it is trimmed to 24 characters.'}, +/* ---------- puzzles and architect runs ---------- */ + pzLinkTo:{args:[['a','cityId'],['b','cityId']],bindsUI:['pending'],decides:true,watch:['links'], + bind:a=>{UI.pending={a:a.a,b:a.b};}, + doc:'Puzzles only: open the link picker between two cities. Answer the decision with pzLink.'}, + pzLink:{args:[['tier','pztTier']],watch:['links'], + doc:'Puzzles only: light the pending link (from pzLinkTo) at a tier, on the picked route, in the picked trench.'}, + pzTier:{args:[['id','entityId'],['tier','pztTier']],watch:['links.#id'], + doc:'Puzzles only: change a link\'s wave size.'}, + pzRmLink:{args:[['id','entityId']],watch:['links.#id'], + doc:'Puzzles only: tear a link down.'}, + pzPop:{args:[['city','cityId']],watch:['pops.#city'], + doc:'Puzzles only: open a POP in a puzzle city.'}, + pzRmPop:{args:[['city','cityId']],watch:['pops.#city'], + doc:'Puzzles only: close a POP and the links that reach it.'}, + pzRtAdd:{args:[['city','cityId']],watch:['pops.#city'], + doc:'Puzzles only: add a router to a POP, up to RMAX.'}, + pzRtRm:{args:[['city','cityId']],watch:['pops.#city'], + doc:'Puzzles only: remove a router, if the ports still fit.'}, + pzRtModel:{args:[['city','cityId'],['g','pzRouterModel']],watch:['pops.#city'], + doc:'Puzzles only: swap every router in a POP for another model.'}, + pzRoute:{args:[['i','integer'],['m','pzRouteMode']],watch:['biz'], + doc:'Puzzles only: send one flow (index i, as state(\'biz\') lists them) along the metrics or the lowest-latency path.'}, + pzUndo:{args:[],watch:['pops','links','pairMet'], + doc:'Puzzles only: undo the last build step, up to sixty of them.'}, + pzReset:{args:[],watch:['pops','links','pairMet'], + doc:'Puzzles only: clear the whole build and start the puzzle over.'}, + pzArGo:{args:[],watch:['ar'], + doc:'Architect runs only: run the chaos monkey\'s review of this brief, every tube snipped in turn.'}, + pzArSkip:{args:[],watch:['ar'], + doc:'Architect runs only: fast-forward the review to the first cut that hurts.'}, + pzArNext:{args:[],watch:['ar'], + doc:'Architect runs only: pass the review and sign the next brief. Rejected while the current one does not pass.'}, + +/* ---------- answering decisions ---------- */ + dkAccept:{args:[],watch:['dk'], + doc:'Take the De-Kicks quote as offered and order the port.'}, + dkHaggle:{args:[],watch:['dk'], + doc:'Haggle. 45% a better price, 30% a worse one, 25% sales stops returning your calls for a few days. Three attempts.'}, + dkWalk:{args:[],watch:['dk'], + doc:'Walk away; the quote is remembered for 90 days.'}, + dkStay:{args:[['city','ixId']],watch:['dk'], + doc:'Take the retention discount instead of leaving: 40% off for six months.'}, + dkOptOut:{args:[['city','ixId'],['n','string']],confirm:'double',watch:['dk'], + doc:'Opt out of an add-on De-Kicks slipped onto the bill.'}, + closeModal:{args:[], + doc:'Close the open window, answering nothing. Always available, so you are never stuck in front of one.'}, +}; + +const API_VIEW={ + help:{args:[],doc:'Open the how-to-play modal.'}, + dash:{args:[],doc:'Open the NOC dashboard.'}, + dashClose:{args:[],doc:'Close the NOC dashboard.'}, + dashTab:{args:[['k','dashTab']],doc:'Switch the NOC dashboard tab.'}, + dashSort:{args:[['k','dashSortKey']],doc:'Flip a dashboard column\'s sort.'}, + dashLink:{args:[['id','entityId']],doc:'Jump from the dashboard to a link\'s panel.'}, + bank:{args:[],doc:'Open the bank.'}, + bankClose:{args:[],doc:'Close the bank.'}, + closePanel:{args:[],doc:'Close the selection panel.'}, + tab:{args:[['t','string']],doc:'Switch the city panel\'s tab.'}, + leftTab:{args:[['t','leftTab']],doc:'Switch the left drawer and open it.'}, + toggleLeft:{args:[],doc:'Open or close the left drawer.'}, + netFocus:{args:[['id','netId']],doc:'Focus one network in the left drawer.'}, + netFilter:{args:[['f','netFilter']],doc:'All networks, or only the out-of-reach ones.'}, + meetGo:{args:[['city','cityId']],doc:'Go to a city and open where to meet networks there.'}, + phoneTab:{args:[['t','leftTab']],doc:'Phone tab bar: switch bottom-sheet tab.'}, + logOpen:{args:[['id','entityId']],doc:'Open the thing a notification refers to.'}, + logAll:{args:[],doc:'Show every notification in the drawer.'}, + focusCity:{args:[['city','cityId']],doc:'Select and centre a city.'}, + selLink:{args:[['id','entityId']],doc:'Select a link.'}, + custGo:{args:[['id','entityId']],doc:'Jump from the dashboard to a customer.'}, + listMore:{args:[['k','listPage']],doc:'Show another page of the dashboard list.'}, + custF:{args:[['v','string']],doc:'Filter the customers list.'}, + custCity:{args:[['v','string']],doc:'Filter the customers list by city.'}, + custSort:{args:[['k','custSortKey']],doc:'Flip the customers list sort.'}, + custOpen:{args:[['sad','boolean',false]],doc:'Open the customers dashboard tab.'}, + goConn:{args:[['city','cityId'],['k','connKind']],doc:'Open a city\'s connections tab.'}, + goEgress:{args:[['city','cityId'],['k','egressKind']],doc:'Open a city\'s connections tab (l2 for the customer list).'}, + connOpen:{args:[],doc:'Open the connections dashboard tab.'}, + connF:{args:[['f','connFilter'],['v','string',false]],doc:'Filter the connections list.'}, + connCity:{args:[['v','string']],doc:'Filter the connections list by city.'}, + connNet:{args:[['v','string']],doc:'Filter the connections list by network.'}, + connSort:{args:[['k','connSortKey']],doc:'Flip the connections list sort.'}, + connFor:{args:[['net','netId']],doc:'Open the connections of one network.'}, + linkCheck:{args:[['id','entityId']],doc:'Open the redundancy check for a link: what a single cut would drop, without changing anything.'}, + findOpen:{args:[],doc:'Open the city finder (the 🔍 in the top bar).'}, + findGo:{args:[['city','cityId']],doc:'Close the finder and jump to a city.'}, + routingOpen:{args:[],doc:'Open the Routing & DDoS window: backbone, Auto-TE and DDoS settings (the button at the top of the NOC tab).'}, + opsOpen:{args:[],doc:'Open the Ops sheet: the NOC intern\'s mood, weekly shift report and standing orders.'}, + opsCity:{args:[['v','cityId',false]],doc:'Show one POP\'s standing-order exceptions in the Ops sheet.'}, + utilities:{args:[['city','cityId',false]],doc:'Open the utilities sheet: route servers, the redundancy kit, caches and bulk peering, for one city or the whole network.'}, + pniAllOpen:{args:[['net','pniAllNet']],doc:'Open the bulk PNI order sheet for one network (or every network with null).'}, + pniFilter:{args:[['f','pniFilter']],doc:'Filter the PNI list: all, via transit, worth it, already PNI.'}, + pniGrp:{args:[['g','string'],['o','boolean',false]],doc:'Fold or unfold one group of the PNI list.'}, + pniSort:{args:[],doc:'Flip the PNI list sort between A-Z and worth-it-first.'}, + puzzleMenu:{args:[],doc:'Open the puzzle list.'}, + puzzleDoor:{args:[],doc:'From the title screen: open the puzzle list (keeps the typed name).'}, + pzFinish:{args:[],doc:'Puzzles only: run the star count and show the results sheet.'}, + pzMonkey:{args:[],doc:'Puzzles only: send the chaos monkey round the build to prove the N-1 star.'}, + pzMkSkip:{args:[],doc:'Puzzles only: skip the monkey\'s tour to the verdict.'}, + pzArAll:{args:[],doc:'Architect runs only: show every city on the map, not just the run\'s own.'}, + tailTog:{args:[],doc:'Show or hide the long tail of small networks.'}, + teEdit:{args:[],doc:'Open the RouteScript editor.'}, + teClose:{args:[],doc:'Close the RouteScript editor.'}, + teHelp:{args:[],doc:'Open the RouteScript reference.'}, + teBack:{args:[],doc:'Back to the RouteScript editor.'}, + models:{args:[],doc:'Open the router catalogue.'}, + decomOpen:{args:[['city','cityId',false]],doc:'Open the decommissioning sheet.'}, + scenarios:{args:[],doc:'Open the scenario picker. Start one with startScn.'}, + helpClose:{args:[],doc:'Close the help modal.'}, + whatsNewShow:{args:[],doc:'Open the release notes.'}, +}; + +const API_BOUND={ + leaseSwap:{command:'orderDf',note:'presets the dark-fiber modal on a leased pair'}, + teOpt:{command:'teDeploy',arg:'script',note:'the optimiser drafts a script'}, + teSlop:{command:'teDeploy',arg:'script',note:'the AI drafts a script'}, + teExample:{command:'teDeploy',arg:'script',note:'the worked example'}, + teRecipe:{command:'teDeploy',arg:'script',note:'a recipe from catalog(\'TE_RECIPES\')'}, + trace:{command:'traceRun',arg:'from'}, + decomToggle:{command:'decomGo',arg:'cities'}, + openVxc:{command:'buyVxc',note:'opens the circuit picker from a fabric port ({from, prov}); buyVxc takes a, b, prov and t itself'}, + connCancel:{command:'cancelTransit',note:'the connections list\'s cancel button: it arms, then dispatches cancelTransit, cancelPni, cancelIx, rmCache or rmNni'}, + cnPrem:{command:'buildLink',arg:'premiumCrossing'}, + addParallel:{command:'buildLink',note:'opens the link modal on the same pair',arg:'a/b'}, + via:{command:'buildLink',arg:'cable'}, + route:{command:'buildLink',arg:'route'}, + dfMode:{command:'orderDf',note:'opens the dark-fiber modal',arg:'a/b'}, + dfSrc:{command:'orderDf',arg:'source'}, + dfSys:{command:'orderDf',arg:'system'}, + seaDesign:{command:'orderCable',arg:'design'}, + seaPackage:{command:'orderCable',arg:'terminal/engineering'}, + ownCab:{command:'orderCable',note:'presets the own-cable flow'}, + randomName:{command:'start',note:'drafts the title-screen name; new_game starts games'}, + pickStart:{command:'start',note:'drafts the home city; new_game starts games'}, + pickHome:{command:'start',note:'drafts the home city; new_game starts games'}, + modeSet:{command:'start',note:'drafts the game mode; new_game starts games'}, + presetSet:{command:'start',note:'drafts the difficulty preset; new_game starts games'}, + chaosSet:{command:'start',note:'drafts the sandbox chaos dial; new_game starts games'}, + rename:{command:'renameGo',note:'opens the rename sheet; renameGo opens it itself'}, + pniAllSize:{command:'pniAll',arg:'tier',note:'steps the port size in the bulk sheet'}, + utilityPick:{command:'utilities',note:'the sheet\'s city picker; pass city to utilities itself'}, + pzAddPar:{command:'pzLink',note:'opens the puzzle picker on the same pair',arg:'tier'}, + pzVia:{command:'pzLink',note:'picks the route (cable or land) for the pending link'}, + pzDiv:{command:'pzLink',note:'same trench or a diverse one for the pending link'}, +}; + +/* Starting, retrying and leaving scenarios, puzzles and architect runs, and the screens a player dismisses. They run + as their buttons run them; new_game, load_save and export_save are the other half of the session (mcp-page.js). */ +const API_SESSION={ + startScn:{args:[['id','scnId']],doc:'Start a scenario (ids from catalog SCN), replacing the current game.'}, + startWeekly:{args:[],doc:'Start this week\'s weekly scenario, replacing the current game. The week follows the real date.'}, + pzStart:{args:[['id','string']],doc:'Start a puzzle by id (the puzzle list, view.puzzleMenu, shows them), replacing the current game.'}, + pzWeekly:{args:[],doc:'Start this week\'s weekly puzzle, replacing the current game.'}, + pzArStart:{args:[['id','string']],doc:'Start an architect run by id (view.puzzleMenu lists them), replacing the current game.'}, + pzRetry:{args:[],doc:'Puzzles and architect runs: start the same one over from scratch.'}, + pzLeave:{args:[],doc:'Leave the running puzzle or architect run.'}, + keepPlaying:{args:[],doc:'Dismiss the win screen and keep playing.'}, + pitchSkip:{args:[],doc:'Skip the opening pitch; a game waiting behind it starts.'}, + tutSkip:{args:[],doc:'Skip the tutorial coaching.'}, +}; + +const API_STATE_DOC={ + v:{type:'integer',doc:'Save format version.'}, + name:{type:'string',doc:'Your network\'s name.'}, + asn:{type:'integer',doc:'Your AS number.'}, + home:{type:'string',doc:'The city you started in.'}, + day:{type:'integer',doc:'Days since the company was founded.'}, + cash:{type:'number',doc:'Cash on hand. Goes negative into the red; -100k is bankruptcy.'}, + priceMul:{type:'number',doc:'Multiplier on transit prices (weekly modifier).'}, + mode:{type:'string',doc:'normal | sandbox | scenario | puzzle.'}, + rules:{type:'map',doc:'The rules this network locked in at its door: preset (soft, freeze, oncall, bgp, sandbox or puzzle), the chaos dial, lead times, the market, and the Best Effort extras (sea, confs, broke, moods, pnis), which are only written where they differ from the classic game. They stay for the network\'s whole life.'}, + charter:{type:'string',doc:'The charter picked in the first month of a normal game: global | boutique.'}, + chartSet:{type:'boolean',doc:'The charter has been picked; false while the choice is still open.'}, + solWon:{type:'integer',doc:'The day the Speed of Light win landed (boutique charter), or 0.'}, + lvl:{type:'integer',doc:'Customer level (unlocks customer types).'}, + ltv:{type:'integer',doc:'Level at which Tier 1 vendors were visible (title-screen pick).'}, + t1v:{type:'integer',doc:'Level at which Tier 1 transit was offered.'}, + auV:{type:'integer',doc:'Australia content level gate.'}, + seen:{type:'array',doc:'Network ids the deals panel has already shown. Vestigial: written by newGame, read nowhere.'}, + pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb), ad boost, downtime, routers, generator, second site.'}, + links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables and fabric circuits (vxc), each with an entity id.'}, + transit:{type:'array',doc:'Transit ports: city, net, tier, LAG members, port history for 95th-percentile billing.'}, + ixp:{type:'map',doc:'IX ports by exchange city; tier per port (may exceed 1 with LAG members in ixn).'}, + rs:{type:'map',doc:'Route-server sessions by exchange city.'}, + ixn:{type:'map',doc:'LAG members on IX ports by exchange city.'}, + ixSite:{type:'map',doc:'Which building each IX port sits in (a, b or ab).'}, + ixPref:{type:'map',doc:'Egress preference per IX port.'}, + myIx:{type:'map',doc:'Exchanges you founded: name, members, join schedule, fabric step.'}, + peers:{type:'map',doc:'Peering sessions, keyed "net@ix".'}, + pairMet:{type:'map',doc:'Routing metric per city pair (prefer/avoid/backup/normal), keyed by pair.'}, + pni:{type:'array',doc:'Private interconnects: city, net, tier, ready day, augments (up), LAG, sacrificial flag.'}, + caches:{type:'array',doc:'CDN cache boxes: city, net, building.'}, + nni:{type:'array',doc:'Fabric ports: city, provider, tier.'}, + biz:{type:'array',doc:'Signed customers: type, cities, bandwidth, rate, mood, contract dates.'}, + offers:{type:'array',doc:'Pending customer offers, each expiring on a day.'}, + done:{type:'map',doc:'Goals landed, by goal id → day.'}, + ach:{type:'map',doc:'Badges earned this game, by badge id → day.'}, + inc:{type:'array',doc:'Open incidents: type, what they hit, until when, optional rush-repair price.'}, + ddosStarts:{type:'array',doc:'The days the attacks of the last week started; at most 14 a week.'}, + ev:{type:'map',doc:'Live world events: the running DDoS, route leaks, fabric failures, price shocks.'}, + stats:{type:'map',doc:'Counters: incidents survived, loans taken, sharks, conferences attended, peak traffic…'}, + log:{type:'array',doc:'The NOC notification feed, newest first, capped at 60; identical notices within a minute fold with a count.'}, + nextFail:{type:'integer',doc:'The day the next failure fires.'}, + nextEvent:{type:'integer',doc:'The day the next world event fires.'}, + rng:{type:'integer',doc:'The scenario seed; it predicts every future random draw.'}, + usedNames:{type:'array',doc:'Customer names already handed out.'}, + spares:{type:'map',doc:'Spare optics on the shelf, by optic id.'}, + scrubs:{type:'array',doc:'Scrubbing centres: city and tier.'}, + scrubMode:{type:'string',doc:'always | ondemand.'}, + cnLic:{type:'map',doc:'Mainland China licence: none | pending (with ready day) | ok.'}, + ppol:{type:'string',doc:'Your published peering policy: open | selective | closed.'}, + pdesk:{type:'map',doc:'This week\'s peering desk summary: sessions accepted and declined at which exchanges.'}, + pdeskRep:{type:'map',doc:'Last week\'s peering desk summary, as the NOC log reported it.'}, + ops:{type:'map',doc:'The NOC intern: who is hired, each standing order\'s on/off switch and settings, the monthly budget and what it spent, per-POP exceptions, the new-POP template and the weekly log.'}, + core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'}, + ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'}, + popStd:{type:'map',doc:'The standard POP: router model and count new POPs start with, or null for none.'}, + demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'}, + seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'}, + monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'}, + fleet:{type:'map',doc:'Cable-ship voyages by ship id: the cut it sails to, when it arrives, splices and comes home.'}, + achP:{type:'map',doc:'Which rule set each badge was earned under (oncall, freeze, bgp), by badge id.'}, + calV:{type:'integer',doc:'Calendar save-format marker: 1 once the real calendar (28-31-day months) applies.'}, + pz:{type:'map',doc:'The running puzzle: its id, cities, flows to deliver, budget and stars.'}, + ar:{type:'map',doc:'The running architect run: its HQ, brief index, gold sites, spend and the build it started from.'}, + loans:{type:'array',doc:'Active loans: bank, balance, APR, term, share (equity banks).'}, + loanOffers:{type:'array',doc:'Pending loan offers.'}, + loanStrikes:{type:'integer',doc:'How many loan offers you have let lapse.'}, + confReg:{type:'map',doc:'Conferences registered for, by key; "sp" when sponsoring.'}, + hw:{type:'map',doc:'Hardware market: price shocks and any price lock.'}, + capDeal:{type:'map',doc:'The pending capacity deal from a capacity conference.'}, + cam:{type:'map',doc:'Map camera position. View state that save() happens to store inside S.'}, + uiSpeed:{type:'number',doc:'The speed you left the game at. View state that save() stores inside S.'}, + won:{type:'boolean',doc:'You reached Tier 1.'}, + t1Now:{type:'boolean',doc:'Tier 1 right now, as of the last day; falling out of it is announced.'}, + lost:{type:'boolean',doc:'The bank repossessed the routers.'}, + neg:{type:'integer',doc:'Days in the red in a row.'}, + hist:{type:'array',doc:'Daily history for the graphs: demand, served, exit split, revenue, cost, cash.'}, + scn:{type:'map',doc:'The running scenario: id, rules, day limit, done/failed, and the day of the next scripted attack (nextDdos).'}, + dk:{type:'map',doc:'De-Kicks state: per-exchange multipliers, add-ons, retention, the live quote (q) and the remembered one (lastQ).'}, + grace:{type:'map',doc:'Courtesy transit after a merger wave, until a day.'}, + merged:{type:'map',doc:'Networks merged into others this game.'}, + tut:{type:'map',doc:'Tutorial progress.'}, + conf:{type:'map',doc:'The conference glow: region and until when; sp when you sponsored.'}, + phpDone:{type:'boolean',doc:'One-shot flag.'}, + krExit:{type:'map',doc:'Korea exit state.'}, + auNews:{type:'boolean',doc:'One-shot flag: the Australia news toast.'}, + richTold:{type:'boolean',doc:'One-shot flag: the cash milestone toast.'}, +}; + +const API_RESULTS_DOC={ + nt:{type:'map',doc:'Traffic per network through transit, by net id.'}, + tNet:{type:'map',doc:'Traffic per network you hand to each upstream, by "net@upstream".'}, + reachNT:{type:'number',doc:'Networks reachable without transit.'}, + teBlack:{type:'number',doc:'Traffic blackholed by RouteScript rules.'}, + teMoved:{type:'number',doc:'Traffic Auto-TE spilled onto alternate paths.'}, + egT:{type:'map',doc:'Egress split by exit kind (c/p/ix/t/l2) in Gbps.'}, + egDesc:{type:'map',doc:'RouteScript drains per exit.'}, + netEg:{type:'map',doc:'Per-network egress split: which exit carries which network.'}, + ef:{type:'map',doc:'LAZY per-link exit breakdown: what crosses each link, per network, built only when a panel asks. What is in here depends on which panels have rendered.'}, + l2:{type:'map',doc:'Layer-2 traffic per customer (L2VPN, SD-WAN, waves).'}, + l2lat:{type:'map',doc:'Latency per L2 customer.'}, + l2route:{type:'map',doc:'Which path an L2 customer\'s traffic takes.'}, + l2split:{type:'map',doc:'L2 traffic split per path.'}, + nodeLoad:{type:'map',doc:'Router forwarding load per city.'}, + nodeCap:{type:'map',doc:'Router forwarding capacity per city.'}, + div:{type:'map',doc:'Traffic diversity per customer (how split their paths are).'}, + gfwLost:{type:'number',doc:'Traffic lost to the Great Firewall.'}, + gfwCross:{type:'number',doc:'Traffic crossing into mainland China.'}, + p95:{type:'map',doc:'95th-percentile transit readings per port.'}, + peered:{type:'number',doc:'Share of traffic that stays on peering.'}, + peerShare:{type:'number',doc:'Fraction of traffic served by peers (mood driver).'}, + load:{type:'map',doc:'Load per link in Gbps.'}, + useT:{type:'map',doc:'Transit use per port id.'}, + useIx:{type:'map',doc:'IX use per exchange city.'}, + usePni:{type:'map',doc:'PNI use per port id.'}, + useCache:{type:'map',doc:'Cache use per box id.'}, + cityDem:{type:'map',doc:'Eyeball + customer demand per city.'}, + citySrv:{type:'map',doc:'Traffic served per city.'}, + cityEye:{type:'map',doc:'Eyeballs online per city.'}, + latF:{type:'map',doc:'Fraction of each city\'s traffic that goes far (over a threshold latency).'}, + latFar:{type:'map',doc:'The far exit each slow city sends traffic through.'}, + demTo:{type:'map',doc:'Your traffic destined to each network, in Gbps. The number CDN caches ask about.'}, + served:{type:'number',doc:'Total traffic served, in Gbps.'}, + demand:{type:'number',doc:'Total traffic demanded, in Gbps.'}, + reach:{type:'number',doc:'Fraction of the internet you can reach (0..1).'}, + sessions:{type:'number',doc:'Peering sessions up.'}, + revMo:{type:'number',doc:'Revenue per month.'}, + costMo:{type:'number',doc:'Cost per month.'}, + cost:{type:'map',doc:'Monthly cost by category (transit, pni, ix, links…).'}, + rev:{type:'map',doc:'Monthly revenue by source.'}, + reachable:{type:'map',doc:'Networks reachable per net id.'}, + cone:{type:'map',doc:'Which peer\'s customer cone carries each network you reach without transit of your own, by net id.'}, + ddos:{type:'array',doc:'Per live attack: the target, its size, which ports it fills, what Flowspec and each scrubbing centre cleaned, and what reaches the target.'}, + haul:{type:'array',doc:'Scrubbing detours: from the attacked city to each centre, one-way latency and how much they carry.'}, + tgtF:{type:'map',doc:'The share of a targeted customer\'s traffic that survives the attack, by customer id.'}, + bbF:{type:'map',doc:'The share of a city\'s broadband subscribers that survive an attack on them, by city id.'}, + fsUse:{type:'map',doc:'Flowspec rules in use per city: used of the routers\' rule capacity.'}, + bizDem:{type:'map',doc:'Business customers\' share of each city\'s demand, in Gbps (what RouteScript\'s protect customers serves first).'}, + bizSrv:{type:'map',doc:'Of that business demand, what was served, per city.'}, + graceNets:{type:'number',doc:'Networks reached over the courtesy route after a merger wave.'}, + cityBlocked:{type:'map',doc:'Set up per city by the traffic computation; nothing fills it at present.'}, + ddosHot:{type:'map',doc:'Cities whose ports a flood is filling, for the map\'s pulse. Keyed by city id.'}, +}; + +/* One arg of a spec as the schema states it: the domain when there is one (catalog() resolves + it), the bare type otherwise, and the concrete value list or range where it is fixed. */ +function apiArgSpec([name,dom,req]){ + const a={name,required:req!==false}; + if(API_DOMAINS[dom])a.domain=dom;else a.type=dom; + const v=apiDomValues(dom); + if(Array.isArray(v))a.values=v;else if(v&&v.from!==undefined)a.range=v; + return a;} + +/* Dotted subtrees, no wildcards. An array walks by index (`biz.3`) or by entity id (`links[#id]`). */ +function apiPath(o,p){ + if(p===undefined||p===null||p==='')return o; + let v=o; + for(const k of String(p).split('.')){ + if(v==null)return undefined; + if(Array.isArray(v)){const i=Number(k); + v=(Number.isInteger(i)&&String(i)===k&&i>=0&&ix&&typeof x==='object'&&x.id===k);} + else if(v instanceof Set)v=[...v]; + else if(v instanceof Map)v=Object.fromEntries(v); + else if(typeof v==='object')v=v[k]; + else return undefined;} + return v;} + +function apiJson(v){ + if(v instanceof Set)return [...v].map(apiJson); + if(v instanceof Map)return apiJson(Object.fromEntries(v)); + if(v&&typeof v==='object')return Array.isArray(v)?v.map(apiJson):Object.fromEntries(Object.entries(v).map(([k,x])=>[k,apiJson(x)])); + if(typeof v==='function')return undefined; + return v;} + +/* The tables the argument domains point at. Everything is a static reference except three, + each computed for a reason: BADGES hides unearned secrets like the badge wall; conferences + carries the keys confGo/confSponsor need, which exist in no field of S; TE_RECIPES renders + each recipe's script, because the source is a function and some read the live network. The + recipes' relevance score is not exposed: judging which one fits is the agent's job. */ +const API_TABLES={CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG}; +const API_MADE={ + BADGES:()=>!S?[]:BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!hof()[b.id]; + return b.secret&&!on&&!ever?{id:b.id,i:'❔',t:'???',d:tr('badges.a_secret_badge'),r:b.r,secret:true}:{...b,ever};}), + conferences:()=>!S?[]:upcomingConfs(75).map(cf=>({key:cf.key,name:cf.n,city:cf.c,day:cf.day,capacity:!!cf.cap,cost:confCost(cf),sponsorCost:confSp(cf)?CONF_SP:null})), + TE_RECIPES:()=>!S?[]:TE_RECIPES.map(r=>({id:r.id,name:tr(r.n),description:tr(r.d),script:r.src().join('\n')})), +}; +function API_CATALOG_TABLE(name){return name in API_MADE?API_MADE[name]():API_TABLES[name];} + +/* UI minus the render caches and pointer scratch, which are inputs to nothing. + Everything a command binds (pending, route, via, dfSrc, dfSys, seaDesign, cnPrem, decom, + teDraft, confirm) stays, so an agent can see what it was given. */ +const API_UI_HIDDEN={_lh:1,_ph:1,_tb:1,_layer:1,layerAt:1,hover:1,drag:1,snap:1}; + +return {API_DOMAINS,API_CMD,API_VIEW,API_BOUND,API_SESSION,API_STATE_DOC,API_RESULTS_DOC,API_TABLES,API_MADE,API_UI_HIDDEN, + apiDomCheck,apiDomValues,apiArgSpec,apiPath,apiJson}; +})(); diff --git a/scripts/lib/mcp-game.js b/scripts/lib/mcp-game.js index 1079e28..fbf0983 100644 --- a/scripts/lib/mcp-game.js +++ b/scripts/lib/mcp-game.js @@ -1,20 +1,21 @@ // The game behind the MCP server (scripts/mcp.js): one game page from src/, loaded in jsdom like the tests load it -// (tests/harness.js: seeded, no animation loop), with scripts/lib/mcp-page.js added to read and drive it. -// TOOLS is the list the server offers; each run() gets the session and the tool's arguments and returns JSON. +// (tests/harness.js: seeded, no animation loop), with scripts/lib/mcp-commands.js (the typed command tables) and +// scripts/lib/mcp-page.js added to read and drive it. TOOLS is the list the server offers; each run() gets the +// session and the tool's arguments and returns JSON. const fs = require('node:fs'); const path = require('node:path'); const { load } = require('../../tests/harness'); -const PAGE_JS = fs.readFileSync(path.join(__dirname, 'mcp-page.js'), 'utf8'); +const PAGE_JS = ['mcp-commands.js', 'mcp-page.js'].map((f) => fs.readFileSync(path.join(__dirname, f), 'utf8')); const ACT_DIR = path.join(__dirname, '..', '..', 'src', 'game', '90-actions'); -// The arguments each action takes, read from its source (`buyTransit:({city,net,tier})=>`): in the page the -// actions are wrapped for puzzle mode, so their own parameter lists are not visible there. +// The arguments of the actions the command tables do not type (the drafts), read from their source +// (`dfSrc:({v})=>`): in the page the actions are wrapped for puzzle mode, so their own parameter lists are not visible. let ACT_ARGS = null; function actArgs() { if (ACT_ARGS) return ACT_ARGS; ACT_ARGS = {}; - const re = /(?:^|[\s,{])([A-Za-z]\w*):\s*(?:async\s*)?\(\s*\{([^}]*)\}\s*\)\s*=>/g; + const re = /(?:^|[\s,{])([A-Za-z]\w*):\s*(?:async\s*)?\(\s*\{([^}]*)\}\s*(?:=\s*\{\s*\}\s*)?\)\s*=>/g; for (const f of fs.readdirSync(ACT_DIR).filter((f) => f.endsWith('.js')).sort()) { const src = fs.readFileSync(path.join(ACT_DIR, f), 'utf8'); for (const m of src.matchAll(re)) if (!ACT_ARGS[m[1]]) ACT_ARGS[m[1]] = m[2].split(',').map((a) => a.split('=')[0].trim()).filter(Boolean); @@ -27,7 +28,7 @@ function createSession(opts = {}) { let game = null; const boot = () => { const g = load({ seed: opts.seed || 12345, file: opts.file }); - g.ev(PAGE_JS); + for (const js of PAGE_JS) g.ev(js); g.call = (fn, ...args) => { g.dom.window.__mcpArgs = JSON.parse(JSON.stringify(args)); return JSON.parse(g.ev(`JSON.stringify(__mcp.${fn}(...window.__mcpArgs))`) || 'null'); @@ -47,14 +48,18 @@ function createSession(opts = {}) { const str = (description, extra = {}) => ({ type: 'string', description, ...extra }); const num = (description, extra = {}) => ({ type: 'number', description, ...extra }); +const bool = (description) => ({ type: 'boolean', description }); const obj = (properties = {}, required = []) => ({ type: 'object', properties, required, additionalProperties: false }); +const SECTIONS = ['clock', 'commands', 'view', 'session', 'drafts', 'denied', 'domains', 'state', 'results']; +const WHERE = ['modal', 'bank', 'dash', 'panel', 'left', 'puzzle']; const TOOLS = [ { name: 'new_game', - description: 'Start a new network, replacing the current one. Presets: freeze (Change Freeze, gentle), oncall (On-call, the classic game), bgp (BGP at 3 a.m., harsh), sandbox (endless money, every level, no chaos). Seeded, so the same seed and the same moves give the same game.', + description: 'Start a new network, replacing the current one. Presets: soft (Best Effort, the gentlest: no DDoS, no cable ships, no conferences, instant PNIs, patient customers, a rescue loan instead of game over), freeze (Change Freeze, gentle), oncall (On-call, the classic game), bgp (BGP at 3 a.m., harsh), sandbox (endless money, every level; chaos sets how often things break, default none). Seeded, so the same seed and the same moves give the same game. Scenarios, puzzles and architect runs start with act (startScn, pzStart, pzArStart).', inputSchema: obj({ city: str('Home city: id (fra) or name (Frankfurt). Default Frankfurt.'), name: str('Network name (24 characters at most). Default: a random pun.'), - preset: str('Rules preset', { enum: ['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.'), + asn: num('Your own AS number, as the title screen takes it. Default: a free one.'), chaos: str('Sandbox only: how often things break. Default none.', { enum: ['none', 'calm', 'normal', 'spicy'] }) }), run: (s, a) => s.call('newGame', a), }, { @@ -86,7 +91,7 @@ const TOOLS = [ }, { name: 'advance', - description: 'Run the game forward day by day, as the game loop does. Stops early when a window opens that needs an answer (then answer it with screen and click) or the network goes bankrupt. Returns what happened: log, toasts, new incidents, cash, and how long each simulated day took.', + 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.', inputSchema: obj({ days: num('Days to run, 1 to 3650. Default 1.') }), run: (s, a) => s.call('advance', a.days), }, @@ -127,41 +132,80 @@ const TOOLS = [ run: (s, a) => s.call('hotSpots', a.limit || 10), }, { - name: 'actions', - description: 'Every game action act can run, with the arguments it takes, e.g. buildPop(city), buyTransit(city,net,tier), buyIx(city,tier), pni(city,net,tier). Port tiers: 0 = 10G, 1 = 100G, 2 = 400G, 3 = 800G. Exchanges are given as city=.', + name: 'schema', + description: 'The typed contract act checks against: every game command with its arguments, their domains and a description, which ones dry-run, decide or confirm; view commands; session actions (scenarios, puzzles, runs); drafts (inputs another command reads); what is not available and why; the argument domains; and a field-by-field reference of state and results. Give section for one part.', + inputSchema: obj({ section: str('One part only', { enum: SECTIONS }) }), + run: (s, a) => s.call('schema', a.section), + }, + { + name: 'catalog', + description: 'The game\'s reference tables, which the argument domains point at: CITIES, NETS, CABLES, PORT, LT, OPT, DF_SYS, FAB, INTERNS, OPSK, CHARTERS, SCN, BANKS… plus three made for you: conferences (the upcoming calendar with the keys confGo and confSponsor take), TE_RECIPES (each RouteScript recipe with its script, ready for teDeploy) and BADGES (as the badge wall shows them). Omit name for the list of tables with their sizes.', + inputSchema: obj({ name: str('One table; omit for the list.') }), + run: (s, a) => s.call('catalog', a.name), + }, + { + name: 'state', + description: 'The saved game itself as JSON, the same object the game saves: offers, loan offers, links, ports, PNIs, customers, the intern, events… with their ids. schema section "state" documents each field. Give a path (pops.fra, links, loanOffers, biz.3, links.): the whole state of a big network is hundreds of KB.', + inputSchema: obj({ path: str('Dotted path: a key, an array index or an entity id per step.') }), + run: (s, a) => s.call('state', a.path), + }, + { + name: 'results', + description: 'The game\'s last traffic computation (R), rebuilt after every action and every day: load per link, use per port, demand and served per city, egress per network, monthly cost and revenue by kind, latency, reach. schema section "results" documents each field. Give a path (load, cost, netEg.ggl).', + inputSchema: obj({ path: str('Dotted path.') }), + run: (s, a) => s.call('results', a.path), + }, + { + name: 'ui', + description: 'The view state actions read and write (the selection, the pending link pair, the drafts of the link, fiber and cable windows, the RouteScript draft, confirmations), without render caches. For working out why an action did what it did.', inputSchema: obj(), - run: (s) => { const a = actArgs(); return s.call('actions').map((k) => (a[k] ? `${k}(${a[k].join(',')})` : k)); }, + run: (s) => s.call('ui'), + }, + { + name: 'actions', + description: 'Every action act can run, with its arguments (? marks an optional one), e.g. buildPop(city), buyTransit(city,net,tier), buildLink(a,b,tier,cable?,route?,premiumCrossing?). Port tiers: 0 = 10G, 1 = 100G, 2 = 400G, 3 = 800G. Exchanges are given as city=. schema has each one\'s argument domains and what it does.', + inputSchema: obj(), + run: (s) => { + const { typed, drafts } = s.call('actions'), a = actArgs(); + return [...Object.entries(typed).map(([k, sig]) => `${k}(${sig})`), ...drafts.map((k) => (a[k] ? `${k}(${a[k].join(',')})` : k))].sort(); + }, }, { name: 'act', - description: 'Do something in the game, as a button would: run one action with its arguments (see actions). Returns the game\'s messages, the change in cash, and what is on screen now: an open window (a quote, a choice) with its numbered buttons, or the side panel.', - inputSchema: obj({ action: str('Action name, e.g. buildPop.'), args: { type: 'object', description: 'Its arguments, e.g. {"city":"ams"}.' } }, ['action']), - run: (s, a) => s.call('run', a.action, a.args || {}), + 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.', + inputSchema: obj({ action: str('Action name, e.g. buildPop (view. prefixes are accepted).'), command: str('Same as action.'), args: { type: 'object', description: 'Its arguments, e.g. {"city":"ams"}.' }, + dryRun: bool('Price it and check it can be done: {setup, monthly, days, blocked}. Nothing happens.') }), + run: (s, a) => { + const name = a.action || a.command; + if (!name) throw new Error('Give action, e.g. {"action":"buildPop","args":{"city":"ams"}}.'); + return s.call('run', name, a.args || {}, { dryRun: !!a.dryRun }); + }, }, { name: 'screen', - description: 'What the player sees now: the open window, or else the side panel, as text with numbered buttons for click.', - inputSchema: obj(), - run: (s) => s.call('screen'), + description: 'What the player sees, as text with numbered buttons for click: the open window, else the bank or the NOC dashboard when open, else the side panel, else the puzzle box. where picks one: modal, bank, dash, panel, left (the left drawer: goals, deals, noc or nets) or puzzle. open lists what is showing. Long text comes in pages: textMore says the offset of the next one. Lists the game acts on when they change come with their options; click them with a value.', + inputSchema: obj({ where: str('Which surface', { enum: WHERE }), offset: num('Start the text here (from textMore).') }), + run: (s, a) => s.call('screen', a.where, a.offset), }, { name: 'panel', - description: 'Open the side panel of a city or a link, or a network in the network list, optionally on a tab (a city has cust, up, peer, infra…), and show it as text with numbered buttons.', - inputSchema: obj({ city: str('City id or name.'), link: str('Link id (from status or hot_spots).'), network: str('Network id or name.'), tab: str('Tab id, as the tab buttons name it.') }), + description: 'Open the side panel of a city or a link, a network in the network list, or a tab of the left drawer (goals, deals: offers and loans, noc, nets), optionally on a tab (a city has cust, up, peer, infra…), and show it as text with numbered buttons.', + inputSchema: obj({ city: str('City id or name.'), link: str('Link id (from status, hot_spots or state links).'), network: str('Network id or name.'), tab: str('Tab id, as the tab buttons name it.'), + left: str('A tab of the left drawer', { enum: ['goals', 'deals', 'noc', 'nets'] }) }), run: (s, a) => s.call('panel', a), }, { name: 'click', - description: 'Press a numbered button from the last screen, panel or act result.', - inputSchema: obj({ button: num('The button\'s n.') }, ['button']), - run: (s, a) => s.call('click', a.button), + description: 'Press a numbered button from the last screen, panel or act result, as a player\'s click does: with the button\'s own arguments, so confirmations arm first and windows step on as in the game. For a list (it has options), give value.', + inputSchema: obj({ button: num('The button\'s n.'), value: str('For a list: the option to pick.') }, ['button']), + run: (s, a) => s.call('click', a.button, a.value), }, { name: 'open_link', - description: 'Open the build window for a link (a leased wave, dark fiber or your own cable) from one of your POPs to any city. Then pick the route and size with click (buildLink takes the tier).', + description: 'Open the build window for a link (a leased wave, dark fiber or your own cable) from one of your POPs to any city, to compare the routes and sizes it offers; then click through it. act buildLink, orderDf and orderCable do the same in one call.', inputSchema: obj({ from: str('One of your POPs.'), to: str('Any city.') }, ['from', 'to']), run: (s, a) => s.call('openLink', a.from, a.to), }, ]; -module.exports = { createSession, TOOLS }; +module.exports = { createSession, TOOLS, actArgs }; diff --git a/scripts/lib/mcp-page.js b/scripts/lib/mcp-page.js index 77afe6e..8853f40 100644 --- a/scripts/lib/mcp-page.js +++ b/scripts/lib/mcp-page.js @@ -1,10 +1,14 @@ // Runs inside the game page (see scripts/lib/mcp-game.js), in the game's own global scope, so it reads S, R, NET, -// CITY… directly. Every function takes and returns plain JSON. It only reads the game, except act(), click(), +// CITY… directly. Every function takes and returns plain JSON. It only reads the game, except run(), click(), // panel(), advance() and the game loaders, which go through the same ACT actions and dayTick() the page uses. +// The command tables run() checks arguments against come from scripts/lib/mcp-commands.js, evaluated first. (() => { + const { API_DOMAINS, API_CMD, API_VIEW, API_BOUND, API_SESSION, API_STATE_DOC, API_RESULTS_DOC, API_TABLES, API_MADE, + API_UI_HIDDEN, apiDomCheck, apiDomValues, apiPath, apiJson } = window.__mcpCmds; const BLOCK = /^(DIV|P|H1|H2|H3|H4|SECTION|LI|UL|OL|TR|TABLE|NAV|HEADER|FOOTER|BUTTON|LABEL|DETAILS|SUMMARY)$/; + const MAX_TEXT = 8000; // Text as a player would read it: one line per block, no runs of spaces. jsdom has no innerText. - const text = (x, max = 8000) => { + const fullText = (x) => { let el = x; if (typeof x === 'string') { el = document.createElement('div'); el.innerHTML = x; } if (!el) return ''; @@ -20,12 +24,13 @@ out.push(sep); }; walk(el); - const s = out.join('').split('\n').map((l) => l.replace(/\s+/g, ' ').replace(/ ([.,;:!?)])/g, '$1').replace(/\( /g, '(').trim()).filter(Boolean).join('\n'); - return s.length > max ? s.slice(0, max) + '\n…' : s; + return out.join('').split('\n').map((l) => l.replace(/\s+/g, ' ').replace(/ ([.,;:!?)])/g, '$1').replace(/\( /g, '(').trim()).filter(Boolean).join('\n'); }; + const text = (x, max = MAX_TEXT) => { const s = fullText(x); return s.length > max ? s.slice(0, max) + '\n…' : s; }; const r1 = (v) => (typeof v === 'number' && isFinite(v) ? Math.round(v * 10) / 10 : v); const fail = (msg) => { throw new Error(msg); }; const norm = (s) => String(s || '').toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').trim(); + const parse = (s) => { try { return JSON.parse(s || '{}'); } catch (e) { return {}; } }; // ---------- finding things by id or by name ---------- const best = (list, q, keys) => { @@ -45,45 +50,83 @@ for (const c of Object.keys(S.myIx || {})) if (!o.includes(c)) o.push(c); return o; }; - const ixOf = (q) => (XIXM[q] || (CITY[q] && CITY[q].ix) || (S.myIx && S.myIx[q]) ? q : best(allIx(), q, (x) => [x, ixName(x)])) || fail(`No exchange matches "${q}".`); const cityName = (c) => (CITY[c] ? CITY[c].name : c); const incText = (i) => text(i.msg || incTitle(i), 400); // ---------- toasts: what the game tells the player ---------- let toasts = []; const t0 = toast; - toast = function (h, kind) { toasts.push((kind ? kind + ': ' : '') + text(String(h), 600)); return t0.apply(this, arguments); }; + toast = function (h, kind) { toasts.push({ kind: kind || '', text: text(String(h), 600) }); return t0.apply(this, arguments); }; const takeToasts = () => { const t = toasts; toasts = []; return t; }; + const toastLines = (t) => t.map((x) => (x.kind ? x.kind + ': ' : '') + x.text); // ---------- what is on screen ---------- + // The surfaces a player can read, by the name screen() takes. The left drawer has tabs (goals, deals, noc, nets). + const ROOT = { modal: 'modal', bank: 'bankBox', dash: 'dash', panel: 'panel', left: 'leftBody', puzzle: 'pzBox' }; + const shown = (w) => { const el = $(ROOT[w]); return !!el && !el.hidden; }; + const modalOpen = () => shown('modal'); let last = []; - const buttons = (root) => [...root.querySelectorAll('[data-act]')].map((b) => { - let args = {}; - try { args = JSON.parse(b.dataset.args || '{}'); } catch (e) {} - return { label: text(b, 200).replace(/\n/g, ' ') || b.getAttribute('aria-label') || b.dataset.act, act: b.dataset.act, args, disabled: !!b.disabled }; - }); - const screen = (where) => { - const modal = !$('modal').hidden; - if (modal && !where) { - last = buttons($('modal')); - return { where: 'modal', text: text($('modal')), buttons: last.map((b, i) => ({ n: i, ...b })) }; + const controls = (root) => { + const out = []; + for (const b of root.querySelectorAll('[data-act],select[data-chg]')) { + if (b.dataset.act) out.push({ label: text(b, 200).replace(/\n/g, ' ') || b.getAttribute('aria-label') || b.dataset.act, act: b.dataset.act, args: parse(b.dataset.args), disabled: !!b.disabled }); + // A list the game acts on when its value changes (the change handler in src/game/96-map/95-clicks.js): click + // it with a value. + else out.push({ label: b.getAttribute('aria-label') || (b.closest('label') && text(b.closest('label'), 120).split('\n')[0]) || b.dataset.chg, + select: b.dataset.chg, value: b.value, options: [...b.options].map((o) => ({ value: o.value, label: o.textContent.trim() })), disabled: !!b.disabled }); } - const p = where === 'left' ? $('leftBody') : $('panel'); - last = p ? buttons(p) : []; - return { where: where === 'left' ? 'network list' : 'panel', modalOpen: modal, selected: UI.sel, tab: UI.tab, text: p ? text(p) : '', buttons: last.map((b, i) => ({ n: i, ...b })) }; + return out; + }; + const screen = (where, offset = 0) => { + if (where === null) where = undefined; + if (where !== undefined && !ROOT[where]) fail(`where is one of ${Object.keys(ROOT).join(', ')}.`); + const open = Object.keys(ROOT).filter((w) => w !== 'left' && shown(w)); + const w = where || ['modal', 'bank', 'dash', 'panel', 'puzzle'].find(shown) || 'panel'; + const root = $(ROOT[w]); + last = root ? controls(root) : []; + const all = root ? fullText(root) : '', from = Math.max(0, Math.floor(+offset) || 0), more = all.length - from - MAX_TEXT; + const out = { where: w, open, selected: UI.sel, tab: UI.tab }; + if (w === 'left') out.leftTab = UI.left || 'goals'; + if (w === 'modal') { const d = decision(); out.question = !!d; } + out.text = all.slice(from, from + MAX_TEXT); + if (from) out.textFrom = from; + if (more > 0) out.textMore = `${more} more characters: call screen with where "${w}" and offset ${from + MAX_TEXT}`; + out.buttons = last.map((b, i) => ({ n: i, ...b })); + return out; + }; + + // ---------- windows: the agent's own sheets, and the game's questions ---------- + // A window the agent opened itself (a view, a draft, the link window, a sheet it clicked inside) is something to read + // and click through. A window the game opened in answer to a game command, or during a day, is a question when one + // of its buttons runs a game command other than closeModal (a De-Kicks quote, a retention offer); then other game + // commands wait until it is answered or closed, as clicks outside an open window do in the game. + let sheet = null; + const card = () => $('modalCard').firstChild; + const markSheet = () => { sheet = modalOpen() ? card() : null; }; + const isSheet = () => modalOpen() && !!sheet && card() === sheet; + const decision = () => { + if (!modalOpen() || isSheet()) return null; + const b = [...$('modal').querySelectorAll('[data-act]')].filter((x) => x.dataset.act !== 'closeModal' && API_CMD[x.dataset.act]); + if (!b.length) return null; + return { text: text($('modal'), 1500), options: b.map((x) => ({ command: x.dataset.act, args: parse(x.dataset.args), label: text(x, 120).replace(/\n/g, ' ') })) }; }; // ---------- starting and loading ---------- - const settle = () => { UI.started = true; UI.pitched = true; UI.speed = 0; if (UI.pendGame) ACT.pitchSkip(); closeModal(); compute(); renderAll(); takeToasts(); }; - const newGame = ({ city = 'fra', name, preset = 'oncall', seed }) => { + const settle = () => { UI.started = true; UI.pitched = true; UI.speed = 0; if (UI.pendGame) ACT.pitchSkip(); closeModal(); sheet = null; compute(); renderAll(); takeToasts(); }; + const newGame = ({ city = 'fra', name, preset = 'oncall', seed, asn, chaos }) => { const c = cityOf(city).id; if (!homeOk(c)) fail(`${cityName(c)} cannot be a home city.`); - if (!['freeze', 'oncall', 'bgp', 'sandbox'].includes(preset)) fail('preset is one of freeze, oncall, bgp, sandbox'); + if (!['soft', 'freeze', 'oncall', 'bgp', 'sandbox'].includes(preset)) fail('preset is one of soft, freeze, oncall, bgp, sandbox'); + if (asn !== undefined && !asnOk(+asn)) fail(`AS${asn} cannot be yours: it is reserved, private or another network's. Leave asn out for a free one.`); + if (chaos !== undefined && preset !== 'sandbox') fail('chaos is the sandbox\'s dial: give preset "sandbox" with it.'); + if (chaos !== undefined && !own(CHAOS, chaos)) fail(`chaos is one of ${Object.keys(CHAOS).join(', ')}.`); if (seed !== undefined && window.__reseed) window.__reseed(Math.max(1, Math.floor(+seed) || 1)); if (UI.pendGame) UI.pendGame = null; UI.pitched = true; - const nm = String(name || randomNetworkName()).slice(0, 24); - beginGame(nm, c, preset === 'sandbox' ? { mode: 'sandbox', rules: { chaos: 'none' } } : { mode: 'normal', preset }); + const nm = String(name || randomNetworkName()).slice(0, 24), was = UI.asnTxt; + // beginGame takes the ASN typed on the title screen. + UI.asnTxt = asn !== undefined ? String(+asn) : ''; + try { beginGame(nm, c, preset === 'sandbox' ? { mode: 'sandbox', rules: { chaos: chaos || 'none' } } : { mode: 'normal', preset }); } finally { UI.asnTxt = was; } settle(); return status(); }; @@ -202,28 +245,194 @@ return { links: top(links), transitPorts: top(transit), pnis: top(pnis), transitBillByCarrier: bill, biggestTrafficStillOnTransit: viaTransit }; }; - // ---------- doing things ---------- + // ---------- the contract: commands, arguments, reference tables, raw state ---------- // Actions the server never runs: files, storage slots, settings and the title screen are not the game's, and time // only moves through advance. - const DENY = new Set(['animSet', 'cont', 'exportSave', 'importGo', 'importPick', 'install', 'langSet', 'menu', 'mute', 'newgame', 'phonePlay', 'phoneSpeed', - 'prefSet', 'pzShare', 'resetAsk', 'settings', 'settingsClose', 'share', 'shareDl', 'shareGo', 'slotBack', 'slotDel', 'slotDelGo', 'slotExport', 'slotMenu', - 'slotRetry', 'slotSpace', 'slotSwitch', 'slotTake', 'soundSet', 'speed', 'start', 'toTitle', 'traceCopy', 'updateLater', 'updateNow', 'vpSet', 'wsShare']); - const run = (name, args) => { - if (DENY.has(name)) fail(`${name} is not available here${name === 'speed' ? ': use advance to move time' : name === 'start' || name === 'newgame' ? ': use new_game' : ''}.`); - const fn = ACT[name]; - if (typeof fn !== 'function') fail(`There is no action "${name}". See the actions list.`); - takeToasts(); - const cash = S.cash; - fn(args && typeof args === 'object' ? args : {}); - return { toasts: takeToasts(), cashChange: Math.round(S.cash - cash), screen: screen() }; + const WHY = { + time: 'use advance to move time', start: 'use new_game', files: 'use load_save or export_save', + slots: 'saved networks in browser storage are not part of this game', prefs: 'device and player settings are not part of the game', + browser: 'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)', }; - const click = (n) => { + const DENY_WHY = { + speed: 'time', phonePlay: 'time', phoneSpeed: 'time', + start: 'start', newgame: 'start', cont: 'start', toTitle: 'start', resetAsk: 'start', + exportSave: 'files', importGo: 'files', importPick: 'files', slotExport: 'files', + slotBack: 'slots', slotDel: 'slots', slotDelGo: 'slots', slotMenu: 'slots', slotRetry: 'slots', slotSpace: 'slots', slotSwitch: 'slots', slotTake: 'slots', + animSet: 'prefs', langSet: 'prefs', menu: 'prefs', mute: 'prefs', prefSet: 'prefs', settings: 'prefs', settingsClose: 'prefs', soundSet: 'prefs', vpSet: 'prefs', + install: 'browser', share: 'browser', shareDl: 'browser', shareGo: 'browser', traceCopy: 'browser', updateLater: 'browser', updateNow: 'browser', wsShare: 'browser', pzShare: 'browser', + }; + const denied = (name) => (Object.prototype.hasOwnProperty.call(DENY_WHY, name) ? WHY[DENY_WHY[name]] : null); + const kindOf = (name) => (API_CMD[name] ? 'game' : API_VIEW[name] ? 'view' : API_BOUND[name] ? 'draft' : API_SESSION[name] ? 'session' : null); + const specOf = (name) => API_CMD[name] || API_VIEW[name] || API_SESSION[name] || null; + const classes = () => ({ game: Object.keys(API_CMD), view: Object.keys(API_VIEW), draft: Object.keys(API_BOUND), session: Object.keys(API_SESSION), denied: Object.keys(DENY_WHY) }); + + // One argument as the schema states it. Table domains name their catalog table rather than list every id. + const argDoc = ([name, dom, req]) => { + const a = { name, required: req !== false }, d = API_DOMAINS[dom]; + if (!d) { a.type = dom; return a; } + a.domain = dom; + if (d.table) a.from = d.table; + else { const v = apiDomValues(dom); if (Array.isArray(v)) a.values = v; else if (v && v.from !== undefined) a.range = v; } + return a; + }; + const schema = (section) => { + const cmd = (s) => ({ args: (s.args || []).map(argDoc), doc: s.doc }); + const doc = { + clock: 'Time moves only with advance: one dayTick() per simulated day, as the game loop runs it. Nothing runs between calls.', + commands: Object.fromEntries(Object.entries(API_CMD).map(([n, s]) => [n, { ...cmd(s), dryRun: !!s.quote, + ...(s.decides ? { decides: true } : {}), ...(s.confirm ? { confirm: s.confirm } : {}), ...(s.open ? { opens: s.open } : {}), ...(s.reads ? { report: true } : {}) }])), + view: Object.fromEntries(Object.entries(API_VIEW).map(([n, s]) => [n, cmd(s)])), + session: Object.fromEntries(Object.entries(API_SESSION).map(([n, s]) => [n, cmd(s)])), + drafts: API_BOUND, + denied: Object.fromEntries(Object.keys(DENY_WHY).sort().map((n) => [n, denied(n)])), + domains: Object.fromEntries(Object.entries(API_DOMAINS).map(([n, d]) => { const v = apiDomValues(n); + return [n, { kind: d.kind === 'fn' ? 'custom' : d.kind, ...(d.table ? { from: d.table } : {}), + ...(!d.table && Array.isArray(v) ? { values: v } : v && v.from !== undefined ? { range: v } : v && v.of ? { of: v.of } : {}) }]; })), + state: API_STATE_DOC, results: API_RESULTS_DOC, + }; + if (section === undefined || section === null || section === '') return doc; + if (!(section in doc)) fail(`No section "${section}". Sections: ${Object.keys(doc).join(', ')}.`); + return doc[section]; + }; + const catalog = (name) => { + if (name === undefined || name === null || name === '') { + return { tables: [...Object.keys(API_TABLES), ...Object.keys(API_MADE)].sort().map((k) => { const t = k in API_MADE ? API_MADE[k]() : API_TABLES[k]; + return { name: k, n: Array.isArray(t) ? t.length : t && typeof t === 'object' ? Object.keys(t).length : 1 }; }) }; + } + if (name in API_MADE) return apiJson(API_MADE[name]()); + if (name in API_TABLES) return apiJson(API_TABLES[name]); + fail(`No table "${name}". Call catalog without a name for the list.`); + }; + const state = (path) => { if (!S) return null; const v = apiJson(apiPath(S, path)); return v === undefined ? null : v; }; + const results = (path) => { const v = apiJson(apiPath(R, path)); return v === undefined ? null : v; }; + const ui = () => { const o = {}; for (const k of Object.keys(UI)) if (!API_UI_HIDDEN[k]) o[k] = apiJson(UI[k]); return o; }; + const actions = () => { + const sig = (s) => (s.args || []).map((a) => a[0] + (a[2] === false ? '?' : '')).join(','); + const typed = {}; + for (const t of [API_CMD, API_VIEW, API_SESSION]) for (const [n, s] of Object.entries(t)) typed[n] = sig(s); + return { typed, drafts: Object.keys(API_BOUND) }; + }; + + // ---------- doing things ---------- + // Arguments: shape and domain only. Anything beyond that is the game's to answer. + const validate = (spec, args) => { + const problems = [], out = {}; + for (const [name, dom, req] of spec.args || []) { + const v = args[name]; + if (v === undefined) { if (req !== false) problems.push(`${name} is required`); continue; } + if (apiDomCheck(dom, v).ok) { out[name] = v; continue; } + const vs = apiDomValues(dom), d = API_DOMAINS[dom]; + problems.push(`${name}: ${JSON.stringify(v)} is not a ${dom}${d && d.table && d.kind === 'id' ? ` (see catalog ${d.table} or find)` : Array.isArray(vs) ? ` (one of ${vs.slice(0, 12).join(', ')}${vs.length > 12 ? '…' : ''})` : vs && typeof vs === 'object' && vs.from !== undefined ? ` (${vs.from}..${vs.to})` : ''}`); + } + for (const k of Object.keys(args)) if (!(spec.args || []).some((a) => a[0] === k)) problems.push(`${k} is not an argument of this action`); + return { ok: !problems.length, problems, args: out }; + }; + // The fingerprint tells "did nothing" from "did something quietly": cash, day, the entity counts, the small + // settings maps, and the paths a command declares in watch. R is left out: it is rebuilt after every action. + const FP_LEN = ['links', 'transit', 'pni', 'caches', 'biz', 'offers', 'nni', 'loans', 'loanOffers', 'inc', 'scrubs']; + const FP_KEYS = ['pops', 'ixp', 'peers', 'myIx', 'done', 'ach', 'merged', 'confReg']; + const FP_JSON = ['name', 'pairMet', 'rs', 'ixn', 'ixSite', 'ixPref', 'spares', 'te', 'cnLic', 'hw', 'scrubMode', 'ppol', 'ops', 'core', 'ddosAuto', 'popStd', 'demo', 'charter', 'monkey', 'seatOff', 'pz', 'ar', 'dk', 'ev']; + const fp = (watch, args) => { + if (!S) return null; + const f = { cash: S.cash, day: S.day, lvl: S.lvl || 1, won: !!S.won, lost: !!S.lost }; + for (const k of FP_LEN) f[k] = (S[k] || []).length; + for (const k of FP_KEYS) f[k] = Object.keys(S[k] || {}).length; + for (const k of FP_JSON) f[k] = JSON.stringify(apiJson(S[k]) ?? null); + for (const p of watch || []) f['@' + p] = JSON.stringify(apiJson(apiPath(S, String(p).replace(/#(\w+)/g, (m, k) => (args && args[k] !== undefined ? args[k] : m)))) ?? null); + return JSON.stringify(f); + }; + // spend() is the game's money gate and a top-level function, so every action reaches it by its global name. + const meter = () => { const real = window.spend; let paid = 0; window.spend = (c) => { const ok = real(c); if (ok) paid += c; return ok; }; return () => { window.spend = real; return paid; }; }; + + // One action, run as the game runs it, and reported: what the game said (toasts), what it charged at the money gate + // (goal rewards that land in the same call are not a price), whether anything changed, and what is on screen now. + // typed: through the command table (bind the UI, type into fields, pass the confirmation); otherwise as a button + // click does it, with the button's own arguments. + const dispatch = (name, kind, spec, args, typed) => { + const mine = isSheet() || (typed && kind === 'game' && !!spec.open); + takeToasts(); + const ref = S, cash = S ? S.cash : 0, f0 = fp(spec && spec.watch, args), paid = meter(); + let threw = null, report; + try { + if (typed && kind === 'game') { + if (spec.open) { ACT[spec.open]({}); markSheet(); } + // The custom metric's field lives in the link's panel. + if (name === 'metricSet' && !$('metIn')) { UI.sel = { type: 'link', id: args.id }; renderAll(); } + const gone = (spec.dom || []).filter((f) => !$(f)); + if (gone.length) throw new Error(`the field it types into (${gone.join(', ')}) is not on screen${name === 'metricSet' ? ': set the link\'s metric to custom first (setMetric v "custom")' : ''}`); + if (spec.bind) spec.bind(args); + const a = spec.pass ? spec.pass(args) : args; + ACT[name](a); + if (spec.confirm === 'double') ACT[name](a); + if (spec.reads === 'modal' && modalOpen()) { report = text($('modal')); closeModal(); } + } else ACT[name](args); + } catch (e) { threw = e; } + const charged = paid(); + if (threw) { takeToasts(); fail(`${name} failed: ${threw && threw.message || threw}`); } + if (!modalOpen()) sheet = null; + else if (mine || kind !== 'game') markSheet(); + else sheet = null; + const said = takeToasts(), d = decision(); + const outcome = d ? 'decision' : S !== ref || fp(spec && spec.watch, args) !== f0 || report !== undefined ? 'applied' + : said.some((t) => t.kind === 'bad') ? 'rejected' : kind === 'view' || kind === 'draft' ? 'shown' : 'no_effect'; + return { action: name, outcome, toasts: toastLines(said), charged, cashChange: Math.round((S ? S.cash : 0) - cash), + ...(report !== undefined ? { report } : {}), ...(d ? { decision: d } : {}), screen: screen() }; + }; + // While the game waits for an answer, game commands other than its options report the question instead. + const waiting = (name) => { + const d = decision(); + return d && name !== 'closeModal' && !d.options.some((o) => o.command === name) + ? { action: name, outcome: 'decision', reason: 'A window is waiting for an answer: run one of its options, or closeModal.', decision: d, screen: screen() } : null; + }; + const quote = (name, spec, args) => { + const ui0 = {}; + for (const k of spec.bindsUI || []) ui0[k] = UI[k]; + const f0 = fp(spec.watch, args); + // A dry run must not use up the dice: some helpers draw (a PNI's lead time), and a draw here would move the seeded + // game. They get the middle of the range instead, so a drawn figure in a quote is a typical one. + const dice = Math.random; + Math.random = () => 0.5; + let q = {}; + try { + if (spec.bind && !spec.dom) spec.bind(args); + if (spec.quote) q = spec.quote(args) || {}; + } catch (e) { fail(`${name}: the price could not be worked out: ${e && e.message || e}`); } finally { Math.random = dice; for (const k of Object.keys(ui0)) UI[k] = ui0[k]; } + return { action: name, outcome: 'quote', quote: { setup: 0, monthly: 0, ...q, blocked: (q.blocked || []).map((b) => text(String(b), 400)) }, consistent: fp(spec.watch, args) === f0, + ...(spec.quote ? {} : { note: 'This command has no price of its own: it costs nothing up front.' }) }; + }; + const run = (name, args, opts = {}) => { + name = String(name || ''); + if (name.startsWith('view.')) name = name.slice(5); + const no = denied(name); + if (no) fail(`${name} is not available here: ${no}.`); + const kind = kindOf(name); + if (!kind || typeof ACT[name] !== 'function') fail(`There is no action "${name}". See actions or schema.`); + args = args && typeof args === 'object' && !Array.isArray(args) ? args : {}; + const spec = specOf(name); + if (spec) { const v = validate(spec, args); if (!v.ok) fail(`${name}: ${v.problems.join('; ')}. See schema for its arguments.`); args = v.args; } + if (kind === 'game') { + if (S && S.lost && name !== 'closeModal') return { action: name, outcome: 'stopped', reason: 'The network went bankrupt: start or load another game.' }; + const w = waiting(name); + if (w) return w; + if (opts.dryRun) return quote(name, spec, args); + } else if (opts.dryRun) fail(`${name} has no price: only game commands (see schema commands) dry-run.`); + return dispatch(name, kind, spec, args, true); + }; + const click = (n, value) => { const b = last[n]; if (!b) fail(`No button ${n} on the last screen. Call screen first.`); if (b.disabled) fail(`"${b.label}" is greyed out.`); - return { clicked: b.label, ...run(b.act, 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)) fail(`"${b.label}" is a list: click it with a value, one of ${b.options.map((o) => JSON.stringify(o.value)).join(', ')}.`); + const no = denied(name); + if (no) fail(`${name} is not available here: ${no}.`); + const kind = kindOf(name); + if (!kind || typeof ACT[name] !== 'function') fail(`"${b.label}" runs ${name}, which is not an action.`); + if (kind === 'game') { const w = waiting(name); if (w) return { clicked: b.label, ...w }; } + return { clicked: b.label, ...dispatch(name, kind, specOf(name), args, false) }; }; - const panel = ({ city: c, link, network: q, tab }) => { + const panel = ({ city: c, link, network: q, tab, left }) => { + if (left !== undefined) { if (!['goals', 'deals', 'noc', 'nets'].includes(left)) fail('left is one of goals, deals, noc, nets.'); ACT.leftTab({ t: left }); return screen('left'); } if (c) UI.sel = { type: 'city', id: cityOf(c).id }; else if (link) { if (!S.links.some((l) => l.id === link)) fail(`No link ${link}. See status or hot_spots for link ids.`); UI.sel = { type: 'link', id: link }; } else if (q) ACT.netFocus({ id: netOf(q).id }); @@ -236,14 +445,15 @@ if (!S.pops[x]) fail(`A link starts at one of your POPs: ${Object.keys(S.pops).map(cityName).join(', ')}.`); takeToasts(); openLinkModal(x, y); - return { toasts: takeToasts(), screen: screen() }; + markSheet(); + return { toasts: toastLines(takeToasts()), screen: screen() }; }; - const actions = () => Object.keys(ACT).filter((k) => !DENY.has(k)).sort(); // ---------- time ---------- const advance = (days = 1) => { days = Math.max(1, Math.min(3650, Math.floor(+days) || 1)); - if (!$('modal').hidden) fail('A window is open. Answer it first (screen, click), the game does not run days behind it.'); + if (modalOpen()) fail('A window is open. Answer it first (screen, click, or act closeModal), the game does not run days behind it.'); + sheet = null; const start = S.day, cash = S.cash, inc0 = new Set(S.inc.map((i) => i.id)), times = []; takeToasts(); let ran = 0, stop = null; @@ -253,21 +463,23 @@ dayTick(); times.push({ day: S.day, ms: r1(performance.now() - t) }); ran++; - if (!$('modal').hidden) { stop = 'a window opened'; break; } + if (modalOpen()) { stop = 'a window opened'; break; } } renderAll(); // The log keeps what mattered; toasts that only repeat a log line are left out. const entries = (S.log || []).filter((e) => e.d > start).slice(-60), logged = entries.map((e) => norm(text(e.t, 400))); const log = entries.map((e) => `${dateStr(e.d)}: ${text(e.t, 400)}`); - const total = times.reduce((a, x) => a + x.ms, 0); + const total = times.reduce((a, x) => a + x.ms, 0), d = stop === 'a window opened' ? decision() : null; return { from: dateStr(start), to: dateStr(S.day), daysRun: ran, stoppedBecause: stop, cash: Math.round(S.cash), cashChange: Math.round(S.cash - cash), newIncidents: S.inc.filter((i) => !inc0.has(i.id)).map(incText), - log, toasts: [...new Set(takeToasts())].filter((t) => { const f = norm(t.replace(/^\w+: /, '').split('\n')[0]); return !logged.some((l) => l.startsWith(f)); }).slice(-40), + log, toasts: [...new Set(toastLines(takeToasts()))].filter((t) => { const f = norm(t.replace(/^\w+: /, '').split('\n')[0]); return !logged.some((l) => l.startsWith(f)); }).slice(-40), timing: { totalMs: r1(total), perDayMs: r1(total / (ran || 1)), slowestDays: times.slice().sort((a, b) => b.ms - a.ms).slice(0, 5).map((x) => ({ date: dateStr(x.day), ms: x.ms })) }, + ...(d ? { decision: d } : {}), screen: stop === 'a window opened' ? screen() : undefined, }; }; - window.__mcp = { newGame, loadSave, exportSave, status, network, city, find, trace, peering, hotSpots, run, click, panel, openLink, actions, advance, screen }; + window.__mcp = { newGame, loadSave, exportSave, status, network, city, find, trace, peering, hotSpots, run, click, panel, openLink, actions, advance, screen, + schema, catalog, state, results, ui, classes }; })(); diff --git a/scripts/mcp.js b/scripts/mcp.js index 5e4fdeb..75f9d4b 100644 --- a/scripts/mcp.js +++ b/scripts/mcp.js @@ -13,7 +13,7 @@ const { version } = require('../package.json'); const VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05']; const INSTRUCTIONS = `Series of Tubes is a cartoon game about building an internet backbone: POPs in cities, links between them, transit, exchanges, PNIs, customers. A game is always loaded (a fresh On-call game in Frankfurt until you start or load another). -Read with status, network, city, find, traceroute, peering_check and hot_spots. Change things with act (see actions), 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. +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. To look into a bug report: load_save with the attached save, then status, hot_spots, and advance with timings.`; const session = createSession(); diff --git a/site/i18n/de.js b/site/i18n/de.js index 5a3312c..6a941ba 100644 --- a/site/i18n/de.js +++ b/site/i18n/de.js @@ -488,6 +488,7 @@ "cables.cuba_s_only_cable_laid_from":"Kubas einziges Kabel, 2011 von Venezuela aus verlegt und zwei Jahre später eingeschaltet. Hängt dir um den Hals.", "cables.cura_ao_to_trinidad_along_the":"Curaçao nach Trinidad entlang der Küste Venezuelas.", "cables.danish_for_sea_fun_probably":"Dänisch für „Meeresspaß“. Wahrscheinlich.", +"cables.darwin_to_port_hedland_past_the":"Darwin nach Port Hedland, vorbei an den Gasplattformen, für die es verlegt wurde. Heute der Umweg des Nordens nach Singapur.", "cables.darwin_to_singapore_via_jakarta":"Darwin nach Singapur über Jakarta. Survival of the fittest packets.", "cables.discovered_the_atlantic_again_old":"Hat den Atlantik nochmal entdeckt. Alt, teuer und zerbrechlich.", "cables.djibouti_down_to_durban_hugging_the":"Dschibuti runter bis Durban, eng an der ostafrikanischen Küste. Lacht über Piraten und Anker.", @@ -728,6 +729,7 @@ "cities.india_s_east_coast_landing_hub":"Indiens Landungs-Hub an der Ostküste, mit Kabeln nach Singapur. Zyklonsaison ist hier ein Thema.", "cities.india_s_tech_capital_packets_move":"Indiens Tech-Hauptstadt. Pakete bewegen sich schneller als die Autos draußen.", "cities.inland_from_ostend_where_the_cables":"Landeinwärts von Ostende, wo die Kabel aus England an Land kommen. Die Nordsee ist flach, viel befahren und voller Trawler.", +"cities.iron_ore_red_dust_and_two":"Eisenerz, roter Staub und zwei Seekabel: Im Hafen der Pilbara landen die Leitung hoch nach Darwin und die raus nach Singapur. Kaum jemand wohnt hier; die Minen kaufen die Bandbreite.", "cities.it_almost_never_rains_but_the":"Es regnet fast nie, aber der Seenebel hält die Racks kühl.", "cities.italian_immigrants_vineyards_and":"Italienische Einwanderer, Weinberge und Fabriken. Deine Racks teilen sich die Hügel mit der Weinlese.", "cities.italy_s_digital_capital_fashion_week":"Italiens digitale Hauptstadt. Fashion-Week-Traffic, ein espressobetriebenes NOC und mehr Exchanges, als man erwarten würde.", @@ -753,6 +755,7 @@ "cities.mountains_mines_and_more_bars_per":"Berge, Minen und mehr Kneipen pro Kopf als irgendwo sonst in Brasilien. Peering-Deals werden bei Käsebrötchen unterschrieben.", "cities.mozambique_s_capital_an_hour_from":"Mosambiks Hauptstadt, eine Stunde von Südafrika. Ihre Kabel sind das Backup der Ostküste, wenn die anderen kaputtgehen.", "cities.new_caledonia_a_slice_of_france":"Neukaledonien, ein Stück Frankreich im Korallenmeer, mit einem Kabel nach Sydney und einer Nickelmine auf jedem Hügel.", +"cities.north_queensland_s_capital_in_waiting":"Die Hauptstadt im Wartestand von North Queensland, falls der neue Bundesstaat je kommt. Das einzige zyklonfeste Rechenzentrum am Ring außerhalb von Brisbane, mit Armee, Uni und Katastrophenschutz als Nachbarn.", "cities.norway_s_oil_capital_now_full":"Norwegens Ölhauptstadt, heute voller Rechenzentren in Bergen, betrieben mit Wasserkraft und gekühlt vom Fjord. Nordseekabel landen hier an.", "cities.norway_s_southern_tip_where_cables":"Norwegens Südspitze, wo Kabel aus Dänemark, vom Atlantik und vom Rest der Küste an Land gehen.", "cities.nova_scotia_s_capital_and_the":"Die Hauptstadt von Nova Scotia und der große nordamerikanische Hafen, der Europa am nächsten liegt. Das schnellste Kabel nach England startet hier, auf der kürzesten Linie über den Ozean, gebaut für Trader, die für jede Millisekunde zahlen.", @@ -814,6 +817,7 @@ "cities.the_harbour_the_bridge_and_most":"Der Hafen, die Brücke und die meisten Rechenzentren des Landes. Die Miete ist die eigentliche Latenz.", "cities.the_highest_seat_of_government_on":"Der höchstgelegene Regierungssitz der Welt, auf 3.600 m. Pendler fahren Seilbahn, und ein Teil der Glasfaser auch.", "cities.the_maldives_capital_a_stop_on":"Die Hauptstadt der Malediven, einen Meter über dem Meer und ein Halt an den Kabeln von Indien zum Golf und nach Singapur.", +"cities.the_middle_of_everywhere_no_sea":"Die Mitte von überall: kein Meer, kein Seekabel, nur Glasfaser den Highway hoch und eine alte Telegrafenstation. Die großen weißen Kuppeln die Straße runter sind ganz sicher fürs Wetter.", "cities.the_most_isolated_big_city_on":"Die abgelegenste Großstadt der Welt. Asien ist näher als Sydney.", "cities.the_north_s_hub_with_its":"Der Hub des Nordens, mit eigenem Exchange und sehr feuchten Lüftungseinlässen. Kabel nach Irland und Dänemark kommen weiter oben an der Küste an Land.", "cities.the_northernmost_town_in_the_united":"Die nördlichste Stadt der Vereinigten Staaten, erreicht von der ersten Subsea-Glasfaser in der amerikanischen Arktis.", @@ -1998,6 +2002,7 @@ "failures.the_sandflies_drove_your_splicing":"Die Sandfliegen haben deinen Spleißtrupp von {a}–{b} vertrieben. Sie kommen wieder, wenn der Wind auffrischt.", "failures.the_seabed_off_tonga_slid_down":"Der Meeresboden vor Tonga ist einen Hang hinuntergerutscht und hat dein Kabel {a}–{b} mitgenommen. Das Reparaturschiff kommt aus Papua-Neuguinea.", "failures.the_smelter_at_tiwai_point_pulled":"Die Aluminiumhütte in Tiwai Point hat etwas fester am Stromnetz gezogen, und dein POP in {city} hat zuerst geblinzelt.", +"failures.the_wet_season_washed_out_the":"Die Regenzeit hat die Piste zu deiner Glasfaser {a}–{b} weggespült. Der Trupp kommt hin, wenn das Wasser zurückgeht.", "failures.thieves_dug_up_your_a_b":"Diebe haben dein Kabel {a}–{b} ausgegraben, überzeugt, es sei Kupfer. Es war Glasfaser. Sie haben es zutiefst enttäuscht durchgeschnitten im Graben liegen lassen.", "failures.traffic_rerouted_customers_barely":"Traffic umgeleitet, die Kunden haben kaum was gemerkt.", "failures.truck_a_spare_amp_out":"Ersatzverstärker per Lkw hinbringen", diff --git a/site/i18n/es.js b/site/i18n/es.js index 0f9312e..5936e6e 100644 --- a/site/i18n/es.js +++ b/site/i18n/es.js @@ -486,6 +486,7 @@ "cables.cuba_s_only_cable_laid_from":"El único cable de Cuba, tendido desde Venezuela en 2011 y encendido dos años después. Te cuelga del cuello.", "cables.cura_ao_to_trinidad_along_the":"De Curazao a Trinidad por la costa de Venezuela.", "cables.danish_for_sea_fun_probably":"En danés significa «diversión marina». Probablemente.", +"cables.darwin_to_port_hedland_past_the":"De Darwin a Port Hedland, pasando por las plataformas de gas para las que se tendió. Hoy es el rodeo del norte hacia Singapur.", "cables.darwin_to_singapore_via_jakarta":"De Darwin a Singapur vía Yakarta. Supervivencia de los paquetes más aptos.", "cables.discovered_the_atlantic_again_old":"Descubrió el Atlántico otra vez. Viejo, caro y frágil.", "cables.djibouti_down_to_durban_hugging_the":"De Yibuti a Durban, pegado a la costa de África Oriental. Se ríe de piratas y anclas.", @@ -726,6 +727,7 @@ "cities.india_s_east_coast_landing_hub":"El hub de aterrizaje de la costa este de la India, con cables a Singapur. La temporada de ciclones es real.", "cities.india_s_tech_capital_packets_move":"La capital tecnológica de la India. Los paquetes se mueven más rápido que los coches de fuera.", "cities.inland_from_ostend_where_the_cables":"Tierra adentro desde Ostende, donde llegan a tierra los cables de Inglaterra. El Mar del Norte es poco profundo, concurrido y lleno de arrastreros.", +"cities.iron_ore_red_dust_and_two":"Mineral de hierro, polvo rojo y dos cables submarinos: en el puerto del Pilbara llegan la línea hacia Darwin y la que sale a Singapur. Casi nadie vive aquí; las minas compran el ancho de banda.", "cities.it_almost_never_rains_but_the":"Casi nunca llueve, pero la niebla marina mantiene frescos los racks.", "cities.italian_immigrants_vineyards_and":"Inmigrantes italianos, viñedos y fábricas. Tus racks comparten las colinas con la vendimia.", "cities.italy_s_digital_capital_fashion_week":"La capital digital de Italia. Tráfico de semana de la moda, un NOC propulsado por espresso y más intercambios de lo que esperarías.", @@ -751,6 +753,7 @@ "cities.mountains_mines_and_more_bars_per":"Montañas, minas y más bares por habitante que en cualquier otro lugar de Brasil. Los acuerdos de peering se firman con pan de queso.", "cities.mozambique_s_capital_an_hour_from":"La capital de Mozambique, a una hora de Sudáfrica. Sus cables son el respaldo de la costa este cuando se rompen los demás.", "cities.new_caledonia_a_slice_of_france":"Nueva Caledonia, un trozo de Francia en el Mar del Coral, con un cable a Sídney y una mina de níquel en cada colina.", +"cities.north_queensland_s_capital_in_waiting":"La capital en espera de North Queensland, si el nuevo estado llega algún día. El único centro de datos a prueba de ciclones del anillo fuera de Brisbane, con el ejército, una universidad y los equipos de emergencias de vecinos.", "cities.norway_s_oil_capital_now_full":"La capital petrolera de Noruega, ahora llena de centros de datos dentro de montañas, alimentados con energía hidroeléctrica y refrigerados por el fiordo. Aquí llegan a tierra cables del Mar del Norte.", "cities.norway_s_southern_tip_where_cables":"La punta sur de Noruega, donde llegan a tierra los cables de Dinamarca, del Atlántico y del resto de la costa.", "cities.nova_scotia_s_capital_and_the":"La capital de Nueva Escocia, y el gran puerto norteamericano más cercano a Europa. El cable más rápido a Inglaterra parte de aquí, por la línea más corta a través del océano, hecho para traders que pagan cada milisegundo.", @@ -812,6 +815,7 @@ "cities.the_harbour_the_bridge_and_most":"El puerto, el puente y la mayoría de los centros de datos del país. El alquiler es la verdadera latencia.", "cities.the_highest_seat_of_government_on":"La sede de gobierno más alta de la Tierra, a 3600 m. Los trabajadores van en teleférico, y parte de la fibra también.", "cities.the_maldives_capital_a_stop_on":"La capital de Maldivas, a un metro sobre el mar y escala de los cables de la India al Golfo y Singapur.", +"cities.the_middle_of_everywhere_no_sea":"El centro de todas partes: sin mar, sin cable submarino, solo fibra por la carretera y una vieja estación de telégrafo. Las grandes cúpulas blancas de más abajo son, sin duda, para el tiempo.", "cities.the_most_isolated_big_city_on":"La gran ciudad más aislada de la Tierra. Asia está más cerca que Sídney.", "cities.the_north_s_hub_with_its":"El hub del Norte, con su propio intercambio y tomas de aire acondicionado muy húmedas. Los cables a Irlanda y Dinamarca llegan a tierra costa arriba.", "cities.the_northernmost_town_in_the_united":"El pueblo más al norte de Estados Unidos, al que llega la primera fibra submarina del Ártico estadounidense.", @@ -1996,6 +2000,7 @@ "failures.the_sandflies_drove_your_splicing":"Los jejenes expulsaron a tu equipo de empalmes de {a}–{b}. Volverán cuando se levante el viento.", "failures.the_seabed_off_tonga_slid_down":"El lecho marino frente a Tonga se deslizó por una pendiente y se llevó tu cable {a}–{b}. El barco de reparación viene desde Papúa Nueva Guinea.", "failures.the_smelter_at_tiwai_point_pulled":"La fundición de Tiwai Point tiró un poco más de la red, y tu POP en {city} parpadeó primero.", +"failures.the_wet_season_washed_out_the":"La estación de lluvias se llevó la pista hacia tu fibra {a}–{b}. La cuadrilla llegará cuando baje el agua.", "failures.thieves_dug_up_your_a_b":"Unos ladrones desenterraron tu cable {a}–{b}, seguros de que era cobre. Era fibra. Lo dejaron cortado en la zanja, profundamente decepcionados.", "failures.traffic_rerouted_customers_barely":"Tráfico redirigido, los clientes apenas lo notaron.", "failures.truck_a_spare_amp_out":"Llevar un amplificador de repuesto en camión", diff --git a/site/i18n/fr.js b/site/i18n/fr.js index c0c9f01..f6ceb6f 100644 --- a/site/i18n/fr.js +++ b/site/i18n/fr.js @@ -486,6 +486,7 @@ "cables.cuba_s_only_cable_laid_from":"Le seul câble de Cuba, posé depuis le Venezuela en 2011 et allumé deux ans plus tard. Il te pend au cou.", "cables.cura_ao_to_trinidad_along_the":"De Curaçao à Trinidad le long de la côte du Venezuela.", "cables.danish_for_sea_fun_probably":"« Plaisir de la mer » en danois. Probablement.", +"cables.darwin_to_port_hedland_past_the":"De Darwin à Port Hedland, en passant par les plateformes gazières pour lesquelles il a été posé. Aujourd'hui le détour du nord vers Singapour.", "cables.darwin_to_singapore_via_jakarta":"De Darwin à Singapore via Jakarta. Seuls les paquets les plus adaptés survivent.", "cables.discovered_the_atlantic_again_old":"A redécouvert l’Atlantique. Vieux, cher et fragile.", "cables.djibouti_down_to_durban_hugging_the":"De Djibouti à Durban, en collant à la côte est-africaine. Se moque des pirates et des ancres.", @@ -726,6 +727,7 @@ "cities.india_s_east_coast_landing_hub":"Le hub d’atterrissement de la côte est de l’Inde, avec des câbles vers Singapore. La saison des cyclones, c’est du sérieux.", "cities.india_s_tech_capital_packets_move":"La capitale tech de l’Inde. Les paquets vont plus vite que les voitures dehors.", "cities.inland_from_ostend_where_the_cables":"Dans les terres derrière Ostende, là où les câbles venus d’Angleterre touchent terre. La mer du Nord est peu profonde, encombrée et pleine de chalutiers.", +"cities.iron_ore_red_dust_and_two":"Du minerai de fer, de la poussière rouge et deux câbles sous-marins : le port du Pilbara accueille la ligne vers Darwin et celle vers Singapour. Presque personne n'habite ici ; ce sont les mines qui achètent la bande passante.", "cities.it_almost_never_rains_but_the":"Il ne pleut presque jamais, mais le brouillard marin garde les baies au frais.", "cities.italian_immigrants_vineyards_and":"Immigrés italiens, vignobles et usines. Tes baies partagent les collines avec les vendanges.", "cities.italy_s_digital_capital_fashion_week":"La capitale numérique de l’Italie. Trafic de fashion week, un NOC qui carbure à l’espresso et plus d’IX que tu ne l’imagines.", @@ -751,6 +753,7 @@ "cities.mountains_mines_and_more_bars_per":"Des montagnes, des mines et plus de bars par habitant que partout ailleurs au Brésil. Les accords de peering se signent autour d’un pão de queijo.", "cities.mozambique_s_capital_an_hour_from":"La capitale du Mozambique, à une heure de l’Afrique du Sud. Ses câbles sont le secours de la côte est quand les autres cassent.", "cities.new_caledonia_a_slice_of_france":"La Nouvelle-Calédonie, un bout de France dans la mer de Corail, avec un câble vers Sydney et une mine de nickel sur chaque colline.", +"cities.north_queensland_s_capital_in_waiting":"La capitale en attente du North Queensland, si le nouvel État voit le jour. Le seul centre de données anticyclone de l'anneau hors de Brisbane, avec l'armée, une université et les équipes de secours pour voisins.", "cities.norway_s_oil_capital_now_full":"La capitale norvégienne du pétrole, désormais pleine de datacenters creusés dans la montagne, alimentés à l’hydroélectricité et refroidis par le fjord. Les câbles de la mer du Nord atterrissent ici.", "cities.norway_s_southern_tip_where_cables":"La pointe sud de la Norvège, où atterrissent les câbles venus du Danemark, de l’Atlantique et du reste de la côte.", "cities.nova_scotia_s_capital_and_the":"La capitale de la Nouvelle-Écosse, et le grand port nord-américain le plus proche de l’Europe. Le câble le plus rapide vers l’Angleterre part d’ici, sur la ligne la plus courte à travers l’océan, construit pour des traders qui paient chaque milliseconde.", @@ -812,6 +815,7 @@ "cities.the_harbour_the_bridge_and_most":"Le port, le pont et la plupart des data centers du pays. La vraie latence, c’est le loyer.", "cities.the_highest_seat_of_government_on":"Le siège de gouvernement le plus haut du monde, à 3 600 m. Les pendulaires prennent le téléphérique, et une partie de la fibre aussi.", "cities.the_maldives_capital_a_stop_on":"La capitale des Maldives, à un mètre au-dessus de la mer, escale des câbles de l’Inde vers le Golfe et Singapour.", +"cities.the_middle_of_everywhere_no_sea":"Le milieu de partout : pas de mer, pas de câble sous-marin, juste de la fibre le long de la route et une vieille station télégraphique. Les grands dômes blancs un peu plus loin servent, bien sûr, à la météo.", "cities.the_most_isolated_big_city_on":"La grande ville la plus isolée de la planète. L’Asie est plus proche que Sydney.", "cities.the_north_s_hub_with_its":"Le hub du Nord, avec son propre IX et des prises d’air de clim très humides. Les câbles vers l’Irlande et le Danemark atterrissent un peu plus haut sur la côte.", "cities.the_northernmost_town_in_the_united":"La ville la plus au nord des États-Unis, desservie par la première fibre sous-marine de l’Arctique américain.", @@ -1996,6 +2000,7 @@ "failures.the_sandflies_drove_your_splicing":"Les mouches des sables ont chassé ton équipe d’épissure de {a}–{b}. Elle reviendra quand le vent se lèvera.", "failures.the_seabed_off_tonga_slid_down":"Le fond marin au large des Tonga a glissé le long d’une pente et a emporté ton câble {a}–{b}. Le navire de réparation arrive de Papouasie-Nouvelle-Guinée.", "failures.the_smelter_at_tiwai_point_pulled":"La fonderie de Tiwai Point a tiré un peu plus fort sur le réseau, et ton POP à {city} a flanché le premier.", +"failures.the_wet_season_washed_out_the":"La saison des pluies a emporté la piste vers ta fibre {a}–{b}. L'équipe y sera quand l'eau aura baissé.", "failures.thieves_dug_up_your_a_b":"Des voleurs ont déterré ton câble {a}–{b}, persuadés que c’était du cuivre. C’était de la fibre. Ils l’ont laissé coupé dans le fossé, profondément déçus.", "failures.traffic_rerouted_customers_barely":"Trafic redirigé, les clients n’ont presque rien vu.", "failures.truck_a_spare_amp_out":"Livrer un ampli de rechange", diff --git a/site/i18n/it.js b/site/i18n/it.js index 1881b8e..a2e7e8f 100644 --- a/site/i18n/it.js +++ b/site/i18n/it.js @@ -486,6 +486,7 @@ "cables.cuba_s_only_cable_laid_from":"L’unico cavo di Cuba, posato dal Venezuela nel 2011 e acceso due anni dopo. Te lo ritrovi appeso al collo.", "cables.cura_ao_to_trinidad_along_the":"Da Curaçao a Trinidad lungo la costa del Venezuela.", "cables.danish_for_sea_fun_probably":"In danese vuol dire “divertimento marino”. Probabilmente.", +"cables.darwin_to_port_hedland_past_the":"Da Darwin a Port Hedland, passando per le piattaforme del gas per cui è stato posato. Oggi la via del nord per Singapore.", "cables.darwin_to_singapore_via_jakarta":"Da Darwin a Singapore via Jakarta. Sopravvivono solo i pacchetti più adatti.", "cables.discovered_the_atlantic_again_old":"Ha riscoperto l’Atlantico. Vecchio, caro e fragile.", "cables.djibouti_down_to_durban_hugging_the":"Da Gibuti giù fino a Durban, rasente la costa dell’Africa orientale. Se la ride di pirati e ancore.", @@ -726,6 +727,7 @@ "cities.india_s_east_coast_landing_hub":"L’hub di approdo sulla costa est dell’India, con cavi per Singapore. La stagione dei cicloni è una cosa seria.", "cities.india_s_tech_capital_packets_move":"La capitale tech dell’India. I pacchetti vanno più veloci delle auto là fuori.", "cities.inland_from_ostend_where_the_cables":"Nell'entroterra di Ostenda, dove arrivano i cavi dall'Inghilterra. Il Mare del Nord è basso, trafficato e pieno di pescherecci.", +"cities.iron_ore_red_dust_and_two":"Minerale di ferro, polvere rossa e due cavi sottomarini: nel porto del Pilbara approdano la linea verso Darwin e quella per Singapore. Qui non abita quasi nessuno; la banda la comprano le miniere.", "cities.it_almost_never_rains_but_the":"Non piove quasi mai, ma la nebbia marina tiene freschi i rack.", "cities.italian_immigrants_vineyards_and":"Immigrati italiani, vigneti e fabbriche. I tuoi rack dividono le colline con la vendemmia.", "cities.italy_s_digital_capital_fashion_week":"La capitale digitale d’Italia. Traffico da fashion week, un NOC a base di espresso e più exchange di quanti te ne aspetteresti.", @@ -751,6 +753,7 @@ "cities.mountains_mines_and_more_bars_per":"Montagne, miniere e più bar per abitante che in qualsiasi altro posto del Brasile. Gli accordi di peering si firmano davanti al pane al formaggio.", "cities.mozambique_s_capital_an_hour_from":"La capitale del Mozambico, a un’ora dal Sudafrica. I suoi cavi sono il backup della costa orientale quando gli altri si rompono.", "cities.new_caledonia_a_slice_of_france":"La Nuova Caledonia, un pezzo di Francia nel Mar dei Coralli, con un cavo per Sydney e una miniera di nichel su ogni collina.", +"cities.north_queensland_s_capital_in_waiting":"La capitale in attesa del North Queensland, se il nuovo stato nascerà mai. L'unico data center a prova di ciclone dell'anello fuori da Brisbane, con l'esercito, un'università e le squadre della protezione civile come vicini.", "cities.norway_s_oil_capital_now_full":"La capitale norvegese del petrolio, ora piena di data center dentro le montagne, alimentati a idroelettrico e raffreddati dal fiordo. Qui approdano i cavi del Mare del Nord.", "cities.norway_s_southern_tip_where_cables":"La punta meridionale della Norvegia, dove approdano i cavi da Danimarca, Atlantico e resto della costa.", "cities.nova_scotia_s_capital_and_the":"La capitale della Nuova Scozia, e il grande porto nordamericano più vicino all’Europa. Da qui parte il cavo più veloce per l’Inghilterra, sulla linea più corta attraverso l’oceano, costruito per i trader che pagano ogni millisecondo.", @@ -812,6 +815,7 @@ "cities.the_harbour_the_bridge_and_most":"Il porto, il ponte e quasi tutti i data center del paese. La vera latenza è l’affitto.", "cities.the_highest_seat_of_government_on":"La sede di governo più alta del mondo, a 3.600 m. I pendolari vanno in funivia, e anche un po’ della fibra.", "cities.the_maldives_capital_a_stop_on":"La capitale delle Maldive, un metro sopra il mare e tappa dei cavi dall’India al Golfo e a Singapore.", +"cities.the_middle_of_everywhere_no_sea":"Il centro di ovunque: niente mare, niente cavo sottomarino, solo fibra lungo la strada e una vecchia stazione del telegrafo. Le grandi cupole bianche lì vicino servono di sicuro per il meteo.", "cities.the_most_isolated_big_city_on":"La grande città più isolata della Terra. L’Asia è più vicina di Sydney.", "cities.the_north_s_hub_with_its":"Lo snodo del Nord, con il suo exchange e prese d’aria dei condizionatori molto umide. I cavi per l’Irlanda e la Danimarca arrivano sulla costa poco più su.", "cities.the_northernmost_town_in_the_united":"La città più settentrionale degli Stati Uniti, raggiunta dalla prima fibra sottomarina dell’Artico americano.", @@ -1996,6 +2000,7 @@ "failures.the_sandflies_drove_your_splicing":"I pappataci hanno cacciato la tua squadra di giuntisti da {a}–{b}. Torneranno quando si alza il vento.", "failures.the_seabed_off_tonga_slid_down":"Il fondale al largo di Tonga è franato giù per un pendio e si è portato via il tuo cavo {a}–{b}. La nave di riparazione arriva dalla Papua Nuova Guinea.", "failures.the_smelter_at_tiwai_point_pulled":"La fonderia di Tiwai Point ha tirato un po’ di più dalla rete, e il tuo POP a {city} ha ceduto per primo.", +"failures.the_wet_season_washed_out_the":"La stagione delle piogge ha spazzato via la pista verso la tua fibra {a}–{b}. La squadra arriva quando l'acqua si ritira.", "failures.thieves_dug_up_your_a_b":"I ladri hanno scavato il tuo cavo {a}–{b}, convinti che fosse rame. Era fibra. L’hanno lasciato tagliato nel fosso, profondamente delusi.", "failures.traffic_rerouted_customers_barely":"Traffico reinstradato, i clienti se ne sono accorti appena.", "failures.truck_a_spare_amp_out":"Porta un amplificatore di ricambio sul posto", diff --git a/site/i18n/pt.js b/site/i18n/pt.js index 5478bed..da20e40 100644 --- a/site/i18n/pt.js +++ b/site/i18n/pt.js @@ -486,6 +486,7 @@ "cables.cuba_s_only_cable_laid_from":"O único cabo de Cuba, lançado a partir da Venezuela em 2011 e ligado dois anos depois. Fica pendurado no seu pescoço.", "cables.cura_ao_to_trinidad_along_the":"De Curaçao a Trinidad pela costa da Venezuela.", "cables.danish_for_sea_fun_probably":"Em dinamarquês quer dizer \"diversão no mar\". Provavelmente.", +"cables.darwin_to_port_hedland_past_the":"De Darwin a Port Hedland, passando pelas plataformas de gás para as quais foi lançado. Hoje o caminho do norte até Singapura.", "cables.darwin_to_singapore_via_jakarta":"De Darwin a Singapura via Jakarta. Só os pacotes mais aptos sobrevivem.", "cables.discovered_the_atlantic_again_old":"Redescobriu o Atlântico. Velho, caro e frágil.", "cables.djibouti_down_to_durban_hugging_the":"De Djibouti até Durban, colado na costa da África Oriental. Ri de piratas e de âncoras.", @@ -726,6 +727,7 @@ "cities.india_s_east_coast_landing_hub":"O hub de chegada da costa leste da Índia, com cabos para Singapura. A temporada de ciclones é coisa séria.", "cities.india_s_tech_capital_packets_move":"A capital tech da Índia. Os pacotes andam mais rápido que os carros lá fora.", "cities.inland_from_ostend_where_the_cables":"No interior a partir de Ostende, onde chegam os cabos da Inglaterra. O Mar do Norte é raso, movimentado e cheio de barcos de arrasto.", +"cities.iron_ore_red_dust_and_two":"Minério de ferro, poeira vermelha e dois cabos submarinos: no porto do Pilbara chegam a linha para Darwin e a que sai para Singapura. Quase ninguém mora aqui; quem compra a banda são as minas.", "cities.it_almost_never_rains_but_the":"Quase nunca chove, mas a neblina do mar mantém os racks fresquinhos.", "cities.italian_immigrants_vineyards_and":"Imigrantes italianos, vinhedos e fábricas. Seus racks dividem as serras com a colheita da uva.", "cities.italy_s_digital_capital_fashion_week":"A capital digital da Itália. Tráfego de fashion week, um NOC movido a espresso e mais exchanges do que você imaginaria.", @@ -751,6 +753,7 @@ "cities.mountains_mines_and_more_bars_per":"Montanhas, minas e mais bares por habitante do que em qualquer outro lugar do Brasil. Acordo de peering se fecha com pão de queijo.", "cities.mozambique_s_capital_an_hour_from":"A capital de Moçambique, a uma hora da África do Sul. Seus cabos são o reserva da costa leste quando os outros quebram.", "cities.new_caledonia_a_slice_of_france":"A Nova Caledônia, um pedaço da França no Mar de Coral, com um cabo para Sydney e uma mina de níquel em cada morro.", +"cities.north_queensland_s_capital_in_waiting":"A capital em espera do North Queensland, se o novo estado um dia sair. O único data center à prova de ciclones do anel fora de Brisbane, com o exército, uma universidade e as equipes de emergência como vizinhos.", "cities.norway_s_oil_capital_now_full":"A capital do petróleo da Noruega, agora cheia de data centers dentro de montanhas, movidos a hidrelétrica e resfriados pelo fiorde. Cabos do Mar do Norte desembarcam aqui.", "cities.norway_s_southern_tip_where_cables":"A ponta sul da Noruega, onde chegam os cabos da Dinamarca, do Atlântico e do resto da costa.", "cities.nova_scotia_s_capital_and_the":"A capital da Nova Escócia, e o grande porto norte-americano mais perto da Europa. Daqui sai o cabo mais rápido para a Inglaterra, na linha mais curta através do oceano, construído para traders que pagam por cada milissegundo.", @@ -812,6 +815,7 @@ "cities.the_harbour_the_bridge_and_most":"O porto, a ponte e quase todos os data centers do país. A latência de verdade é o aluguel.", "cities.the_highest_seat_of_government_on":"A sede de governo mais alta do planeta, a 3.600 m. O pessoal vai trabalhar de teleférico, e parte da fibra também.", "cities.the_maldives_capital_a_stop_on":"A capital das Maldivas, a um metro acima do mar e parada dos cabos da Índia para o Golfo e Singapura.", +"cities.the_middle_of_everywhere_no_sea":"O meio de todo lugar: sem mar, sem cabo submarino, só fibra pela estrada e uma velha estação de telégrafo. As grandes cúpulas brancas ali perto são, com certeza, para o tempo.", "cities.the_most_isolated_big_city_on":"A cidade grande mais isolada da Terra. A Ásia fica mais perto que Sydney.", "cities.the_north_s_hub_with_its":"O hub do Norte, com exchange próprio e entradas de ar-condicionado bem úmidas. Cabos para a Irlanda e a Dinamarca chegam pela costa.", "cities.the_northernmost_town_in_the_united":"A cidade mais ao norte dos Estados Unidos, alcançada pela primeira fibra submarina do Ártico americano.", @@ -1996,6 +2000,7 @@ "failures.the_sandflies_drove_your_splicing":"Os borrachudos expulsaram sua equipe de emenda de {a}–{b}. Ela volta quando o vento aumentar.", "failures.the_seabed_off_tonga_slid_down":"O fundo do mar perto de Tonga deslizou encosta abaixo e levou junto o seu cabo {a}–{b}. O navio de reparo está vindo de Papua-Nova Guiné.", "failures.the_smelter_at_tiwai_point_pulled":"A fundição de Tiwai Point puxou um pouco mais da rede, e seu POP em {city} piscou primeiro.", +"failures.the_wet_season_washed_out_the":"A estação das chuvas levou a estrada até a sua fibra {a}–{b}. A equipe chega quando a água baixar.", "failures.thieves_dug_up_your_a_b":"Ladrões desenterraram seu cabo {a}–{b}, certos de que era cobre. Era fibra. Deixaram tudo cortado na vala, profundamente decepcionados.", "failures.traffic_rerouted_customers_barely":"Tráfego redirecionado, os clientes mal perceberam.", "failures.truck_a_spare_amp_out":"Levar um amplificador reserva de caminhão", diff --git a/src/game/20-world/40-city-coords.js b/src/game/20-world/40-city-coords.js index 93bffa2..e965808 100644 --- a/src/game/20-world/40-city-coords.js +++ b/src/game/20-world/40-city-coords.js @@ -10,6 +10,7 @@ const CITY_LL={ "anc":[-149.9,61.22], "apw":[-171.76,-13.83], "ash":[-77.49,39.04], + "asp":[133.88,-23.7], "asu":[-57.58,-25.26], "ath":[23.73,37.98], "atn":[-84.39,33.75], @@ -172,6 +173,7 @@ const CITY_LL={ "pdl":[-25.67,37.74], "pek":[116.4,39.9], "per":[115.86,-31.95], + "phe":[118.61,-20.31], "phx":[-112.07,33.45], "pkc":[158.65,53.02], "pmo":[13.36,38.12], @@ -228,6 +230,7 @@ const CITY_LL={ "tok":[139.69,35.69], "tor":[-79.38,43.65], "tpe":[121.56, 25.03], + "tsv":[146.82,-19.26], "tun":[10.18,36.81], "uio":[-78.47,-0.18], "uus":[142.74,46.96], diff --git a/src/game/20-world/50-cities.js b/src/game/20-world/50-cities.js index 7e0fe5f..24cf468 100644 --- a/src/game/20-world/50-cities.js +++ b/src/game/20-world/50-cities.js @@ -144,7 +144,7 @@ const CITIES=[ {id:'gbe',name:'Gaborone',x:0,y:0,land:'af',reg:'AF',P:25,cc:'BW',ix:'Seswaa-IX',dc:'Diamond Dust DC',note:tr('cities.botswana_quiet_safe_and_rich_in')}, {id:'mel',name:'Melbourne',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:450,ix:'Flat-White-IX',dc:'Four-Seasons-a-Day DC',dc2:'Next-Door-DC M#',dc2N:3,note:tr('cities.four_seasons_in_one_day_and')}, {id:'bne',name:'Brisbane',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:250,ix:'Bris-Vegas-IX',dc:'Sunshine State Shed',dc2:'Next-Door-DC B#',dc2N:2,note:tr('cities.brisvegas_big_sky_a_thunderstorm_at')}, - {id:'drw',name:'Darwin',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:15,ix:'Gator-IX',dc:'Crocodile-proof Landing Station',note:tr('cities.tiny_tropical_and_the_closest')}, + {id:'drw',name:'Darwin',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,wet:true,arpu:AU_ARPU,P:15,ix:'Gator-IX',dc:'Crocodile-proof Landing Station',note:tr('cities.tiny_tropical_and_the_closest')}, {id:'adl',name:'Adelaide',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:150,ix:'Vineyard-IX',dc:'OurDC',dc2:'Next-Door-DC A1',note:tr('cities.twenty_minutes_from_everything')}, {id:'cbr',capital:true,name:'Canberra',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:50,ix:'Capital-IX',dc:'Classified Data Cupboard',dc2:'Next-Door-DC C1',note:tr('cities.built_for_the_government_the_data')}, {id:'chc',name:'Christchurch',x:0,y:0,land:'nzs',reg:'OC',cc:'NZ',P:40,ix:'Garden-City-IX',dc:'Mainland Colo',note:tr('cities.the_garden_city_and_the_biggest')}, @@ -243,6 +243,9 @@ const CITIES=[ // The Philippines beyond Luzon {id:'ceb',name:'Cebu',x:0,y:0,land:'ceb',reg:'AS',cc:'PH',ph:true,arpu:PH_ARPU,P:125,ix:'GotchaFIX Cebu',ixCheap:1.8,dc:"Magellan's Last Rack",note:tr('cities.the_philippines_second_city_reached')}, {id:'dvo',name:'Davao',x:0,y:0,land:'mdn',reg:'AS',cc:'PH',ph:true,arpu:PH_ARPU,P:135,ix:'GotchaFIX Davao',ixCheap:1.8,dc:"Heimdall's Hut",note:tr('cities.mindanao_s_big_city_and_the')}, + {id:'phe',name:'Port Hedland',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,wet:true,arpu:AU_ARPU,P:2,ix:'',dc:'Next-Door-DC PH1',note:tr('cities.iron_ore_red_dust_and_two')}, + {id:'tsv',name:'Townsville',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,wet:true,arpu:AU_ARPU,P:20,ix:'',dc:'DigiCroc TSV1',note:tr('cities.north_queensland_s_capital_in_waiting')}, + {id:'asp',name:'Alice Springs',x:0,y:0,land:'oc',reg:'OC',cc:'AU',au:true,arpu:AU_ARPU,P:3,ix:'',dc:'Old Telegraph Station',note:tr('cities.the_middle_of_everywhere_no_sea')}, ]; // Display-only nudges for cities that sit on top of each other at map scale; distances still use real lon/lat. const CITY_NUDGE={ diff --git a/src/game/20-world/55-city-pdb.js b/src/game/20-world/55-city-pdb.js index 02b7f38..79fe1d8 100644 --- a/src/game/20-world/55-city-pdb.js +++ b/src/game/20-world/55-city-pdb.js @@ -15,6 +15,7 @@ const CITY_PDB={ anc:[3,12,33300], // est. apw:[0,0,11], ash:[86,1010,33300], + asp:[0,0,3196], // est.: no carrier-neutral facility, the incumbent's exchange asu:[3,8,124], ath:[6,108,307], atn:[42,589,33300], @@ -177,6 +178,7 @@ const CITY_PDB={ pdl:[1,3,187], // est. pek:[10,15,6717], per:[12,248,3196], + phe:[1,3,3196], // est.: one carrier-neutral facility phx:[26,279,33300], pkc:[1,2,6683], // est. pmo:[3,46,1534], @@ -233,6 +235,7 @@ const CITY_PDB={ tok:[58,917,1330], tor:[46,509,2595], tpe:[15,274,500], + tsv:[1,2,3196], // est. tun:[2,0,30], uio:[9,16,287], uus:[1,3,6683], // est. diff --git a/src/game/20-world/60-cables.js b/src/game/20-world/60-cables.js index 294fa31..58c1cd5 100644 --- a/src/game/20-world/60-cables.js +++ b/src/game/20-world/60-cables.js @@ -62,7 +62,8 @@ const CABLES=[ {"id":"tse","name":"Strait Outta Taipei","price":1.5,"age":"old","blurb":tr('cables.a_short_cable_across_a_very'),"pairs":[["tpe","sha",[[122.2,26.5],[122.6,29],[122.2,31]]]]}, {"id":"gbi","name":"Gulf Bridge Over Troubled Water","price":1.0,"age":"mid","blurb":tr('cables.leaves_the_gulf_from_fujairah_and'),"pairs":[["fuj","mrs",[[56.5,25],[56.75,25],[57,25],[58,24.5],[59,24],[59.75,23.25],[60.5,22.5],[60.24,22.11],[59.99,21.72],[59.74,21.34],[59.49,20.95],[59.24,20.56],[58.99,20.17],[58.74,19.78],[58.5,19.39],[58.25,19],[57.5,18.25],[57.08,17.96],[56.66,17.67],[56.24,17.38],[55.83,17.09],[55.41,16.79],[55,16.5],[54.55,16.28],[54.09,16.06],[53.64,15.83],[53.19,15.61],[52.74,15.39],[52.29,15.16],[51.84,14.93],[51.39,14.71],[50.95,14.48],[50.5,14.25],[49.5,13.88],[48.5,13.5],[47.5,13.13],[46.5,12.75],[45.5,12.38],[44.5,12],[44,12],[43.75,12.25],[43.5,12.5],[43.25,12.75],[43.25,13],[43.25,13.25],[43,13.5],[42.75,13.75],[42.5,14],[42.26,14.43],[42.02,14.86],[41.78,15.3],[41.54,15.73],[41.3,16.16],[41.05,16.59],[40.81,17.02],[40.56,17.45],[40.31,17.88],[40.06,18.31],[39.82,18.74],[39.56,19.17],[39.31,19.6],[39.06,20.03],[38.8,20.46],[38.55,20.88],[38.29,21.31],[38.03,21.74],[37.77,22.17],[37.51,22.59],[37.24,23.02],[36.98,23.44],[36.71,23.87],[36.44,24.29],[36.17,24.72],[35.89,25.14],[35.62,25.56],[35.34,25.99],[35.06,26.41],[34.78,26.83],[34.5,27.25],[34.25,27.5],[34,27.75],[33.75,28],[33.5,28.25],[33.25,28.5],[33,28.75],[33,29],[32.75,29.25],[32.5,29.5],[32.5,29.75],[32.5,30.5],[32.5,31.25],[32.25,31.5],[32,31.75],[31.6,32.11],[31.2,32.47],[30.8,32.83],[30.39,33.19],[29.98,33.55],[29.56,33.9],[29.14,34.25],[28.72,34.61],[28.3,34.96],[27.87,35.31],[27.44,35.65],[27,36],[26.43,36.01],[25.86,36.01],[25.29,36.02],[24.71,36.02],[24.14,36.01],[23.57,36.01],[23,36],[22,36],[21.42,36.02],[20.83,36.03],[20.25,36.04],[19.67,36.05],[19.08,36.05],[18.5,36.05],[17.92,36.05],[17.33,36.05],[16.75,36.04],[16.17,36.03],[15.58,36.02],[15,36],[14.07,36.36],[13.14,36.71],[12.21,37.07],[11.29,37.43],[10.36,37.79],[9.43,38.14],[8.5,38.5],[7.75,39.25],[7.45,39.69],[7.15,40.13],[6.84,40.57],[6.53,41.01],[6.22,41.44],[5.9,41.88],[5.58,42.32],[5.25,42.75],[5.25,43],[5.25,43.25]]]]}, {"id":"aagony","name":"AAG-ony","price":1.1,"age":"old","blurb":tr('cables.an_asia_america_gateway_cable_that'),"pairs":[["sgn","hkg",[[108,10],[109.75,11.5]]],["sgn","sin",[[106,7],[104.6,3]]]]}, - {"id":"darwin","name":"Darwin Award Cable","price":1.0,"age":"new","blurb":tr('cables.darwin_to_singapore_via_jakarta'),"pairs":[["drw","jkt",[[117,-10],[114.25,-7.25],[111.75,-6],[107.5,-5.5]]],["drw","sin",[[117,-10]]]]}, + {"id":"darwin","name":"Darwin Award Cable","price":1.0,"age":"new","blurb":tr('cables.darwin_to_singapore_via_jakarta'),"pairs":[["drw","jkt",[[117,-10],[114.25,-7.25],[111.75,-6],[107.5,-5.5]]],["drw","sin",[[117,-10]]],["phe","sin",[[118.25,-19.5],[117,-10]]]]}, + {"id":"nwcs","name":"No Worries Cable System","price":1.0,"age":"mid","blurb":tr('cables.darwin_to_port_hedland_past_the'),"pairs":[["drw","phe",[[130.25,-12],[128,-12.75],[124.5,-14.25],[121.5,-17.25],[119,-19.5]]]]}, {"id":"jga","name":"J-G’day-A (Japan–Guam–Aussie)","price":0.9,"age":"new","blurb":tr('cables.brisbane_to_tokyo_with_a_beach'),"pairs":[["bne","tok",[[155,-25],[156,-5],[146,13],[141,30]]],["bne","gum",[[155,-25],[156,-5],[146,12.8]]],["gum","tok",[[145.3,14.5],[141,30]]]]}, {"id":"smw4","name":"SEE-ME-WAVE 4","price":1.2,"age":"old","blurb":tr('cables.the_previous_generation_still'),"pairs":[["khi","mrs",[[66.75,24.75],[66.5,24.75],[65.54,24.06],[64.58,23.38],[63.63,22.69],[62.67,22],[61.71,21.31],[60.75,20.63],[59.79,19.94],[58.83,19.25],[57.88,18.56],[56.92,17.88],[55.96,17.19],[55,16.5],[54.55,16.28],[54.09,16.06],[53.64,15.83],[53.19,15.61],[52.74,15.39],[52.29,15.16],[51.84,14.93],[51.39,14.71],[50.95,14.48],[50.5,14.25],[49.5,13.88],[48.5,13.5],[47.5,13.13],[46.5,12.75],[45.5,12.38],[44.5,12],[44,12],[43.75,12.25],[43.5,12.5],[43.25,12.75],[43.25,13],[43.25,13.25],[43,13.5],[42.75,13.75],[42.5,14],[42.26,14.43],[42.02,14.86],[41.78,15.3],[41.54,15.73],[41.3,16.16],[41.05,16.59],[40.81,17.02],[40.56,17.45],[40.31,17.88],[40.06,18.31],[39.82,18.74],[39.56,19.17],[39.31,19.6],[39.06,20.03],[38.8,20.46],[38.55,20.88],[38.29,21.31],[38.03,21.74],[37.77,22.17],[37.51,22.59],[37.24,23.02],[36.98,23.44],[36.71,23.87],[36.44,24.29],[36.17,24.72],[35.89,25.14],[35.62,25.56],[35.34,25.99],[35.06,26.41],[34.78,26.83],[34.5,27.25],[34.25,27.5],[34,27.75],[33.75,28],[33.5,28.25],[33.25,28.5],[33,28.75],[33,29],[32.75,29.25],[32.5,29.5],[32.5,29.75],[32.5,30.5],[32.5,31.25],[32.25,31.5],[32,31.75],[31.6,32.11],[31.2,32.47],[30.8,32.83],[30.39,33.19],[29.98,33.55],[29.56,33.9],[29.14,34.25],[28.72,34.61],[28.3,34.96],[27.87,35.31],[27.44,35.65],[27,36],[26.43,36.01],[25.86,36.01],[25.29,36.02],[24.71,36.02],[24.14,36.01],[23.57,36.01],[23,36],[22,36],[21.42,36.02],[20.83,36.03],[20.25,36.04],[19.67,36.05],[19.08,36.05],[18.5,36.05],[17.92,36.05],[17.33,36.05],[16.75,36.04],[16.17,36.03],[15.58,36.02],[15,36],[14.07,36.36],[13.14,36.71],[12.21,37.07],[11.29,37.43],[10.36,37.79],[9.43,38.14],[8.5,38.5],[7.75,39.25],[7.45,39.69],[7.15,40.13],[6.84,40.57],[6.53,41.01],[6.22,41.44],[5.9,41.88],[5.58,42.32],[5.25,42.75],[5.25,43],[5.25,43.25]]],["khi","bom",[[67,23],[70,20.5]]],["bom","cbo",[[72,15],[75,8],[78.5,6.3]]],["cbo","maa",[[80.6,8.6],[81,11.5]]],["maa","dac",[[89.5,21.5]]],["dac","sin",[[91.5,22.75],[91.25,22],[93.75,16.5],[97.75,12.5],[97.75,8.25],[100.5,3.5],[102.75,1.25]]],["mrs","pmo",[[5.25,42.75],[9,38.25]]],["pmo","cai",[[12,38],[13.25,36.75],[29.5,31.5]]],["cai","jed",[[32.5,29.75],[33,28.75]]],["jed","fuj",[[39,21.5],[38.75,21.25],[38.75,21],[38.99,20.56],[39.24,20.13],[39.48,19.69],[39.72,19.26],[39.95,18.82],[40.19,18.38],[40.43,17.95],[40.66,17.51],[40.89,17.07],[41.13,16.63],[41.36,16.19],[41.59,15.76],[41.82,15.32],[42.05,14.88],[42.27,14.44],[42.5,14],[42.75,13.75],[43,13.5],[43.25,13.25],[43.25,13],[43.25,12.75],[43.5,12.5],[43.75,12.25],[44,12],[44.5,12],[45.5,12.38],[46.5,12.75],[47.5,13.13],[48.5,13.5],[49.5,13.88],[50.5,14.25],[50.95,14.48],[51.39,14.71],[51.84,14.93],[52.29,15.16],[52.74,15.39],[53.19,15.61],[53.64,15.83],[54.09,16.06],[54.55,16.28],[55,16.5],[55.41,16.79],[55.83,17.09],[56.24,17.38],[56.66,17.67],[57.08,17.96],[57.5,18.25],[58.25,19],[58.5,19.39],[58.74,19.78],[58.99,20.17],[59.24,20.56],[59.49,20.95],[59.74,21.34],[59.99,21.72],[60.24,22.11],[60.5,22.5],[59.75,23.25],[59,24],[58,24.5],[57,25],[56.75,25],[56.5,25]]],["fuj","khi",[[62.5,24.5]]]]}, {"id":"balt","anchor":true,"name":"Baltic Anchor Magnet","price":0.8,"age":"mid","blurb":tr('cables.short_hops_under_the_baltic_sea'),"pairs":[["tll","hel",[[24.8,59.8]]],["tll","sto",[[22,59.3],[19.5,59.3]]]]}, diff --git a/src/game/30-networks/10-networks.js b/src/game/30-networks/10-networks.js index bf6682d..e8ac20a 100644 --- a/src/game/30-networks/10-networks.js +++ b/src/game/30-networks/10-networks.js @@ -43,7 +43,7 @@ NETS.push( {id:'dto',name:'Ditto',asn:139831,type:'eye',cc:'PH',pol:'open',up:['ntt','tat'],share:.002,col:'#B5121B',pops:['mnl'],ix:['mnl','mnl~2'],blurb:tr('networks.the_third_mobile_network_same_towers')}, {id:'rsh',name:'RISE & Shine',asn:63927,type:'eye',cc:'PH',pol:'open',up:['ntt','tat'],share:.002,col:'#F5A623',pops:['mnl','ceb','dvo','sin','hkg','fra','ams','lon','sto'],ix:['mnl','mnl~2','mnl~3','ceb','dvo','sin','sin~2','hkg','hkg~2','fra','ams','lon','sto'],blurb:tr('networks.up_early_in_cebu_and_already')}, {id:'spk',name:'Spark-le',asn:4771,type:'eye',cc:'NZ',pol:'open',share:.005,col:'#6A2C91',pops:['akl','syd','chc','ivc'],ix:['akl','syd','chc'],blurb:tr('networks.new_zealand_s_shiniest_isp')}, - {id:'tsy',name:'Telstraya',asn:1221,type:'t2',cc:'AU',pol:'selective',minIx:15,minPni:40,share:.01,price:9,col:'#0099F8',pops:['hnl','gum','suv','pom','nou','hir','syd','per','sin','hkg','lax','tpe','mel','bne','drw','adl','cbr','hba'],ix:['gum','sin','hkg'],blurb:tr('networks.australia_s_big_one_g_day')}); + {id:'tsy',name:'Telstraya',asn:1221,type:'t2',cc:'AU',pol:'selective',minIx:15,minPni:40,share:.01,price:9,col:'#0099F8',pops:['hnl','gum','suv','pom','nou','hir','syd','per','sin','hkg','lax','tpe','mel','bne','drw','adl','cbr','hba','phe','tsv','asp'],ix:['gum','sin','hkg'],blurb:tr('networks.australia_s_big_one_g_day')}); NETS.push( {id:'liq',name:'Liquid Lunch Networks',asn:30846,type:'t2',cc:['ZW'],pol:'open',up:['tat','tly'],share:.006,price:6,col:'#00A0DF',pops:['jnb','cpt','dur','hre','lun','gbe','mpm','dar','nbo','mba','kla','kgl','fih','add','jib','cai','wdh'],ix:['jnb','cpt','dur','hre','lun','gbe','mpm','dar','nbo','mba','kla','kgl','fih','add','jib','cai','wdh'],blurb:tr('networks.cape_to_cairo_fiber_across_a')}, {id:'scm',name:'Sea-Comedy Networks',asn:37102,type:'t2',pol:'open',up:['ntt','tat'],share:.005,price:5,col:'#1C3F94',pops:['jnb','cpt','dur','mpm','dar','mba','nbo','kla','kgl','jib','cai','mrs','bom','lon'],ix:['jnb','cpt','dur','mpm','dar','mba','nbo','kla','jib','mrs'],blurb:tr('networks.owns_the_cable_that_brought_east')}, @@ -74,8 +74,8 @@ NETS.push( {id:'kdi',name:'KD-DIY',asn:2561,type:'t2',cc:'JP',pol:'selective',minIx:10,minPni:30,share:.008,price:6,col:'#E85D04',pops:['tok','osa','lax','sin','hkg','fuk'],ix:['tok','osa','fuk'],blurb:tr('networks.japanese_carrier_that_builds')}, {id:'opt',name:'Floptus',asn:4804,type:'eye',cc:'AU',pol:'selective',minIx:8,minPni:25,share:.006,up:['sgt'],col:'#00837E',pops:['syd','mel','bne','per'],ix:[],blurb:tr('networks.australia_s_number_two_once_took')}, {id:'tpr',name:'Toilet Paper Group',asn:7545,type:'eye',cc:'AU',pol:'selective',minIx:8,minPni:25,share:.0035,col:'#4E2A84',pops:['syd','mel','bne','per','adl','cbr'],ix:[],blurb:tr('networks.stockpiled_bandwidth_in_2020_and')}, - {id:'abb',name:'Aussie Boyband',asn:4764,type:'eye',cc:'AU',pol:'open',share:.002,col:'#00B140',pops:['syd','mel','bne','per','adl','cbr','drw','hba'],ix:['syd','mel','bne','per','adl','drw'],blurb:tr('networks.matching_outfits_perfect_harmonies')}, - {id:'voc',name:'Hocus Pocus',asn:4826,type:'t2',pol:'open',up:['ntt','tly'],share:.002,price:7,col:'#E4002B',pops:['syd','mel','bne','per','adl','cbr','drw','hba','sin'],ix:['syd','mel','bne','per','adl','hba','drw','sin'],blurb:tr('networks.now_you_see_the_fibre_now')}, + {id:'abb',name:'Aussie Boyband',asn:4764,type:'eye',cc:'AU',pol:'open',share:.002,col:'#00B140',pops:['syd','mel','bne','per','adl','cbr','drw','hba','tsv'],ix:['syd','mel','bne','per','adl','drw'],blurb:tr('networks.matching_outfits_perfect_harmonies')}, + {id:'voc',name:'Hocus Pocus',asn:4826,type:'t2',pol:'open',up:['ntt','tly'],share:.002,price:7,col:'#E4002B',pops:['syd','mel','bne','per','adl','cbr','drw','hba','sin','phe','tsv'],ix:['syd','mel','bne','per','adl','hba','drw','sin'],blurb:tr('networks.now_you_see_the_fibre_now')}, {id:'ddo',name:'Doodoo',asn:9443,type:'eye',cc:'AU',pol:'open',up:['voc'],share:.0011,col:'#FFC20E',pops:['syd','mel','bne','per','adl'],ix:[],blurb:tr('networks.the_cheapest_plan_in_the_country')}, {id:'stb',name:'Musklink',asn:14593,type:'eye',cc:'US',pol:'selective',minIx:3,minPni:10,share:.001,col:'#1B1F24',pops:['syd','mel','bne','per','drw','sea','lax','dal','chi','ash'],ix:['mel','bne','per','drw'],blurb:tr('networks.beams_the_outback_online_from_550')}, {id:'spl',name:'Speedyloop',asn:38195,type:'t2',cc:'AU',pol:'open',up:['tly'],share:.001,price:6,col:'#FF5F00',pops:['syd','mel','bne','per','adl','sin','hkg','cbr','drw'],ix:['mel','bne','per','adl','hba','drw','sin','hkg'],blurb:tr('networks.speedy_by_name_owns_a_slice')}, diff --git a/src/game/60-features/50-traceroute.js b/src/game/60-features/50-traceroute.js index ce195c1..cb35437 100644 --- a/src/game/60-features/50-traceroute.js +++ b/src/game/60-features/50-traceroute.js @@ -40,7 +40,7 @@ function traceroute(src,to){const P=trPaths(src),me=slug(S.name)+'.net',lines=[] else if(e.k==='p'){hop(`pni-${slug(NET[e.via||N.id].name)}.${e.city}.${me}`,ip(hstr(N.id),3),0.2,tr('traceroute.private_cross_connect'));} // Down the cone one customer at a time: the shortest chain of upstreams from the peer to the network, each AS on the path. if(e.via){const ch=coneChain(e.via,N.id);for(let i=0;iS.day?35:20}):''; diff --git a/src/game/85-incidents/20-failures.js b/src/game/85-incidents/20-failures.js index 542aa84..df141aa 100644 --- a/src/game/85-incidents/20-failures.js +++ b/src/game/85-incidents/20-failures.js @@ -1,5 +1,7 @@ // Anchors Away (Baltic): a link on an anchor-prone cable, or on a pair one serves (the map calls those overland). const anchorProne=l=>!!(l.cable&&CAB[l.cable]&&CAB[l.cable].anchor)||anchorPair(l); +// The wet season in the tropical north (November to April): floods close the tracks, so a cut on land takes twice as long to reach. +const wetSeason=()=>{const m=cal(S.day).m;return m>=10||m<=3;},wetCut=l=>!l.sub&&!!(CITY[l.a].wet||CITY[l.b].wet)&&wetSeason(); function fireFailure(only){ const opts=[]; const live=S.links.filter(l=>l.kind!=='vxc'&&!linkDown(l));const fabsUsed=[...new Set(S.links.filter(l=>l.kind==='vxc').map(l=>l.prov))]; @@ -81,9 +83,9 @@ function fireFailure(only){ addInc({type,ref:l.id,until:S.day+dur,msg:pick([tr('failures.a_optic_on_a_b_overheated',{optic:OPT[o].n,a:A,b:B}),tr('failures.the_laser_in_a_optic_on',{optic:OPT[o].n,a:A,b:B}),tr('failures.a_optic_on_a_b_started',{optic:OPT[o].n,a:A,b:B})])+(l.spares?' '+tr('failures.swapped_from_your_spares_kit_by'):''),cost:l.spares?0:OPT[o].cost,fix:tr('failures.buy_a_replacement')}); }else if(type==='cut'){ const mon=cal(S.day).m,monsoon=mon>=5&&mon<=8,tw=x=>(x.sub&&(x.a==='tpe'||x.b==='tpe'||(x.cable&&CAB[x.cable].anchor)))||(scnRule('anchors')&&anchorProne(x)),vn=x=>x.sub&&(x.a==='sgn'||x.b==='sgn'),inl=x=>!x.sub&&(CITY[x.a].india||CITY[x.b].india); - const pool=only&&scnRule('anchors')?live.filter(anchorProne):live;if(!pool.length)return;const l=pick(pool.flatMap(x=>{const w=(x.cable&&CAB[x.cable].age==='old'?3:1)*(x.cable&&CAB[x.cable].fragile?3:1)*(tw(x)?4*(scnRule('anchors')?3:1):1)*(scnRule('sharks')&&x.sub?2:1)*(vn(x)?3:1)*(!x.sub&&andesPair(x.a,x.b)?4:1)*(monsoon&&inl(x)?3:1)*(x.sub&&(x.a==='oos'||x.b==='oos')?3:1);return Array(w).fill(x);})),dur=10+Math.floor(Math.random()*8),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc);hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur)); + const pool=only&&scnRule('anchors')?live.filter(anchorProne):live;if(!pool.length)return;const l=pick(pool.flatMap(x=>{const w=(x.cable&&CAB[x.cable].age==='old'?3:1)*(x.cable&&CAB[x.cable].fragile?3:1)*(tw(x)?4*(scnRule('anchors')?3:1):1)*(scnRule('sharks')&&x.sub?2:1)*(vn(x)?3:1)*(!x.sub&&andesPair(x.a,x.b)?4:1)*(monsoon&&inl(x)?3:1)*(x.sub&&(x.a==='oos'||x.b==='oos')?3:1);return Array(w).fill(x);})),dur=(10+Math.floor(Math.random()*8))*(wetCut(l)?2:1),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc);hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur)); const A=CITY[l.a].name,B=CITY[l.b].name,au=CITY[l.a].au&&CITY[l.b].au,auSummer=mon>=11||mon<=1; - const en=l.sub&&(CITY[l.a].au||CITY[l.b].au)&&!(l.cable&&CAB[l.cable].fragile)&&Math.random()<0.35?pick([N_('failures.box_jellyfish_season_at_the_a'),N_('failures.a_great_white_took_an_interest')]):l.cable&&CAB[l.cable].fragile&&Math.random()<0.8?pick([N_('failures.your_a_b_cable_is_cut'),N_('failures.a_b_is_down_same_cable')]):!l.sub&&CITY[l.a].land==='nzs'&&CITY[l.b].land==='nzs'&&Math.random()<0.75?pick([N_('failures.a_kea_pulled_the_rubber_seals'),N_('failures.the_sandflies_drove_your_splicing'),N_('failures.a_farmer_s_post_hole_digger')]):l.cable==='cook'&&Math.random()<0.6?N_('failures.a_ferry_dropped_anchor_in_cook'):!l.sub&&au&&Math.random()<0.75?pick([N_('failures.a_sulphur_crested_cockatoo_chewed'),N_('failures.a_kangaroo_hit_the_fiber_hut'),N_('failures.thieves_dug_up_your_a_b'),N_('failures.a_kilometre_of_copper_went_missing'),N_('failures.a_backhoe_putting_in_a_new'),N_('failures.the_emus_won_again_a_mob'),N_('failures.a_kangaroo_boxed_your_field_tech'),N_('failures.a_drop_bear_fell_on_the'),N_('failures.an_eastern_brown_snake_moved_into'),...((S.day%365)/30.42>=8&&(S.day%365)/30.42<11?[N_('failures.magpie_swooping_season_the_field')]:[]),...(auSummer?[N_('failures.bushfire_season_the_fiber_along_a')]:[]),...(nullPair(l.a,l.b)?[N_('failures.your_a_b_fiber_broke_somewhere')]:[])]):l.sub&&(l.a==='bda'||l.b==='bda')&&Math.random()<0.7?pick([N_('failures.your_a_b_cable_went_quiet'),N_('failures.the_repair_ship_s_compass_spun')]):l.sub&&(l.a==='tbu'||l.b==='tbu')&&Math.random()<0.7?pick([N_('failures.an_undersea_volcano_erupted_next_to'),N_('failures.the_seabed_off_tonga_slid_down')]):vn(l)&&Math.random()<0.8?pick([N_('failures.another_of_vietnam_s_subsea_cables'),N_('failures.your_a_b_cable_broke_in')]):!l.sub&&(l.a==='drw'||l.b==='drw')&&Math.random()<0.7?pick([N_('failures.a_crocodile_took_a_bite_out'),N_('failures.termites_ate_the_duct_on_a')]):tw(l)&&Math.random()<0.8?pick([N_('failures.a_cargo_ship_forgot_to_raise'),N_('failures.another_anchor_another_cut_your_a'),N_('failures.a_fishing_boat_with_an_unusually')]):l.sub&&(l.a==='oos'||l.b==='oos')&&Math.random()<0.8?pick([N_('failures.a_trawler_off_ostend_dragged_its'),N_('failures.a_wind_farm_service_vessel_dropped')]):!l.sub&&(CITY[l.a].ca||CITY[l.b].ca)&&Math.random()<0.4?pick([N_('failures.a_beaver_chewed_through_your_a'),N_('failures.your_a_b_fiber_is_down'),N_('failures.frost_heave_cracked_the_duct_on')]):!l.sub&&andesPair(l.a,l.b)?pick([N_('failures.a_landslide_in_the_andes_buried'),N_('failures.snow_closed_the_mountain_pass_and'),N_('failures.an_earthquake_shook_your_a_b'),N_('failures.a_llama_herd_trampled_the_fiber')]):!l.sub&&(CITY[l.a].india||CITY[l.b].india)?pick([N_('failures.road_widening_near_a_cut_your'),N_('failures.the_monsoon_flooded_a_manhole_on'),N_('failures.a_digger_found_your_a_b')]):l.sub?pick([N_('failures.a_curious_shark_bit_your_subsea'),N_('failures.a_ship_dragged_its_anchor_across'),N_('failures.an_undersea_landslide_snapped_a_b')]):pick([N_('failures.a_backhoe_found_your_fiber_between'),N_('failures.squirrels_chewed_through_a_b_they'),N_('failures.road_works_cut_a_b_nobody')]); + const en=wetCut(l)?N_('failures.the_wet_season_washed_out_the'):l.sub&&(CITY[l.a].au||CITY[l.b].au)&&!(l.cable&&CAB[l.cable].fragile)&&Math.random()<0.35?pick([N_('failures.box_jellyfish_season_at_the_a'),N_('failures.a_great_white_took_an_interest')]):l.cable&&CAB[l.cable].fragile&&Math.random()<0.8?pick([N_('failures.your_a_b_cable_is_cut'),N_('failures.a_b_is_down_same_cable')]):!l.sub&&CITY[l.a].land==='nzs'&&CITY[l.b].land==='nzs'&&Math.random()<0.75?pick([N_('failures.a_kea_pulled_the_rubber_seals'),N_('failures.the_sandflies_drove_your_splicing'),N_('failures.a_farmer_s_post_hole_digger')]):l.cable==='cook'&&Math.random()<0.6?N_('failures.a_ferry_dropped_anchor_in_cook'):!l.sub&&au&&Math.random()<0.75?pick([N_('failures.a_sulphur_crested_cockatoo_chewed'),N_('failures.a_kangaroo_hit_the_fiber_hut'),N_('failures.thieves_dug_up_your_a_b'),N_('failures.a_kilometre_of_copper_went_missing'),N_('failures.a_backhoe_putting_in_a_new'),N_('failures.the_emus_won_again_a_mob'),N_('failures.a_kangaroo_boxed_your_field_tech'),N_('failures.a_drop_bear_fell_on_the'),N_('failures.an_eastern_brown_snake_moved_into'),...((S.day%365)/30.42>=8&&(S.day%365)/30.42<11?[N_('failures.magpie_swooping_season_the_field')]:[]),...(auSummer?[N_('failures.bushfire_season_the_fiber_along_a')]:[]),...(nullPair(l.a,l.b)?[N_('failures.your_a_b_fiber_broke_somewhere')]:[])]):l.sub&&(l.a==='bda'||l.b==='bda')&&Math.random()<0.7?pick([N_('failures.your_a_b_cable_went_quiet'),N_('failures.the_repair_ship_s_compass_spun')]):l.sub&&(l.a==='tbu'||l.b==='tbu')&&Math.random()<0.7?pick([N_('failures.an_undersea_volcano_erupted_next_to'),N_('failures.the_seabed_off_tonga_slid_down')]):vn(l)&&Math.random()<0.8?pick([N_('failures.another_of_vietnam_s_subsea_cables'),N_('failures.your_a_b_cable_broke_in')]):!l.sub&&(l.a==='drw'||l.b==='drw')&&Math.random()<0.7?pick([N_('failures.a_crocodile_took_a_bite_out'),N_('failures.termites_ate_the_duct_on_a')]):tw(l)&&Math.random()<0.8?pick([N_('failures.a_cargo_ship_forgot_to_raise'),N_('failures.another_anchor_another_cut_your_a'),N_('failures.a_fishing_boat_with_an_unusually')]):l.sub&&(l.a==='oos'||l.b==='oos')&&Math.random()<0.8?pick([N_('failures.a_trawler_off_ostend_dragged_its'),N_('failures.a_wind_farm_service_vessel_dropped')]):!l.sub&&(CITY[l.a].ca||CITY[l.b].ca)&&Math.random()<0.4?pick([N_('failures.a_beaver_chewed_through_your_a'),N_('failures.your_a_b_fiber_is_down'),N_('failures.frost_heave_cracked_the_duct_on')]):!l.sub&&andesPair(l.a,l.b)?pick([N_('failures.a_landslide_in_the_andes_buried'),N_('failures.snow_closed_the_mountain_pass_and'),N_('failures.an_earthquake_shook_your_a_b'),N_('failures.a_llama_herd_trampled_the_fiber')]):!l.sub&&(CITY[l.a].india||CITY[l.b].india)?pick([N_('failures.road_widening_near_a_cut_your'),N_('failures.the_monsoon_flooded_a_manhole_on'),N_('failures.a_digger_found_your_a_b')]):l.sub?pick([N_('failures.a_curious_shark_bit_your_subsea'),N_('failures.a_ship_dragged_its_anchor_across'),N_('failures.an_undersea_landslide_snapped_a_b')]):pick([N_('failures.a_backhoe_found_your_fiber_between'),N_('failures.squirrels_chewed_through_a_b_they'),N_('failures.road_works_cut_a_b_nobody')]); addInc({type,ref:trc,until:S.day+dur,msg:tr(en,{a:A,b:B})+(hit.length>1?' '+tr('failures.all_n_links_in_that_trench',{n:hit.length}):''),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))},en); // At sea a cable ship sails out to it (50-cable-ships.js): it sets how long the cut lasts and what a charter costs. // Without ships (Best Effort) a sea cut mends on the same clock as one on land. diff --git a/src/i18n/en.js b/src/i18n/en.js index beef4d8..8d691b0 100644 --- a/src/i18n/en.js +++ b/src/i18n/en.js @@ -487,6 +487,7 @@ "cables.cuba_s_only_cable_laid_from":"Cuba’s only cable, laid from Venezuela in 2011 and switched on two years later. Hangs around your neck.", "cables.cura_ao_to_trinidad_along_the":"Curaçao to Trinidad along the coast of Venezuela.", "cables.danish_for_sea_fun_probably":"Danish for “sea fun”. Probably.", +"cables.darwin_to_port_hedland_past_the":"Darwin to Port Hedland, past the gas rigs it was laid for. Now the north's way round to Singapore.", "cables.darwin_to_singapore_via_jakarta":"Darwin to Singapore via Jakarta. Survival of the fittest packets.", "cables.discovered_the_atlantic_again_old":"Discovered the Atlantic again. Old, pricey and fragile.", "cables.djibouti_down_to_durban_hugging_the":"Djibouti down to Durban, hugging the East African coast. Laughs at pirates and anchors.", @@ -727,6 +728,7 @@ "cities.india_s_east_coast_landing_hub":"India’s east-coast landing hub, with cables to Singapore. Cyclone season is a thing.", "cities.india_s_tech_capital_packets_move":"India’s tech capital. Packets move faster than the cars outside.", "cities.inland_from_ostend_where_the_cables":"Inland from Ostend, where the cables from England come ashore. The North Sea is shallow, busy and full of trawlers.", +"cities.iron_ore_red_dust_and_two":"Iron ore, red dust and two subsea cables: the Pilbara's port lands the line up to Darwin and the one out to Singapore. Hardly anyone lives here; the mines buy the bandwidth.", "cities.it_almost_never_rains_but_the":"It almost never rains, but the sea fog keeps the racks cool.", "cities.italian_immigrants_vineyards_and":"Italian immigrants, vineyards and factories. Your racks share the hills with the grape harvest.", "cities.italy_s_digital_capital_fashion_week":"Italy’s digital capital. Fashion-week traffic, an espresso-powered NOC and more exchanges than you would expect.", @@ -752,6 +754,7 @@ "cities.mountains_mines_and_more_bars_per":"Mountains, mines and more bars per head than anywhere else in Brazil. Peering deals get signed over cheese bread.", "cities.mozambique_s_capital_an_hour_from":"Mozambique’s capital, an hour from South Africa. Its cables are the east coast’s backup when the others break.", "cities.new_caledonia_a_slice_of_france":"New Caledonia, a slice of France in the Coral Sea, with a cable to Sydney and a nickel mine on every hill.", +"cities.north_queensland_s_capital_in_waiting":"North Queensland's capital in waiting, if the new state ever happens. The one cyclone-proof data centre on the ring outside Brisbane, with the army, a university and the disaster crews as neighbours.", "cities.norway_s_oil_capital_now_full":"Norway’s oil capital, now full of data centers inside mountains, run on hydro and cooled by the fjord. North Sea cables land here.", "cities.norway_s_southern_tip_where_cables":"Norway’s southern tip, where cables from Denmark, the Atlantic and the rest of the coast come ashore.", "cities.nova_scotia_s_capital_and_the":"Nova Scotia’s capital, and the big North American port closest to Europe. The fastest cable to England starts here, on the shortest line across the ocean, built for traders who pay for every millisecond.", @@ -813,6 +816,7 @@ "cities.the_harbour_the_bridge_and_most":"The harbour, the bridge and most of the country’s data centres. Rent is the real latency.", "cities.the_highest_seat_of_government_on":"The highest seat of government on Earth, at 3,600 m. Commuters ride cable cars, and so does some of the fiber.", "cities.the_maldives_capital_a_stop_on":"The Maldives’ capital, one metre above the sea and a stop on the cables from India to the Gulf and Singapore.", +"cities.the_middle_of_everywhere_no_sea":"The middle of everywhere: no sea, no cable, just fibre up the highway and an old telegraph station. The big white domes down the road are definitely for the weather.", "cities.the_most_isolated_big_city_on":"The most isolated big city on Earth. Asia is closer than Sydney.", "cities.the_north_s_hub_with_its":"The North’s hub, with its own exchange and very damp air-conditioning intakes. Cables to Ireland and Denmark come ashore up the coast.", "cities.the_northernmost_town_in_the_united":"The northernmost town in the United States, reached by the first subsea fiber in the American Arctic.", @@ -1997,6 +2001,7 @@ "failures.the_sandflies_drove_your_splicing":"The sandflies drove your splicing crew off {a}–{b}. They will be back when the wind picks up.", "failures.the_seabed_off_tonga_slid_down":"The seabed off Tonga slid down a slope and took your {a}–{b} cable with it. The repair ship is coming from Papua New Guinea.", "failures.the_smelter_at_tiwai_point_pulled":"The smelter at Tiwai Point pulled a little harder on the grid, and your POP in {city} blinked first.", +"failures.the_wet_season_washed_out_the":"The wet season washed out the track to your {a}–{b} fiber. The crew gets there when the water goes down.", "failures.thieves_dug_up_your_a_b":"Thieves dug up your {a}–{b} cable, sure it was copper. It was fiber. They left it cut in the ditch, deeply disappointed.", "failures.traffic_rerouted_customers_barely":"Traffic rerouted, customers barely noticed.", "failures.truck_a_spare_amp_out":"Truck a spare amp out", diff --git a/tests/au-north.test.js b/tests/au-north.test.js new file mode 100644 index 0000000..6d5cdaa --- /dev/null +++ b/tests/au-north.test.js @@ -0,0 +1,42 @@ +// #255: northern Australia. Port Hedland lands the cable up to Darwin and the one out to Singapore, Townsville is North +// Queensland's data centre, Alice Springs sits in the middle with no sea at all. In the wet season (November to April) +// a cut on land in the tropical north takes twice as long to reach. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +const J = (ev, code) => JSON.parse(ev(`JSON.stringify(${code})`)); + +test('#255 Port Hedland, Townsville and Alice Springs are on the map and playable', () => { + const { ev, errors } = load(); + for (const c of ['phe', 'tsv', 'asp']) { + const x = J(ev, `(({cc,land,reg,au})=>({cc,land,reg,au}))(CITY.${c})`); + assert.deepEqual(x, { cc: 'AU', land: 'oc', reg: 'OC', au: true }, c); + assert.ok(ev(`homeOk('${c}')`), `${c} can be a home city`); + assert.ok(ev(`NETS.some(n=>n.id==='tsy'&&n.pops.includes('${c}')&&sellsAt(n,'${c}'))`), `${c}: Telstraya sells transit there`); + } + const cabs = (c) => J(ev, `CABLE_PAIRS.filter(p=>p.a==='${c}'||p.b==='${c}').map(p=>p.a==='${c}'?p.b:p.a).sort()`); + assert.deepEqual(cabs('phe'), ['drw', 'sin'], 'Port Hedland: up the coast to Darwin, out to Singapore'); + assert.deepEqual(cabs('asp'), [], 'Alice Springs has no sea'); + assert.deepEqual(cabs('tsv'), [], 'Townsville is reached over land'); + assert.equal(ev("CAB.nwcs.name"), 'No Worries Cable System'); + assert.deepEqual(errors, []); +}); + +test('#255 the wet season doubles the time to reach a cut in the tropical north, and only there', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e9;S.lvl=6;for(const g of GOALS)S.done[g.id]=0;S.nextFail=S.nextEvent=1e9;"); + const cut = (a, b, month) => { + ev(`S.day=dayOf(cal(S.day).y,${month},15);S.inc=[];S.links=[{id:'l',a:'${a}',b:'${b}',kind:'wave',sub:false,tier:0,km:kmBetween('${a}','${b}'),cut:0,mo:1000}];compute();`); + ev("Math.random=(()=>{let s=7;return()=>{s=(s*16807)%2147483647;return s/2147483647;};})();fireFailure('cut')"); + const i = J(ev, "S.inc.find(i=>i.type==='cut')"); + return { days: i.until - ev('S.day'), msg: i.msg }; + }; + const wet = cut('tsv', 'bne', 0), dry = cut('tsv', 'bne', 6), south = cut('syd', 'mel', 0); + assert.equal(wet.days, dry.days * 2, 'January takes twice as long as July in Townsville'); + assert.match(wet.msg, /wet season washed out the track/); + assert.doesNotMatch(dry.msg, /wet season/); + assert.equal(south.days, dry.days, 'Sydney–Melbourne has no wet season'); + assert.equal(ev("CITY.drw.wet&&CITY.phe.wet&&!CITY.asp.wet"), true, 'Darwin is tropical too; Alice Springs is desert'); + assert.deepEqual(errors, []); +}); diff --git a/tests/gameplay-rules.test.js b/tests/gameplay-rules.test.js index d6ed446..8e46993 100644 --- a/tests/gameplay-rules.test.js +++ b/tests/gameplay-rules.test.js @@ -94,9 +94,9 @@ const REAL_NAMES = [ // eyeballs and incumbents 'A1', 'A1 Telekom Austria', 'AIS', 'Airtel', 'Algérie Télécom', 'Altibox', 'Altice', 'America Movil', 'Angola Cables', 'Antel', 'ASTCA', 'Aussie Broadband', 'Bell', 'Bell Canada', 'Belong', 'Bemobile', 'Brisanet', 'BT', 'BTC', 'Cable & Wireless', 'Cable Bahamas', "CAN'L", 'Canal+', 'CANTV', 'CelcomDigi', 'China Mobile', 'China Telecom', 'China Unicom', 'Chunghwa Telecom', 'Citymesh', 'Claro', 'Comcast', 'Cosmote', 'Cox', 'CV Telecom', 'Deutsche Telekom', 'Dhiraagu', 'Dialog', 'Digi', 'Digicel', 'Djezzy', 'Djibouti Telecom', 'DNA', 'Docomo', 'Docomo Pacific', 'Dodo', 'du', 'Eastlink', 'Elisa', 'Emtel', 'Entel', 'ER-Telecom', 'Etisalat', 'ETECSA', 'Ethio Telecom', 'Exetel', 'Far EasTone', 'Fastweb', 'FINTEL', 'Flow', 'Free', 'Frontier', 'GCI', 'Globe', 'Google Fiber', 'Grameenphone', 'GSL Networks', 'GTA', 'Hawaiian Telcom', 'HKBN', 'HKT', 'iiNet', 'Jazz', 'Jio', 'KDDI', 'KPN', 'KT', 'Kyivstar', 'Launtel', 'Leaptel', 'LG U+', 'Liberty Latin America', 'lifecell', 'LMT', 'Magyar Telekom', 'Maroc Telecom', 'Mascom', 'Mauritius Telecom', 'MegaFon', 'MEO', 'Mobily', 'Movicel', 'Movistar', 'Movitel', 'MTC', 'MTN', 'mts', 'Neptune', 'Netvigator', 'Norlys', 'NOS', 'Nova', 'NTA', 'NTT Docomo', 'Oi', 'Omantel', 'One Communications', 'One NZ', 'Ooredoo', 'OPT', 'Optimum', 'Optus', 'Palau Mobile', 'Paradise Mobile', 'Pentanet', 'PLDT', 'PNCC', 'POST', 'Proximus', 'PTCL', 'Reliance Jio', 'Robi', 'Rogers', 'Rostelecom', 'Safaricom', 'SFR', 'Síminn', 'SK Broadband', 'Sky', 'SLT', 'Sonic', 'Spark', 'Spectrum', 'Spintel', 'Starlink', 'StarHub', 'STC', 'Superloop', 'Sure', 'Swisscom', 'T-Mobile', 'Tango', 'TCC', 'TDC', 'Tele2', 'Telecel', 'Telecom Argentina', 'Telecom Egypt', 'Telecom Fiji', 'Telecom Namibia', 'Telekom Malaysia', 'Telekom Srbija', 'Telenet', 'Telenor', 'Telikom PNG', 'Telkomsel', 'Telma', 'Telmex', 'TelOne', 'Telstra', 'Telus', 'Tet', 'TIM', 'Tigo', 'TPG', 'True', 'True Move', 'TSTT', 'Turk Telekom', 'Unitel', 'UPC', 'Verizon', 'Viettel', 'Vini', 'Virgin Media', 'Vivacom', 'Vivo', 'VNPT', 'Vocus', 'Yas', 'Yettel', 'YouSee', 'Zeop', // exchanges and data centers - 'AMS-IX', 'Any2', 'BCIX', 'CoreSite', 'DE-CIX', 'Digital Realty', 'Equinix', 'France-IX', 'Interxion', 'IX.br', 'JPIX', 'LINX', 'NAPAfrica', 'NetIX', 'NIX', 'NL-ix', 'SIX', 'Telehouse', + 'AMS-IX', 'Any2', 'BCIX', 'CoreSite', 'DE-CIX', 'DigiCo', 'Digital Realty', 'Equinix', 'France-IX', 'Interxion', 'iseek', 'IX.br', 'JPIX', 'LINX', 'NAPAfrica', 'NetIX', 'NEXTDC', 'NIX', 'NL-ix', 'SIX', 'Telehouse', // cables - '2Africa', 'Amitié', 'Dunant', 'EllaLink', 'Equiano', 'Grace Hopper', 'Hibernia Express', 'Jupiter', 'MAREA', 'PEACE', 'SEA-ME-WE 6', + '2Africa', 'Amitié', 'Darwin-Jakarta-Singapore Cable', 'Dunant', 'EllaLink', 'Equiano', 'Grace Hopper', 'Hibernia Express', 'Jupiter', 'MAREA', 'North West Cable System', 'PEACE', 'SEA-ME-WE 6', // cable ships, their operators and maintenance clubs 'ACMA', 'ASEAN Explorer', 'ASEAN Protector', 'ASEAN Restorer', 'Cable Innovator', 'Cable Retriever', 'Global Marine', 'Léon Thévenin', 'MECMA', 'Orange Marine', 'Pierre de Fermat', 'René Descartes', 'SEAIOCMA', 'Sophie Germain', 'Sovereign', 'Wave Sentinel', 'Yokohama Zone', // vendors diff --git a/tests/mcp-commands.test.js b/tests/mcp-commands.test.js new file mode 100644 index 0000000..566da68 --- /dev/null +++ b/tests/mcp-commands.test.js @@ -0,0 +1,355 @@ +// The MCP server's act tool (scripts/lib/mcp-commands.js, scripts/lib/mcp-page.js): typed, checked commands with +// outcomes and quotes, the raw reads (schema, catalog, state, results, ui), and screens beyond the side panel. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { createSession, TOOLS, actArgs } = require('../scripts/lib/mcp-game'); + +const tools = (s) => (name, args = {}) => TOOLS.find((t) => t.name === name).run(s, args); +const BIG = path.join(__dirname, 'fixtures', 'big-network.json'); +// A sandbox network (money and every level, nothing breaks) with a POP in each city, broadband and transit at home. +function sandbox({ city = 'fra', pops = ['ams'], seed = 7 } = {}) { + const s = createSession(), T = tools(s), ev = (x) => s.game.ev(x); + T('new_game', { city, preset: 'sandbox', seed, name: 'Probe' }); + T('act', { action: 'launchBB', args: { city } }); + T('act', { action: 'buyTransit', args: { city, net: 'cog', tier: 1 } }); + for (const c of pops) T('act', { action: 'buildLink', args: { a: city, b: c, tier: 1 } }); + return { s, T, ev }; +} +const act = (T, action, args, dryRun) => T('act', { action, args, dryRun }); + +test('every action in the game is in exactly one class, so a new one forces a decision', () => { + const { s, ev } = sandbox({ pops: [] }); + const c = s.call('classes'); + const all = [...c.game, ...c.view, ...c.draft, ...c.session, ...c.denied]; + const acts = ev('JSON.stringify(Object.keys(ACT).sort())'); + assert.deepEqual(all.filter((x, i) => all.indexOf(x) !== i), [], 'no action in two classes'); + assert.deepEqual(JSON.parse(acts).filter((x) => !all.includes(x)), [], 'every action is classified'); + assert.deepEqual(all.filter((x) => !JSON.parse(acts).includes(x)), [], 'every classified action exists'); + // Every argument domain resolves, and the tools' fixed vocabularies are the game's. + const bad = ev(`(()=>{const {API_CMD,API_VIEW,API_SESSION,API_DOMAINS,API_TABLES,API_MADE}=window.__mcpCmds,out=[]; + for(const [n,s] of Object.entries({...API_CMD,...API_VIEW,...API_SESSION})) + for(const [nm,d] of (s.args||[])) if(!['string','boolean','integer'].includes(d)&&!API_DOMAINS[d]) out.push(n+'.'+nm+': no domain '+d); + for(const [n,d] of Object.entries(API_DOMAINS)) if(d.table&&!API_TABLES[d.table]&&!(d.table in API_MADE)) out.push('domain '+n+': no table '+d.table); + return JSON.stringify(out);})()`); + assert.deepEqual(JSON.parse(bad), []); + assert.deepEqual(TOOLS.find((t) => t.name === 'new_game').inputSchema.properties.chaos.enum, JSON.parse(ev('JSON.stringify(Object.keys(CHAOS))'))); + assert.deepEqual(s.errors(), []); +}); + +test('every declared argument is one the action really reads', () => { + const { s } = sandbox({ pops: [] }); + // Confirmations act passes itself; args the game's own buttons pass (the intern's auto, the sheets' modal flag). + const injected = { cancelTransit: ['ok'], cancelPni: ['ok'], cancelIx: ['ok', 'sure'], accept: ['auto'], utilityKit: ['modal'], utilityCaches: ['modal'] }; + // What each action destructures, from its source (in the page the actions are wrapped for puzzle mode). + const reads = actArgs(), sch = TOOLS.find((t) => t.name === 'schema').run(s, {}), bad = []; + for (const [n, c] of Object.entries({ ...sch.commands, ...sch.view, ...sch.session })) { + const declared = c.args.map((a) => a.name), r = reads[n]; + if (!r) { if (declared.length && !c.opens && !['buildLink', 'orderDf', 'orderCable', 'decomGo', 'metricSet', 'traceRun', 'pzLinkTo', 'openVxc'].includes(n)) bad.push(`${n}: declares ${declared} but takes no {…}`); continue; } + for (const x of r) if (!declared.includes(x) && !(injected[n] || []).includes(x)) bad.push(`${n} reads {${x}} but declares no such argument`); + for (const d of declared) if (!r.includes(d) && !(injected[n] || []).includes(d) && !['buildLink', 'orderDf', 'orderCable', 'decomGo', 'metricSet', 'pzLinkTo'].includes(n)) bad.push(`${n} declares ${d} but does not read it`); + } + assert.deepEqual(bad, []); +}); + +test('the state and results references cover every field', () => { + const s = createSession(), T = tools(s), ev = (x) => s.game.ev(x); + const docs = T('schema', { section: 'state' }), rdoc = T('schema', { section: 'results' }); + for (const [label, setup] of [['a new game', () => {}], ['a scenario', () => T('act', { action: 'startScn', args: { id: 'stg' } })], ['the big network', () => T('load_save', { path: BIG })]]) { + setup(); + assert.deepEqual(Object.keys(T('state')).filter((k) => !docs[k]), [], `${label}: every state field has a line in schema state`); + assert.deepEqual(Object.keys(T('results')).filter((k) => !rdoc[k]), [], `${label}: every results field has a line in schema results`); + } + assert.deepEqual(JSON.parse(ev('JSON.stringify(Object.keys(emptyR()))')).filter((k) => !rdoc[k]), []); +}); + +test('typed text reaches the game: rename, RouteScript, the custom metric, traceroute', () => { + const { s, T, ev } = sandbox(); + const r = act(T, 'renameGo', { name: 'Renamed Net' }); + assert.equal(r.outcome, 'applied'); + assert.equal(ev('S.name'), 'Renamed Net'); + for (let i = 0; i < 3; i++) act(T, 'coreUp'); + assert.equal(act(T, 'buyTE').outcome, 'applied'); + const chk = act(T, 'teCheck', { script: 'avoid transit for ggl' }); + assert.equal(chk.outcome, 'applied'); + assert.ok(chk.report.length > 10, 'the check comes back as a report'); + assert.equal(ev("$('modal').hidden"), true, 'and its window is closed'); + const dep = act(T, 'teDeploy', { script: 'avoid transit for ggl' }); + assert.equal(dep.outcome, 'applied'); + assert.equal(ev('S.te.script'), 'avoid transit for ggl', 'the script given is the one deployed'); + const l = ev('S.links[0].id'); + assert.equal(act(T, 'setMetric', { id: l, v: 'custom' }).outcome, 'applied'); + act(T, 'metricMode', { id: l, k: 'w' }); + assert.equal(act(T, 'metricSet', { id: l, v: '42' }).outcome, 'applied'); + assert.equal(ev(`JSON.stringify(Object.values(S.pairMet)[0])`), JSON.stringify({ k: 'w', v: 42 })); + const t = act(T, 'traceRun', { from: 'fra', to: 'ggl' }); + assert.equal(t.outcome, 'applied'); + assert.match(t.report, /traceroute/); + assert.deepEqual(s.errors(), []); +}); + +test('multi-step builds take their choices as arguments: waves, dark fiber, own cable, circuits, closing POPs', () => { + const { s, T, ev } = sandbox({ city: 'lon', pops: [] }); + const w = act(T, 'buildLink', { a: 'lon', b: 'ams', tier: 1 }); + assert.equal(w.outcome, 'applied'); + assert.equal(ev("S.links.filter(l=>l.kind==='wave').length"), 1); + assert.ok(ev('!!S.pops.ams'), 'the far end gets a POP'); + assert.equal(act(T, 'orderDf', { a: 'lon', b: 'par', source: 'lease', system: 'roadm' }).outcome, 'applied'); + assert.equal(ev("S.links.filter(l=>l.kind==='df').length"), 1); + const cab = act(T, 'orderCable', { a: 'lon', b: 'nyc', design: 'standard' }); + assert.equal(cab.outcome, 'applied'); + assert.ok(cab.charged > 0, 'charged is what the cable cost'); + const fab = ev('Object.keys(FAB)[0]'); + act(T, 'buyNni', { city: 'lon', prov: fab, tier: 0 }); + act(T, 'buyNni', { city: 'ams', prov: fab, tier: 0 }); + assert.equal(act(T, 'buyVxc', { a: 'lon', b: 'ams', prov: fab, t: 0 }).outcome, 'applied'); + assert.equal(ev("S.links.filter(l=>l.kind==='vxc').length"), 1); + assert.equal(act(T, 'decomGo', { cities: ['par'] }).outcome, 'applied'); + assert.ok(ev('!S.pops.par')); + assert.deepEqual(s.errors(), []); +}); + +test('confirmations are given in one call; a click still arms them as in the game', () => { + const { s, T, ev } = sandbox({ pops: ['ams', 'par'] }); + ev(`ACT.addSite({city:'ams'});S.scrubs.push({city:'fra',tier:0}); + S.biz.push({id:'b1',city:'fra',city2:null,reqs:[],name:'C',type:'dia',bw:10,rate:5,mood:100,since:0}); + S.pni.push({id:'p1',city:'fra',net:'lvl',tier:1,ready:S.day});spawnLoanOffer();compute()`); + act(T, 'takeLoan', { id: ev('S.loanOffers[0].id') }); + const checks = [ + ['rmLink', { id: ev('S.links[0].id') }, 'S.links.length===1'], ['rmSite', { city: 'ams' }, '!S.pops.ams.site2'], + ['rmScrub', { city: 'fra' }, 'S.scrubs.length===0'], ['dropBiz', { id: 'b1' }, 'S.biz.length===0'], + ['repayLoan', { id: ev('S.loans[0].id') }, 'S.loans.length===0'], ['cancelPni', { id: 'p1' }, '!S.pni.length'], + ['cancelTransit', { id: ev('S.transit[0].id') }, '!S.transit.length'], + ]; + for (const [n, args, did] of checks) { + assert.equal(act(T, n, args).outcome, 'applied', n); + assert.equal(ev(did), true, `${n} really did it`); + } + const p = T('panel', { link: ev('S.links[0].id') }); + const rm = p.buttons.find((b) => b.act === 'rmLink'); + const c1 = T('click', { button: rm.n }); + assert.equal(ev('S.links.length'), 1, 'the first click only arms the button'); + const again = c1.screen.buttons.find((b) => b.act === 'rmLink'); + T('click', { button: again.n }); + assert.equal(ev('S.links.length'), 0, 'the second one removes the link'); + assert.deepEqual(s.errors(), []); +}); + +test('the utilities sheet\'s one-call buttons work without a quote in hand', () => { + const { s, T, ev } = sandbox({ pops: [] }); + const kit = act(T, 'utilityKit', { city: 'fra' }); + assert.equal(kit.outcome, 'applied'); + assert.ok(ev('!!S.pops.fra.gen'), 'the generator is in'); + assert.notEqual(act(T, 'utilityCaches', { city: 'fra' }).outcome, 'rejected'); + assert.deepEqual(s.errors(), []); +}); + +test('arguments are checked before anything runs, with what would fit', () => { + const { s, T, ev } = sandbox({ pops: [] }); + const before = ev('JSON.stringify(S)'); + for (const [n, args, re] of [ + ['buyTransit', { city: 'fra', net: 'cog', tier: 9 }, /tier: 9 is not a portTier \(0\.\.\d\)/], + ['buyTransit', { city: 'fra', net: 'nope', tier: 1 }, /net: "nope" is not a netId \(see catalog NETS or find\)/], + ['buildPop', { city: 'atlantis' }, /city: "atlantis" is not a cityId/], + ['peerPol', { p: 'yolo' }, /p: "yolo" is not a peerPolicy \(one of open, selective, closed\)/], + ['lagT', { id: 'x', d: 5 }, /d: 5 is not a step \(one of 1, -1\)/], + ['buyTransit', { city: 'fra', net: 'cog' }, /tier is required/], + ['buildPop', { city: 'ams', size: 3 }, /size is not an argument/], + ]) assert.throws(() => act(T, n, args), re, n); + assert.equal(ev('JSON.stringify(S)'), before, 'nothing ran'); + assert.throws(() => act(T, 'dash', {}, true), /only game commands/); + assert.deepEqual(s.errors(), []); +}); + +test('the outcome says what happened', () => { + const { s, T, ev } = sandbox({ pops: [] }); + assert.equal(act(T, 'buildPop', { city: 'ams' }).outcome, 'applied'); + assert.equal(act(T, 'buildPop', { city: 'ams' }).outcome, 'no_effect', 'a POP that is already there'); + assert.equal(act(T, 'setStandby', { id: 'nope', on: true }).outcome, 'no_effect', 'a wrong id'); + assert.equal(act(T, 'dash').outcome, 'shown'); + ev('closeModal();$("dash").hidden=true;S.cash=0'); + const r = act(T, 'buildPop', { city: 'nyc' }); + assert.equal(r.outcome, 'rejected'); + assert.ok(r.toasts.some((t) => /^bad: /.test(t)), 'with the game\'s words'); + ev('S.cash=1e9'); + const tr = act(T, 'buyTransit', { city: 'fra', net: 'ntt', tier: 1 }); + assert.equal(tr.charged, ev('PORT[1].setup'), 'charged is the price at the money gate'); + // A De-Kicks quote is a question: other game commands wait until it is answered or closed. + const d = act(T, 'buyIx', { city: 'fra', tier: 1 }); + assert.equal(d.outcome, 'decision'); + assert.ok(d.decision.options.some((o) => o.command === 'dkAccept')); + const wait = act(T, 'buildPop', { city: 'par' }); + assert.equal(wait.outcome, 'decision', 'blocked behind the question'); + assert.ok(!ev('S.pops.par')); + assert.equal(act(T, 'dkAccept').outcome, 'applied', 'an option answers it'); + assert.equal(act(T, 'buildPop', { city: 'par' }).outcome, 'applied'); + // A sheet the agent opened itself is not a question, even with game commands on it. + act(T, 'opsOpen'); + assert.equal(T('screen').question, false); + assert.equal(act(T, 'buildPop', { city: 'lon' }).outcome, 'applied'); + ev('closeModal();S.lost=true'); + assert.equal(act(T, 'buildPop', { city: 'nyc' }).outcome, 'stopped'); + assert.deepEqual(s.errors(), []); +}); + +test('dry runs do not use up the dice: the seeded game plays on exactly as without them', () => { + const play = (dry) => { + const s = createSession(), T = tools(s); + T('new_game', { city: 'fra', seed: 9 }); + act(T, 'launchBB', { city: 'fra' }); + act(T, 'buyTransit', { city: 'fra', net: 'cog', tier: 1 }); + if (dry) for (const [n, a] of [['pni', { city: 'fra', net: 'lvl', tier: 1 }], ['buildLink', { a: 'fra', b: 'ams', tier: 1 }], ['buildPop', { city: 'ams' }], + ['orderDf', { a: 'fra', b: 'ams', source: 'lease', system: 'lite' }], ['hackback', {}], ['coreUp', {}]]) assert.equal(act(T, n, a, true).outcome, 'quote'); + T('advance', { days: 90 }); + // Entity ids and the log's wall-clock stamps differ from run to run anyway; everything else is the game. + return JSON.stringify(JSON.parse(s.game.ev('JSON.stringify(S)'), (k, v) => (k === 'id' || k === 'at' ? undefined : v))); + }; + assert.equal(play(true), play(false)); +}); + +test('a dry run prices every command that has a price, and changes nothing', () => { + const { s, T, ev } = sandbox({ pops: ['ams'] }); + act(T, 'orderDf', { a: 'fra', b: 'par', source: 'lease', system: 'lite' }); + ev(`S.scrubs.push({city:'fra',tier:0});spawnLoanOffer();compute()`); + const quoted = Object.entries(T('schema', { section: 'commands' })).filter(([, c]) => c.dryRun).map(([n]) => n); + assert.ok(quoted.length >= 50, 'the priceable surface: ' + quoted.length); + const wave = ev("S.links.find(l=>l.kind==='wave').id"), df = ev("S.links.find(l=>l.kind==='df').id"), fab = ev('Object.keys(FAB)[0]'); + const sample = { + buildPop: { city: 'nyc' }, launchBB: { city: 'ams' }, ad: { city: 'fra' }, addRouter: { city: 'fra' }, rmRouter: { city: 'fra' }, upRouter: { city: 'fra' }, + addGen: { city: 'fra' }, addSite: { city: 'fra' }, buyTransit: { city: 'fra', net: 'cog', tier: 2 }, lagT: { id: ev('S.transit[0].id'), d: 1 }, + cleanPipe: { id: ev('S.transit[0].id') }, buyIx: { city: 'ams', tier: 1 }, foundIx: { city: 'nyc' }, myIxUp: { city: 'nyc' }, + pni: { city: 'fra', net: 'lvl', tier: 1 }, cache: { city: 'fra', net: 'nfx' }, buildLink: { a: 'fra', b: 'nyc', tier: 1 }, upLink: { id: wave, tier: 2 }, + rmLink: { id: wave }, buyNni: { city: 'fra', prov: fab, tier: 0 }, buyVxc: { a: 'fra', b: 'ams', prov: fab, t: 0 }, upVxc: { id: wave, t: 1 }, + orderDf: { a: 'fra', b: 'ams', source: 'lease', system: 'lite' }, orderCable: { a: 'lis', b: 'nyc' }, subUpgrade: { id: df, k: 'terminal' }, + crews: { id: df }, addCh: { id: df, o: 'zr4' }, addPair: { id: df }, upSys: { id: df }, regen: { id: df, d: 1 }, buySpare: { o: 'zr4' }, sellSpare: { o: 'zr4' }, + setChCount: { id: df, o: 'zr4', n: 2 }, repayLoan: { id: 'none' }, buildScrub: { city: 'ams', tier: 1 }, scrubUp: { city: 'fra', tier: 1 }, + fixInc: { id: 'none' }, confGo: { key: T('catalog', { name: 'conferences' })[0].key }, confSponsor: { key: T('catalog', { name: 'conferences' })[0].key }, + opsHire: { id: ev('Object.keys(INTERNS)[0]') }, opsNewPop: { city: 'nyc' }, pniAll: { net: 'cog', tier: 1 }, seatBuy: { n: 2 }, layShip: { id: df }, + utilityKit: { city: 'fra' }, utilityCaches: { city: 'fra' }, teDeploy: { script: 'spill at 85%' }, upLinkX: {}, + }; + const missing = quoted.filter((n) => !sample[n] && T('schema', { section: 'commands' })[n].args.some((a) => a.required)); + assert.deepEqual(missing, [], 'every priced command with arguments has a sample here'); + for (const n of quoted) { + const S0 = ev('JSON.stringify(S)'), U0 = JSON.stringify(T('ui')); + const q = act(T, n, sample[n] || {}, true); + assert.equal(q.outcome, 'quote', n); + assert.equal(q.consistent, true, n); + assert.ok(Number.isFinite(q.quote.setup) && Array.isArray(q.quote.blocked) && q.quote.blocked.every((b) => typeof b === 'string'), n); + assert.equal(ev('JSON.stringify(S)'), S0, `${n} leaves the game alone`); + assert.equal(JSON.stringify(T('ui')), U0, `${n} leaves the view alone`); + } + // The price is what the game then charges. + for (const [n, args] of [['buildPop', { city: 'nyc' }], ['addRouter', { city: 'fra' }], ['buyTransit', { city: 'nyc', net: 'cog', tier: 1 }], ['buildLink', { a: 'fra', b: 'par', tier: 1 }], ['hwLock', {}]]) { + const q = act(T, n, args, true), r = act(T, n, args); + assert.equal(r.outcome, 'applied', n); + assert.equal(r.charged, q.quote.setup, `${n}: the quote is the price`); + } + assert.match(act(T, 'orderCable', { a: 'fra', b: 'ams' }, true).quote.blocked[0], /on land/i, 'a blocked quote says why, in the game\'s words'); + assert.deepEqual(s.errors(), []); +}); + +test('everything an action needs can be read: loan offers, conference keys, recipes, reference tables', () => { + const { s, T, ev } = sandbox({ pops: [] }); + ev('spawnLoanOffer();compute()'); + const offers = T('state', { path: 'loanOffers' }); + assert.equal(offers.length, 1); + assert.equal(act(T, 'takeLoan', { id: offers[0].id }).outcome, 'applied'); + assert.equal(T('state', { path: 'loans' }).length, 1); + const cf = T('catalog', { name: 'conferences' }).find((c) => !c.capacity); + assert.equal(act(T, 'confGo', { key: cf.key }).outcome, 'applied'); + assert.equal(T('state', { path: `confReg.${cf.key}` }), true); + for (let i = 0; i < 3; i++) act(T, 'coreUp'); + act(T, 'buyTE'); + const rec = T('catalog', { name: 'TE_RECIPES' })[0]; + assert.equal(act(T, 'teDeploy', { script: rec.script }).outcome, 'applied'); + assert.equal(ev('S.te.script'), rec.script); + const idx = T('catalog').tables.map((t) => t.name); + for (const k of ['CITIES', 'NETS', 'OPT', 'INTERNS', 'OPSK', 'CHARTERS', 'SCN', 'conferences', 'BADGES']) assert.ok(idx.includes(k), k); + assert.throws(() => T('catalog', { name: 'NOPE' }), /No table/); + assert.deepEqual(T('state', { path: 'pops.fra' }), JSON.parse(ev('JSON.stringify(S.pops.fra)')), 'a subtree is the save\'s own'); + assert.equal(T('state', { path: 'nextFail' }), ev('S.nextFail'), 'nothing is held back'); + assert.equal(T('results', { path: 'served' }), ev('R.served')); + 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.throws(() => T('schema', { section: 'nope' }), /No section/); + assert.deepEqual(Object.keys(T('schema')).sort(), ['clock', 'commands', 'denied', 'domains', 'drafts', 'results', 'session', 'state', 'view']); + 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); + assert.deepEqual(s.errors(), []); +}); + +test('the dashboard, the bank, the left drawer and the puzzle box read as text; long text comes in pages', () => { + const { s, T, ev } = sandbox({ pops: ['ams'] }); + ev('spawnLoanOffer();compute()'); + const bank = act(T, 'bank'); + assert.equal(bank.screen.where, 'bank'); + assert.ok(bank.screen.buttons.some((b) => b.act === 'takeLoan' && b.args.id === ev('S.loanOffers[0].id')), 'the loan offer and its button'); + act(T, 'bankClose'); + ev(`for(const c of ['fra','ams'])S.biz.push({id:uid(),city:c,city2:null,reqs:[],name:'C '+c,type:'dia',bw:10,rate:5,mood:100,since:0});compute()`); + const dash = act(T, 'dash'); + assert.equal(dash.screen.where, 'dash'); + assert.ok(dash.screen.text.length > 50); + act(T, 'custOpen'); + const sel = T('screen').buttons.find((b) => b.select === 'custCity'); + assert.ok(sel && sel.options.length > 1, 'a list the game acts on, with its options'); + const pick = T('click', { button: sel.n, value: 'fra' }); + assert.equal(pick.outcome, 'shown'); + assert.throws(() => T('click', { button: T('screen').buttons.find((b) => b.select === 'custCity').n, value: 'nowhere' }), /is a list/); + act(T, 'dashClose'); + const deals = T('panel', { left: 'deals' }); + assert.equal(deals.where, 'left'); + assert.equal(deals.leftTab, 'deals'); + T('act', { action: 'pzStart', args: { id: ev('PZ[0].id') } }); + assert.equal(ev('S.mode'), 'puzzle'); + const pz = T('screen'); + assert.equal(pz.where, 'puzzle', 'a puzzle shows its box'); + assert.ok(pz.text.length > 50); + // A big network's panel is longer than one page. + T('load_save', { path: BIG }); + const p1 = T('panel', { city: 'fra', tab: 'peer' }); + assert.match(p1.textMore || '', /offset \d+/, 'the panel says where the next page starts'); + const off = +/offset (\d+)/.exec(p1.textMore)[1]; + const p2 = T('screen', { where: 'panel', offset: off }); + assert.equal(p2.textFrom, off); + assert.ok(p2.text.length > 0 && p2.text !== p1.text); + assert.throws(() => T('screen', { where: 'nope' }), /where is one of/); + assert.deepEqual(s.errors(), []); +}); + +test('new_game takes your own ASN and the sandbox chaos dial', () => { + const s = createSession(), T = tools(s), ev = (x) => s.game.ev(x); + assert.equal(T('new_game', { city: 'ams', asn: 213337, seed: 2 }).asn, 213337); + assert.throws(() => T('new_game', { asn: ev('NET.dtk.asn') }), /cannot be yours/, 'a real network\'s ASN'); + assert.throws(() => T('new_game', { asn: 64512 }), /cannot be yours/, 'a private ASN'); + T('new_game', { preset: 'sandbox', chaos: 'spicy' }); + assert.equal(ev('S.rules.chaos'), 'spicy'); + assert.throws(() => T('new_game', { chaos: 'calm' }), /sandbox/); + assert.throws(() => T('new_game', { preset: 'sandbox', chaos: 'mayhem' }), /chaos is one of/); + assert.notEqual(T('new_game', { city: 'fra' }).asn, 213337, 'the ASN does not stick to the next game'); + assert.deepEqual(s.errors(), []); +}); + +test('every button the panels, drawers, dashboard and windows render is classified, and typed ones pass their domains', () => { + const { s, T, ev } = sandbox({ pops: ['ams'] }); + ev(`ACT.buyIx({city:'ams',tier:1,signed:true});ACT.rs({city:'ams'});S.scrubs.push({city:'fra',tier:0}); + S.pni.push({id:uid(),city:'fra',net:'lvl',tier:1,ready:S.day});S.biz.push({id:uid(),city:'fra',city2:null,reqs:[],name:'C',type:'dia',bw:10,rate:5,mood:100,since:0}); + S.offers.push({id:uid(),city:'fra',name:'O',type:'dia',bw:10,rate:5,exp:S.day+30});spawnLoanOffer();compute()`); + const c = s.call('classes'), known = new Set([...c.game, ...c.view, ...c.draft, ...c.session, ...c.denied]); + const typed = T('schema'); + const seen = []; + const scan = (scr, where) => { for (const b of scr.buttons) { const n = b.act || b.select; seen.push(n); + assert.ok(known.has(n), `${where}: unclassified ${n}`); + const spec = typed.commands[n] || typed.view[n]; + if (spec && b.act) for (const k of Object.keys(b.args)) assert.ok(spec.args.some((a) => a.name === k) || ['ok', 'sure', 'auto', 'modal'].includes(k), `${where}: ${n} passes ${k}`); } }; + for (const t of ['cust', 'up', 'peer', 'infra', 'links']) scan(T('panel', { city: 'fra', tab: t }), 'city ' + t); + scan(T('panel', { link: ev('S.links[0].id') }), 'link'); + for (const l of ['goals', 'deals', 'noc', 'nets']) scan(T('panel', { left: l }), 'left ' + l); + scan(act(T, 'bank').screen, 'bank'); act(T, 'bankClose'); + for (const k of JSON.parse(ev('JSON.stringify(DTABS)'))) { act(T, 'dash'); scan(act(T, 'dashTab', { k }).screen, 'dash ' + k); } + act(T, 'dashClose'); + for (const v of ['opsOpen', 'utilities', 'models', 'teHelp', 'puzzleMenu', 'scenarios']) { scan(act(T, v).screen, v); ev('closeModal()'); } + scan(T('open_link', { from: 'fra', to: 'nyc' }).screen, 'link window'); + assert.ok(seen.length > 100, 'a real sweep: ' + seen.length + ' buttons'); + assert.deepEqual(s.errors(), []); +}); diff --git a/tests/mcp.test.js b/tests/mcp.test.js index 76a1dad..2880e95 100644 --- a/tests/mcp.test.js +++ b/tests/mcp.test.js @@ -31,7 +31,7 @@ test('speaks MCP over stdio: initialize, list tools, call one, and errors as err await ask({ method: 'notifications/initialized' }); const list = await ask({ id: 2, method: 'tools/list' }); const names = list.result.tools.map((t) => t.name); - for (const n of ['new_game', 'load_save', 'export_save', 'status', 'advance', 'network', 'city', 'find', 'traceroute', 'peering_check', 'hot_spots', 'actions', 'act', 'screen', 'panel', 'click', 'open_link']) assert.ok(names.includes(n), n); + for (const n of ['new_game', 'load_save', 'export_save', 'status', 'advance', 'network', 'city', 'find', 'traceroute', 'peering_check', 'hot_spots', 'actions', 'act', 'screen', 'panel', 'click', 'open_link', 'schema', 'catalog', 'state', 'results', 'ui']) assert.ok(names.includes(n), n); assert.ok(list.result.tools.every((t) => t.description && t.inputSchema && t.inputSchema.type === 'object')); const st = await ask({ id: 3, method: 'tools/call', params: { name: 'status', arguments: {} } }); assert.equal(st.result.isError, undefined); @@ -122,7 +122,7 @@ test('panels and the network list read as text with buttons', () => { assert.match(p.text, /DE-KICKS/); assert.ok(p.buttons.some((b) => b.act === 'tab')); const l = T('panel', { network: 'ggl' }); - assert.equal(l.where, 'network list'); + assert.equal(l.where, 'left'); assert.match(l.text, /Goggle/); assert.deepEqual(s.errors(), []); }); diff --git a/tests/traceroute.test.js b/tests/traceroute.test.js new file mode 100644 index 0000000..a0caf05 --- /dev/null +++ b/tests/traceroute.test.js @@ -0,0 +1,21 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { load } = require('./harness'); + +test('traceroute shows an embedded cache hop only when a cache is the exit', () => { + const { ev, errors } = load(); + ev("ACT.start({});S.cash=1e8;for(const g of GOALS)S.done[g.id]=0"); + ev("S.pops.fra.bb={d:20/NSH.cfl};ACT.buyTransit({city:'fra',net:'cog',tier:1});compute()"); + // The hops, without the "traceroute to …" header line. + const trace = () => { const r = ev("traceroute('fra',{net:'cfl'})"); return { ...r, hops: r.text.split('\n').slice(1).join('\n') }; }; + const before = trace(); + assert.match(before.why, /Cogentle/, 'over transit'); + assert.doesNotMatch(before.hops, /cache-|embedded cache/, 'no cache hop without a cache'); + assert.match(before.hops, /www\.crowdflare\.example/, 'ends at the network itself'); + ev("ACT.cache({city:'fra',net:'cfl'});compute()"); + assert.equal(ev('S.caches.length'), 1); + const after = trace(); + assert.match(after.hops, /cache-crowdflare\.fra\..*embedded cache in your rack$/, 'the cache is the last hop'); + assert.doesNotMatch(after.hops, /cogentle|www\.crowdflare/, 'nothing leaves the network'); + assert.deepEqual(errors, []); +});