The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
import {clone,validateProject,history,digest,canonical} from './project.mjs';
import {esc,slug,componentSVG,boardSVG,sheets,sheetSVG,rulebookHTML,printHTML,kitFiles} from './formats.mjs';
import {zipFiles} from './archive.mjs';
const $=id=>document.getElementById(id),boot=JSON.parse($('relay-data').textContent),bootHTML='<!doctype html>\n'+document.documentElement.outerHTML;
let project=validateProject(boot.project),baseRevision=boot.project.revision,sourceConnected=false,engineReady=false,sourcePending=null,edits=history(project),selected=project.components[0].id,runningProject=clone(project),runRevision='',view=null,report=null,worker=null,sequence=0,pending=new Map(),busy=false,noticeTimer,editorApply,sourceTimer;
const storageKey='relay-draft:'+location.href;
const download=(name,body,type='application/octet-stream')=>{const u=URL.createObjectURL(body instanceof Blob?body:new Blob([body],{type})),a=document.createElement('a');a.href=u;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(u),10000);};
function notify(message,error=false){clearTimeout(noticeTimer);$('notice').textContent=message;$('notice').hidden=false;$('notice').classList.toggle('error',error);noticeTimer=setTimeout(()=>$('notice').hidden=true,error?14000:6500);}
const guard=fn=>async(...args)=>{try{return await fn(...args);}catch(e){notify(e.message,true);}};
function remember(){try{localStorage.setItem(storageKey,JSON.stringify({baseRevision,project}));}catch{notify('Browser draft storage is full. Download the project to keep this edition.',true);}}
function makeWorker(){if(worker)worker.terminate();for(const p of pending.values()){clearTimeout(p.timer);p.reject(new Error('The previous rules worker stopped.'));}pending.clear();const u=URL.createObjectURL(new Blob([boot.worker],{type:'text/javascript'}));worker=new Worker(u);URL.revokeObjectURL(u);worker.onmessage=({data})=>{const p=pending.get(data.id);if(!p)return;pending.delete(data.id);clearTimeout(p.timer);data.error?p.reject(new Error(data.error)):p.resolve(data.result);};worker.onerror=e=>{for(const p of pending.values()){clearTimeout(p.timer);p.reject(new Error(e.message||'Rules worker failed.'));}pending.clear();};}
function call(type,payload={}){return new Promise((resolve,reject)=>{const id=++sequence;const timer=setTimeout(()=>{worker.terminate();engineReady=false;renderEdition();for(const p of pending.values()){clearTimeout(p.timer);p.reject(new Error('Rules exceeded the time limit. Your source is kept; revise it and apply again.'));}pending.clear();},type==='simulate'?30000:4000);pending.set(id,{resolve,reject,timer});worker.postMessage({id,type,payload});});}
function portable(p){const payload=JSON.stringify({project:p,worker:boot.worker}).replace(/</g,'\\u003c');return bootHTML.replace(/(<script id="relay-data" type="application\/json">)[\s\S]*?(<\/script>)/,(_,a,b)=>a+payload+b);}
async function start(p,{seed=$('seed').value,curtain=true}={}){engineReady=false;renderEdition();makeWorker();const next=await call('load',{project:p,seed});engineReady=true;runningProject=clone(p);runRevision=next.revision;view=next;report=null;$('simulation-report').replaceChildren();renderPlay(curtain);renderEdition();}
async function preservePlaytest(){if(!view)return;let replay=null;try{replay=await call('replay');}catch{}download(slug(runningProject.title)+'-previous-playtest.zip',zipFiles({'game.html':portable(runningProject),'project.relay.json':JSON.stringify(runningProject,null,2),'replay.json':JSON.stringify(replay,null,2)}));}
function edit(mutator){const next=clone(project);mutator(next);project=validateProject(next);edits.push(project);remember();renderEditor();renderEdition();}
function renderEdition(){const changed=canonical(project)!==canonical(runningProject);$('edition-notice').hidden=!changed&&engineReady;$('restart').disabled=!engineReady;$('edition-notice').querySelector('span').textContent=engineReady?'The table is playing the previous edition.':'Apply a valid edition to start the table.';$('game-title').textContent=project.title;$('game-subtitle').textContent=project.subtitle;$('source-state').textContent=(sourceConnected?'Workspace source':'Portable game')+(sourcePending?' · source changed':changed?' · draft edition':' · playing current edition');$('undo-edit').disabled=!edits.canUndo;$('redo-edit').disabled=!edits.canRedo;$('save-source').disabled=!sourceConnected;document.title=project.title+' — Relay';}
function renderEditor(){
$('library-title').textContent=project.title;
$('component-list').innerHTML=project.components.map(c=>`<button class="component-row ${c.id===selected?'active':''}" data-component="${esc(c.id)}"><span class="swatch" style="background:${c.color};color:${c.ink}">${esc(c.symbol)}</span><span>${esc(c.name)}${c.locked?' · locked':''}<small>${c.quantity} ${esc(c.kind)}${c.quantity===1?'':'s'} · ${c.widthMm} × ${c.heightMm} mm</small></span></button>`).join('');
$('component-list').querySelectorAll('button').forEach(b=>b.onclick=()=>{selected=b.dataset.component;renderEditor();});
$('settings').innerHTML=project.settings.map(s=>`<label>${esc(s.label)}<input data-setting="${s.id}" type="number" min="${s.min}" max="${s.max}" step="${s.step}" value="${s.value}"></label>`).join('');
$('settings').querySelectorAll('input').forEach(el=>el.onchange=guard(()=>edit(p=>p.settings.find(s=>s.id===el.dataset.setting).value=Number(el.value))));
const c=project.components.find(c=>c.id===selected)??project.components[0];selected=c.id;
try{$('component-preview').innerHTML=componentSVG(c);}catch(e){$('component-preview').textContent=e.message;}
const disabled=c.locked?'disabled':'';
$('component-form').innerHTML=`<label>Name<input name="name" maxlength="80" value="${esc(c.name)}" ${disabled}></label><label>Card text<textarea name="body" rows="4" maxlength="700" ${disabled}>${esc(c.body)}</textarea></label><div class="row"><label>Color<input name="color" type="color" value="${c.color}" ${disabled}></label><label>Ink<input name="ink" type="color" value="${c.ink}" ${disabled}></label></div><label>Symbol<input name="symbol" maxlength="8" value="${esc(c.symbol)}" ${disabled}></label><div class="row"><label>Width · mm<input name="widthMm" type="number" min="12" max="190" step=".5" value="${c.widthMm}" ${disabled}></label><label>Height · mm<input name="heightMm" type="number" min="12" max="273" step=".5" value="${c.heightMm}" ${disabled}></label></div><label>Copies<input name="quantity" type="number" min="1" max="100" value="${c.quantity}" ${disabled}></label><div class="row"><button type="button" id="import-face" ${disabled}>Import face artwork</button>${c.face?`<button type="button" id="reset-face" ${disabled}>Use generated face</button>`:''}</div>${c.face?'<p class="muted" style="font-size:11px">Custom artwork owns the printed face. Update its text when you change rules values.</p>':''}<h3>Rules values</h3>${Object.entries(c.values).map(([k,v])=>`<label>${esc(k)}<input data-value="${esc(k)}" data-type="${typeof v}" value="${esc(v)}" ${disabled}></label>`).join('')}<div class="row"><button type="button" id="lock-component">${c.locked?'Unlock':'Lock'} component</button><button type="button" id="duplicate-component">Duplicate</button></div><p class="muted" style="font-size:10px;margin-top:14px">Rules read component ids and values. Editing this draft keeps the running playtest intact until you apply it.</p>`;
$('component-form').onsubmit=e=>e.preventDefault();
$('component-form').querySelectorAll('input,textarea').forEach(el=>el.onchange=guard(()=>edit(p=>{const target=p.components.find(x=>x.id===selected);if(target.locked)throw new Error('Unlock this approved component before editing.');if(el.dataset.value){const type=el.dataset.type;if(type==='boolean'&&!['true','false'].includes(el.value))throw new Error('Enter true or false.');target.values[el.dataset.value]=type==='number'?Number(el.value):type==='boolean'?el.value==='true':el.value;}else target[el.name]=['widthMm','heightMm','quantity'].includes(el.name)?Number(el.value):el.value;})));
$('import-face').onclick=()=>$('face-file').click();if($('reset-face'))$('reset-face').onclick=guard(()=>edit(p=>delete p.components.find(c=>c.id===selected).face));
$('lock-component').onclick=guard(()=>edit(p=>p.components.find(x=>x.id===selected).locked=!c.locked));
$('duplicate-component').onclick=guard(()=>{const copy=clone(c);copy.id='piece-'+Date.now().toString(36);copy.name=c.name+' copy';copy.locked=false;selected=copy.id;edit(p=>p.components.push(copy));});
}
function renderPlay(curtain=false){if(!view)return;
const p=runningProject;$('scores').innerHTML=view.view.scores.map(s=>`<div>${esc(s.label)}<strong>${esc(s.value)}</strong></div>`).join('');$('turn-title').textContent=view.outcome?.title??view.view.title;$('turn-message').textContent=view.view.message??'';$('turn-count').textContent='Turn '+view.step;$('undo-turn').disabled=!view.step;
const piece=item=>{const c=p.components.find(c=>c.id===item.component);item={...item,action:view.actions.some(a=>a.id===item.action)?item.action:null};if(!c)throw new Error('Observation refers to unknown component '+item.component);return`<div class="table-piece"><button class="game-piece" ${item.action?`data-move="${esc(item.action)}"`:''} aria-label="${esc(item.faceDown?'Face-down piece':c.name)}" ${item.action?'':'disabled'}><div style="transform:rotate(${Number(item.rotation)||0}deg)">${componentSVG(c,{back:!!item.faceDown})}</div>${item.badge!==undefined?`<span class="badge">${esc(item.badge)}</span>`:''}</button>${c.kind==='card'&&!item.faceDown?`<span class="piece-label">${esc(c.name)}<small>${Object.entries(c.values).map(([k,v])=>esc(k)+': '+esc(v)).join(' · ')}</small></span><details><summary>Read card</summary><p>${esc(c.body)}</p></details>`:''}</div>`;};
$('zones').innerHTML=view.view.zones.map(z=>{let content;if(z.board){const b=p.boards.find(b=>b.id===z.board);if(!b)throw new Error('Unknown board '+z.board);content=`<div class="board" style="grid-template-columns:repeat(${b.cols},1fr)">${b.cells.map((cell,i)=>`<div class="board-cell" style="background:${cell.color}"><small>${esc(cell.label)}</small>${z.items.filter(item=>item.cell===i).map(piece).join('')}</div>`).join('')}</div>`;}else content=`<div class="cards">${z.items.map(piece).join('')||'<small>No components here yet.</small>'}</div>`;return`<section class="zone"><h3>${esc(z.label)}</h3>${content}</section>`;}).join('');
$('actions').innerHTML=view.actions.map(a=>`<button data-move="${esc(a.id)}">${esc(a.label)}</button>`).join('');
document.querySelectorAll('[data-move]').forEach(b=>b.onclick=guard(()=>move(b.dataset.move)));
const privateTurn=!view.outcome&&!!view.view.private;$('curtain').hidden=!(curtain&&privateTurn);for(const id of ['scores','zones','actions'])$(id).inert=!$('curtain').hidden;$('curtain-title').textContent='Player '+(view.player+1)+', your turn.';
}
async function move(id){if(busy)return;busy=true;try{const before=view.player;view=await call('step',{id});renderPlay(view.player!==before);rememberReplay();}finally{busy=false;}}
async function rememberReplay(){try{const replay=await call('replay');localStorage.setItem(storageKey+':replay',JSON.stringify({project:runningProject,replay}));}catch{}}
function renderRules(){$('rulebook-editor').innerHTML=project.rulebook.map((s,i)=>`<section class="rule-section"><label>Section heading<input data-heading="${i}" maxlength="160" value="${esc(s.heading)}"></label><label>Instructions<textarea data-body="${i}" rows="5" maxlength="10000">${esc(s.body)}</textarea></label></section>`).join('');$('rulebook-editor').querySelectorAll('input,textarea').forEach(el=>el.onchange=guard(()=>edit(p=>{const i=Number(el.dataset.heading??el.dataset.body);p.rulebook[i][el.dataset.heading===undefined?'body':'heading']=el.value;})));}
function openPrint(html){const url=URL.createObjectURL(new Blob([html],{type:'text/html'}));window.open(url,'_blank','noopener');setTimeout(()=>URL.revokeObjectURL(url),60000);}
function dialog(title,content,apply){$('editor-title').textContent=title;$('editor-content').innerHTML=content;editorApply=apply;$('editor-dialog').showModal();}
$('editor-apply').onclick=guard(()=>{editorApply();$('editor-dialog').close();});
$('edit-rules').onclick=()=>dialog('Author this game’s rules',`<p>The complete JavaScript module defines mechanics. Export initial, legal, apply, observe, outcome and validate; optional bot supplies a named policy. Use only local code. An edited module becomes a new edition when you apply it to the table.</p><textarea id="rules-code" class="code" spellcheck="false">${esc(project.rules)}</textarea>`,()=>edit(p=>p.rules=$('rules-code').value));
$('edit-metadata').onclick=()=>dialog('Game details',`<label>Title<input id="game-name-edit" value="${esc(project.title)}" maxlength="160"></label><label>Subtitle<textarea id="game-subtitle-edit" maxlength="400">${esc(project.subtitle)}</textarea></label><label>Players<input id="game-players-edit" type="number" min="1" max="6" value="${project.players}"></label><p>Player count must match the authored rules.</p>`,()=>edit(p=>{p.title=$('game-name-edit').value;p.subtitle=$('game-subtitle-edit').value;p.players=Number($('game-players-edit').value);}));
$('add-component').onclick=()=>dialog('Add a component',`<label>Name<input id="new-name" value="New card" maxlength="80"></label><label>Kind<select id="new-kind"><option value="card">Card</option><option value="tile">Tile</option><option value="token">Token</option></select></label><p>Adding a design does not invent its behavior. Reference its id and values in the rules module.</p>`,()=>{const id='piece-'+Date.now().toString(36),kind=$('new-kind').value;selected=id;edit(p=>p.components.push({id,name:$('new-name').value,body:'',kind,widthMm:kind==='card'?63:35,heightMm:kind==='card'?88:35,quantity:1,color:'#365948',ink:'#fff8e9',symbol:'✦',values:{},locked:false}));});
$('undo-edit').onclick=()=>{project=edits.undo();remember();renderEditor();renderEdition();};$('redo-edit').onclick=()=>{project=edits.redo();remember();renderEditor();renderEdition();};
$('apply-edition').onclick=guard(async()=>{await preservePlaytest();await start(project);notify('Previous game and replay downloaded. Playing the edited edition.');});
$('restart').onclick=guard(async()=>{await preservePlaytest();view=await call('restart',{seed:$('seed').value});renderPlay(true);notify('A fresh playtest is ready. The previous game was kept.');});
$('undo-turn').onclick=guard(async()=>{view=await call('undo');renderPlay(true);rememberReplay();});$('reveal').onclick=()=>{$('curtain').hidden=true;for(const id of ['scores','zones','actions'])$(id).inert=false;};
$('save-replay').onclick=guard(async()=>download(slug(runningProject.title)+'-replay.json',JSON.stringify(await call('replay'),null,2),'application/json'));
$('open-replay').onclick=()=>$('replay-file').click();$('replay-file').onchange=guard(async e=>{const f=e.target.files[0];if(!f)return;if(f.size>5000000)throw new Error('Choose a replay below 5 MB.');view=await call('restore',JSON.parse(await f.text()));$('seed').value=view.seed;renderPlay(true);notify('Replay verified against its rules and actions.');e.target.value='';});
$('simulate').onclick=guard(async()=>{if(busy)return;busy=true;$('simulate').disabled=true;$('simulate').textContent='Testing…';try{report=await call('simulate',{count:Number($('simulation-count').value),policy:$('policy').value,maxTurns:400});$('simulation-report').innerHTML=`<div class="simulation-stats"><span><strong>${report.completed}/${report.count}</strong>completed</span><span><strong>${report.errors}</strong>errors</span><span><strong>${report.capped}</strong>turn caps</span><span><strong>${report.meanTurns.toFixed(1)}</strong>mean turns</span>${report.wins.map((n,i)=>`<span><strong>${n}</strong>Player ${i+1} wins</span>`).join('')}</div><p>${esc(report.scope)}</p><button id="save-simulation">Download seeds, outcomes & replays</button>`;$('save-simulation').onclick=()=>download(slug(runningProject.title)+'-simulation.json',JSON.stringify(report,null,2),'application/json');}finally{busy=false;$('simulate').disabled=false;$('simulate').textContent='Run playtest';}});
async function exportKit(){validateProject(project);sheets(project);const same=canonical(project)===canonical(runningProject);if(!same||!engineReady)throw new Error('Apply this edition to the table before exporting its complete kit. Your draft project can always be downloaded.');const replay=await call('replay');download(slug(project.title)+'-print-and-play.zip',zipFiles(kitFiles(project,portable(project),replay,report)));notify('Complete playable and printable game exported.');}
$('export-kit').onclick=guard(exportKit);$('export-kit-secondary').onclick=guard(exportKit);
$('export-html').onclick=guard(()=>download(slug(project.title)+'.html',portable(validateProject(project)),'text/html'));$('export-project').onclick=()=>download(slug(project.title)+'.relay.json',JSON.stringify(project,null,2),'application/json');
$('print-components').onclick=guard(()=>openPrint(printHTML(project)));$('print-rulebook').onclick=$('print-rules').onclick=guard(()=>openPrint(rulebookHTML(project)));
$('add-section').onclick=guard(()=>{edit(p=>p.rulebook.push({heading:'New section',body:'Describe the next part of the game.'}));renderRules();});
$('face-file').onchange=guard(async e=>{const f=e.target.files[0];if(!f)return;const types=['image/png','image/jpeg','image/webp','image/svg+xml'];if(!types.includes(f.type)||f.size>500000)throw new Error('Use a PNG, JPEG, WebP or SVG face below 500 KB.');const bytes=new Uint8Array(await f.arrayBuffer());let binary='';for(const byte of bytes)binary+=String.fromCharCode(byte);const face='data:'+f.type+';base64,'+btoa(binary),img=new Image();img.src=face;await img.decode();edit(p=>{const c=p.components.find(c=>c.id===selected);if(c.locked)throw new Error('Unlock the component before replacing its artwork.');c.face=face;});e.target.value='';});
$('open-project').onclick=()=>$('project-file').click();$('project-file').onchange=guard(async e=>{const f=e.target.files[0];if(!f)return;if(f.size>3000000)throw new Error('Choose a game project below 3 MB.');const next=validateProject(JSON.parse(await f.text()));await preservePlaytest();project=next;edits=history(project);selected=project.components[0].id;remember();renderEditor();renderEdition();await start(project);e.target.value='';notify('Game source opened. Save source to replace the workspace edition.');});
async function saveSource(){const response=await fetch('/api/project',{method:'PUT',headers:{'content-type':'application/json','if-match':baseRevision},body:JSON.stringify(project)}),body=await response.json();if(response.status===409){sourcePending=body.project;$('source-notice').hidden=false;throw new Error('The agent changed the source. Keep both editions before choosing.');}if(!response.ok)throw new Error(body.error);baseRevision=body.project.revision;sourcePending=null;$('source-notice').hidden=true;remember();renderEdition();notify('Source saved with the previous edition in workspace history.');}
$('save-source').onclick=guard(saveSource);$('keep-draft').onclick=()=>download(slug(project.title)+'-draft.relay.json',JSON.stringify(project,null,2),'application/json');
$('load-source').onclick=guard(async()=>{if(!sourcePending)return;download(slug(project.title)+'-before-source.relay.json',JSON.stringify(project,null,2),'application/json');project=validateProject(sourcePending);baseRevision=sourcePending.revision;sourcePending=null;$('source-notice').hidden=true;edits=history(project);remember();renderEditor();renderEdition();notify('Both source editions kept. Apply the new edition when ready to restart the playtest.');});
async function pollSource(){try{const response=await fetch('/api/project',{cache:'no-store'});if(!response.ok)return;const body=await response.json();sourceConnected=true;if(body.project.revision!==baseRevision){sourcePending=body.project;$('source-notice').hidden=false;}renderEdition();}catch{}}
for(const b of document.querySelectorAll('[data-tab]'))b.onclick=guard(()=>{for(const id of ['workbench','rules','print'])$(id).hidden=id!==b.dataset.tab;document.querySelectorAll('[data-tab]').forEach(x=>x.classList.toggle('active',x===b));if(b.dataset.tab==='rules')renderRules();if(b.dataset.tab==='print')$('print-preview').innerHTML=sheets(project).slice(0,8).map((items,i)=>sheetSVG(project,items,i)).join('')+project.boards.map(boardSVG).join('');});
try{const saved=JSON.parse(localStorage.getItem(storageKey)??'null');if(saved?.project&&canonical(saved.project)!==canonical(project)){project=validateProject(saved.project);baseRevision=saved.baseRevision;edits=history(project);notify('Restored the last browser draft.');}}catch{}
renderEditor();renderEdition();guard(async()=>{await start(project);if(['http:','https:'].includes(location.protocol)){await pollSource();sourceTimer=setInterval(pollSource,5000);}const saved=JSON.parse(localStorage.getItem(storageKey+':replay')??'null');if(saved?.replay&&saved.replay.revision===runRevision){view=await call('restore',saved.replay);renderPlay(true);notify('Restored and verified the previous playtest.');}})();