const $=(s,p=document)=>p.querySelector(s),$$=(s,p=document)=>[...p.querySelectorAll(s)]; const API_ORIGIN=String(window.CENNOMO_API_ORIGIN||'').replace(/\/$/,''); const R={data:null,gateway:[],operators:[],skills:[],events:[],selected:0,filter:'all',wallet:null,address:'',toast:0,roomTimer:0,roomOperatorId:null,reload:0,wallSignature:''}; const esc=(v='')=>String(v).replace(/[&<>'"]/g,c=>({'&':'&','<':'<','>':'>',"'":''','"':'"'}[c])); const text=(s,v,p=document)=>{const n=$(s,p);if(n)n.textContent=v}; const senmiloName=(value='')=>String(value).replace(/tardigrade/gi,match=>match===match.toUpperCase()?'OCTOPUS':match[0]===match[0].toUpperCase()?'Octopus':'octopus'); function brandSnapshot(snapshot){ snapshot.operators=(snapshot.operators||[]).map(operator=>({...operator,_backendName:operator.name,name:senmiloName(operator.name)})); snapshot.skills=(snapshot.skills||[]).map(skill=>({...skill,operator_name:senmiloName(skill.operator_name)})); snapshot.events=(snapshot.events||[]).map(event=>({...event,operator_name:senmiloName(event.operator_name)})); return snapshot; } const brandCopy=value=>String(value) .replace(/Tardigrade Agents?/g,match=>match.endsWith('s')?'Octopus Agents':'Octopus Agent') .replace(/TARDIGRADES/g,'OCTOPUSES') .replace(/TARDIGRADE/g,'OCTOPUS') .replace(/Tardigrades/g,'Octopuses') .replace(/Tardigrade/g,'Octopus') .replace(/tardigrades/g,'octopuses') .replace(/tardigrade/g,'octopus') .replace(/TARDUMO/g,'SENMILO') .replace(/Tardumo/g,'Senmilo') .replace(/tardumo/g,'senmilo') .replace(/\$TADM\b/g,'$SENMILO') .replace(/\bTADM\b/g,'SENMILO'); function brandInterface(root=document.body){ if(!root)return; const walker=document.createTreeWalker(root,NodeFilter.SHOW_TEXT); while(walker.nextNode())if(/tard|TADM/i.test(walker.currentNode.nodeValue))walker.currentNode.nodeValue=brandCopy(walker.currentNode.nodeValue); root.querySelectorAll?.('[alt],[title],[placeholder]').forEach(node=>['alt','title','placeholder'].forEach(attr=>{if(node.hasAttribute(attr))node.setAttribute(attr,brandCopy(node.getAttribute(attr)))})); } const age=v=>{if(!v)return'never';const s=Math.max(0,Math.floor((Date.now()-new Date(v))/1000));return s<60?`${s}s`:s<3600?`${Math.floor(s/60)}m`:s<86400?`${Math.floor(s/3600)}h`:`${Math.floor(s/86400)}d`}; function toast(m){const n=$('#toast');n.textContent=m;n.classList.add('show');clearTimeout(R.toast);R.toast=setTimeout(()=>n.classList.remove('show'),2600)} async function api(path,options={}){const r=await fetch(`${API_ORIGIN}/api${path}`,{...options,headers:{Accept:'application/json',...(options.headers||{})}}),b=await r.json().catch(()=>({}));if(!r.ok)throw Error(b.error||`request failed (${r.status})`);return b} async function registryData(){ try{return await Promise.all([api('/snapshot'),api('/v1/skills')]);} catch(primaryError){ const [snapshotResponse,skillsResponse]=await Promise.all([ fetch('./snapshot.json',{cache:'no-store'}), fetch('./skills.json',{cache:'no-store'}) ]); if(!snapshotResponse.ok||!skillsResponse.ok)throw primaryError; return Promise.all([snapshotResponse.json(),skillsResponse.json()]); } } const active=s=>!['offline','dead','queued'].includes(s); const frame=o=>o?.stream_path?`${API_ORIGIN}${o.stream_path}`:''; const videoStream=o=>o?`${API_ORIGIN}/api/operators/${encodeURIComponent(o._backendName||o.name)}/video.webm?session=${crypto.randomUUID?.()||Date.now()}`:''; function stopVideo(video){if(!video)return;video.pause();video.removeAttribute('src');video.load();video.classList.remove('connected');delete video.dataset.operatorId} function playVideo(video,o,wait){if(!video||!o)return;if(video.classList.contains('crawl-browser-frame'))setVerifiedMark('#stageVerifiedMark',o);if(video.id==='roomLiveFrame')setVerifiedMark('#roomVerifiedMark',o);if(video.dataset.operatorId===String(o.id)&&video.src)return;stopVideo(video);video.dataset.operatorId=String(o.id);if(wait)wait.hidden=false;video.onplaying=()=>{video.classList.add('connected');if(wait)wait.hidden=true};video.onerror=()=>{video.classList.remove('connected');if(wait)wait.hidden=false};video.src=videoStream(o);video.load();void video.play().catch(()=>{})} function setVerifiedMark(selector,operator){const mark=$(selector);if(mark)mark.hidden=operator?.state!=='verified'} function swapFrame(img,o,wait){if(!img)return;if(!o?.stream_path){if(!img.classList.contains('connected')&&wait)wait.hidden=false;return}const path=o.stream_path;if(img.dataset.framePath===path||img.dataset.pendingPath===path)return;img.dataset.pendingPath=path;const holder=img.parentElement,oldBuffer=$('.frame-buffer',holder);oldBuffer?.remove();const next=new Image,url=frame(o),kind=img.id==='roomLiveFrame'?'room-live-frame':img.classList.contains('crawl-browser-frame')?'crawl-browser-frame':'operator-live-frame';next.className=`${kind} frame-buffer`;next.alt='';next.onload=()=>{if(img.dataset.pendingPath!==path)return;holder.append(next);requestAnimationFrame(()=>next.classList.add('ready'));setTimeout(()=>{if(img.dataset.pendingPath!==path){next.remove();return}img.src=url;img.dataset.framePath=path;delete img.dataset.pendingPath;img.classList.add('connected');next.remove();if(wait)wait.hidden=true},420)};next.onerror=()=>{if(img.dataset.pendingPath===path)delete img.dataset.pendingPath;if(!img.classList.contains('connected')&&wait)wait.hidden=false};next.src=url} function configure(){ const c=R.data.config,m=c.tokenMint; $$('.ca-pill strong').forEach(n=>n.textContent=m?`${m.slice(0,4)}…${m.slice(-4)}`:'TBA'); $$('.ca-row code').forEach(n=>n.textContent=m||'TBA'); $$('a[href*="pump.fun"]').forEach(n=>n.href=c.pumpfunUrl); $$('[data-pending="CA"]').forEach(n=>{n.dataset.copy=m||''}); const ready=R.data.readiness||{},networkLive=ready.database&&ready.workerNetwork&&ready.httpsOrigin; text('#networkPhase',networkLive?'NETWORK LIVE':'NETWORK DEGRADED'); const x=R.data.metrics,s=$('.crawl-inline-stats'); if(s)s.innerHTML=`${x.activeOperators} octopuses awake, ${x.officialOperators} official Octopus Agents, ${x.skills} action routes, ${x.territories} territories, network live`; text('#awakeCount',x.activeOperators);text('#routeCount',x.skills); const cmd=$('#route-operators .route-command em'); if(cmd)cmd.innerHTML=`${x.activeOperators} awake · ${x.officialOperators} official Octopus Agents`; const meter=$('.ascii-meter'),awake=x.operators?Math.round(x.activeOperators/x.operators*100):0,verified=x.skills?Math.round(x.verifiedSkills/x.skills*100):0; if(meter)meter.innerHTML=`1[${x.activeOperators}/${x.operators} awake]2[${x.verifiedSkills}/${x.skills} verified]Map[${x.territories} territories]`; const summary=$('.network-summary>div:last-child'); if(summary)summary.innerHTML=`Agents: ${x.activeOperators} active · ${x.officialOperators} official octopusesRegistry: ${x.skills} routes · ${x.verifiedSkills} verifiedEvidence: ${R.events.length} recent records`; } function selectOperator(i){if(!R.operators.length){text('#operatorIndex','00/00');text('#operatorName','no octopus registered');text('#operatorState','offline');text('#operatorTerritory','—');text('#operatorRoute','—');text('#operatorTarget','No real worker data is available.');text('#liveUrl','waiting for worker');text('#liveEndpoint','—');stopVideo($('.crawl-browser-frame'));return}R.selected=(i+R.operators.length)%R.operators.length;const o=R.operators[R.selected],ev=R.events.find(e=>e.operator_id===o.id),skill=R.skills.find(s=>s.operator_id===o.id&&s.state==='verified');text('#operatorIndex',`${String(R.selected+1).padStart(2,'0')}/${String(R.operators.length).padStart(2,'0')}`);text('#operatorName',o.name);text('#operatorState',o.state);text('#operatorTerritory',o.territory);text('#operatorRoute',o.current_route||'discovering');text('#operatorTarget',o.target_url);text('#liveUrl',o.target_url);try{text('#liveEndpoint',new URL(o.target_url).pathname||'/')}catch{text('#liveEndpoint','/')};text('#feedAction',ev?.message||'waiting for first observation');text('#feedTime',o.last_seen?o.last_seen.slice(11,23):'--:--:--');text('#feedPhase',o.state.toUpperCase());text('#stageHttp',o.http_status||'—');text('#stageLatency',o.latency_ms?`${o.latency_ms}ms`:'—');text('#stageProofState',skill?'verified':o.state);text('#stageFrameState',o.stream_path?'published':'waiting');text('#proofAge',skill?`${age(skill.last_verified)} ago`:'never');text('#proofRouteState',skill?`${skill.name} · ${Number(skill.success_rate).toFixed(1)}%`:'no verified route');const proofChain=$('#proofChain');if(proofChain)proofChain.innerHTML=skill?`01public probe executedHTTP ${esc(o.http_status||'observed')}02response validated${esc(skill.name)}03proof committedsha ${esc(skill.proof.slice(0,12))}`:`01registry observing${esc(o.credential_required?'credential required':'verification pending')}`;renderVision($('#stageVision'),o.telemetry);playVideo($('.crawl-browser-frame'),o);const label=$('.feed-label');if(label)label.textContent=o.last_seen?`real evidence · ${age(o.last_seen)} ago`:'awaiting first worker report';const tail=$('.crawl-tail p');if(tail)tail.innerHTML=ev?` ${esc(o.name)} ${esc(ev.message)}${ev.proof?` ${esc(ev.proof.slice(0,12))}`:''}`:` ${esc(o.name)} no evidence yet`} function renderTable(){const b=$('#operatorRows');b.innerHTML='';if(!R.operators.length){b.innerHTML='No registered Octopus Agents.';return}R.operators.forEach((o,i)=>{const r=document.createElement('tr');r.innerHTML=`${o.id}${esc(o.name)}${active(o.state)?'R':'—'}${esc(o.territory)}${o.verified_skills}${o.http_status||'—'}${age(o.last_seen)}${esc(o.target_url)}`;r.onclick=()=>selectOperator(i);$('button',r).onclick=e=>{e.stopPropagation();openLive(o)};b.append(r)})} function traceSteps(o){const flags=[true,!!o.current_route,Number(o.verified_skills)>0,o.state==='verified'],names=['observe','locate','test','verify'];let current=flags.findIndex(value=>!value);if(current<0)current=3;return names.map((name,index)=>`${name}`).join('')} function renderVision(layer,telemetry){if(!layer||!telemetry)return;const progress=Math.max(0,Math.min(1,Number(telemetry.progress||0))),phase=telemetry.phase||'reading',label=phase==='opening-next-page'?'OPENING NEXT PAGE':phase==='awaiting-recheck'?'ROUTE COMPLETE · RECHECK QUEUED':'READING PAGE';layer.innerHTML=`
${label}${Math.round(progress*100)}%${Number(telemetry.actionableCount||0)} OBSERVED ELEMENTS · PASS ${Number(telemetry.auditRound||1)}
`} function card(o,i){const ev=R.events.find(e=>e.operator_id===o.id);return `
${String(i).padStart(2,'0')}:${esc(o.name)}${esc(o.state)}
${esc(o.target_url)}${active(o.state)?'live':'offline'}
Latest Tardigrade Agent browser output from ${esc(o.name)}
${active(o.state)?'LOADING FEED':'AWAITING WORKER'}${esc(o.territory)}
TARDIGRADE VISION${esc(o.current_route||'observing')}
${traceSteps(o)}

${esc(ev?.message||`observing ${o.territory} interface`)}

${o.http_status||'--'}${o.latency_ms?o.latency_ms+' ms':'-- ms'}
`} function renderWall(){const g=$('#monitorGrid'),list=R.operators.filter(o=>R.filter==='all'||o.state===R.filter),signature=`${R.filter}:${list.map(o=>o.id).join(',')}`;if(!list.length){if(R.wallSignature!==signature)g.innerHTML='
NO TARDIGRADES IN THIS STATEThe registry updates only from real worker reports.
';R.wallSignature=signature;return}if(R.wallSignature!==signature){g.innerHTML=list.map(card).join('');R.wallSignature=signature;$$('.operator-monitor',g).forEach(c=>{c.onclick=()=>openLive(R.operators.find(o=>String(o.id)===c.dataset.operatorId));c.onkeydown=e=>{if(e.key==='Enter'||e.key===' ')c.click()}})}list.forEach(o=>{const c=$(`[data-operator-id="${o.id}"]`,g),ev=R.events.find(e=>e.operator_id===o.id);if(!c)return;c.dataset.state=o.state;text('[data-role="state"]',o.state,c);text('[data-role="url"]',o.target_url,c);text('[data-role="signal"]',active(o.state)?'live':'offline',c);text('[data-role="http"]',o.http_status||'--',c);text('[data-role="latency"]',o.latency_ms?`${o.latency_ms} ms`:'-- ms',c);text('[data-role="meta"]',`${o.official?'OFFICIAL · ':''}${o.territory}`,c);text('[data-role="seen"]',o.last_seen?`${age(o.last_seen)} ago`:'never seen',c);text('[data-role="route"]',o.current_route||'observing',c);text('[data-role="event"]',ev?.message||`observing ${o.territory} interface`,c);const route=$('.vision-route',c);if(route)route.innerHTML=traceSteps(o);swapFrame($('.operator-live-frame',c),o,$('.feed-awaiting',c))});$$('[data-wall-filter]').forEach(b=>{const n=$('b',b);if(n)n.textContent=b.dataset.wallFilter==='all'?R.operators.length:R.operators.filter(o=>o.state===b.dataset.wallFilter).length})} function renderEvents(){const b=$('#eventStream');b.innerHTML='';if(!R.events.length){b.innerHTML='
registrywaitingwaiting for the first real worker report—
';return}R.events.slice(0,30).forEach(e=>{const n=document.createElement('div');n.className='event';n.innerHTML=`${esc(e.operator_name||'network')}${esc(e.type||'observed')}${esc(e.message)}${e.proof?esc(e.proof.slice(0,12)):'—'}`;b.append(n)})} function renderSkills(q=''){const b=$('#skillRows'),table=$('#route-skills .skill-table'),needle=q.toLowerCase(),list=R.skills.filter(s=>!needle||[s.name,s.territory,s.operator_name,s.state].join(' ').toLowerCase().includes(needle));b.innerHTML='';table?.classList.toggle('empty',!list.length);if(!list.length){const evidence=R.events.slice(0,4).map(e=>`
  • ${esc(e.operator_name||'network')}${esc(e.type)}${age(e.created_at)} ago
  • `).join('');b.innerHTML=`
    VERIFIED SKILL REGISTRY

    No callable routes match this view.

    The registry only exposes routes backed by an executable path, an explicit permission map and a reproducible proof.

    0
    OBSERVING${R.data.metrics.activeOperators}active Tardigrade AgentsEVIDENCE${R.events.length}recent recordsVERIFIED${R.data.metrics.verifiedSkills}callable routesQUERY${needle?'FILTERED':'OPEN'}${needle?esc(q):'all territories'}
    01 · EXECUTABLE ROUTE

    Typed inputs, deterministic steps and an isolated execution boundary.

    required
    02 · PERMISSION MAP

    Every account, wallet and data scope must be explicit before execution.

    required
    03 · REPLAY PROOF

    An independent run must reproduce the expected result before publication.

    required
    RECENT NETWORK EVIDENCEobservations only
    `;return}list.forEach(s=>{const h=Number(s.success_rate||0),n=document.createElement('div');n.className='skill-row';n.innerHTML=`${esc(s.name)}${esc(s.territory)}${esc(s.operator_name)}${h?h.toFixed(1)+'%':'—'}${age(s.last_verified)}${s.fee_lamports==null?'TBA':s.fee_lamports+' lamports'}`;$('button',n).onclick=()=>toast(s.proof?`proof ${s.proof}`:'No proof published');b.append(n)});const territories=new Set(list.map(s=>s.territory)).size,latest=list.map(s=>s.last_verified).filter(Boolean).sort().at(-1),proofs=R.events.filter(e=>e.type==='skill.verified').slice(0,4).map(e=>`
  • ${esc(e.operator_name||'network')}${esc(e.message)}${age(e.created_at)} ago
  • `).join('');b.insertAdjacentHTML('beforeend',`
    REGISTRY OPERATIONS

    Routes become callable through proof, not claims.

    ${list.length} visible routes
    TERRITORIES${territories}represented hereSUCCESS FLOOR${Math.min(...list.map(s=>Number(s.success_rate||0))).toFixed(1)}%visible route healthLATEST PROOF${latest?age(latest):'never'}${latest?'ago':'not recorded'}CALL FEES${list.some(s=>s.fee_lamports!=null)?'ACTIVE':'TBA'}prelaunch policy
    ADMISSION PATH01OBSERVEpublic interface02EXECUTEsandbox route03REPLAYindependent proof04PUBLISHgateway ready
    VERIFICATION LEDGERlive worker reports
      ${proofs||'
    • registryno verification event in the current window—
    • '}
    `)} function renderGateway(){const rows=$('#gatewayRows');if(!rows)return;const example=$('#gatewayExample');if(example)example.textContent=`curl -X POST ${API_ORIGIN||location.origin}/api/v1/skills/quote.fetch/invoke \\\n -H "Content-Type: application/json" \\\n -d '{}'`;text('#gatewayToolCount',`${R.gateway.length} tools`);text('#gatewayWorkers',R.data.metrics.onlineWorkers||0);text('#gatewayCalls',R.data.metrics.skillCalls||0);text('#gatewaySucceeded',R.data.metrics.successfulSkillCalls||0);text('#gatewayVault',R.data.readiness?.credentialVault?'READY':'LOCKED');text('#gatewaySettlement',R.data.readiness?.paidSettlement?'ACTIVE':'PRELAUNCH');rows.innerHTML='';R.gateway.forEach(skill=>{const n=document.createElement('article');n.className='gateway-tool';n.innerHTML=`
    ${esc(skill.name)}${esc(skill.operator)} · ${esc(skill.territory)} · ${skill.providerCount||1} provider

    ${esc(skill.description)}

    `;$('button',n).onclick=async()=>{const button=$('button',n);button.disabled=true;button.textContent='running';try{const result=await api(`/v1/skills/${encodeURIComponent(skill.name)}/invoke`,{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});toast(`${skill.name} succeeded · ${result.callId.slice(0,8)}`);await load(true)}catch(e){toast(e.message)}finally{button.disabled=false;button.textContent='run'}};rows.append(n)})} function renderTerritories(){const b=$('#territoryList');b.innerHTML='';text('#territoryCount',R.data.territories.length);text('#territoryHudCount',`${R.data.territories.length} territories observed`);text('#territoryHudEvidence',`${R.data.metrics.activeOperators} active Tardigrade Agents · ${R.events.length} evidence records`);R.data.territories.forEach((t,i)=>{const n=document.createElement('div'),state=t.state||((t.active_count)?'observing':'offline');n.className='territory-item';n.innerHTML=`${String(i+1).padStart(2,'0')}
    ${esc(t.territory)}${t.operator_count} registered Tardigrade Agent${t.operator_count===1?'':'s'}
    ${esc(state)}`;b.append(n)});drawTerritories()} function drawTerritories(){const c=$('#territoryCanvas');if(!c||!c.clientWidth)return;const x=c.getContext('2d'),w=c.clientWidth,h=c.clientHeight,d=Math.min(devicePixelRatio||1,2);c.width=w*d;c.height=h*d;x.setTransform(d,0,0,d,0,0);x.clearRect(0,0,w,h);const cx=w*.51,cy=h*.52,rx=w*.34,ry=h*.31,items=R.data.territories,ns=items.map((t,i)=>{const a=-Math.PI/2+i/items.length*Math.PI*2;return{...t,a,x:cx+Math.cos(a)*rx,y:cy+Math.sin(a)*ry,r:17+Math.min(10,t.operator_count*2)}});x.lineWidth=.5;x.strokeStyle='rgba(200,96,64,.07)';for(let gx=24;gx{x.beginPath();x.ellipse(cx,cy,w*s,h*s,0,0,7);x.stroke()});ns.forEach((n,i)=>{const next=ns[(i+1)%ns.length];x.strokeStyle=n.active_count?'rgba(200,96,64,.28)':'rgba(90,110,96,.15)';x.beginPath();x.moveTo(cx,cy);x.bezierCurveTo((cx+n.x)/2,cy,(cx+n.x)/2,n.y,n.x,n.y);x.stroke();x.strokeStyle='rgba(200,96,64,.11)';x.beginPath();x.moveTo(n.x,n.y);x.lineTo(next.x,next.y);x.stroke()});const glow=x.createRadialGradient(cx,cy,0,cx,cy,54);glow.addColorStop(0,'rgba(200,96,64,.16)');glow.addColorStop(1,'rgba(200,96,64,0)');x.fillStyle=glow;x.beginPath();x.arc(cx,cy,54,0,7);x.fill();x.fillStyle='#020603';x.strokeStyle='#c86040';x.lineWidth=1;x.beginPath();x.arc(cx,cy,27,0,7);x.fill();x.stroke();x.fillStyle='#c86040';x.textAlign='center';x.font='700 8px monospace';x.fillText('TARDUMO',cx,cy-2);x.fillStyle='#6d8172';x.font='7px monospace';x.fillText(`${R.data.metrics.activeOperators} ACTIVE`,cx,cy+10);ns.forEach((n,i)=>{x.fillStyle='#010301';x.strokeStyle=n.active_count?'#c86040':'#445047';x.lineWidth=1;x.beginPath();x.arc(n.x,n.y,n.r,0,7);x.fill();x.stroke();x.strokeStyle=n.active_count?'rgba(200,96,64,.28)':'rgba(90,110,96,.18)';x.beginPath();x.arc(n.x,n.y,n.r+6,0,7);x.stroke();x.fillStyle=n.active_count?'#c86040':'#778179';x.font='700 8px monospace';x.fillText(n.territory.toUpperCase(),n.x,n.y+2);x.fillStyle='#657168';x.font='7px monospace';x.fillText(`${n.active_count}/${n.operator_count}`,n.x,n.y+12);x.fillStyle=n.active_count?'#c86040':'#59635b';x.fillRect(n.x+n.r+4,n.y-1,3,3)})} function renderTreasury(){ const t=R.data.treasury,c=R.data.config,m=R.data.metrics,token=R.data.token||{},address=t.address||c.treasuryAddress||'',mint=c.tokenMint||''; const chainVerified=token.status==='verified',launched=Boolean(mint),treasuryReady=Boolean(address),phase=chainVerified?'TOKEN VERIFIED':launched?'TOKEN CHECKING':treasuryReady?'LAUNCH ADDRESS READY':'NOT CONFIGURED'; text('.treasury-total strong',Number(t.creatorRewardsSol).toFixed(3)+' SOL'); text('.pool-total strong',Number(t.incentivePoolSol).toFixed(3)+' SOL'); text('#treasuryNetwork',String(c.cluster||'mainnet-beta').replace('-beta','').toUpperCase()); text('#treasuryBurns',`${m.burns} / ${Number(m.tokensBurned).toLocaleString()} TOKENS`); text('#treasurySettlements',m.settlements||0); text('#treasuryGross',`${Number(m.grossCallLamports||0).toLocaleString()} LAMPORTS`); text('#treasuryMint',mint||'TBA'); text('#treasuryWallet',address||'TBA'); text('#treasuryPhase',phase); text('#tokenName',token.name||'TBA'); text('#tokenSymbol',token.symbol||'TBA'); text('#tokenSupply',token.supply!=null?`${Number(token.supply).toLocaleString('en-US',{maximumFractionDigits:6})} ${token.symbol||'TADM'}`:launched?'CHECKING':'TBA'); text('#tokenDecimals',token.decimals??(launched?'CHECKING':'TBA')); text('#tokenProgram',token.program||(launched?'CHECKING':'TBA')); text('#tokenMintAuthority',token.mintAuthority?`${token.mintAuthority.slice(0,4)}…${token.mintAuthority.slice(-4)}`:chainVerified?'REVOKED':launched?'CHECKING':'TBA'); text('#tokenFreezeAuthority',token.freezeAuthority?`${token.freezeAuthority.slice(0,4)}…${token.freezeAuthority.slice(-4)}`:chainVerified?'REVOKED':launched?'CHECKING':'TBA'); text('#tokenSlot',token.slot?Number(token.slot).toLocaleString():launched?'CHECKING':'TBA'); text('#tokenChainStatus',chainVerified?(token.rpcStatus==='degraded'?'VERIFIED · RPC RETRY':'VERIFIED ON SOLANA'):token.status==='degraded'?'RPC DEGRADED':launched?'CHECKING SOLANA':'TOKEN CA · TBA'); text('#tokenVerifiedAt',token.verifiedAt?`verified ${age(token.verifiedAt)} ago`:launched?'awaiting first verification':'awaiting official CA'); $('#tokenChainLight')?.classList.toggle('verified',chainVerified); const pumpfun=$('#treasuryPumpfun'); if(pumpfun){pumpfun.hidden=false;pumpfun.href=c.pumpfunUrl||'https://pump.fun/'} const tokenExplorer=$('#tokenExplorer'); if(tokenExplorer){tokenExplorer.hidden=!mint;tokenExplorer.href=token.explorerUrl||`https://solscan.io/token/${encodeURIComponent(mint)}`} const explorer=$('#treasuryExplorer'); if(explorer){explorer.hidden=!address;explorer.href=address?`https://solscan.io/account/${encodeURIComponent(address)}`:'#'} const allocation=$('#allocationBars'); allocation.innerHTML=''; [['Agent Compute Pool',35,'#c86040'],['Verification Pool',15,'#ad4f35'],['Infrastructure Pool',10,'#8f402c'],['Tardigrade Incentive Pool',40,'#e59a83']].forEach(([name,share,color])=>{ const row=document.createElement('div'); row.className='alloc-row'; row.innerHTML=`${name}${share}%policy`; allocation.append(row); }); const checks=$$('.treasury-checklist>span'); if(checks[0]){checks[0].dataset.ready=String(chainVerified);$('b',checks[0]).textContent=chainVerified?'VERIFIED':launched?'CHECKING':'TBA'} if(checks[1]){checks[1].dataset.ready=String(treasuryReady);$('b',checks[1]).textContent=treasuryReady?'READY':'MISSING'} const settlementState=c.settlementEnabled?'ACTIVE':'NOT ENABLED'; const notice=launched?`Token and Treasury are configured. Creator Rewards, burns and settlements remain at zero until independently recorded; paid skill-call settlement is ${settlementState.toLowerCase()}.`:`The official token CA and Treasury address remain TBA. Token burns and paid settlement stay locked.`; $('#payoutList').innerHTML=`
    CURRENT RECORDED WINDOW${m.burns} confirmed burns · ${Number(m.tokensBurned).toLocaleString()} tokens

    ${notice}

    `; const rows=[ ['official token CA',mint||'TBA',chainVerified?'on-chain verified':launched?'checking':'awaiting'], ['current token supply',token.supply!=null?`${Number(token.supply).toLocaleString('en-US',{maximumFractionDigits:6})} ${token.symbol||'TADM'}`:'not available',chainVerified?'confirmed RPC':'checking'], ['token program',token.program||'not available',chainVerified?'confirmed RPC':'checking'], ['mint / freeze authority',chainVerified?(token.authoritiesRevoked?'revoked / revoked':'authority present'):'not available',chainVerified?'confirmed RPC':'checking'], ['launch / tax address',address||'TBA',treasuryReady?'published':'awaiting'], ['creator rewards',Number(t.creatorRewardsSol).toFixed(3)+' SOL',Number(t.creatorRewardsSol)>0?'recorded':'none recorded'], ['skill calls',`${m.successfulSkillCalls||0} succeeded`,m.skillCalls?'recorded':'none recorded'], ['paid settlement',`${m.settlements||0} recorded`,settlementState.toLowerCase()] ]; const stamp=new Date().toISOString().slice(11,19); $('#treasuryEvents').innerHTML=rows.map(([name,value,state])=>`
    ${stamp}${esc(state)}${esc(name)}${esc(String(value))}
    `).join(''); } async function refreshToken(){const b=$('#tokenRefresh');if(!b)return;if(!R.data?.config?.tokenMint)return toast('Token CA is TBA');b.disabled=true;b.textContent='checking…';try{R.data.token=await api('/token?refresh=1');renderTreasury();toast(R.data.token.status==='verified'?'Token state verified on Solana':'Solana RPC is temporarily degraded')}catch(e){toast(`token refresh failed: ${e.message}`)}finally{b.disabled=false;b.textContent='refresh chain'}} function render(){R.operators=R.data.operators;R.skills=R.data.skills;R.events=R.data.events;configure();selectOperator(Math.min(R.selected,R.operators.length-1));renderTable();renderWall();renderEvents();renderSkills($('#skillSearch')?.value||'');renderGateway();renderTerritories();renderTreasury();deployState()} async function load(quiet=false){try{const [snapshot,gateway]=await registryData();R.data=brandSnapshot(snapshot);R.gateway=gateway.data||[];document.documentElement.dataset.api='online';render();brandInterface()}catch(e){document.documentElement.dataset.api='offline';text('.feed-label','API offline');if(!quiet)toast(`network unavailable: ${e.message}`)}} function events(){const s=new EventSource(`${API_ORIGIN}/api/events/stream`);s.addEventListener('snapshot',()=>{clearTimeout(R.reload);R.reload=setTimeout(()=>load(true),900)});s.addEventListener('frame',event=>{try{const data=JSON.parse(event.data),o=R.operators.find(item=>item.id===data.operatorId||item.name===data.operator);if(!o)return;o.stream_path=data.streamPath;o.last_seen=data.observedAt;o.telemetry=data.telemetry;const c=$(`[data-operator-id="${o.id}"]`);if(c){swapFrame($('.operator-live-frame',c),o,$('.feed-awaiting',c));text('[data-role="seen"]','live',c);text('[data-role="event"]',`${data.telemetry?.phase||'reading'} · ${data.observedAt.slice(11,19)} UTC`,c)}if(R.roomOperatorId===o.id){text('#roomSignal','VIDEO · '+String(data.telemetry?.phase||'reading').replaceAll('-',' ').toUpperCase());text('#roomUrl',data.telemetry?.currentUrl||o.target_url);try{text('#roomEndpoint',new URL(data.telemetry?.currentUrl||o.target_url).pathname||'/')}catch{}}setTimeout(()=>{if(R.operators[R.selected]?.id===o.id)renderVision($('#stageVision'),data.telemetry);const current=$(`[data-operator-id="${o.id}"]`);if(current)renderVision($('[data-role="vision"]',current),data.telemetry);if(R.roomOperatorId===o.id)renderVision($('#roomVision'),data.telemetry)},430)}catch{}});s.onerror=()=>document.documentElement.dataset.stream='offline';s.onopen=()=>document.documentElement.dataset.stream='online'} const wb=$('#connectWallet'),wm=$('#walletModal'),wo=$('#walletOptions'),we=$('#walletEmpty'); const registry=(()=>{const w=new Set,l=new Set,register=(...a)=>{a.forEach(x=>w.add(x));l.forEach(f=>f());return()=>{a.forEach(x=>w.delete(x));l.forEach(f=>f())}},api=Object.freeze({register});try{addEventListener('wallet-standard:register-wallet',e=>e.detail?.(api));const e=new Event('wallet-standard:app-ready');Object.defineProperty(e,'detail',{value:api});dispatchEvent(e);const q=Array.isArray(navigator.wallets)?[...navigator.wallets]:[];Object.defineProperty(navigator,'wallets',{configurable:true,value:Object.freeze({push:(...c)=>c.forEach(f=>f(api))})});q.forEach(f=>f(api))}catch{}return{all:()=>[...w],on:f=>l.add(f)}})(); function choices(){const out=[],names=new Set;registry.all().forEach(w=>{if(w?.chains?.some(c=>String(c).startsWith('solana:'))&&w.features?.['standard:connect']){names.add(w.name.toLowerCase());out.push({type:'standard',name:w.name,icon:w.icon||'',wallet:w})}});const add=(name,p)=>{if(p?.connect&&!names.has(name.toLowerCase())){names.add(name.toLowerCase());out.push({type:'legacy',name,provider:p,icon:''})}};add('Phantom',window.phantom?.solana);add('Solflare',window.solflare);add('Backpack',window.backpack?.solana||window.backpack);if(window.solana)add(window.solana.isPhantom?'Phantom':'Solana wallet',window.solana);return out.sort((a,b)=>a.name.localeCompare(b.name))} function setWallet(address='',choice=null,account=null){R.address=address;R.wallet=address?{choice,account}:null;wb.textContent=address?`${address.slice(0,4)}…${address.slice(-4)}`:'connect wallet';wb.classList.toggle('connected',!!address);deployState()} function walletList(){const list=choices();wo.innerHTML='';list.forEach(c=>{const b=document.createElement('button');b.type='button';b.className='wallet-option';const i=document.createElement(c.icon?'img':'span');if(c.icon){i.src=c.icon;i.alt=''}else i.textContent=c.name.slice(0,2).toUpperCase();const s=document.createElement('span');s.innerHTML=`${esc(c.name)}detected · Solana`;b.append(i,s);b.onclick=()=>connect(c);wo.append(b)});we.hidden=!!list.length;text('#walletCount',list.length?`${list.length} wallet${list.length===1?'':'s'} detected`:'no wallet detected')} function walletOpen(){walletList();wm.classList.add('open');wm.setAttribute('aria-hidden','false')}function walletClose(){wm.classList.remove('open');wm.setAttribute('aria-hidden','true')} async function connect(c){wb.disabled=true;wb.textContent='connecting…';try{if(c.type==='standard'){const r=await c.wallet.features['standard:connect'].connect(),a=r?.accounts?.[0]||c.wallet.accounts?.[0];if(!a?.address)throw Error('wallet returned no account');setWallet(a.address,c,a)}else{const r=await c.provider.connect(),a=(r?.publicKey||c.provider.publicKey)?.toString();if(!a)throw Error('wallet returned no account');setWallet(a,c)}walletClose();toast(`${c.name} connected`)}catch(e){setWallet();toast(e.code===4001?'wallet connection cancelled':e.message)}finally{wb.disabled=false}} async function disconnect(){try{if(R.wallet?.choice.type==='standard')await R.wallet.choice.wallet.features['standard:disconnect']?.disconnect();else await R.wallet?.choice.provider?.disconnect?.()}catch{}setWallet();toast('wallet disconnected')} function deployState(){const b=$('#spawnButton'),c=R.data?.config;if(!b)return;const alias=$('#operatorAlias')?.value.trim(),steps=$$('.spawn-steps li'),ready=!!c?.deployEnabled&&!!R.address;text('#deployWalletStatus',R.address?'CONNECTED':'NOT CONNECTED');text('#deployMintStatus',c?.tokenMint?'CONFIGURED':'TBA');text('#deployWorkerStatus',R.data?`${R.data.metrics.activeOperators}/${R.data.metrics.operators} ONLINE`:'CHECKING');text('#deployReadiness',!c?.deployEnabled?'TOKEN CA REQUIRED':!R.address?'WALLET REQUIRED':'READY TO SIGN');steps.forEach((step,index)=>{step.classList.remove('active','complete','locked');if(index<2)step.classList.add('complete');else if(index===2)step.classList.add(ready?'active':'locked');else step.classList.add('locked')});text('.spawn-preview>.panel-head b',ready&&alias?'READY TO COMMIT':'NOT COMMITTED');if(!c?.deployEnabled){b.disabled=true;b.classList.remove('ready');b.textContent='token CA TBA · deployment locked'}else if(!R.address){b.disabled=false;b.classList.remove('ready');b.textContent='connect wallet to continue'}else{b.disabled=false;b.classList.add('ready');b.textContent=`burn ${Number(c.burnAmount).toLocaleString()} $TADM · wake`}} const from64=s=>Uint8Array.from(atob(s),c=>c.charCodeAt(0));function b58(bytes){const a='123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz',d=[0];for(const b of bytes){let c=b;for(let i=0;ia[x]).join('')} async function deploy(){const c=R.data?.config;if(!c?.deployEnabled)return toast('Deployment is locked until the real token CA is configured.');if(!R.address)return walletOpen();if(R.wallet.choice.type!=='standard')return toast('Wallet Standard signing is required for the burn.');const signer=R.wallet.choice.wallet.features['solana:signAndSendTransaction'];if(!signer)return toast('This wallet cannot sign Solana transactions.');const alias=$('#operatorAlias').value.trim().toLowerCase(),territory=$('#territorySelect').value.split(' ')[0].toLowerCase(),button=$('#spawnButton');button.disabled=true;try{button.textContent='preparing burn…';const p=await api('/operators/prepare-burn',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({wallet:R.address,alias,territory})});button.textContent='confirm burn in wallet…';const outs=await signer.signAndSendTransaction({account:R.wallet.account,chain:p.chain,transaction:from64(p.transaction),options:{commitment:'confirmed'}}),o=Array.isArray(outs)?outs[0]:outs,sig=typeof o.signature==='string'?o.signature:b58(o.signature);button.textContent='verifying on-chain…';await api('/operators/confirm-burn',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({wallet:R.address,intentId:p.intentId,signature:sig})});toast('Burn confirmed. Tardigrade Agent queued.');await load(true);nav('operators')}catch(e){toast(e.message)}finally{deployState()}} function openLive(o=R.operators[R.selected]){if(!o)return toast('No real Tardigrade Agent is registered.');const room=$('#liveRoom'),skill=R.skills.find(s=>s.operator_id===o.id&&s.state==='verified');R.roomOperatorId=o.id;stopVideo($('.crawl-browser-frame'));room.classList.add('open');room.setAttribute('aria-hidden','false');text('#roomName',o.name);text('#roomPointerName',`${o.name} / ${o.state}`);text('#roomTerritory',o.territory);text('#roomMission',o.mission||'territory exploration');text('#roomCapabilities',(o.capabilities||[]).join(' · ')||'discovering');text('#roomRoute',o.current_route||'discovering');text('#roomEvidenceRoute',skill?.name||o.current_route||'not published');text('#roomEvidenceSeen',o.last_seen?`${age(o.last_seen)} ago`:'never');text('#roomEvidenceProof',skill?.proof?`sha ${skill.proof.slice(0,16)}`:'not available');text('#roomHttp',o.http_status?`${o.http_status} OBSERVED`:'NO HTTP STATUS');text('#roomUrl',o.telemetry?.currentUrl||o.target_url);try{text('#roomEndpoint',new URL(o.telemetry?.currentUrl||o.target_url).pathname||'/')}catch{}text('#roomSession',`tardigrade ${o.id}`);text('#sessionAge',age(o.created_at));const log=$('#roomLog'),ev=R.events.filter(e=>e.operator_id===o.id);log.innerHTML=ev.length?'':'
    waiting for first worker reportregistry
    ';ev.slice(0,20).forEach(e=>{const n=document.createElement('div');n.className='room-log-entry';n.innerHTML=`${esc(e.message)}${esc(e.type)}`;log.append(n)});const wait=$('#roomFeedWaiting');playVideo($('#roomLiveFrame'),o,wait);text('#roomSignal','LIVE · WEBM VIDEO');renderVision($('#roomVision'),o.telemetry)}function closeLive(){R.roomOperatorId=null;stopVideo($('#roomLiveFrame'));$('#liveRoom').classList.remove('open');$('#liveRoom').setAttribute('aria-hidden','true');if($('#route-live').classList.contains('active'))playVideo($('.crawl-browser-frame'),R.operators[R.selected])} function nav(id){$$('.route').forEach(r=>r.classList.toggle('active',r.id===`route-${id}`));$$('.nav-item').forEach(b=>b.classList.toggle('active',b.dataset.route===id));history.replaceState(null,'',`#${id}`);if(id==='territories')setTimeout(drawTerritories,30);if(id==='live'&&!R.roomOperatorId)playVideo($('.crawl-browser-frame'),R.operators[R.selected]);else if(id!=='live')stopVideo($('.crawl-browser-frame'))} function init(){$$('[data-route]').forEach(b=>b.onclick=()=>nav(b.dataset.route));$$('[data-jump]').forEach(b=>b.onclick=()=>nav(b.dataset.jump));addEventListener('hashchange',()=>{const id=location.hash.slice(1);if($(`#route-${id}`))nav(id)});$('#prevOperator').onclick=()=>selectOperator(R.selected-1);$('#nextOperator').onclick=()=>selectOperator(R.selected+1);$('#watchLive').onclick=()=>openLive();$('#closeLive').onclick=closeLive;wb.onclick=()=>R.address?disconnect():walletOpen();$('#closeWalletModal').onclick=walletClose;wm.onclick=e=>{if(e.target===wm)walletClose()};registry.on(()=>{if(wm.classList.contains('open'))walletList()});$$('[data-wall-filter]').forEach(b=>b.onclick=()=>{R.filter=b.dataset.wallFilter;$$('[data-wall-filter]').forEach(x=>x.classList.toggle('active',x===b));renderWall()});$$('[data-wall-view]').forEach(b=>b.onclick=()=>{$$('[data-wall-view]').forEach(x=>x.classList.toggle('active',x===b));$('#monitorGrid').classList.toggle('board',b.dataset.wallView==='board')});$('#skillSearch').oninput=e=>renderSkills(e.target.value);$('#copyGatewayExample').onclick=async()=>{await navigator.clipboard.writeText($('#gatewayExample').textContent);toast('Gateway example copied')};$('#operatorAlias').oninput=e=>text('#previewAlias',e.target.value||'unnamed-tardigrade');$('#territorySelect').onchange=e=>text('#previewTerritory','territory / '+e.target.value.split(' ')[0].toLowerCase());$('#spawnButton').onclick=deploy;$('#tokenRefresh').onclick=refreshToken;$$('[data-manual-target]').forEach(b=>b.onclick=()=>{$$('[data-manual-target]').forEach(x=>x.classList.toggle('active',x===b));$$('.manual-topic').forEach(x=>x.classList.toggle('active',x.id===`manual-${b.dataset.manualTarget}`))});$$('[data-pending]').forEach(n=>n.onclick=async e=>{e.preventDefault();if(!n.dataset.copy)return toast(`${n.dataset.pending} is TBA`);await navigator.clipboard.writeText(n.dataset.copy);toast('contract copied')});addEventListener('resize',drawTerritories);addEventListener('keydown',e=>{if(e.key==='Escape'){walletClose();closeLive()}})} function graph(){const c=$('#actionGraph'),x=c?.getContext('2d');if(!x)return;function d(t){const w=c.clientWidth,h=c.clientHeight,p=Math.min(devicePixelRatio||1,2);if(c.width!==Math.floor(w*p)||c.height!==Math.floor(h*p)){c.width=w*p;c.height=h*p;x.setTransform(p,0,0,p,0,0)}x.clearRect(0,0,w,h);const n=Math.max(1,R.operators.length);x.strokeStyle='rgba(200,96,64,.18)';x.fillStyle='#c86040';for(let i=0;i{ if(media?.tagName==='IMG'){ media.removeAttribute('src'); media.classList.remove('connected'); delete media.dataset.operatorId; delete media.dataset.framePath; return; } stopVideoStream(media); }; const playVideoStream=playVideo; playVideo=(media,operator,wait)=>{ if(media?.tagName==='IMG'){ if(media.classList.contains('crawl-browser-frame'))setVerifiedMark('#stageVerifiedMark',operator); if(media.id==='roomLiveFrame')setVerifiedMark('#roomVerifiedMark',operator); swapFrame(media,operator,wait); return; } playVideoStream(media,operator,wait); }; drawTerritories=()=>{ const canvas=$('#territoryCanvas'); if(!canvas?.clientWidth)return; const context=canvas.getContext('2d'),density=Math.min(devicePixelRatio||1,2); const width=canvas.clientWidth,height=canvas.clientHeight; canvas.width=Math.floor(width*density);canvas.height=Math.floor(height*density); context.setTransform(density,0,0,density,0,0);context.clearRect(0,0,width,height); const green='#00ff57',dim='rgba(0,255,87,.22)',faint='rgba(0,255,87,.07)'; const centerX=width*.48,centerY=height*.42,items=R.data?.territories||[]; context.save();context.strokeStyle=faint;context.lineWidth=1; for(let radius=56;radius{ const point=anchors[index%anchors.length],px=width*point[0],py=height*point[1]; const side=px{ navLegacy(id); const navigation=$('.nav'),activeItem=$(`[data-route="${id}"]`,navigation); if(navigation&&activeItem&&navigation.scrollWidth>navigation.clientWidth){ activeItem.scrollIntoView({behavior:'smooth',block:'nearest',inline:'center'}); } }; const legacyIdentityHash=$('.identity-hash'); if(legacyIdentityHash){ legacyIdentityHash.className='identity-orbit'; legacyIdentityHash.innerHTML='
    00SEED
    DISCOVERLEARNVERIFYPUBLISH'; } const huggingFaceSource=$('.hf-link'); if(huggingFaceSource){ huggingFaceSource.href='https://huggingface.co/spaces/tardumo/Senmilo'; huggingFaceSource.setAttribute('aria-label','Senmilo on Hugging Face'); huggingFaceSource.classList.add('senmilo-source'); } $('.github-link')?.remove(); $$('.core-mark img').forEach(image=>image.src='senmilo-logo-transparent.png'); brandInterface(); new MutationObserver(records=>records.forEach(record=>record.addedNodes.forEach(node=>{ if(node.nodeType===Node.TEXT_NODE){if(/tard|TADM/i.test(node.nodeValue))node.nodeValue=brandCopy(node.nodeValue);} else if(node.nodeType===Node.ELEMENT_NODE)brandInterface(node); }))).observe(document.body,{childList:true,subtree:true}); init();graph();const clock=()=>text('#clock',new Date().toISOString().slice(11,19)+' UTC');clock();setInterval(clock,1000);load();events();setInterval(()=>load(true),30000);if(location.hash&&$(`#route-${location.hash.slice(1)}`))nav(location.hash.slice(1));