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

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

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

View file

@ -1,8 +1,9 @@
/* ================= AGENT API: argument domains =================
The agent facade (window.TUBES, this folder) is how tools play the game: the MCP server (scripts/mcp.js) calls it in
its own jsdom page. It is part of the development page only (<!-- @include-dev agent -->): the page players get has
none of it, so nothing in src/game/ may name anything defined here. Nothing here runs until a tool calls it: these
files only define tables and functions.
its own jsdom page, or in the player's tab through the agent relay (80-relay.js). It is part of the development page
only (<!-- @include-dev agent -->): the page players get has none of it, so nothing in src/game/ may name anything
defined here; the game offers HOOKS instead. Nothing here runs until a tool calls it or the player switches agent
mode on: these files define tables and functions, and 99-start.js wires agent mode in.
A domain is what an argument may be: an id in a catalog table, a key, an index, a small fixed list, or a check. */
const API_DOMAINS={
// Tables from the catalog: an id in a list, a key in an object, or an index into a list.

View file

@ -510,7 +510,8 @@ const API_BOUND={
/* Starting, retrying and leaving scenarios, puzzles and architect runs, and the screens a player dismisses. They run
as their buttons run them; new_game, load_save and export_save are the other half of the session, and exist only in
the MCP server's own page (scripts/lib/mcp-headless.js). */
the MCP server's own page (scripts/lib/mcp-headless.js). In the player's tab the player owns the game, so the ones
that replace or leave it are refused there (API_PLAYER_OWNS). */
const API_SESSION={
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.'},
@ -523,11 +524,14 @@ const API_SESSION={
pitchSkip:{args:[],doc:'Skip the opening pitch; a game waiting behind it starts.'},
tutSkip:{args:[],doc:'Skip the tutorial coaching.'},
};
// Session actions that would replace or leave the game in the player's tab: refused over the relay.
const API_OWN_WHY='the game in this tab is the player\'s: only the player starts, loads or leaves one';
const API_PLAYER_OWNS={startScn:1,startWeekly:1,pzStart:1,pzWeekly:1,pzArStart:1,pzRetry:1,pzLeave:1};
/* Actions no tool runs, by reason: files, storage slots, settings and the title screen are not the game's, and time
moves only through advance (or the page's own clock). */
const API_WHY={
time:'use advance to move time',start:'use new_game',files:'use load_save or export_save',
time:'use advance to move time, or wait when the clock runs on its own',start:'use new_game',files:'use load_save or export_save',
slots:'saved networks in browser storage are not part of this game',prefs:'device and player settings are not part of the game',
browser:'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)',
};

View file

@ -143,3 +143,12 @@ const API_RESULTS_DOC={
cityBlocked:{type:'map',doc:'Set up per city by the traffic computation; nothing fills it at present.'},
ddosHot:{type:'map',doc:'Cities whose ports a flood is filling, for the map\'s pulse. Keyed by city id.'},
};
/* The dice rather than the board: in the player's tab (over the relay) state never returns these, and schema says why.
The MCP server's own page returns them, for debugging. */
const API_WITHHELD={
rng:'the seed: it predicts every future random draw',
nextFail:'the day the next failure fires',
nextEvent:'the day the next world event fires',
'scn.nextDdos':'the day of the next scripted attack in a scenario',
};

View file

@ -183,19 +183,20 @@ function apiArgDoc([name,dom,req]){
else{const v=apiDomValues(dom);if(Array.isArray(v))a.values=v;else if(v&&v.from!==undefined)a.range=v;}
return a;}
function apiSchema(section){
const cmd=s=>({args:(s.args||[]).map(apiArgDoc),doc:s.doc});
const cmd=s=>({args:(s.args||[]).map(apiArgDoc),doc:s.doc}),relay=API_CTX.relay;
const doc={
mode:apiMode(),
clock:apiClockDoc(),
commands:Object.fromEntries(Object.entries(API_CMD).map(([n,s])=>[n,{...cmd(s),dryRun:!!s.quote,
...(s.decides?{decides:true}:{}),...(s.confirm?{confirm:s.confirm}:{}),...(s.open?{opens:s.open}:{}),...(s.reads?{report:true}:{})}])),
view:Object.fromEntries(Object.entries(API_VIEW).map(([n,s])=>[n,cmd(s)])),
session:Object.fromEntries(Object.entries(API_SESSION).map(([n,s])=>[n,cmd(s)])),
session:Object.fromEntries(Object.entries(API_SESSION).map(([n,s])=>[n,{...cmd(s),...(relay&&API_PLAYER_OWNS[n]?{refused:API_OWN_WHY}:{})}])),
drafts:API_BOUND,
denied:Object.fromEntries(Object.keys(API_DENY).sort().map(n=>[n,apiDenied(n)])),
domains:Object.fromEntries(Object.entries(API_DOMAINS).map(([n,d])=>{const v=apiDomValues(n);
return [n,{kind:d.kind==='fn'?'custom':d.kind,...(d.table?{from:d.table}:{}),
...(!d.table&&Array.isArray(v)?{values:v}:v&&v.from!==undefined?{range:v}:v&&v.of?{of:v.of}:{})}];})),
state:API_STATE_DOC,
state:relay?Object.fromEntries(Object.entries(API_STATE_DOC).map(([k,d])=>[k,API_WITHHELD[k]?{...d,withheld:API_WITHHELD[k]}:d])):API_STATE_DOC,
results:API_RESULTS_DOC,
};
if(section===undefined||section===null||section==='')return doc;
@ -208,7 +209,19 @@ function apiCatalog(name){
if(name in API_MADE)return apiJson(API_MADE[name]());
if(name in API_TABLES)return apiJson(API_TABLES[name]);
apiFail(`No table "${name}". Call catalog without a name for the list.`);}
function apiState(path){if(!S)return null;const v=apiJson(apiPath(S,path));return v===undefined?null:v;}
// In the player's tab the dice are held back: a withheld field, or one inside the subtree asked for, is left out.
function apiState(path){
if(!S)return null;
const p=path===undefined||path===null?'':String(path),v=apiJson(apiPath(S,p));
if(v===undefined)return null;
if(!API_CTX.relay)return v;
for(const w of Object.keys(API_WITHHELD)){
if(w===p||p.startsWith(w+'.'))return null;
if(p&&!w.startsWith(p+'.'))continue;
const ks=(p?w.slice(p.length+1):w).split('.');let o=v;
for(let i=0;i<ks.length-1&&o&&typeof o==='object';i++)o=o[ks[i]];
if(o&&typeof o==='object')delete o[ks[ks.length-1]];}
return v;}
function apiResults(path){const v=apiJson(apiPath(R,path));return v===undefined?null:v;}
function apiUi(){const o={};for(const k of Object.keys(UI))if(!API_UI_HIDDEN[k])o[k]=apiJson(UI[k]);return o;}
function apiActions(){

View file

@ -4,15 +4,19 @@
const API_ROOT={modal:'modal',bank:'bankBox',dash:'dash',panel:'panel',left:'leftBody',puzzle:'pzBox'};
const apiShown=w=>{const el=$(API_ROOT[w]);return !!el&&!el.hidden;};
const apiModalOpen=()=>apiShown('modal');
// A window the player opened by hand (API_MODAL.hand, 75-mode.js) is theirs: a tool reads it but never answers,
// closes or replaces it, and it is never a question the game is waiting on.
const apiPlayerWin=()=>apiModalOpen()&&API_MODAL.hand;
// The buttons of the last screen a tool read, for click. Set by apiScreen.
let API_LAST=[];
function apiControls(root){
function apiControls(root,player){
const out=[];
for(const b of root.querySelectorAll('[data-act],select[data-chg]')){
const o=b.dataset.act?{label:apiText(b,200).replace(/\n/g,' ')||b.getAttribute('aria-label')||b.dataset.act,act:b.dataset.act,args:apiParse(b.dataset.args),disabled:!!b.disabled}
// A list the game acts on when its value changes (the change handler in 96-map/95-clicks.js): click it with a value.
:{label:b.getAttribute('aria-label')||(b.closest('label')&&apiText(b.closest('label'),120).split('\n')[0])||b.dataset.chg,
select:b.dataset.chg,value:b.value,options:[...b.options].map(o=>({value:o.value,label:o.textContent.trim()})),disabled:!!b.disabled};
if(player)o.player=true;
out.push(o);}
return out;}
function apiScreen(where,offset=0){
@ -20,12 +24,12 @@ function apiScreen(where,offset=0){
if(where!==undefined&&!API_ROOT[where])apiFail(`where is one of ${Object.keys(API_ROOT).join(', ')}.`);
const open=Object.keys(API_ROOT).filter(w=>w!=='left'&&apiShown(w));
const w=where||['modal','bank','dash','panel','puzzle'].find(apiShown)||'panel';
const root=$(API_ROOT[w]);
API_LAST=root?apiControls(root):[];
const root=$(API_ROOT[w]),player=w==='modal'&&apiPlayerWin();
API_LAST=root?apiControls(root,player):[];
const all=root?apiFullText(root):'',from=Math.max(0,Math.floor(+offset)||0),more=all.length-from-API_MAX_TEXT;
const out={where:w,open,selected:UI.sel,tab:UI.tab};
if(w==='left')out.leftTab=UI.left||'goals';
if(w==='modal')out.question=!!apiDecision();
if(w==='modal'){out.question=!!apiDecision();if(player)out.playerWindow='the player opened this window: read it, but its buttons are theirs to press';}
out.text=all.slice(from,from+API_MAX_TEXT);
if(from)out.textFrom=from;
if(more>0)out.textMore=`${more} more characters: call screen with where "${w}" and offset ${from+API_MAX_TEXT}`;
@ -39,14 +43,24 @@ function apiScreen(where,offset=0){
commands wait until it is answered or closed, as clicks outside an open window do in the game. */
let API_SHEET=null;
const apiCard=()=>$('modalCard').firstChild;
const apiMarkSheet=()=>{API_SHEET=apiModalOpen()?apiCard():null;};
const apiMarkSheet=()=>{API_SHEET=apiModalOpen()&&!apiPlayerWin()?apiCard():null;};
const apiIsSheet=()=>apiModalOpen()&&!!API_SHEET&&apiCard()===API_SHEET;
function apiDecision(){
if(!apiModalOpen()||apiIsSheet())return null;
if(!apiModalOpen()||apiIsSheet()||apiPlayerWin())return null;
const b=[...$('modal').querySelectorAll('[data-act]')].filter(x=>x.dataset.act!=='closeModal'&&API_CMD[x.dataset.act]);
if(!b.length)return null;
return {text:apiText($('modal'),1500),options:b.map(x=>({command:x.dataset.act,args:apiParse(x.dataset.args),label:apiText(x,120).replace(/\n/g,' ')}))};}
/* A player's window stays where it is: its very nodes are set aside while a tool's command runs, and put back after,
so typed text survives. Only a question the game asks in answer to the tool's move takes the screen, as it would
after a click. */
function apiHold(){const m=$('modal'),c=$('modalCard');
return {nodes:[...c.childNodes],cls:m.className,aria:c.getAttribute('aria-modal'),setOpen:UI.setOpen,pending:UI.pending};}
function apiRestore(h){const m=$('modal'),c=$('modalCard');
if(!m.hidden&&m.className===h.cls&&c.childNodes.length===h.nodes.length&&h.nodes.every((n,i)=>c.childNodes[i]===n)){API_MODAL.hand=true;return;}
m.className=h.cls;if(h.aria!==null)c.setAttribute('aria-modal',h.aria);c.replaceChildren(...h.nodes);
if(m.hidden)markLayer();m.hidden=false;UI.setOpen=h.setOpen;UI.pending=h.pending;API_MODAL.hand=true;API_SHEET=null;}
function apiPanel({city:c,link,network:q,tab,left}={}){
if(left!==undefined){if(!['goals','deals','noc','nets'].includes(left))apiFail('left is one of goals, deals, noc, nets.');ACT.leftTab({t:left});return apiScreen('left');}
if(c)UI.sel={type:'city',id:apiCityOf(c).id};
@ -58,6 +72,7 @@ function apiPanel({city:c,link,network:q,tab,left}={}){
function apiOpenLink(a,b){
const x=apiCityOf(a).id,y=apiCityOf(b).id;
if(!S.pops[x])apiFail(`A link starts at one of your POPs: ${apiMyPops()}.`);
if(apiPlayerWin())apiFail('The player has a window open, and the link window would replace it. Use act buildLink, orderDf or orderCable, or wait until it is closed.');
apiTake();
openLinkModal(x,y);
apiMarkSheet();

View file

@ -34,7 +34,7 @@ function apiMeter(){const real=window.spend;let paid=0;window.spend=c=>{const ok
/* typed: through the command table (bind the UI, type into fields, pass the confirmation); otherwise as a button click
does it, with the button's own arguments. */
function apiDispatch(name,kind,spec,args,typed){
const mine=apiIsSheet()||(typed&&kind==='game'&&!!spec.open);
const mine=apiIsSheet()||(typed&&kind==='game'&&!!spec.open),held=apiPlayerWin()?apiHold():null;
apiTake();
const ref=S,cash=S?S.cash:0,f0=apiFp(spec&&spec.watch,args),paid=apiMeter();
let threw=null,report;
@ -49,19 +49,25 @@ function apiDispatch(name,kind,spec,args,typed){
const a=spec.pass?spec.pass(args):args;
ACT[name](a);
if(spec.confirm==='double')ACT[name](a);
if(spec.reads==='modal'&&apiModalOpen()){report=apiText($('modal'));closeModal();}
if(spec.reads==='modal'&&apiModalOpen()&&!apiPlayerWin()){report=apiText($('modal'));closeModal();}
}else ACT[name](args);
}catch(e){threw=e;}
const charged=paid();
if(held&&(threw||!apiDecision())){
// The tool's own sheet is read before the player's window goes back over it.
const shot=!threw&&apiModalOpen()&&!apiPlayerWin()?apiScreen('modal'):null;
apiRestore(held);
if(shot)shot.note='The player has a window open, so this one was shown to you and closed again.';
held.shot=shot;}
if(threw){apiTake();apiFail(`${name} failed: ${threw&&threw.message||threw}`);}
if(!apiModalOpen())API_SHEET=null;
if(!apiModalOpen()||apiPlayerWin())API_SHEET=null;
else if(mine||kind!=='game')apiMarkSheet();
else API_SHEET=null;
const said=apiTake(),d=apiDecision();
const outcome=d?'decision':S!==ref||apiFp(spec&&spec.watch,args)!==f0||report!==undefined?'applied'
:said.some(t=>t.kind==='bad')?'rejected':kind==='view'||kind==='draft'?'shown':'no_effect';
return {action:name,outcome,toasts:apiToastLines(said),charged,cashChange:Math.round((S?S.cash:0)-cash),
...(report!==undefined?{report}:{}),...(d?{decision:d}:{}),screen:apiScreen()};}
...(report!==undefined?{report}:{}),...(d?{decision:d}:{}),screen:held&&held.shot||apiScreen()};}
// While the game waits for an answer, game commands other than its options report the question instead.
function apiWaiting(name){
const d=apiDecision();
@ -82,10 +88,11 @@ function apiQuote(name,spec,args){
}catch(e){apiFail(`${name}: the price could not be worked out: ${e&&e.message||e}`);}finally{Math.random=dice;for(const k of Object.keys(ui0))UI[k]=ui0[k];}
return {action:name,outcome:'quote',quote:{setup:0,monthly:0,...q,blocked:(q.blocked||[]).map(b=>apiText(String(b),400))},consistent:apiFp(spec.watch,args)===f0,
...(spec.quote?{}:{note:'This command has no price of its own: it costs nothing up front.'})};}
// Checks shared by act and click: what no tool runs.
// Checks shared by act and click: what no tool runs, and what only the player runs in their own tab.
function apiAllowed(name,what){
const no=apiDenied(name);
if(no)apiFail(`${name} is not available here: ${no}.`);
if(API_CTX.relay&&API_PLAYER_OWNS[name])apiFail(`${name} is not available here: ${API_OWN_WHY}.`);
const kind=apiKind(name);
if(!kind||typeof ACT[name]!=='function')apiFail(what);
return kind;}
@ -107,6 +114,7 @@ function apiClick(n,value){
const b=API_LAST[n];
if(!b)apiFail(`No button ${n} on the last screen. Call screen first.`);
if(b.disabled)apiFail(`"${b.label}" is greyed out.`);
if(b.player&&apiPlayerWin())apiFail(`"${b.label}" is in a window the player opened: it is theirs to press.`);
const name=b.select||b.act,args=b.select?{v:value===undefined?undefined:String(value)}:b.args;
if(b.select&&!b.options.some(o=>o.value===args.v))apiFail(`"${b.label}" is a list: click it with a value, one of ${b.options.map(o=>JSON.stringify(o.value)).join(', ')}.`);
const kind=apiAllowed(name,`"${b.label}" runs ${name}, which is not an action.`);

View file

@ -1,8 +1,21 @@
/* ================= AGENT API: time =================
The agent's clock: nothing moves until a tool asks for days with advance, one dayTick() per simulated day. */
const apiClockDoc=()=>'Time moves only with advance: one dayTick() per simulated day, as the game loop runs it. Nothing runs between calls.';
Two clocks, in the MCP server's own page and in the player's tab alike. The agent's clock: nothing moves until a tool
asks for days with advance. A running clock: days pass at a fixed pace whatever the tool does, and the tool can only
wait and react. In the player's tab the player picks one in Settings (apiAgentMs(), 0 for the agent's clock); the MCP
server's own page is told by the server (API_CLK). */
let API_CLK={mode:'agent',paceMs:0,running:false};
const apiClockNow=()=>API_CTX.relay?(apiAgentMs()>0?{mode:'realtime',paceMs:apiAgentMs(),running:!!UI.speed}:{mode:'agent',paceMs:0,running:false}):API_CLK;
function apiMode(){const c=apiClockNow();
return {backend:API_CTX.relay?'browser':'headless',clock:c.mode,...(c.mode==='realtime'?{paceMs:c.paceMs}:{}),
...(API_CTX.relay?{withheld:API_WITHHELD,playerOwns:Object.keys(API_PLAYER_OWNS)}:{})};}
function apiClockDoc(){const c=apiClockNow();
return c.mode==='agent'?'Time moves only with advance: one dayTick() per simulated day, as the game loop runs it. Nothing runs between calls.'
:`The clock runs on its own: one simulated day every ${apiR1(c.paceMs/1000)} s of real time, behind open windows too, and no tool can stop it${API_CTX.relay?' (it holds while no tool is connected)':''}. advance is not available; wait returns once days have passed.`;}
function apiClock(){const c=apiClockNow();
return {mode:c.mode,paceMs:c.paceMs||undefined,running:c.mode==='realtime'?!!c.running:false,
day:S?S.day:null,date:S?dateStr(S.day):null,cash:S?S.cash:null,lost:!!(S&&S.lost),incidents:S?S.inc.map(i=>i.id):[],question:!!apiDecision()};}
// What happened since a moment (the start of an advance): the log, new incidents, cash.
// What happened since a moment (the start of an advance, or a clock reading before wait): the log, new incidents, cash.
// The log keeps what mattered; toasts that only repeat a log line are left out.
function apiSince({day=0,cash=0,inc=[]}={},toasts=[]){
const seen=new Set(inc),entries=(S.log||[]).filter(e=>e.d>day).slice(-60),logged=entries.map(e=>apiNorm(apiText(e.t,400)));
@ -15,7 +28,9 @@ function apiSince({day=0,cash=0,inc=[]}={},toasts=[]){
function apiAdvanceStart(days){
if(!S)apiFail('No game is running.');
if(apiModalOpen())apiFail('A window is open. Answer it first (screen, click, or act closeModal), the game does not run days behind it.');
const c=apiClockNow();
if(c.mode!=='agent')apiFail(`The clock runs on its own here, one day every ${apiR1(c.paceMs/1000)} s: use wait to let days pass.`);
if(apiModalOpen()&&!apiPlayerWin())apiFail('A window is open. Answer it first (screen, click, or act closeModal), the game does not run days behind it.');
API_SHEET=null;
apiTake();
return {days:Math.max(1,Math.min(3650,Math.floor(+days)||1)),start:S.day,cash:S.cash,inc:S.inc.map(i=>i.id),times:[],ran:0,stop:null};}
@ -26,7 +41,7 @@ function apiAdvanceDay(a){
const t=performance.now();
dayTick();
a.times.push({day:S.day,ms:apiR1(performance.now()-t)});a.ran++;
if(apiModalOpen()){a.stop='a window opened';return false;}
if(apiModalOpen()&&!apiPlayerWin()){a.stop='a window opened';return false;}
return a.ran<a.days;}
function apiAdvanceEnd(a){
renderAll();
@ -36,3 +51,17 @@ function apiAdvanceEnd(a){
timing:{totalMs:apiR1(total),perDayMs:apiR1(total/(a.ran||1)),slowestDays:a.times.slice().sort((x,y)=>y.ms-x.ms).slice(0,5).map(x=>({date:dateStr(x.day),ms:x.ms}))},
...(out.decision?{decision:out.decision,screen:out.screen}:{})};}
function apiAdvance(days){const a=apiAdvanceStart(days);while(apiAdvanceDay(a));return apiAdvanceEnd(a);}
/* In the player's tab the days run where the player can watch them: a frame's worth of days, then the page draws.
A hidden tab draws nothing (and its timers are throttled), so there they run straight through. A day the route
worker is still routing finishes first. */
const apiSleep=ms=>new Promise(r=>setTimeout(r,ms));
async function apiAdvanceLive(days){
const a=apiAdvanceStart(days);let t=performance.now();
for(;;){
while(RW.job)await apiSleep(20);
if(!apiAdvanceDay(a))break;
if(document.visibilityState!=='hidden'&&performance.now()-t>30){renderHUD();UI.panelsDue=true;await apiSleep(0);t=performance.now();}}
return apiAdvanceEnd(a);}
// One day of a running clock in the MCP server's own page (the server keeps the time); the player's tab runs its own loop.
function apiTick(){if(!S||S.lost||pzOn()||!rule('clock'))return false;dayTick();renderAll();return true;}

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

@ -0,0 +1,86 @@
/* ================= AGENT MODE: the player's switch and clock =================
In the player's own tab (the development page, served locally), the player can let an agent drive: the page dials
the agent relay (80-relay.js) and answers tool calls through TUBES.call. While it does, the clock is not the
player's (UI.clockLocked): either a fixed pace, one simulated day every 30 s to 5 min, that nobody can pause and
that holds while no tool is connected; or the agent's clock, which stands still until the agent asks for days.
The game itself knows none of this: it calls HOOKS (50-state.js), which this file fills in, and reads
UI.clockLocked. Settings of its own, in their own storage key, so the game's preferences stay as they are. */
const API_AGENT_MS=[0,30000,60000,120000,300000],API_AGENT_KEY='sot-agent';
const API_AGENT_PREFS=(()=>{let j={};try{j=JSON.parse(localStorage.getItem(API_AGENT_KEY)||'{}')||{};}catch(e){}
return {on:j.on===true,ms:API_AGENT_MS.includes(j.ms)?j.ms:60000};})();
/* Only where a relay can be: plain http (an https page cannot open ws://) to an address, never a DNS name, which the
relay refuses (DNS rebinding). The public site is https and a name, so it never shows the switch. The test
harness's made-up origin opts in, and a test page loaded from the public address does not. */
const apiAgentLocal=(p,h)=>p==='http:'&&(h==='localhost'||/\.localhost$/.test(h)||/^\[[0-9a-f:.]+\]$/i.test(h)||/^\d{1,3}(\.\d{1,3}){3}$/.test(h));
const API_AGENT_OK=apiAgentLocal(location.protocol,location.hostname)||!!window.__TUBES_TEST__&&location.hostname==='tests.invalid';
const apiAgentMs=()=>API_AGENT_PREFS.ms;
const apiMsLabel=ms=>ms>=60000?tr('settings.n_min',{n:Math.round(ms/60000)}):tr('settings.n_sec',{n:Math.round(ms/1000)});
const apiAgentMsLabel=()=>apiAgentMs()>0?apiMsLabel(apiAgentMs()):tr('settings.agent_s_clock');
/* The speed a locked clock runs at: the pace while a tool is connected, else held (0); always 0 on the agent's clock,
where only advance moves days; and only in a game with a clock (the rule the pause buttons follow). */
function apiAgentSpeed(){const r=API_RELAY;return r.on&&r.tools>0&&apiAgentMs()>0&&S&&rule('clock')?DAY_MS/apiAgentMs():0;}
// k: 'on' (true/false) or 'ms' (one of API_AGENT_MS). Anything else is ignored, never coerced.
function apiAgentSet(k,v){
if(k==='on')API_AGENT_PREFS.on=v===true||v==='1'||v===1;
else if(k==='ms'){if(!API_AGENT_MS.includes(+v))return;API_AGENT_PREFS.ms=+v;}
else return;
try{localStorage.setItem(API_AGENT_KEY,JSON.stringify(API_AGENT_PREFS));}catch(e){}
apiAgentSync();}
/* Locks or frees the clock to match the switch, and keeps the speed where it belongs. Switching on leaves the save's
speed alone (save() does not overwrite it while the clock is locked), so switching off puts back the one the player
left the game at. Safe to run any number of times. */
function apiAgentSync(){
const on=!RW_IN&&API_AGENT_OK&&API_AGENT_PREFS.on;
if(on!==UI.clockLocked){
if(on&&S&&[0,0.5,1,2,4,8].includes(UI.speed))S.uiSpeed=UI.speed;
UI.clockLocked=on;
if(!on)UI.speed=S&&[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:(UI.lastSpeed||1);}
if(on)UI.speed=apiAgentSpeed();
apiRelaySync();
apiTickerSync();
renderHUD();renderTabbar();}
/* What the game draws for a locked clock: the badge in the HUD in place of the speed buttons, and on phones the two
tab bar slots of play and speed, disabled, the second one reading the pace. */
function apiAgentHud(){
const p=$('spPace');if(!p)return;
p.hidden=!UI.clockLocked;
if(UI.clockLocked)p.textContent=apiAgentMs()>0?tr('settings.pace_t_per_day',{t:apiAgentMsLabel()}):apiAgentMsLabel();}
function apiAgentTabbar(){
return `<button class="play${UI.speed?'':' paused'}" disabled aria-label="${UI.speed?tr('common.pause'):tr('common.play')}"><span class="ic" aria-hidden="true">${UI.speed?'❚❚':'▶'}</span>${UI.speed?tr('common.pause'):tr('common.play')}</button>`+
`<button class="pace" disabled aria-label="${tr('common.game_speed')}"><span class="ic" aria-hidden="true">${apiAgentMs()>0?apiAgentMsLabel():'🤖'}</span>${tr('common.speed')}</button>`;}
/* The Settings section. Its buttons are the agent's own (data-agent-set, answered below), not game actions, so no
tool can find them on a screen and switch the agent off, or on. */
function apiAgentSettings(){
if(!API_AGENT_OK)return '';
const b=(v,l,on)=>`<button class="b ${on?'pink sm':'ghost sm'}" data-agent-set="${v}">${l}</button>`;
const line=(lab,btns,note)=>`<div class="setline"><span>${lab}</span><div class="seg">${btns}</div></div><p class="meta" style="margin:0 0 6px">${note}</p>`;
return `<h3 class="sub4">${tr('settings.agent_api')}</h3>`+
line(tr('settings.let_an_ai_agent_drive_this_game'),b('on:1',tr('common.on'),API_AGENT_PREFS.on)+b('on:0',tr('common.off'),!API_AGENT_PREFS.on),tr('settings.while_agent_mode_is_on_the'))+
line(tr('settings.the_clock_while_an_agent_plays'),API_AGENT_MS.map(m=>b('ms:'+m,m?apiMsLabel(m):tr('settings.the_agent_moves_it'),apiAgentMs()===m)).join(''),tr('settings.a_pace_runs_one_simulated_day'));}
function apiAgentClick(e){
const el=e.target&&e.target.closest&&e.target.closest('[data-agent-set]');if(!el||el.disabled)return;
const [k,v]=String(el.dataset.agentSet).split(':');
apiAgentSet(k,k==='on'?v==='1':v);sfx('click');refreshSettings();}
/* Who opened the window on screen: the player (a click, a key, a picker: window.event is the input being handled), or
the game itself (a day, a tool's call inside a relay message). A tool leaves the player's windows alone. */
const API_MODAL={hand:false};
const apiByHand=()=>{const e=window.event;return !!e&&/^(click|keydown|keyup|pointerup|touchend|change|input|submit)$/.test(e.type);};
// Wires agent mode into the page: the hooks, the badge and its style, the Settings buttons. Once, at load.
function apiAgentStart(){
if(RW_IN)return;
Object.assign(HOOKS,{speed:apiAgentSpeed,hud:apiAgentHud,tabbar:apiAgentTabbar,settings:apiAgentSettings,modal:open=>{API_MODAL.hand=open&&apiByHand();}});
const sp8=$('sp8');
if(sp8&&!$('spPace')){const p=document.createElement('span');p.id='spPace';p.hidden=true;sp8.after(p);}
const st=document.createElement('style');
st.textContent='.speed #spPace[hidden]{display:none}#spPace{border:2.5px solid var(--ink);background:var(--sun);border-radius:9px;height:32px;padding:0 8px;display:flex;align-items:center;font-family:var(--display);font-weight:800;font-size:12.5px;white-space:nowrap}'+
'#tabbar button.pace .ic{font-size:13px;line-height:1.25}';
document.head.appendChild(st);
document.addEventListener('click',apiAgentClick);
apiAgentSync();}

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

@ -0,0 +1,77 @@
/* ================= AGENT RELAY: the in-page transport =================
With agent mode on (75-mode.js), the page dials the agent relay (scripts/agent/relay.js, which npm run dev hosts on
its own port) and answers tool calls from connected tools (the MCP server, node scripts/mcp.js --browser) through
TUBES.call, so a human follows along on the real UI: toasts fire, panels render, the map moves.
No endpoint to configure and no token: the relay rides the server that served the page, same port, path
API_RELAY_PATH, so the endpoint is where the page already is. The relay refuses a page from any other origin and a
Host that is a name, so no website can reach it through the player's browser; who else can reach it is the
operator's choice of bind address. No eval ever: a message is JSON with a tool name from TUBES.tools, a fixed list,
answered as the relay (ctx.relay): the player's game, clock, windows and settings stay theirs, and the dice stay
hidden. Nothing dials or polls while the switch is off.
API_RELAY_HOST is a var because tests point it at their relay (under __TUBES_TEST__ nothing dials unless the test
opts in with __AGENT_RELAY_TEST__): a jsdom page is not loaded from the relay's server. */
var API_RELAY_HOST=''; // tests: '127.0.0.1:<port>'; live pages use their own host
const API_RELAY={ws:null,on:false,timer:null,tries:0,said:false,tools:0,host:null,queue:null};
const API_RELAY_PATH='/agent';
const apiRelayUrl=()=>`ws://${API_RELAY_HOST||location.host}${API_RELAY_PATH}`;
/* The relay reports tool presence on every connect and disconnect: the clock holds while no tool is connected and
runs again the moment one arrives. A missing relay (dial failed, retry backoff) holds it too. */
function apiRelayPresence(tools){
API_RELAY.tools=tools|0;
if(!UI.clockLocked||!API_RELAY.on)return;
const run=apiAgentSpeed();
if(run!==UI.speed){UI.speed=run;renderHUD();}}
function apiRelaySync(){
const want=!RW_IN&&UI.clockLocked&&(!window.__TUBES_TEST__||!!window.__AGENT_RELAY_TEST__);
// Nothing to do when the switch and the endpoint stand: tearing a healthy dial down for nothing drops the calls in
// flight and holds the clock for no reason.
if(API_RELAY_HOST===API_RELAY.host&&API_RELAY.on===want&&(want?!!(API_RELAY.ws||API_RELAY.timer):true))return;
clearTimeout(API_RELAY.timer);API_RELAY.timer=null;API_RELAY.tries=0;
if(API_RELAY.ws){const w=API_RELAY.ws;API_RELAY.ws=null;try{w.close();}catch(e){}}
API_RELAY.on=want;API_RELAY.host=API_RELAY_HOST;
apiRelayPresence(0); // off the relay: nobody driving, the clock holds
if(want)apiRelayDial();}
// Dev reloads and relay restarts heal on their own, without a spinning reconnect.
function apiRelayRetry(){
if(!API_RELAY.on)return;
const wait=Math.min(15000,500*Math.pow(2,Math.min(API_RELAY.tries++,5)));
API_RELAY.timer=setTimeout(()=>{API_RELAY.timer=null;apiRelayDial();},wait);}
/* One call, answered in order: calls queue behind each other, so a move sent while days are still running waits for
them, as the tool sent it. A promise (days the player watches) is awaited; a throw is the tool's error. */
function apiRelayAnswer(ws,m){
const dayBefore=S?S.day:null,send=o=>{if(API_RELAY.ws===ws)ws.send(JSON.stringify({kind:'result',id:m.id,dayBefore,dayAfter:S?S.day:null,...o}));};
const run=()=>Promise.resolve().then(()=>TUBES.call(m.tool,m.args||{},{relay:true}))
.then(value=>send({value}),er=>send({error:String(er&&er.message||er)}));
API_RELAY.queue=(API_RELAY.queue||Promise.resolve()).then(run);}
function apiRelayDial(){
if(!API_RELAY.on)return;
let ws;
try{ws=new WebSocket(apiRelayUrl());}catch(e){return apiRelayRetry();}
API_RELAY.ws=ws;
ws.onopen=()=>{
if(API_RELAY.ws!==ws)return;
ws.send(JSON.stringify({kind:'auth',role:'page'}));
API_RELAY.tries=0;
if(!API_RELAY.said){API_RELAY.said=true;toast(tr('settings.agent_relay_connected'),'good');}};
ws.onmessage=e=>{
if(API_RELAY.ws!==ws)return;
let m;try{m=JSON.parse(e.data);}catch(_){return;}
if(!m||typeof m!=='object')return;
if(m.kind==='presence'){apiRelayPresence(m.tools);return;}
if(m.kind!=='call'||m.id===undefined)return;
// A call this page cannot make sense of is answered, never ignored: a silent drop would hang the tool that sent it.
if(typeof m.tool!=='string'||!TUBES.tools.includes(m.tool)){ws.send(JSON.stringify({kind:'result',id:m.id,error:`no tool "${m.tool}" here`}));return;}
apiRelayAnswer(ws,m);};
// Replaced (4000): another tab took the relay, so this one yields instead of fighting it: redialing would just
// replace the new tab back, forever. Toggling agent mode dials again.
ws.onclose=e=>{if(API_RELAY.ws!==ws)return;API_RELAY.ws=null;
apiRelayPresence(0); // off the relay: the clock holds
if(e&&e.code===4000)API_RELAY.on=false;else apiRelayRetry();};
ws.onerror=()=>{};}

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

@ -0,0 +1,24 @@
/* ================= AGENT MODE: the clock where frames do not run =================
A paced clock runs through the game's own loop (UI.speed is the pace, runClock() the days), but frames stop in a
hidden tab, and the frame runs no days behind an open window. Agent mode keeps time in both: a hidden tab is the
normal place for an agent to drive while the player does something else, and an agent that deliberates over a
window pays for it in days. This ticker covers exactly those moments, under the frame's other conditions, and
leaves every other moment to the frame. Hidden-tab timers are throttled (to 1 Hz, after five minutes to once a
minute in Chrome), so an unthrottled worker posts the ticks; a plain interval is the fallback without Worker.
The agent's clock (pace 0) needs no ticks: its days run when the agent asks. Never under __TUBES_TEST__: tests call
apiAgentTick() by hand. */
const API_TICKER={on:false,worker:null,interval:null,last:0};
// Days for the time since the last tick, if the frame is not running them now.
function apiAgentTick(now=performance.now()){
const dt=API_TICKER.last?Math.max(0,Math.min(1000,now-API_TICKER.last)):0;API_TICKER.last=now;
const behind=document.visibilityState==='hidden'||!$('modal').hidden;
if(behind&&UI.clockLocked&&S&&!S.lost&&UI.speed&&!pzOn())runClock(dt);}
function apiTickerSync(){
const want=UI.clockLocked&&apiAgentMs()>0&&!window.__TUBES_TEST__;
if(want===API_TICKER.on)return;API_TICKER.on=want;API_TICKER.last=0;
if(!want){if(API_TICKER.worker){try{API_TICKER.worker.terminate();}catch(e){}API_TICKER.worker=null;}
if(API_TICKER.interval){clearInterval(API_TICKER.interval);API_TICKER.interval=null;}return;}
try{const url=URL.createObjectURL(new Blob(['setInterval(()=>postMessage(0),250)'],{type:'text/javascript'}));
API_TICKER.worker=new Worker(url);URL.revokeObjectURL(url);
API_TICKER.worker.onmessage=()=>apiAgentTick();}
catch(e){API_TICKER.interval=setInterval(()=>apiAgentTick(),250);}}

View file

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

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

@ -0,0 +1,4 @@
/* ================= AGENT API: start =================
Last, once every file of the facade has loaded: agent mode wires itself in (75-mode.js). Everything before this only
defines tables and functions. */
apiAgentStart();