busybits 2.5.0 → 2.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +18 -0
  3. package/dist/build.json +2 -2
  4. package/dist/cli/busybits.js +6 -0
  5. package/dist/client/bundle/{app-Cn3BvqjA.css → app-BODKiLC2.css} +1 -1
  6. package/dist/client/bundle/app-D5bRv3Io.js +24 -0
  7. package/dist/client/bundle/{city-S-WD2HZe.js → city-1iWQHg0m.js} +1 -1
  8. package/dist/client/bundle/{daystats-BaQmwDUl.js → daystats-8-rKd2hK.js} +1 -1
  9. package/dist/client/bundle/{dom-z_NH7Uh7.js → dom-BZgsJMv9.js} +1 -1
  10. package/dist/client/bundle/{en-DK_q-bO7.js → en-ChmFNZf9.js} +1 -1
  11. package/dist/client/bundle/{es-CUFTupoF.js → es-Dxz3P98Y.js} +1 -1
  12. package/dist/client/bundle/{format-BrkFnmVF.js → format-DrvIRA6J.js} +1 -1
  13. package/dist/client/bundle/{fr-CY87v2sh.js → fr-CINcBINu.js} +1 -1
  14. package/dist/client/bundle/{main-DNVSCypp.js → main-CJZNyhMz.js} +2 -2
  15. package/dist/client/bundle/{ptypane-DAVYBQ48.js → ptypane-B_D8yEvn.js} +1 -1
  16. package/dist/client/bundle/{room-name-Cg36nI5X.js → room-name-CSxOS6Qg.js} +1 -1
  17. package/dist/client/bundle/{simulator-CDeHv4xc.js → simulator-DSTKHVKF.js} +1 -1
  18. package/dist/client/bundle/world-model-DIM3eqSC.js +1 -0
  19. package/dist/client/bundle/world-stream-D8eI5CKj.js +1 -0
  20. package/dist/client/index.html +1 -1
  21. package/dist/server/index.js +37 -13
  22. package/mod/habblaud/.claude-plugin/plugin.json +1 -1
  23. package/mod/habblaud-mensagens/.claude-plugin/plugin.json +1 -1
  24. package/mod/habblaud-permissoes/.claude-plugin/plugin.json +1 -1
  25. package/mod/habblaud-pi/package.json +1 -1
  26. package/package.json +2 -1
  27. package/dist/client/bundle/app-QVC1DacC.js +0 -24
  28. package/dist/client/bundle/world-model-CPBvh77_.js +0 -1
  29. package/dist/client/bundle/world-stream-FBFp8Oax.js +0 -1
@@ -1,24 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["bundle/daystats-BaQmwDUl.js","bundle/main-DNVSCypp.js","bundle/simulator-CDeHv4xc.js","bundle/dom-z_NH7Uh7.js","bundle/room-name-Cg36nI5X.js","bundle/format-BrkFnmVF.js","bundle/ptypane-DAVYBQ48.js","bundle/ptypane-BrP-ENHg.css","bundle/city-S-WD2HZe.js","bundle/world-model-CPBvh77_.js","bundle/city-DPTwQLdi.css","bundle/world-stream-FBFp8Oax.js"])))=>i.map(i=>d[i]);
2
- import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./main-DNVSCypp.js";import{a as s,c,d as l,i as u,l as d,m as f,o as p,p as m,s as h}from"./simulator-CDeHv4xc.js";import{$t as g,A as _,At as v,B as y,Bt as b,C as x,Ct as S,D as C,E as w,Et as ee,F as te,Ft as T,G as E,Gt as D,H as ne,Ht as re,I as ie,It as ae,Jt as oe,K as se,Kt as ce,L as le,Lt as ue,M as de,N as fe,O as pe,Ot as me,P as he,Pt as ge,Qt as _e,R as ve,Rt as ye,S as be,St as xe,T as Se,U as Ce,Ut as we,V as O,Vt as Te,W as Ee,Xt as De,Y as Oe,Yt as ke,Zt as k,_ as Ae,_t as je,a as Me,b as Ne,c as Pe,d as Fe,f as Ie,g as Le,h as Re,i as ze,j as Be,jt as Ve,k as He,l as Ue,m as We,n as Ge,nn as Ke,o as qe,p as Je,qt as Ye,r as Xe,s as Ze,t as Qe,tn as $e,u as et,v as tt,vt as nt,w as rt,wt as it,x as at,y as ot,yt as st,z as ct,zt as lt}from"./world-model-CPBvh77_.js";import{i as ut,n as dt,r as ft,t as pt}from"./room-name-Cg36nI5X.js";import{_ as mt,a as ht,b as gt,c as _t,d as A,f as vt,g as yt,h as bt,i as j,l as M,m as xt,n as St,o as N,p as Ct,r as P,s as F,t as wt,u as Tt,v as Et,y as Dt}from"./dom-z_NH7Uh7.js";import{_ as Ot,a as kt,c as At,d as jt,f as Mt,g as Nt,h as Pt,i as Ft,l as It,m as Lt,n as Rt,o as zt,p as Bt,r as Vt,s as Ht,t as Ut,u as Wt,v as Gt,y as Kt}from"./format-BrkFnmVF.js";var qt=Object.defineProperty,Jt=(e,t)=>{let n={};for(var r in e)qt(n,r,{get:e[r],enumerable:!0});return t||qt(n,Symbol.toStringTag,{value:`Module`}),n},Yt=null,Xt=new Set;function Zt(e){return Xt.add(e),()=>void Xt.delete(e)}function Qt(e,t){return!!e&&!!t&&Object.keys(e).every(n=>e[n]===t[n])&&Object.keys(e).length===Object.keys(t).length}function $t(e){let t=e.toLowerCase().replace(/^\[|\]$/g,``);return t===`localhost`||t.endsWith(`.localhost`)||t===`::1`||/^127(?:\.\d{1,3}){3}$/.test(t)}function en(e){let t=$t(e);return{remote:!1,local:t,permissions:t,messages:t,terminal:t,spawn:!1}}var tn=5e3;function nn(e){let t=e;return!!t&&[`remote`,`local`,`permissions`,`messages`,`terminal`].every(e=>typeof t[e]==`boolean`)}function I(){return Yt??en(typeof location>`u`?``:location.hostname)}async function rn(e=fetch,t=e=>location.assign(e)){try{let n=await e(`/api/access`,{credentials:`same-origin`,cache:`no-store`,signal:AbortSignal.timeout(tn)});if(n.status===401)return t(`/login`),I();if(n.ok){let e=await n.json();if(nn(e)){let t={...e,spawn:e.spawn===!0},n=!Qt(Yt,t);Yt=t,n&&Xt.forEach(e=>e())}}}catch{}return I()}async function an(e=fetch,t=e=>location.assign(e)){try{if(!(await e(`/api/remote/logout`,{method:`POST`,headers:{"Content-Type":`application/json`},body:`{}`,credentials:`same-origin`,cache:`no-store`})).ok)return!1}catch{return!1}return t(`/login`),!0}var on={desk:{mount:`floor`,footprint:{w:2,h:1},blocks:!0,variants:[`wood`,`white`,`dark`]},desk_back:{mount:`floor`,footprint:{w:2,h:1},blocks:!0,variants:[`wood`,`white`,`dark`]},office_chair_front:{mount:`floor`,footprint:{w:1,h:1},blocks:!1,seat:!0,variants:[`black`,`blue`,`red`,`green`,`gray`]},office_chair:{mount:`floor`,footprint:{w:1,h:1},blocks:!1,seat:!0,variants:[`black`,`blue`,`red`,`green`,`gray`]},bookshelf:{mount:`floor`,footprint:{w:2,h:1},blocks:!0},filing_cabinet:{mount:`floor`,footprint:{w:1,h:1},blocks:!0},printer:{mount:`floor`,footprint:{w:1,h:1},blocks:!0},trash_bin:{mount:`floor`,footprint:{w:1,h:1},blocks:!0},plant_small:{mount:`floor`,footprint:{w:1,h:1},blocks:!0,variants:[`fern`,`succulent`,`flower`]},plant_tall:{mount:`floor`,footprint:{w:1,h:1},blocks:!0,variants:[`palm`,`ficus`,`monstera`,`bonsai`]},glass_partition:{mount:`floor`,footprint:{w:1,h:1},blocks:!0,variants:[`h`,`v`,`end`]},binder_shelf:{mount:`floor`,footprint:{w:1,h:1},blocks:!0},meeting_table:{mount:`floor`,footprint:{w:3,h:2},blocks:!0},stool:{mount:`floor`,footprint:{w:1,h:1},blocks:!1,seat:!0},floor_lamp:{mount:`floor`,footprint:{w:1,h:1},blocks:!0},water_cooler:{mount:`floor`,footprint:{w:1,h:1},blocks:!0},whiteboard:{mount:`wall`,footprint:{w:3,h:0},blocks:!1},window:{mount:`wall`,footprint:{w:2,h:0},blocks:!1},clock:{mount:`wall`,footprint:{w:1,h:0},blocks:!1},poster:{mount:`wall`,footprint:{w:1,h:0},blocks:!1,variants:[`code`,`coffee`,`rocket`,`cat`,`bug`,`ship_it`]},painting:{mount:`wall`,footprint:{w:2,h:0},blocks:!1},tv:{mount:`wall`,footprint:{w:2,h:0},blocks:!1},light_switch:{mount:`wall`,footprint:{w:1,h:0},blocks:!1,variants:[`on`,`off`]},elevator:{mount:`wall`,footprint:{w:2,h:0},blocks:!1,states:5},door_frame:{mount:`wall`,footprint:{w:2,h:0},blocks:!1},sign:{mount:`wall`,footprint:{w:3,h:0},blocks:!1},mirror:{mount:`wall`,footprint:{w:1,h:0},blocks:!1},shelf_wall:{mount:`wall`,footprint:{w:2,h:0},blocks:!1},counter:{mount:`floor`,footprint:{w:1,h:1},blocks:!0,variants:[`plain`,`drawers`]},counter_sink:{mount:`floor`,footprint:{w:1,h:1},blocks:!0},coffee_machine:{mount:`floor`,footprint:{w:1,h:1},blocks:!0,states:2},microwave:{mount:`floor`,footprint:{w:1,h:1},blocks:!0},fridge:{mount:`floor`,footprint:{w:1,h:1},blocks:!0},vending_machine:{mount:`floor`,footprint:{w:1,h:1},blocks:!0},cafe_table:{mount:`floor`,footprint:{w:1,h:1},blocks:!0},cafe_chair:{mount:`floor`,footprint:{w:1,h:1},blocks:!1,seat:!0,variants:[`up`,`down`,`left`,`right`]},sofa:{mount:`floor`,footprint:{w:3,h:1},blocks:!1,seat:!0,variants:[`down`,`up`]},armchair:{mount:`floor`,footprint:{w:1,h:1},blocks:!1,seat:!0,variants:[`up`,`down`,`left`,`right`]},coffee_table:{mount:`floor`,footprint:{w:2,h:1},blocks:!0},pingpong_table:{mount:`floor`,footprint:{w:3,h:2},blocks:!0},beanbag:{mount:`floor`,footprint:{w:1,h:1},blocks:!1,seat:!0,variants:[`red`,`blue`,`yellow`,`green`]},arcade:{mount:`floor`,footprint:{w:1,h:1},blocks:!0},toilet_stall:{mount:`floor`,footprint:{w:2,h:2},blocks:!0,states:2},sink:{mount:`floor`,footprint:{w:1,h:1},blocks:!0},reception_desk:{mount:`floor`,footprint:{w:3,h:1},blocks:!0},bench:{mount:`floor`,footprint:{w:2,h:1},blocks:!1,seat:!0}},sn=new Map,cn=[255,0,255,255];function ln(e){let t=sn.get(e);return t||(t=un(e),sn.set(e,t)),t}function un(e){let t=e.trim().toLowerCase();if(t===`transparent`)return[0,0,0,0];if(t.startsWith(`#`)){let e=t.slice(1);if(e.length===3||e.length===4){let t=[...e].map(e=>parseInt(e+e,16));return[t[0],t[1],t[2],e.length===4?t[3]:255]}if(e.length===6||e.length===8){let t=t=>parseInt(e.slice(t,t+2),16);return[t(0),t(2),t(4),e.length===8?t(6):255]}return cn}let n=/^(rgba?|hsla?)\(([^)]*)\)$/.exec(t);if(!n)return cn;let r=n[2].split(/[\s,/]+/).filter(Boolean),i=(e,t)=>e===void 0?1:e.endsWith(`%`)?parseFloat(e)/100*t:parseFloat(e),a=e=>{if(e===void 0)return 255;let t=e.endsWith(`%`)?parseFloat(e)/100:parseFloat(e);return Math.round(dn(t)*255)};if(n[1].startsWith(`rgb`))return[Math.round(i(r[0],255)),Math.round(i(r[1],255)),Math.round(i(r[2],255)),a(r[3])];let[o,s,c]=hn(parseFloat(r[0]??`0`),i(r[1],1),i(r[2],1));return[o,s,c,a(r[3])]}function dn(e){return e<0?0:e>1?1:e}var fn=e=>Math.round(Math.max(0,Math.min(255,e))).toString(16).padStart(2,`0`);function pn(e,t,n,r=255){return r>=255?`#${fn(e)}${fn(t)}${fn(n)}`:`#${fn(e)}${fn(t)}${fn(n)}${fn(r)}`}function mn(e,t,n){let r=e/255,i=t/255,a=n/255,o=Math.max(r,i,a),s=Math.min(r,i,a),c=(o+s)/2;if(o===s)return[0,0,c];let l=o-s,u=c>.5?l/(2-o-s):l/(o+s),d;return d=o===r?(i-a)/l+(i<a?6:0):o===i?(a-r)/l+2:(r-i)/l+4,[d*60,u,c]}function hn(e,t,n){let r=(e%360+360)%360/360;if(t===0){let e=Math.round(n*255);return[e,e,e]}let i=n<.5?n*(1+t):n+t-n*t,a=2*n-i,o=e=>{let t=e;return t<0&&(t+=1),t>1&&--t,t<1/6?a+(i-a)*6*t:t<1/2?i:t<2/3?a+(i-a)*(2/3-t)*6:a};return[Math.round(o(r+1/3)*255),Math.round(o(r)*255),Math.round(o(r-1/3)*255)]}function gn(e,t,n){let r=(t-e+540)%360-180;return Math.abs(r)<n?t:(r=Math.sign(r)*n,(e+r+360)%360)}var _n=new Map;function L(e,t){if(t===0)return e;let n=`${e}|${t}`,r=_n.get(n);if(r)return r;let[i,a,o,s]=ln(e),[c,l,u]=mn(i,a,o),d=Math.abs(t);t<0?(c=gn(c,235,d*55*Math.min(1,l*2+.2)),l=dn(l+d*.12)):(c=gn(c,48,d*35*Math.min(1,l*2+.2)),l=dn(l-d*.05)),u=dn(u+t);let[f,p,m]=hn(c,l,u),h=pn(f,p,m,s);return _n.set(n,h),h}function R(e,t,n){let r=ln(e),i=ln(t),a=dn(n);return pn(r[0]+(i[0]-r[0])*a,r[1]+(i[1]-r[1])*a,r[2]+(i[2]-r[2])*a,r[3]+(i[3]-r[3])*a)}function vn(e){let[t,n,r]=ln(e);return(.2126*t+.7152*n+.0722*r)/255}var yn=new Map;function z(e,t=.08){let n=`${e}|${t}`,r=yn.get(n);return r||(r={hi:L(e,t*2),lt:L(e,t),base:e,dk:L(e,-t),dd:L(e,-t*2)},yn.set(n,r)),r}var bn=`#272b3b`,xn=new Map;function Sn(e,t,n){let r=e<<16|t<<8|n,i=xn.get(r);return i||(i=R(L(pn(e,t,n),-.45),bn,.7),xn.set(r,i)),i}var Cn=class e{w;h;data;ox=0;oy=0;constructor(e,t){this.w=e,this.h=t,this.data=new Uint8ClampedArray(e*t*4)}inside(e,t){return e>=0&&t>=0&&e<this.w&&t<this.h}alpha(e,t){let n=e+this.ox,r=t+this.oy;return this.inside(n,r)?this.data[(r*this.w+n)*4+3]:0}set(e,t,n){if(!n)return;let r=Math.floor(e)+this.ox,i=Math.floor(t)+this.oy;if(!this.inside(r,i))return;let[a,o,s,c]=ln(n);this.blend(r,i,a,o,s,c)}put(e,t,n){let r=e+this.ox,i=t+this.oy;if(r<0||i<0||r>=this.w||i>=this.h)return;let a=(i*this.w+r)*4;this.data[a]=n[0],this.data[a+1]=n[1],this.data[a+2]=n[2],this.data[a+3]=n[3]}blend(e,t,n,r,i,a){let o=(t*this.w+e)*4,s=this.data;if(a>=255){s[o]=n,s[o+1]=r,s[o+2]=i,s[o+3]=255;return}if(a<=0)return;let c=a/255,l=s[o+3]/255,u=c+l*(1-c);s[o]=(n*c+s[o]*l*(1-c))/u,s[o+1]=(r*c+s[o+1]*l*(1-c))/u,s[o+2]=(i*c+s[o+2]*l*(1-c))/u,s[o+3]=u*255}under(e,t,n){let r=Math.floor(e)+this.ox,i=Math.floor(t)+this.oy;if(!this.inside(r,i))return;let a=(i*this.w+r)*4,o=this.data,[s,c,l,u]=ln(n),d=o[a+3]/255;if(d>=1)return;let f=u/255*(1-d),p=d+f;p<=0||(o[a]=(o[a]*d+s*f)/p,o[a+1]=(o[a+1]*d+c*f)/p,o[a+2]=(o[a+2]*d+l*f)/p,o[a+3]=p*255)}clear(e,t){let n=e+this.ox,r=t+this.oy;this.inside(n,r)&&this.data.fill(0,(r*this.w+n)*4,(r*this.w+n)*4+4)}clearRect(e,t,n,r){for(let i=t;i<t+r;i++)for(let t=e;t<e+n;t++)this.clear(t,i)}rect(e,t,n,r,i){if(!(!i||n<=0||r<=0))for(let a=t;a<t+r;a++)for(let t=e;t<e+n;t++)this.set(t,a,i)}hline(e,t,n,r){let i=Math.min(e,t),a=Math.max(e,t);for(let e=i;e<=a;e++)this.set(e,n,r)}vline(e,t,n,r){let i=Math.min(t,n),a=Math.max(t,n);for(let t=i;t<=a;t++)this.set(e,t,r)}line(e,t,n,r,i,a=1){let o=Math.round(e),s=Math.round(t),c=Math.round(n),l=Math.round(r),u=Math.abs(c-o),d=-Math.abs(l-s),f=o<c?1:-1,p=s<l?1:-1,m=u+d;for(;a<=1?this.set(o,s,i):this.rect(o,s,a,a,i),o!==c||s!==l;){let e=2*m;e>=d&&(m+=d,o+=f),e<=u&&(m+=u,s+=p)}}ellipse(e,t,n,r,i){if(i)for(let a=Math.floor(t-r);a<=Math.ceil(t+r);a++)for(let o=Math.floor(e-n);o<=Math.ceil(e+n);o++){let s=(o+.5-e)/n,c=(a+.5-t)/r;s*s+c*c<=1&&this.set(o,a,i)}}shadow(e,t,n,r,i=`#1c2034`,a=.22){let[o,s,c]=ln(i),l=`rgba(${o},${s},${c},${a})`,u=`rgba(${o},${s},${c},${Math.min(1,a*1.35)})`;for(let i=Math.floor(t-r);i<=Math.ceil(t+r);i++)for(let a=Math.floor(e-n);a<=Math.ceil(e+n);a++){let o=(a+.5-e)/n,s=(i+.5-t)/r,c=o*o+s*s;c<=1&&this.under(a,i,c<.45?u:l)}}stamp(e,t,n,r,i=!1){for(let a=0;a<e.length;a++){let o=e[a];for(let e=0;e<o.length;e++){let s=o[e];if(s===`.`||s===` `)continue;let c=r[s];if(!c)continue;let l=i?o.length-1-e:e;this.set(t+l,n+a,c)}}}draw(e,t,n,r=!1){for(let i=0;i<e.h;i++)for(let a=0;a<e.w;a++){let o=(i*e.w+a)*4,s=e.data[o+3];if(!s)continue;let c=t+this.ox+(r?e.w-1-a:a),l=n+this.oy+i;this.inside(c,l)&&this.blend(c,l,e.data[o],e.data[o+1],e.data[o+2],s)}}flipped(){let t=new e(this.w,this.h);return t.draw(this,0,0,!0),t}crop(t,n,r,i){let a=new e(r,i);for(let e=0;e<i;e++)for(let i=0;i<r;i++){if(!this.inside(t+i,n+e))continue;let o=((n+e)*this.w+(t+i))*4,s=(e*r+i)*4;a.data[s]=this.data[o],a.data[s+1]=this.data[o+1],a.data[s+2]=this.data[o+2],a.data[s+3]=this.data[o+3]}return a}outline(e){let{w:t,h:n}=this,r=this.data.slice(),i=e?Math.max(0,e.x):0,a=e?Math.max(0,e.y):0,o=e?Math.min(t,e.x+e.w):t,s=e?Math.min(n,e.y+e.h):n,c=(e,i)=>e>=0&&i>=0&&e<t&&i<n&&r[(i*t+e)*4+3]>=160;for(let e=a;e<s;e++)for(let n=i;n<o;n++){let i=(e*t+n)*4;if(r[i+3]>=160)continue;let a=-1,o=1e9,s=(e,n)=>{if(!c(e,n))return;let i=(n*t+e)*4,s=r[i]*.3+r[i+1]*.59+r[i+2]*.11;s<o&&(o=s,a=i)};if(s(n,e-1),s(n-1,e),s(n+1,e),s(n,e+1),a<0)continue;let[l,u,d]=ln(Sn(r[a],r[a+1],r[a+2]));this.data[i]=l,this.data[i+1]=u,this.data[i+2]=d,this.data[i+3]=255}}bounds(){let e=this.w,t=this.h,n=-1,r=-1;for(let i=0;i<this.h;i++)for(let a=0;a<this.w;a++)this.data[(i*this.w+a)*4+3]!==0&&(a<e&&(e=a),a>n&&(n=a),i<t&&(t=i),i>r&&(r=i));return n<0?null:{x:e,y:t,w:n-e+1,h:r-t+1}}countOpaque(){let e=0;for(let t=3;t<this.data.length;t+=4)this.data[t]&&e++;return e}},B=(e,t,n)=>({x:e,y:t,rows:n}),wn={down:B(0,4,[`...ssssssss...`,`..ssssssssss..`,`.sssssssssssS.`,`.sssssssssssS.`,`.sssssssssssS.`,`.sssssssssssS.`,`ssssessssessSs`,`SsssEssssEssSS`,`.ssbssssssbsS.`,`..ssssmmsssS..`,`...sssssssS...`]),up:B(0,4,[`...ssssssss...`,`..ssssssssss..`,`.sssssssssssS.`,`.sssssssssssS.`,`.sssssssssssS.`,`.sssssssssssS.`,`ssssssssssssSs`,`SssssssssssSSS`,`.sssssssssssS.`,`..ssssssssSS..`,`...sssssssS...`]),side:B(0,4,[`...ssssssss...`,`..ssssssssss..`,`.sssssssssssS.`,`.sssssssssssS.`,`.sssssssssssS.`,`.sssssssssssS.`,`.sseSssssrsSS.`,`sssEsssssrsSS.`,`.sssbsssssSS..`,`.smssssssSS...`,`..sssssssS....`])},Tn={short:{down:{front:B(0,2,[`....oooooo....`,`..ooohhhhooo..`,`.oohhHHhhoood.`,`oohhhhhhoooodd`,`ohhooooooooddd`,`oooooooo...odd`,`ood.d.......dd`,`od..........dd`])},up:{front:B(0,2,[`....oooooo....`,`..ooohhhhooo..`,`.oohhHHhhoood.`,`oohhhhhhoooodd`,`ohhooooooooddd`,`oooooooooooodd`,`oooooooooooodd`,`oooooooooooddd`,`.oooooooooodd.`,`.dooooooooodd.`,`..ddoooooddd..`,`....dddddd....`])},side:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`oohhhhhhoooodd`,`oooooohooooodd`,`.o.o.ooooooodd`,`.......oooodd.`,`.......ooooddd`,`.......d.oodd.`,`.........oddd.`,`..........dd..`])}},buzz:{down:{front:B(0,3,[`...oooooooo...`,`..ohhhhooood..`,`.ohhooooooood.`,`.oooooooooood.`,`.od........do.`,`.d..........d.`])},up:{front:B(0,3,[`...oooooooo...`,`..ohhhhooood..`,`.ohhooooooood.`,`.oooooooooood.`,`.oooooooooood.`,`.oooooooooodd.`,`.oooooooooodd.`,`.dooooooooodd.`,`..dooooooodd..`,`...dddddddd...`])},side:{front:B(0,3,[`...oooooooo...`,`..ohhhhooood..`,`.ohhooooooood.`,`.oooooooooood.`,`....oooooood..`,`.......ooood..`,`.......d.ood..`,`.........od...`,`.........dd...`])}},spiky:{down:{front:B(0,0,[`...o...o..o...`,`..oo..oho.oo..`,`.ooohhhhhoood.`,`.ohhHHhhooood.`,`oohhhhhooooodd`,`ohhooooooooodd`,`oooo.ooo.oo.dd`,`oo.o..o.....dd`,`od..........dd`,`.d..........d.`])},up:{front:B(0,0,[`...o...o..o...`,`..oo..oho.oo..`,`.ooohhhhhoood.`,`.ohhHHhhooood.`,`oohhhhhooooodd`,`ohhooooooooodd`,`oooooooooooodd`,`oooooooooooodd`,`oooooooooooddd`,`.oooooooooodd.`,`.dooooooooodd.`,`..ddoooooddd..`,`....dddddd....`])},side:{front:B(0,0,[`.......o...o..`,`....oo.oo.oo..`,`..ooohhhhooo..`,`.ohhHHhhhoood.`,`oohhhhhhoooodd`,`oooooohooooodd`,`oo.o.ooooooodd`,`.......oooodd.`,`.......ooooddd`,`.......d.oodd.`,`.........oddd.`,`..........dd..`])}},side_part:{down:{front:B(0,2,[`....oooooo....`,`..ooDhhhhooo..`,`.ooDhHHhhhood.`,`oooDhhhhhhoodd`,`ooo.oooooooddd`,`oo....oooooodd`,`od.......oo.dd`,`od..........dd`])},up:{front:B(0,2,[`....oooooo....`,`..ooDhhhhooo..`,`.ooDhHHhhhood.`,`oooDhhhhhhoodd`,`oooDoooooooddd`,`oooooooooooodd`,`oooooooooooodd`,`oooooooooooddd`,`.oooooooooodd.`,`.dooooooooodd.`,`..ddoooooddd..`,`....dddddd....`])},side:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`oohhhhhhoooodd`,`ohhhooooooodd.`,`oo.ooooooooodd`,`o......oooodd.`,`.......ooooddd`,`.......d.oodd.`,`.........oddd.`,`..........dd..`])}},curly:{down:{front:B(0,1,[`....ohoooo....`,`..ohoHohooho..`,`.oHohhohohood.`,`ohohoohooohodd`,`oohoohoooohodd`,`ohoodoohodoodd`,`oodo.o..o.oodd`,`odo........odd`,`do..........dd`])},up:{front:B(0,1,[`....ohoooo....`,`..ohoHohooho..`,`.oHohhohohood.`,`ohohoohooohodd`,`oohoohoooohodd`,`ohoodoohodoodd`,`oodoohoodoohdd`,`odohoodohoodod`,`ooodohooododdd`,`.ohoodohoodod.`,`.dodoohodoodd.`,`..ddodooddd...`,`....dddddd....`])},side:{front:B(0,1,[`....ohoooo....`,`..ohoHohooho..`,`.oHohhohohood.`,`ohohoohooohodd`,`oohoohoooohodd`,`odo.dooohodood`,`.o.o..oodoohdd`,`.......ohooddd`,`.......doodod.`,`........d.odd.`,`.........oddd.`,`..........dd..`])}},afro:{down:{front:B(-1,0,[`....oohhhooo....`,`..oohhHHhhoooo..`,`.oohhHHhhhooooo.`,`oohhhhhhoooooodd`,`ohhhhooooooooodd`,`ohhooooooooooodd`,`oooooooooooooodd`,`oooo........oodd`,`ooo..........odd`,`ood..........ddd`,`od............dd`,`.d............d.`])},up:{front:B(-1,0,[`....oohhhooo....`,`..oohhHHhhoooo..`,`.oohhHHhhhooooo.`,`oohhhhhhoooooodd`,`ohhhhooooooooodd`,`ohhooooooooooodd`,`oooooooooooooodd`,`oooooooooooooodd`,`oooooooooooooddd`,`oooooooooooooddd`,`.oooooooooooodd.`,`.ddooooooooddd..`,`...ddddddddd....`])},side:{front:B(-1,0,[`....oohhhooo....`,`..oohhHHhhoooo..`,`.oohhHHhhhooooo.`,`oohhhhhhoooooodd`,`ohhhoooooooooodd`,`ohhooooooooooodd`,`oooooooooooooodd`,`oo...ooooooooodd`,`........oooooddd`,`........d.oooddd`,`..........oooddd`,`..........oddd..`,`...........dd...`])}},bob:{down:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`ohhhhhhhoooodd`,`ohhooooooooodd`,`oooooooooooodd`,`ooo........odd`,`ood........odd`,`od..........dd`,`od..........dd`,`od..........dd`,`odd........ddd`,`.dd........dd.`])},up:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`ohhhhhhhoooodd`,`ohhooooooooodd`,`oooooooooooodd`,`oooooooooooodd`,`oooooooooooodd`,`oooooooooooddd`,`oooooooooooddd`,`oooooooooooddd`,`odoooooooodddd`,`.dddddddddddd.`])},side:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`oohhhhhhoooodd`,`ohhooooooooood`,`ooooooooooood.`,`oo....oooooodd`,`o.....oooooddd`,`......ohoooddd`,`......oooooddd`,`......ooooodd.`,`......dddoddd.`,`.......ddddd..`])}},long:{down:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHhDhhHood.`,`ohhhhDDohhoodd`,`ohhoo....ooodd`,`oho........odd`,`oho........odd`,`oo..........dd`,`oo..........dd`,`oh..........dd`,`oo..........dd`,`oo..........dd`,`oho........odd`,`ooo........odd`,`odd........ddd`,`.dd........dd.`]),back:B(-1,8,[`oooooooooooooodd`,`oooooooooooooodd`,`oooooooooooooodd`,`oooooooooooooodd`,`oooooooooooooodd`,`oooooooooooooodd`,`oooooooooooooodd`,`oooooooooooooodd`,`dooooooooooooddd`,`dddoooooooooddd.`,`.dddddddddddd...`])},up:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`ohhhhhhhoooodd`,`ohhooooooooodd`,`oooooooooooodd`,`ohoooooooooodd`,`ohoooooooooodd`,`oooooooooooddd`,`oooooooooooddd`,`ooohoooooooddd`,`oooooooooooddd`,`ooohooooooodd.`,`oooooooooooddd`,`odoooooooooddd`,`oddooooooodddd`,`.dddoooooddd..`,`...dddddddd...`])},side:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`oohhhhhhoooodd`,`ohhooooooooodd`,`ooooooooooood.`,`oo....oooooodd`,`o.....ooooodd.`,`......ohooodd.`,`......oooooddd`,`......ooohoddd`,`.......oooodd.`,`.......ooooddd`,`.......ohooodd`,`.......oooodd.`,`.......ooood..`,`........dddd..`])}},ponytail:{down:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`ohhhhhhhoooodd`,`ohoooooooooodd`,`oo..........dd`,`od..........dd`,`.d...........d`]),back:B(12,4,[`.aa`,`ohd`,`ohd`,`ood`,`ohd`,`.od`,`.od`,`.od`,`.dd`,`..d`])},up:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`ohhhhhhhoooodd`,`ohoooohooooddd`,`ooooodaadooodd`,`oooooohhoooodd`,`ooooohoodooood`,`.ooooohoddood.`,`.dooooohodood.`,`..ddooohodod..`,`....ddohoddd..`,`......ohod....`,`......ohdd....`,`......ood.....`,`.......dd.....`])},side:{front:B(0,2,[`....oooooo.....`,`..oohhhhhoooo..`,`.ohhHHhhhooaad.`,`oohhhhhhoooohd.`,`ohoooooooooohd.`,`oo.ooooooooohd.`,`.......ooood.od`,`.......oood..od`,`.......d.od..od`,`.........dd..dd`,`..............d`])}},bun:{down:{front:B(0,0,[`.....oooo.....`,`....ohHhod....`,`...ooddddoo...`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`ohhhhhhhoooodd`,`ohoooooooooodd`,`oo..........dd`,`od..........dd`,`.d..........d.`])},up:{front:B(0,0,[`.....oooo.....`,`....ohHhod....`,`...ooddddoo...`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`ohhhhhhhoooodd`,`ohoooooooooodd`,`oooooooooooodd`,`oooooooooooodd`,`oooooooooooddd`,`.oooooooooodd.`,`.dooooooooodd.`,`..ddoooooddd..`,`....dddddd....`])},side:{front:B(0,0,[`.........ooo..`,`........ohHod.`,`....ooooodddd.`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`oohhhhhhoooodd`,`ohoooooooooodd`,`oo.ooooooooodd`,`.......oooodd.`,`.......ooooddd`,`.......d.oodd.`,`.........oddd.`,`..........dd..`])}},pigtails:{down:{front:B(0,2,[`....oooooo....`,`..oohhDhhooo..`,`.ohhHhDhHhood.`,`ohhhhhDhhhoodd`,`ohhooooooooodd`,`ooo.o....o.odd`,`od..........dd`,`od..........dd`]),back:B(-2,8,[`.a..............a.`,`oho............ohd`,`ohd............ohd`,`ohd............odd`,`ood............odd`,`.od............dd.`,`.d..............d.`])},up:{front:B(-2,2,[`......oooooo......`,`....oohhDhhooo....`,`...ohhHhDhHhood...`,`..ohhhhhDhhhoodd..`,`..ohhoooDooooodd..`,`..ooooooDoooooddd.`,`..ooooooDoooooodd.`,`.aooooooDooooodda.`,`ohooooooDoooooodhd`,`ohd.ooooDooooo.ohd`,`ohd..ddoDoodd..odd`,`ood....dddd....odd`,`.od............dd.`,`.d..............d.`])},side:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`oohhhhhhoooodd`,`ohhooooooooodd`,`oo.o.ooooooodd`,`.......oooodd.`,`.......oooaad.`,`.......d.oohd.`,`.........ohdd.`,`.........ohd..`,`.........ood..`,`.........odd..`,`..........d...`])}},mohawk:{down:{front:B(0,0,[`......oo......`,`.....ohoo.....`,`.....hHod.....`,`...zzhhodzz...`,`..zzzohodzzz..`,`.zzzzoooodzzz.`,`.zzzzoood.zzz.`,`.z..........z.`])},up:{front:B(0,0,[`......oo......`,`.....ohoo.....`,`.....hHod.....`,`...zzhhodzz...`,`..zzzohodzzz..`,`.zzzzoooodzzz.`,`.zzzzoooodzzz.`,`.zzzzoooodzzz.`,`.zzzzoooodzzz.`,`.zzzzzoodzzzz.`,`.zzzzzoodzzzz.`,`..zzzzoddzzz..`,`....zzddzz....`])},side:{front:B(0,0,[`...ooo.o......`,`..oohhoooo.o..`,`..ohHHhhoooo..`,`..zzzzzzzzodd.`,`.zzzzzzzzzzzz.`,`.zzzzzzzzzzzz.`,`.......zzzzzz.`,`........zzzzz.`,`.......z.zzzz.`,`.........zzz..`])}},bald:{down:{front:B(0,4,[`..............`,`....kk........`,`...k..........`,`..............`,`zz..........zz`,`zz..........zz`])},up:{front:B(0,4,[`..............`,`....kk........`,`...k..........`,`..............`,`.zzzzzzzzzzzz.`,`zzzzzzzzzzzzzz`,`.zzzzzzzzzzzz.`,`..zzzzzzzzzz..`])},side:{front:B(0,4,[`..............`,`....kk........`,`...k..........`,`..............`,`.......zzzzzz.`,`.......z.zzzz.`,`.........zzz..`])}},wavy:{down:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`ohhhhhhhoooodd`,`ohhooooooooddd`,`oooooo....oodd`,`ohd.......oodd`,`oo........ohdd`,`ho..........dh`,`oh..........od`,`oo..........hd`,`ho..........do`,`dho........ohd`,`.dd........dd.`]),back:B(-1,9,[`oooooooooooooodd`,`hoooooooooooooho`,`oooooooooooooodd`,`ohooooooooooodhd`,`oooooooooooooodd`,`dhooooooooooohdd`,`.ddoooooooooddd.`])},up:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`ohhhhhhhoooodd`,`ohhooooooooddd`,`oooooooooooodd`,`ohoooohooooodd`,`oohooooohooodd`,`ooohoooooohodd`,`oohooooohooodd`,`ohoooohooooddd`,`oohoooooohoddd`,`ooohoooohooddd`,`dohooohooohodd`,`.ddohooohoddd.`,`...dddddddd...`])},side:{front:B(0,2,[`....oooooo....`,`..oohhhhhooo..`,`.ohhHHhhhoood.`,`oohhhhhhoooodd`,`ohhooooooooodd`,`oooooo.oooood.`,`oo....oooooodd`,`......ohoooodd`,`......oohoohd.`,`......ohooohdd`,`.......oohoodd`,`.......ohoohd.`,`.......dohodd.`,`........ddd...`])}}},En=new Set([`curly`,`afro`]),Dn=5,On=3,kn=`#39f0ff`,An={stand:2,walk:4,run:4,sit:2,type:4,sleep:2,drink:2,use:2,raise_hand:2,talk:2,stretch:2,read:2,play:2,wait:2,cheer:2,laugh:2,game:2,rps:2,groom:2,sulk:2},jn={stand:650,walk:140,run:95,sit:800,type:120,sleep:1e3,drink:700,use:380,raise_hand:320,talk:280,stretch:800,read:1100,play:200,wait:480,cheer:260,laugh:190,game:150,rps:300,groom:420,sulk:1300},Mn=new Set([`sit`,`type`,`sleep`,`wait`]),Nn=new Set([`walk`,`run`,`stretch`,`play`,`groom`]),Pn=new Set([`play`,`drink`,`raise_hand`,`stretch`,`cheer`,`laugh`,`game`,`rps`,`groom`,`sulk`]),Fn=new Set([`rock`,`paper`,`scissors`]);function In(e,t){return Mn.has(e)||!!t&&!Nn.has(e)}var Ln=new Map;function Rn(e){let t=Ln.get(e);if(t)return t;let n=z(e.skin,.07),r=vn(e.skin)<.38;return t={skin:n,hair:z(e.hair,.09),top:z(e.top,.08),acc:z(e.topAccent,.08),bottom:z(e.bottom,.07),shoes:z(e.shoes,.08),item:z(e.accessoryColor,.1),face:z(e.faceColor??`#2b2b33`,.1),eyeTop:r?`#ece8f2`:`#1d1826`,eyeBot:r?R(e.eyes,`#0c0910`,.55):R(e.eyes,`#1d1826`,.25),blush:R(e.skin,`#ff7a7a`,.32),mouth:L(e.skin,-.2),mouthOpen:`#7a2e35`,shaved:R(e.skin,e.hair,.42),stubble:R(e.skin,e.hair,.3)},Ln.size>4096&&Ln.clear(),Ln.set(e,t),t}var zn={pts:[[6,18],[6,22]]},Bn={pts:[[16,18],[16,22]]};function V(...e){return{pts:e}}var Vn=new Set([`box`,`laptop`,`papers`,`book`]);function Hn(e,t){let n=e.pose,r=An[n],i=(Math.floor(e.frame)%r+r)%r,a=In(n,e.seated),o=e.held??`none`,s={view:t,seated:a,ub:a?4:0,hd:0,lean:0,legA:{dx:0,dy:0},legB:{dx:0,dy:0},armA:t===`side`?V([12,18],[12,22]):zn,armB:t===`side`?V([10,18],[10,22]):Bn,eyes:`open`,mouth:`none`,held:o,itemBehind:t===`up`,twoHands:!1,itemAt:null,toeTap:!1,tapAt:null,kernelAt:null,crossFront:null},c=t===`side`;switch(n){case`stand`:case`sit`:i===1&&(s.hd=1);break;case`walk`:case`run`:{let e=n===`run`,t=e?2:1;if((i===1||i===3)&&--s.ub,c){let n=[t+2,0,-(t+2),0][i];s.legB={dx:-n,dy:i===3?-2:0},s.legA={dx:n,dy:i===1?-2:0};let r=[-2-!!e,0,2+ +!!e,0][i];s.armB=V([10,18],[10+r,e?21:22]),s.armA=V([12,18],[12-r,e?21:22]),e&&(s.lean=-1)}else{s.legA.dy=[1,0,0,-t][i],s.legB.dy=[0,-t,1,0][i];let n=[-1,0,1,0][i]*(e?2:1);s.armA=V([6,18],[6-!!e,22+n]),s.armB=V([16,18],[16+ +!!e,22-n])}break}case`type`:{let e=i%2==0;t===`up`?(s.armA=V([7,19],[5,21],[6,18+(e?-1:0)]),s.armB=V([15,19],[17,21],[16,18+(e?0:-1)])):t===`down`?(s.armA=V([6,18],[6,21],[8,22+ +!e]),s.armB=V([16,18],[16,21],[14,22+ +!!e])):(s.armB=V([10,18],[9,21],[6,21+(e?0:-1)]),s.armA=V([12,18],[11,21],[7,21+(e?-1:0)]));break}case`sleep`:s.hd=i===0?2:3,s.eyes=`closed`,t===`down`&&(s.armA=V([6,18],[7,21],[9,22]),s.armB=V([16,18],[15,21],[13,22]));break;case`raise_hand`:{let e=+(i===1);s.armB=c?V([10,18],[4,14],[3-e,6]):V([16,18],[19,14],[19+e,7+e]),s.mouth=t===`down`&&i===0?`open`:`none`;break}case`talk`:s.mouth=i===0?`open`:`none`,c?s.armB=V([10,18],[9,21],i===0?[6,19]:[7,21]):i===0?s.armB=V([16,18],[17,21],[18,19]):s.armA=V([6,18],[5,21],[4,19]);break;case`stretch`:s.eyes=`closed`,s.mouth=t===`down`?`open`:`none`,i===1&&--s.ub,c?(s.armB=V([10,18],[5,13],[5,i===0?4:3]),s.armA=V([12,18],[17,12],[16,i===0?4:3])):(s.armA=V([6,18],[4,13],i===0?[5,5]:[4,4]),s.armB=V([16,18],[18,13],i===0?[17,5]:[18,4]));break;case`read`:s.held=o===`none`?`book`:o,i===1&&(s.hd=1);break;case`play`:s.held=`paddle`,s.armB=c?i===0?V([10,18],[13,20],[15,18]):V([10,18],[8,19],[5,18]):i===0?V([16,18],[18,20],[19,18]):V([16,18],[18,17],[19,14]);break;case`use`:{let e=+(i===1);s.armB=t===`up`?V([16,18],[17,15],[16,12-e]):t===`down`?V([16,18],[16,21],[14,23+e]):V([10,18],[8,20],[5-e,20]);break}case`wait`:Un(s,t,i,o);break;case`drink`:{o===`none`&&(s.held=`coffee`);let e=i===1;s.armB=c?e?V([10,18],[8,19],[6,15]):V([10,18],[10,21],[8,21]):t===`down`?e?V([16,18],[16,19],[13,15]):V([16,18],[17,21],[16,21]):e?V([16,18],[18,17],[16,14]):V([16,18],[17,21],[16,21]);break}case`cheer`:Wn(s,t,i);break;case`laugh`:Gn(s,t,i);break;case`game`:Kn(s,t,i);break;case`rps`:qn(s,t,i,o);break;case`groom`:Jn(s,t,i,o);break;case`sulk`:Yn(s,t,i)}let l=s.held;return l!==`none`&&!s.itemAt&&!Pn.has(n)&&(Vn.has(l)||n===`read`?(s.twoHands=!0,c?(s.armB=V([10,18],[10,21],[7,21]),s.armA=V([12,18],[12,21],[8,20])):(s.armA=V([6,18],[6,20],[8,21]),s.armB=V([16,18],[16,20],[14,21]))):n!==`type`&&n!==`use`&&n!==`sleep`&&n!==`talk`&&(s.armB=c?V([10,18],[10,21],[8,21]):V([16,18],[17,21],[16,21]))),l===`paddle`&&n!==`play`&&(s.held=n===`stand`||n===`walk`||n===`run`?`paddle`:`none`),s}function Un(e,t,n,r){t===`down`?--e.ub:t===`up`?e.ub+=1:e.lean=1;let i=n===1;if(r===`popcorn`){e.itemBehind=!1,t===`down`?(e.itemAt=[9,17],e.armA=V([6,18],[6,21],[9,21]),e.armB=i?V([16,18],[17,19],[11,15]):V([16,18],[16,20],[15,20]),e.mouth=i?`none`:`open`,i&&(e.kernelAt=[11,14])):t===`up`?(e.itemAt=[0,18],e.armB=V([16,18],[16,22]),e.armA=i?V([6,18],[3,16],[6,13]):V([6,18],[4,20],[3,18])):(e.itemAt=[3,18],e.armA=V([12,18],[12,21],[8,22]),e.armB=i?V([10,18],[9,21],[5,16]):V([10,18],[10,21],[6,19]),e.mouth=i?`none`:`open`,i&&(e.kernelAt=[5,15]));return}if(r!==`none`)return;let a=n===1;e.eyes=`half`,e.toeTap=a;let o=a?-1:0;t===`down`?e.crossFront=+!!a:t===`up`?(e.armA=V([6,18],[4,20],[6,22]),e.armB=V([16,18],[18,20],[16,22]),e.tapAt=[3,19+o]):(e.armA=V([12,18],[12,21],[9,21]),e.armB=V([10,18],[10,21],[7,20+o]))}function Wn(e,t,n){let r=n===1;if(e.mouth=`open`,r&&(e.eyes=`happy`),r&&(e.seated?--e.ub:(e.ub-=2,e.legA={dx:0,dy:-2},e.legB={dx:0,dy:-2})),t===`side`){e.armB=r?V([10,18],[5,13],[3,3]):V([10,18],[6,13],[4,4]),e.armA=r?V([12,18],[17,12],[18,2]):V([12,18],[16,12],[17,3]);return}e.armA=r?V([6,18],[3,12],[2,3]):V([6,18],[4,12],[3,4]),e.armB=r?V([16,18],[19,12],[20,3]):V([16,18],[18,12],[19,4])}function Gn(e,t,n){if(e.eyes=`happy`,e.mouth=n===0?`wide`:`open`,n===0&&--e.ub,t===`side`){e.lean=n===0?1:-1,e.armB=V([10,18],[10,21],[7,22]),e.armA=n===0?V([12,18],[12,22]):V([12,18],[11,21],[9,23]);return}if(t===`up`){e.armA=V([6,18],[4,21],[7,22]),e.armB=V([16,18],[18,21],[15,22]);return}e.armB=V([16,18],[17,21],[14,22]),e.armA=n===0?V([6,18],[6,22]):V([6,18],[5,21],[4,23])}function Kn(e,t,n){e.held=`controller`,e.twoHands=!0;let r=n===0?0:1,i=1-r;if(t===`down`){e.itemAt=[9,20],e.armA=V([6,18],[6,20],[8,20+r]),e.armB=V([16,18],[16,20],[15,20+i]);return}if(t===`side`){e.lean=-1,e.itemAt=[4,19],e.armA=V([12,18],[11,21],[7,20+r]),e.armB=V([10,18],[10,21],[6,20+i]);return}e.held=`none`,e.twoHands=!1,e.armA=V([6,18],[4,20],[7,21+r]),e.armB=V([16,18],[18,20],[15,21+i])}function qn(e,t,n,r){let i=Fn.has(r);if(e.held=i?r:`rock`,e.itemBehind=!1,!i){let r=n===0;t!==`up`&&(e.mouth=r?`open`:`none`),t===`side`?(e.armB=r?V([10,18],[6,16],[3,12]):V([10,18],[6,18],[3,16]),e.armA=V([12,18],[12,22])):t===`down`?(e.armB=r?V([16,18],[18,15],[18,11]):V([16,18],[18,18],[18,15]),e.armA=V([6,18],[5,21],[6,22])):(e.armB=r?V([16,18],[19,15],[20,11]):V([16,18],[19,18],[20,15]),e.armA=V([6,18],[6,22]));return}let a=n===1?-1:0;t===`side`?(e.armB=V([10,18],[7,19],[4,19+a]),e.armA=V([12,18],[12,22])):t===`down`?(e.armB=V([16,18],[16,20],[13,20+a]),e.armA=V([6,18],[6,22])):(e.armB=V([16,18],[19,18],[21,17+a]),e.armA=V([6,18],[6,22]))}function Jn(e,t,n,r){e.itemBehind=!1;let i=r===`comb`;if(t===`up`){e.armB=n===0?V([16,18],[20,15],[18,11]):V([16,18],[20,14],[17,9]);return}if(t===`side`){e.armB=i?n===0?V([10,18],[8,15],[9,9]):V([10,18],[8,14],[11,8]):n===0?V([10,18],[9,17],[6,15]):V([10,18],[9,16],[6,14]);return}e.armB=i?n===0?V([16,18],[19,14],[18,9]):V([16,18],[19,13],[16,8]):n===0?V([16,18],[18,17],[14,15]):V([16,18],[18,17],[13,15]),i||(e.mouth=`none`)}function Yn(e,t,n){if(e.eyes=`half`,e.mouth=`frown`,e.hd=n===0?1:2,e.seated||(e.ub+=1),t===`side`){e.lean=-1,e.armB=V([10,18],[10,22]),e.armA=V([12,18],[12,22]);return}e.armA=V([6,18],[7,22]),e.armB=V([16,18],[15,22])}function Xn(e,t,n,r){let{b:i,p:a,r:o}=e,s=o.ub,c=t,l=n<4?a.skin:c,u=a.skin;for(let e=18;e<=20;e++)i.set(6,e+s,e===20?c.dk:c.base),i.set(7,e+s,c.dk),i.set(16,e+s,c.base),i.set(17,e+s,e===20?c.dd:c.dk);i.hline(8,15,21+s,l.dk),i.set(16,21+s,u.base),i.set(17,21+s,u.dk),i.hline(8,17,19+s,l.lt),i.hline(8,17,20+s,l.base),i.set(17,20+s,l.dk),i.set(12,20+s,l.dk);let d=r?18:19;i.set(5,d+s,u.lt),i.set(6,d+s,u.base),i.set(5,d+1+s,u.base),i.set(6,d+1+s,u.dk),i.set(7,19+s,u.base),i.set(7,20+s,u.dk)}function Zn(e,t){let n=e.hair;return t?{o:R(n.base,e.skin.base,.3),h:R(n.lt,e.skin.base,.3),H:R(n.hi,e.skin.base,.35),d:R(n.dk,e.skin.base,.2),D:n.dd,z:e.shaved,k:e.skin.hi}:{o:n.base,h:n.lt,H:n.hi,d:n.dk,D:n.dd,z:e.shaved,k:e.skin.hi}}function Qn(e,t,n,r,i=!1){let{b:a}=e,o=Dn+t.x+e.r.lean,s=On+t.y+r;if(!i){a.stamp(t.rows,o,s,n);return}for(let e=0;e<t.rows.length;e++){let r=t.rows[e];for(let i=0;i<r.length;i++){let c=r[i];if(c!==`.`&&c!==` `){if(c===`o`){let n=(i*5+(t.y+e)*3)%7;n===0?c=`d`:n===3&&e<t.rows.length/2&&(c=`h`)}a.set(o+i,s+e,n[c])}}}}function $n(e){let{p:t,r:n}=e,r=wn[n.view],i=n.ub+n.hd,a=n.eyes===`closed`||n.eyes===`happy`,o=n.eyes===`half`,s=vn(t.eyeTop)>.5?t.eyeBot:t.eyeTop,c={s:t.skin.base,S:t.skin.dk,L:t.skin.lt,e:a?t.skin.base:o?L(t.skin.base,-.16):t.eyeTop,E:a?L(t.skin.base,-.3):o?s:t.eyeBot,b:t.blush,m:n.mouth===`open`||n.mouth===`wide`?t.mouthOpen:e.a.look===`f`?R(t.mouth,`#c0505a`,.25):t.mouth,r:t.skin.dk};e.b.stamp(r.rows,Dn+r.x+n.lean,On+r.y+i,c);let l=Dn+r.x+n.lean,u=On+r.y+i;if(n.eyes===`happy`&&n.view!==`up`){let r=R(t.skin.base,`#1d1826`,.7);for(let i of n.view===`down`?[4,9]:[3])e.b.set(l+i,u+6,r),e.b.set(l+i,u+7,t.skin.base),e.b.set(l+i-1,u+7,r),e.b.set(l+i+1,u+7,r)}if(n.mouth===`frown`&&n.view!==`up`){let r=L(t.mouth,-.12);n.view===`down`?(e.b.set(l+5,u+10,r),e.b.set(l+8,u+10,r)):e.b.set(l+3,u+10,r)}if(n.mouth===`wide`&&n.view!==`up`){let r=`#d8646e`;n.view===`down`?(e.b.set(l+5,u+9,t.mouthOpen),e.b.set(l+8,u+9,t.mouthOpen),e.b.set(l+6,u+10,r),e.b.set(l+7,u+10,r)):(e.b.set(l+1,u+9,t.mouthOpen),e.b.set(l+2,u+10,r))}n.view!==`up`&&e.b.set(8+n.lean,10+i,t.skin.lt)}function er(e){let t=e.a.facialHair??`none`;if(t===`none`||e.r.view===`up`)return;let{b:n,p:r,r:i}=e,a=Dn+i.lean,o=On+i.ub+i.hd,s=t===`stubble`?r.stubble:r.hair.base,c=t===`stubble`?L(r.stubble,-.04):r.hair.dk,l=(e,t,r=s)=>n.set(a+e,o+t,r);if(i.view===`down`){if(t===`beard`||t===`stubble`){for(let e of[1,12])for(let t of[10,11])l(e,t,c);for(let e=1;e<=12;e++)l(e,12,e>9?c:s);for(let e=2;e<=11;e++)(e<6||e>7)&&l(e,13,e>9?c:s);for(let e=3;e<=10;e++)l(e,14,c);t===`beard`&&(l(5,12,r.hair.dk),l(8,12,r.hair.dk))}else if(t===`mustache`)for(let e=5;e<=8;e++)l(e,12,e===8?c:s);else if(t===`goatee`){l(5,13,s),l(8,13,c);for(let e=5;e<=8;e++)l(e,14,e>6?c:s)}}else if(t===`beard`||t===`stubble`){for(let e of[10,11])l(7,e,c);for(let e=1;e<=8;e++)l(e,12,s);for(let e=1;e<=8;e++)e!==2&&l(e,13,e>5?c:s);for(let e=2;e<=8;e++)l(e,14,c)}else t===`mustache`?(l(1,12,s),l(2,12,s),l(3,12,c)):t===`goatee`&&(l(1,13,s),l(2,14,s),l(3,14,c))}function tr(e,t){let n=e.a.hairStyle,r=Tn[n]?.[e.r.view]?.[t];r&&Qn(e,r,{...Zn(e.p,n===`buzz`),a:e.a.accessory===`bow`?e.p.item.base:L(e.a.top,.05)},e.r.ub+e.r.hd,En.has(n))}function nr(e,t){let{b:n,p:r,r:i}=e,a=Dn+i.lean,o=On+i.ub+i.hd,s=(e,t,r)=>n.set(a+e,o+t,r),c=r.item,l=i.view,u=kn,d=R(kn,`#0c1018`,.45);if(l===`side`){for(let e=5;e<=9;e++)s(e,2,e===7?c.lt:c.base);s(4,3,c.base),s(10,3,c.dk);for(let e=4;e<=8;e++)s(7,e,c.dk);for(let e=9;e<=12;e++)for(let t=6;t<=9;t++)s(t,e,e===9||t===6?c.lt:c.base);s(9,12,c.dk),t&&(s(7,10,u),s(8,10,u),s(7,11,d),s(8,11,d),s(7,3,u),s(6,13,c.dk),s(5,13,c.dk),s(4,14,c.dk),s(3,14,u));return}for(let e=3;e<=10;e++)s(e,1,e<6?c.lt:c.base);s(2,2,c.base),s(11,2,c.dk);for(let e=3;e<=8;e++)s(1,e,c.base),s(12,e,c.dk);for(let e=9;e<=12;e++)s(0,e,c.base),s(1,e,e===9?c.lt:c.base),s(12,e,c.dk),s(13,e,c.dk);if(t){for(let e of[10,11])s(0,e,e===10?u:d),s(13,e,e===10?u:d);s(6,1,u),s(7,1,u),l===`down`&&(s(0,13,c.dk),s(1,14,c.dk),s(2,14,c.dk),s(3,14,u))}}function rr(e){let{b:t,p:n,r,a:i}=e,a=Dn+r.lean,o=On+r.ub+r.hd,s=(e,n,r)=>t.set(a+e,o+n,r),c=n.item,l=r.view;switch(i.accessory){case`glasses`:{let e=L(c.dk,-.08);if(l===`down`){for(let t of[3,8])s(t,10,e),s(t+1,10,e),s(t+2,10,e),s(t,11,e),s(t+2,11,`rgba(225,240,255,0.6)`);for(let e of[1,2,6,7,11,12])s(e,10,c.base)}else if(l===`side`){s(2,10,e),s(3,10,e),s(4,10,e),s(2,11,e),s(4,11,e);for(let e=5;e<=8;e++)s(e,10,c.base)}else s(0,10,c.dk),s(13,10,c.dk);break}case`sunglasses`:if(l===`down`){for(let e=2;e<=11;e++)s(e,10,`#15161c`);for(let e of[2,3,4,5,8,9,10,11])s(e,11,e===3||e===9?`#5a6b8a`:`#15161c`);s(0,10,`#15161c`),s(13,10,`#15161c`)}else if(l===`side`){for(let e=1;e<=4;e++)s(e,10,`#15161c`);for(let e=1;e<=3;e++)s(e,11,e===2?`#5a6b8a`:`#15161c`);for(let e=5;e<=8;e++)s(e,10,`#15161c`)}else s(0,10,`#15161c`),s(13,10,`#15161c`);break;case`headphones`:nr(e,!1);break;case`gamer_headphones`:nr(e,!0);break;case`cap`:{let e=c.dk;l===`down`?(t.stamp([`....oooooo....`,`..oohhhhoooo..`,`.ohhHhhhooood.`,`.oohhhooooood.`,`bbbbbbbbbbbbbb`],a,o+2,{o:c.base,h:c.lt,H:c.hi,d:c.dk,b:e}),s(6,3,`#f4f2ee`),s(7,3,`#f4f2ee`)):l===`up`?t.stamp([`....oooooo....`,`..oohhhhoooo..`,`.ohhHhhhooood.`,`.oohhhooooood.`,`.oooo....oodd.`,`.....d..d.....`],a,o+2,{o:c.base,h:c.lt,H:c.hi,d:c.dk}):t.stamp([`.....oooooo...`,`...oohhhhooo..`,`..ohHhhhoooood`,`..ohhhooooooo.`,`bbbbbboooood..`],a-1,o+2,{o:c.base,h:c.lt,H:c.hi,d:c.dk,b:e});break}case`beanie`:{let e=c.dk,n=l===`side`?[`.....ww.......`,`....oooooo....`,`..oohhhooooo..`,`.ohhHhhoooood.`,`.ohhhhooooood.`,`.rrrrrrrrrrrr.`]:[`......ww......`,`....oooooo....`,`..oohhhooooo..`,`.ohhHhhoooood.`,`.ohhhhooooood.`,`rrrrrrrrrrrrrr`];t.stamp(n,a,o+1,{o:c.base,h:c.lt,H:c.hi,d:c.dk,r:e,w:`#f4f2ee`});for(let t=1;t<=12;t+=2)s(t,6,L(e,-.06));break}case`earrings`:l===`down`?(s(0,12,c.base),s(13,12,c.dk)):l===`side`&&s(8,12,c.base);break;case`bow`:{let e=[`oo.oo`,`ohdho`,`.o.o.`],n={o:c.base,h:c.lt,d:c.dd};l===`down`?t.stamp(e,a+8,o+2,n):l===`up`?t.stamp(e,a+1,o+2,n):t.stamp(e,a+7,o+1,n);break}}}function ir(e,t,n,r,i=0,a=!1){let{b:o,p:s,r:c}=e,l=[];for(let e=0;e<t.pts.length-1;e++){let[n,r]=t.pts[e],[i,a]=t.pts[e+1],o=Math.max(Math.abs(i-n),Math.abs(a-r));for(let t=e===0?0:1;t<=o;t++)l.push([Math.round(n+(i-n)*t/Math.max(1,o)),Math.round(r+(a-r)*t/Math.max(1,o))])}t.pts.length===1&&l.push([t.pts[0][0],t.pts[0][1]]);let u=c.ub,d=c.lean,f=i?z(L(s.skin.base,-i),.07):s.skin,p=i?z(L(n.base,-i),.08):n;if(a){let e=L(n.dd,-.06);for(let[t,n]of l)o.alpha(t+2+d,n+u)>0&&o.set(t+2+d,n+u,e)}l.forEach(([e,t],n)=>{let i=n===l.length-1,a=n<r&&!i,s=a?p:f;o.set(e+d,t+u,s.base),o.set(e+1+d,t+u,s.dk),o.set(e+d,t+1+u,a&&n===r-1?s.dk:s.base),o.set(e+1+d,t+1+u,s.dk)});let[m,h]=l[l.length-1];o.set(m+d,h+u,f.lt),o.set(m+1+d,h+u,f.base),o.set(m+d,h+1+u,f.base),o.set(m+1+d,h+1+u,f.dk)}function ar(e){switch(e.topStyle){case`tshirt`:case`polo`:return 2;case`blouse`:return 3;default:return 99}}function or(e){let{b:t,p:n,r,a:i}=e,a=n.bottom,o=n.shoes,s=i.bottomStyle??`pants`,c=s!==`pants`;if(r.view===`side`){sr(e,a,o,c);return}if(r.seated){if(r.view===`down`){let e=24+r.ub,i=s===`skirt`?n.bottom:a;t.rect(8,e,8,1,i.lt),t.rect(8,e+1,8,1,i.base),t.set(15,e,i.base),t.set(15,e+1,i.dk),t.set(11,e+1,i.dk),c?(t.rect(9,e+2,2,1,n.skin.base),t.rect(13,e+2,2,1,n.skin.dk)):(t.rect(8,e+2,3,1,a.dk),t.rect(13,e+2,3,1,a.dk)),t.rect(8,30,3,1,o.base),t.set(8,30,o.lt),r.toeTap?(t.rect(13,29,3,1,o.base),t.set(13,29,o.lt),t.set(14,30,o.dk)):(t.rect(13,30,3,1,o.base),t.set(13,30,o.lt))}else{let e=24+r.ub;t.rect(8,e,8,2,a.base),t.rect(8,e+1,8,1,a.dk),t.set(11,e,a.dk),t.set(12,e,a.dk)}return}let l=24+r.ub;t.rect(8,l,8,2,a.base),t.set(15,l,a.dk),t.set(15,l+1,a.dk),s===`skirt`&&(t.rect(7,l+2,10,1,a.base),t.set(16,l+2,a.dk),t.rect(8,l+2,1,1,a.lt),t.set(11,l+1,a.dk),t.set(12,l+2,a.dk));let u=(e,r,i)=>{let s=28+r;for(let r=l+2;r<=s;r++){let o=c&&r>=l+3?n.skin:a;t.set(e,r,o.base),t.set(e+1,r,o.base),t.set(e+2,r,i?o.dk:o.base)}t.rect(e,s+1,3,1,o.base),t.set(e,s+1,o.lt),t.rect(e,s+2,3,1,o.dk)},d=r.view===`up`?r.legB.dy:r.legA.dy,f=r.view===`up`?r.legA.dy:r.legB.dy;u(8,d,!0),u(13,f,!0),(!c||s===`shorts`)&&(t.set(10,l+2,a.dk),t.set(13,l+2,a.base))}function sr(e,t,n,r){let{b:i,p:a,r:o,a:s}=e,c=s.bottomStyle??`pants`;if(o.seated){let e=24+o.ub;i.rect(7,e-1,7,2,t.base),i.rect(7,e-1,6,1,t.lt),i.set(13,e,t.dk);let s=r?a.skin:t;i.rect(7,e+1,2,30-(e+1),s.base),i.set(8,e+1,s.dk),o.toeTap?(i.rect(5,29,2,1,n.base),i.set(5,29,n.lt),i.rect(7,30,2,1,n.base)):(i.rect(5,30,4,1,n.base),i.set(5,30,n.lt));return}let l=24+o.ub;i.rect(9,l,5,2,t.base),i.set(9,l,t.lt),i.set(13,l,t.dk),i.set(13,l+1,t.dk),c===`skirt`&&(i.rect(8,l+1,7,2,t.base),i.set(8,l+1,t.lt),i.set(14,l+2,t.dk));let u=(e,o,s)=>{let c=s?z(t.dk,.07):t,u=s?z(a.skin.dk,.07):a.skin,d=s?z(n.dk,.08):n,f=l+2,p=28-o;for(let t=f;t<=p;t++){let n=(t-f)/Math.max(1,p-f),a=Math.round(10+e*n),o=r&&t>=l+3?u:c;i.set(a,t,o.lt),i.set(a+1,t,o.base),i.set(a+2,t,o.dk)}let m=Math.round(10+e);i.rect(m-1,p+1,4,1,d.base),i.set(m-1,p+1,d.lt),i.rect(m-1,p+2,4,1,d.dk)};u(o.legA.dx,-o.legA.dy,!0),u(o.legB.dx,-o.legB.dy,!1)}function cr(e){let{b:t,p:n,r,a:i}=e,a=18+r.ub,o=n.top,s=n.acc,c=r.lean;if(r.view===`side`){t.rect(8+c,a,7,6,o.base);for(let e=a;e<a+6;e++)t.set(8+c,e,o.lt),t.set(14+c,e,o.dk);switch(t.rect(8+c,a+5,7,1,o.dk),i.topStyle){case`hoodie`:case`hoodie_up`:t.rect(12+c,a-1,3,2,o.dk),t.set(13+c,a-1,o.base),t.set(9+c,a+1,s.base),t.set(9+c,a+2,s.base),t.rect(9+c,a+4,4,1,o.dk);break;case`shirt_tie`:t.set(9+c,a,o.hi),t.set(10+c,a,o.hi);for(let e=a+1;e<=a+4;e++)t.set(9+c,e,s.base);t.set(9+c,a,s.dk);break;case`jacket`:t.set(9+c,a+1,s.base),t.set(9+c,a+2,s.base),t.set(9+c,a+3,s.base),t.set(10+c,a,o.hi);break;case`sweater`:t.rect(9+c,a+2,6,1,s.base),t.rect(9+c,a+5,6,1,o.dd);break;case`polo`:t.set(10+c,a,s.base),t.set(11+c,a,s.base);break;case`blouse`:t.set(9+c,a,s.lt),t.set(10+c,a,s.lt),t.set(9+c,a+2,s.base),t.rect(8+c,a+5,7,1,o.dk);break;case`tshirt`:t.set(9+c,a+2,s.base)}lr(e);return}t.rect(8,a,8,6,o.base);for(let e=a;e<a+6;e++)t.set(8,e,o.lt),t.set(15,e,o.dk);t.rect(8,a+5,8,1,o.dk),t.set(8,a+5,o.base);let l=r.view===`down`;switch(i.topStyle){case`tshirt`:t.rect(10,a,4,1,o.dk),l&&(t.rect(10,a+2,2,2,s.base),t.set(11,a+3,s.dk));break;case`hoodie`:case`hoodie_up`:l?(t.rect(9,a,6,1,o.dk),t.set(9,a,o.lt),t.set(10,a+1,s.lt),t.set(10,a+2,s.base),t.set(13,a+1,s.lt),t.set(13,a+2,s.base),t.rect(9,a+3,6,2,o.dk),t.rect(10,a+3,4,1,o.base)):(t.rect(9,a,6,3,o.dk),t.rect(10,a,4,2,o.dd),t.rect(10,a,4,1,o.dk)),t.rect(8,a+5,8,1,o.dd);break;case`shirt_tie`:if(l){t.set(9,a,o.hi),t.set(10,a,o.hi),t.set(13,a,o.hi),t.set(14,a,o.hi),t.set(11,a,s.lt),t.set(12,a,s.base);for(let e=a+1;e<=a+4;e++)t.set(11,e,s.base),t.set(12,e,s.dk);t.set(11,a+5,s.dk)}else t.rect(9,a,6,1,o.hi);break;case`sweater`:l&&t.rect(10,a,4,1,o.dd),t.rect(8,a+2,8,1,s.base),t.set(15,a+2,s.dk),t.rect(8,a+5,8,1,o.dd);break;case`jacket`:if(l){t.rect(10,a,4,6,s.base),t.set(13,a,s.dk);for(let e=a;e<a+6;e++)t.set(13,e,s.dk);t.set(10,a,o.hi),t.set(13,a,o.lt),t.set(10,a+1,o.lt),t.set(13,a+1,o.base)}else t.vline(11,a+1,a+5,o.dk),t.rect(9,a,6,1,o.lt);break;case`blouse`:l?(t.rect(9,a,6,1,s.lt),t.set(11,a+1,s.lt),t.set(12,a+1,s.base),t.set(11,a+3,s.dk)):t.rect(9,a,6,1,s.base),t.rect(7,a+5,10,1,o.dk),t.set(7,a+5,o.base);break;case`polo`:l?(t.set(9,a,s.lt),t.set(10,a,s.base),t.set(13,a,s.base),t.set(14,a,s.dk),t.set(11,a,o.dk),t.set(12,a,o.dk),t.set(11,a+1,o.dk),t.set(11,a+2,s.lt)):t.rect(9,a,6,1,s.base)}lr(e)}function lr(e){let t=e.a.lanyard;if(!t)return;let{b:n,r}=e,i=18+r.ub,a=`#f6f4ee`,o=r.lean;r.view===`down`?(n.set(10,i,t),n.set(13,i,t),n.set(10,i+1,t),n.set(13,i+1,t),n.set(11,i+2,t),n.set(12,i+2,t),n.rect(10,i+3,4,3,a),n.rect(10,i+3,4,1,L(t,-.05)),n.set(11,i+4,`#7f93b3`),n.set(12,i+4,`#c9d2e0`),n.set(13,i+5,`#d6d3cb`)):r.view===`up`?(n.hline(9,14,i,t),n.set(9,i+1,L(t,-.1)),n.set(14,i+1,L(t,-.1))):(n.set(11+o,i,t),n.set(10+o,i+1,t),n.set(9+o,i+2,t),n.rect(8+o,i+3,2,3,a),n.set(8+o,i+3,L(t,-.05)),n.set(9+o,i+3,L(t,-.05)))}var ur=[`wwwo`,`cccw`,`rrrh`,`wwwh`,`www.`],dr=[`bbb`,`www`,`www`,`.w.`];function fr(e,t,n){let{b:r,r:i}=e,a=i.held,o=i.view===`side`;switch(a){case`coffee`:r.stamp(ur,t,n,{w:`#f4f2ee`,c:`#6b4226`,r:`#e2604f`,h:`#cfcac0`,o:`#f4f2ee`},o);break;case`water`:r.stamp(dr,t,n,{b:`#9ad4f5`,w:`#eef6fb`});break;case`papers`:if(o)r.rect(t,n,2,6,`#f6f4ee`),r.vline(t+1,n,n+5,`#d9d5cb`);else{r.rect(t+1,n-1,6,6,`#e7e3d8`),r.rect(t,n,6,6,`#f8f6f0`);for(let e=0;e<3;e++)r.hline(t+1,t+3+e%2,n+1+e*2,`#a6b0c0`)}break;case`book`:if(o)r.rect(t,n,2,6,`#3f63a8`),r.vline(t+1,n+1,n+4,`#f2efe6`);else if(i.view===`down`&&i.twoHands){r.rect(t,n,8,5,`#f6f3ea`),r.vline(t+3,n,n+4,`#cfc8b8`),r.vline(t+4,n,n+4,`#e2dccd`);for(let e=0;e<2;e++)r.hline(t+1,t+2,n+1+e*2,`#a8b0bf`),r.hline(t+5,t+6,n+1+e*2,`#a8b0bf`);r.hline(t,t+7,n+5,`#3f63a8`)}else r.rect(t,n,5,6,`#3f63a8`),r.rect(t+1,n+1,3,1,`#f2c14e`),r.vline(t+4,n,n+5,`#2d4a85`);break;case`laptop`:o?(r.rect(t,n,2,7,`#aeb6c2`),r.vline(t,n,n+6,`#d3d8df`)):(r.rect(t,n,8,5,`#b9c0cb`),r.hline(t,t+7,n,`#d9dee5`),r.rect(t+3,n+2,2,1,`#eef1f5`),r.hline(t,t+7,n+4,`#8d96a5`));break;case`box`:{let e=o?6:10;r.rect(t,n,e,7,`#c99a5e`),r.hline(t,t+e-1,n,`#dcb27a`),r.hline(t,t+e-1,n+6,`#a87b45`),r.rect(t+Math.floor(e/2)-1,n,2,7,`#e8d3a8`),r.vline(t+e-1,n+1,n+5,`#b3854d`);break}case`paddle`:r.stamp([`.rr.`,`rRrr`,`rrrd`,`.rd.`,`.h..`,`.h..`],t,n,{r:`#d64545`,R:`#ef7a6a`,d:`#a83232`,h:`#6b4a32`},o);break;case`popcorn`:r.stamp(wr,t,n,Tr);break;case`controller`:r.stamp(o?mr:pr,t,n,hr);break;case`phone`:r.stamp(o?_r:gr,t,n,vr);break;case`lipstick`:i.view!==`up`&&r.stamp([`rgG`],t,n,{r:`#d8365a`,g:`#f0c75a`,G:`#b38a2e`});break;case`comb`:r.stamp([`cccc`,`c.c.`],t,n,{c:`#3d4252`});break;case`rock`:case`paper`:case`scissors`:xr(e,a,t,n)}}var pr=[`.hLLLL.`,`LdLLrbL`,`cc...cc`],mr=[`hLL`,`cLr`],hr={L:`#4c5263`,h:`#737b8f`,d:`#1d2029`,r:`#e8545a`,b:`#4f8fe6`,c:`#363b48`},gr=[`dDd`,`dBd`,`dbd`,`dbd`,`ddd`],_r=[`dB`,`db`,`db`,`dd`],vr={d:`#2b2f3a`,D:`#5a6172`,b:`#6fbdf0`,B:`#c8eaff`},yr={rock:{rows:[`.LLs`,`LsLs`,`sssS`,`.SS.`],dx:-2,dy:-1},paper:{rows:[`..L.L.`,`L.L.Ls`,`.LsLss`,`LsssSS`,`.SSSS.`],dx:-4,dy:-3},scissors:{rows:[`L....`,`.L...`,`..Lss`,`.SsSS`,`S....`],dx:-3,dy:-2}},br={rock:{rows:[`.LL.`,`LsLs`,`sSsS`,`.SS.`],dx:-1,dy:-1},paper:{rows:[`L.L.L`,`L.L.s`,`sLsLs`,`sssss`,`SsssS`,`.SSS.`],dx:-2,dy:-4},scissors:{rows:[`L...s`,`L...s`,`.L.s.`,`.LsS.`,`.sSS.`,`..S..`],dx:-2,dy:-4}};function xr(e,t,n,r){let{b:i,p:a,r:o}=e,s={L:a.skin.lt,s:a.skin.base,S:a.skin.dk},c,l,u=!1;if(o.view===`down`){let e=br[t];c=e.rows,l=n+e.dx,r+=e.dy}else{let e=yr[t];c=e.rows,u=o.view===`up`,l=u?n-e.dx-c[0].length+2:n+e.dx,r+=e.dy}i.stamp(c,l,r,s,u);let d=R(a.skin.dd,`#1d2433`,.45),f=c[0].length,p=(e,t)=>{if(t<0||t>=c.length||e<0||e>=f)return!1;let n=c[t][u?f-1-e:e];return n!==`.`&&n!==` `},m=[a.skin.lt,a.skin.base,a.skin.dk,a.skin.hi].map(Sr);for(let e=-1;e<=c.length;e++)for(let t=-1;t<=f;t++){if(p(t,e)||!(p(t-1,e)||p(t+1,e)||p(t,e-1)||p(t,e+1)))continue;let n=l+t,a=r+e;i.alpha(n,a)<160||m.includes(Cr(i,n,a))||i.set(n,a,d)}}function Sr(e){let t=/^#([0-9a-f]{6})$/i.exec(e);return t?parseInt(t[1],16):-1}function Cr(e,t,n){let r=t+e.ox,i=n+e.oy;if(!e.inside(r,i))return-1;let a=(i*e.w+r)*4;return e.data[a]<<16|e.data[a+1]<<8|e.data[a+2]}var wr=[`.pk.p.`,`kpypkK`,`aAAAAa`,`lwrwrW`,`lwrwrW`,`lwrwrW`,`.wrwr.`],Tr={p:`#fff9e6`,k:`#f3e3b8`,K:`#e2cc92`,y:`#ffd75e`,a:`#e9e3d6`,A:`#fbf8f1`,l:`#ef6457`,r:`#d8413f`,w:`#f6f1e6`,W:`#cfc6b6`};function Er(e){let{r:t}=e,n=t.held;if(n===`none`)return null;if(t.itemAt)return[t.itemAt[0]+t.lean,t.itemAt[1]+t.ub];let r=t.armB.pts[t.armB.pts.length-1],i=r[0]+t.lean,a=r[1]+t.ub;if(Fn.has(n))return[i,a];if(t.twoHands){if(t.view===`side`)return[i-2,a-3];let e=18+t.ub+1;return n===`phone`?[10,e]:n===`box`?[7,e]:n===`laptop`||n===`book`&&t.view===`down`?[8,e+1]:[9,e]}switch(n){case`coffee`:return t.view===`side`?[i-3,a-3]:[i,a-3];case`water`:return t.view===`side`?[i-2,a-3]:[i,a-3];case`paddle`:return t.view===`side`?[i-2,a-5]:[i+1,a-4];case`popcorn`:return t.view===`side`?[i-5,a-4]:[i+1,a-4];case`controller`:return t.view,[i-2,a];case`phone`:return t.view===`side`?[i-2,a-3]:[i,a-4];case`lipstick`:return t.view,[i-2,a+1];case`comb`:return[i-1,a-2];default:return[i,a-2]}}var Dr={idle:`#6dff9a`,work:`#5de8ff`,wait:`#ffc857`,done:`#8dff6a`},Or={idle:[[4,10],[9,10],[4,12],[5,13],[6,13],[7,13],[8,13],[9,12]],work:[[6,10],[8,10],[5,11],[6,11],[7,11],[8,11],[9,11],[5,12],[6,12],[8,12],[9,12],[6,13],[8,13],[7,9],[7,13]],wait:[[6,9],[7,9],[8,9],[8,10],[7,11],[7,13]],done:[[4,12],[5,13],[6,12],[7,11],[8,10],[9,9]]},kr={idle:[[2,10],[2,12],[3,13]],work:[[2,9],[3,10],[2,11],[3,12],[2,13]],wait:[[2,9],[3,9],[3,10],[2,11],[2,13]],done:[[2,12],[3,13],[3,11],[2,10]]};function Ar(e,t){let n=e.a.face??`none`;if(n===`none`)return;let{b:r,p:i,r:a}=e,o=Dn+a.lean,s=On+a.ub+a.hd,c=(e,t,n)=>r.set(o+e,s+t,n),l=i.face,u=a.view,d=l.dk;switch(n){case`led_mask`:{let e=Dr[t],n=R(e,`#06100c`,.78);if(u===`down`){for(let e=2;e<=11;e++)for(let t=8;t<=14;t++)t===14&&(e<3||e>10)||c(e,t,e===2||e===11||t===8||t===14?e===2||t===8?l.lt:l.dk:`#06100c`);for(let e=3;e<=10;e++)for(let t=9;t<=13;t++)(e+t)%2==0&&c(e,t,n);for(let[n,r]of Or[t])c(n,r,e);for(let e of[10,11])c(0,e,d),c(1,e,d),c(12,e-0,d),c(13,e,d)}else if(u===`side`){for(let e=1;e<=4;e++)for(let t=8;t<=14;t++)c(e,t,e===1||e===4||t===8||t===14?l.dk:`#06100c`);c(1,8,l.lt),c(2,8,l.lt);for(let[n,r]of kr[t])c(n,r,e);for(let e=5;e<=8;e++)c(e,10,d)}else for(let e=0;e<=13;e++)c(e,10,d);break}case`bandana`:{let e=l.base,t=l.lt,n=l.dk,r=R(l.base,vn(l.base)>.5?`#1d1826`:`#f4f2ee`,.55);if(u===`down`){for(let e=2;e<=11;e++)c(e,12,t);for(let t=2;t<=11;t++)c(t,13,t>8?n:e);for(let t=3;t<=10;t++)c(t,14,t>7?n:e);c(6,11,e),c(7,11,n);for(let e of[3,5,7,9])c(e,13,r);for(let e of[4,6,8,10])c(e,14,r);c(1,12,n),c(12,12,n)}else if(u===`side`){for(let e=1;e<=8;e++)c(e,12,t);for(let t=1;t<=8;t++)c(t,13,t>6?n:e);for(let t=2;t<=7;t++)c(t,14,t>5?n:e);c(2,11,e);for(let e of[2,4,6])c(e,13,r);c(9,12,n),c(10,12,e),c(10,13,e),c(11,14,n)}else{for(let t=0;t<=13;t++)c(t,12,t===0||t===13?n:e);c(6,13,n),c(7,13,e),c(5,14,e),c(8,14,n)}break}case`respirator`:{let e=l.lt,t=l.base,n=l.dk;if(u===`down`){for(let e of[5,6,7,8])c(e,11,t);for(let n=3;n<=10;n++)c(n,12,n<5?e:t);for(let e=3;e<=10;e++)c(e,13,e>8?n:t);for(let e=4;e<=9;e++)c(e,14,n);c(6,13,e),c(7,13,e),c(6,12,n),c(7,12,n);for(let r of[12,13])c(1,r,e),c(2,r,t),c(11,r,t),c(12,r,n);c(0,12,n),c(13,12,n);for(let e of[0,1,2,11,12,13])c(e,10,d);c(2,11,d),c(11,11,d)}else if(u===`side`){for(let n=1;n<=5;n++)c(n,11,n<3?e:t);for(let n=1;n<=6;n++)c(n,12,n<3?e:t);for(let e=1;e<=6;e++)c(e,13,t);for(let e=2;e<=6;e++)c(e,14,n);c(0,12,n),c(0,13,n),c(5,12,e),c(6,12,n);for(let e=6;e<=9;e++)c(e,10,d)}else{for(let e=0;e<=13;e++)c(e,10,d);c(0,12,n),c(13,12,n)}break}case`visor`:{let e=R(l.base,`#ffffff`,.25),t=l.base,n=`#14161d`;if(u===`down`){for(let e=2;e<=11;e++)c(e,9,n);for(let n=1;n<=12;n++)c(n,10,e),c(n,11,t);for(let e=2;e<=11;e++)c(e,12,R(t,`#0c1018`,.6));c(3,10,`#ffffff`),c(4,10,`#ffffff`),c(0,10,n),c(13,10,n),c(0,11,n),c(13,11,n)}else if(u===`side`){for(let n=0;n<=4;n++)c(n,10,e),c(n,11,t);for(let e=1;e<=4;e++)c(e,9,n);for(let e=1;e<=4;e++)c(e,12,R(t,`#0c1018`,.6));c(1,10,`#ffffff`);for(let e=5;e<=9;e++)c(e,10,n)}else{for(let e=0;e<=13;e++)c(e,10,n);c(6,10,t),c(7,10,t)}break}case`ar_monocle`:{let e=l.base,t=`rgba(${parseInt(l.base.slice(1,3),16)},${parseInt(l.base.slice(3,5),16)},${parseInt(l.base.slice(5,7),16)},0.38)`,n=`#14161d`;if(u===`down`){for(let t=8;t<=10;t++)c(t,9,e),c(t,12,e);for(let n of[10,11])c(8,n,e),c(10,n,e),c(9,n,t);for(let e=11;e<=12;e++)c(e,10,n);c(13,10,n),c(11,8,`#ffffff`),c(12,8,e)}else if(u===`side`){for(let t=1;t<=4;t++)c(t,9,e),c(t,12,e);for(let n of[10,11])c(1,n,e),c(4,n,e),c(2,n,t),c(3,n,t);for(let e=5;e<=8;e++)c(e,10,n);c(1,8,`#ffffff`),c(2,7,e)}else c(12,10,n),c(13,10,n);break}case`smile_mask`:{let e=`#2a2430`,t=wn[u].rows;for(let e=2;e<t.length;e++){let n=t[e];for(let t=1;t<=(u===`side`?11:12);t++){if(n[t]===`.`||n[t]===void 0||u!==`side`&&(t===0||t===13))continue;let r=t<=2?l.lt:t>=(u===`side`?9:11)?l.dk:l.base;c(t,e+4,r)}}if(u===`down`){for(let[t,n]of[[3,11],[4,10],[5,11],[8,11],[9,10],[10,11],[3,12],[10,12]])c(t,n,e);for(let t=4;t<=9;t++)c(t,13,e);c(5,12,R(l.base,`#e08a96`,.5)),c(8,12,R(l.base,`#e08a96`,.5))}else if(u===`side`){for(let[t,n]of[[2,11],[3,10],[4,11],[2,12],[3,13],[4,13],[5,13]])c(t,n,e);c(1,9,l.hi)}else for(let e=1;e<=12;e++)c(e,10,d);break}}}function jr(e){if(e.a.topStyle!==`hoodie_up`)return;let{b:t,p:n,r}=e,i=n.top,a=Dn+r.lean,o=On+r.ub+r.hd,s={o:i.base,h:i.lt,H:i.hi,d:i.dk,D:i.dd};if(r.view===`down`)t.stamp([`....oooooo....`,`..oohhhhhooo..`,`.ohhHhhhoooodd`,`oohhhoooooooDd`,`oodddddddddddD`,`ood........dDD`,`ood........dDD`,`ood........dDD`,`ood........dDD`,`ood........dDD`,`.od........dD.`,`.od........dD.`,`..dd......dD..`],a,o+2,s);else if(r.view===`up`){let e=[`....oooooo....`,`..oohhhhhooo..`,`.ohhHhhhoooodd`,`ohhhooooooooDd`];for(let t=0;t<6;t++)e.push(`ohhooodddooooD`);e.push(`.oooooddoooodD`,`..ooooddooodD.`,`...dooddoodD..`),t.stamp(e,a,o+2,s)}else t.stamp([`....ooooooo...`,`..ooohhhhhoo..`,`.oohhHhhhooood`,`.ohhoooooooodd`,`oddddddooooodD`,`.....dooooooDD`,`.....dooooooDD`,`.....dooooooDD`,`.....dooooooDD`,`.....dooooooDD`,`.....dooooooD.`,`......ddoooD..`,`.......ddoD...`],a,o+2,s)}function Mr(e,t){$n(e),er(e),Ar(e,t.led??`idle`),e.a.topStyle!==`hoodie_up`&&tr(e,`front`),jr(e),rr(e),Nr(e,t.costume)}function Nr(e,t){if(!t)return;let{b:n,r}=e,i=Dn+r.lean,a=On+r.ub+r.hd;t===`santa`?(n.rect(i+2,a,9,4,`#c93945`),n.rect(i+4,a-2,5,2,`#e95452`),n.rect(i+9,a-1,3,3,`#a82436`),n.rect(i+11,a+1,3,3,`#fff3d9`),n.rect(i+1,a+4,11,2,`#fff3d9`),n.hline(i+2,i+10,a+5,`#ddd9cb`)):t===`witch`?(n.rect(i+6,a-2,2,2,`#50336f`),n.rect(i+5,a,4,2,`#69428e`),n.rect(i+3,a+2,7,3,`#50336f`),n.hline(i+3,i+9,a+4,`#e9a548`),n.rect(i-1,a+5,15,2,`#372641`),n.set(i+7,a+4,`#ffe0a3`)):t===`pumpkin`?(n.rect(i+6,a-2,2,3,`#47754b`),n.rect(i+2,a+1,10,4,`#ed963c`),n.rect(i+1,a+2,12,3,`#dc792e`),n.vline(i+4,a+1,a+4,`#f9ae48`),n.vline(i+8,a+1,a+4,`#f9ae48`),n.hline(i+2,i+11,a+5,`#8d4930`)):(n.rect(i,a+12,2,5,`#702743`),n.rect(i+12,a+12,2,5,`#702743`))}function Pr(e){if(e.dir===`right`){let t=Pr({...e,dir:`left`});return{buf:t.buf.flipped(),ax:24-t.ax,ay:t.ay}}let t=e.dir===`up`?`up`:e.dir===`down`?`down`:`side`,n=new Cn(24,34),r=e.appearance,i={b:n,a:r,p:Rn(r),r:Hn(e,t)},a=i.r,o=ar(r),s=i.p.top,c=Er(i);e.costume===`vampire`&&(n.rect(5+a.lean,18+a.ub,14,8,`#35283e`),n.rect(6+a.lean,19+a.ub,12,6,`#702743`)),r.topStyle!==`hoodie_up`&&tr(i,`back`),c&&a.itemBehind&&fr(i,c[0],c[1]);let l=()=>Mr(i,e);if(t!==`side`&&a.itemAt)or(i),cr(i),t===`up`?(c&&fr(i,c[0],c[1]),ir(i,a.armA,s,o),ir(i,a.armB,s,o),l()):(l(),c&&fr(i,c[0],c[1]),ir(i,a.armA,s,o),ir(i,a.armB,s,o));else if(t===`side`)ir(i,a.armA,s,o,.08),or(i),cr(i),Mr(i,e),c&&!a.itemBehind&&fr(i,c[0],c[1]),ir(i,a.armB,s,o,0,!0);else{or(i);let t=a.view===`up`&&(e.pose===`type`||e.pose===`use`||e.pose===`drink`);cr(i),t&&(ir(i,a.armA,s,o),ir(i,a.armB,s,o));let n=e=>e.pts[e.pts.length-1][1]<16;a.crossFront===null&&!t&&(n(a.armA)||ir(i,a.armA,s,o),!n(a.armB)&&!(c&&!a.itemBehind&&a.twoHands)&&ir(i,a.armB,s,o)),Mr(i,e),a.crossFront!==null&&Xn(i,s,o,a.crossFront===1),c&&!a.itemBehind&&(fr(i,c[0],c[1]),a.twoHands&&(ir(i,a.armA,s,o),ir(i,a.armB,s,o))),!t&&a.crossFront===null&&(n(a.armA)&&ir(i,a.armA,s,o),n(a.armB)&&ir(i,a.armB,s,o))}if(a.tapAt){let[e,t]=a.tapAt;n.set(e+a.lean,t+a.ub,i.p.skin.base),n.set(e+a.lean,t+1+a.ub,i.p.skin.dk)}if(a.kernelAt){let[e,t]=a.kernelAt;n.set(e+a.lean,t+a.ub,Tr.p),n.set(e+1+a.lean,t+a.ub,Tr.y)}return n.outline(),a.seated||n.shadow(12,30.5,6,2,`#1c2034`,.2),{buf:n,ax:12,ay:31}}var Fr=-1/0,Ir=-1/0,Lr=1/0,Rr=1/0;function zr(e,t,n,r){Fr=e,Ir=t,Lr=e+n,Rr=t+r}function H(e,t,n,r,i,a){let o=Math.max(t,Fr),s=Math.max(n,Ir),c=Math.min(t+r,Lr),l=Math.min(n+i,Rr);c<=o||l<=s||(e.fillStyle=a,e.fillRect(o,s,c-o,l-s))}function Br(e,t=0){let n=(Math.imul(e|0,668265261)^Math.imul(t|0,374761393))>>>0;return n^=n>>>15,n=Math.imul(n,2246822507)>>>0,n^=n>>>13,n>>>0}function Vr(e){return e-Math.floor(e)}var Hr=[`#ff79c6`,`#8be9fd`,`#f1fa8c`,`#50fa7b`,`#bd93f9`,`#ffb86c`,`#f8f8f2`];function Ur(e,t,n,r,i){let a=Math.round(t.x),o=Math.round(t.y),s=Math.round(t.w),c=Math.round(t.h);if(s<=0||c<=0)return;zr(a,o,s,c);let l=i>>>0;switch(n){case`off`:{H(e,a,o,s,c,`#22324f`),H(e,a,o,s,1,`#2a3d5f`),H(e,a,o+c-1,s,1,`#1d2b45`);let t=s-3-Math.floor(c/3);for(let n=0;n<c;n++){let r=a+t-n;H(e,r,o+n,2,1,`#2f4569`),H(e,r+2,o+n,1,1,`#293c5e`),H(e,r+5,o+n,1,1,`#283b5b`)}break}case`standby`:{let t=[`#2d63ad`,`#285a9f`,`#235192`,`#1f4884`];for(let n=0;n<c;n++)H(e,a,o+n,s,1,t[Math.min(t.length-1,Math.floor(n*t.length/c))]);H(e,a,o,s,1,`#3a74c0`);let n=a+Math.floor((s-1)/2),i=o+Math.floor((c-1)/2)-+(c>=9),u=[`#9fcaf5`,`#b7d8f8`,`#d3e8fb`,`#b7d8f8`][(Math.floor(r/700)+l%3)%4];H(e,n,i-1,1,1,u),H(e,n-1,i,1,1,u),H(e,n+1,i,1,1,u),H(e,n,i+1,1,1,u),H(e,n,i,1,1,`#6aa6e6`),c>=7&&H(e,n-2,i+3,5,1,`#4f86c9`);break}case`idle`:{for(let t=0;t<c;t++)H(e,a,o+t,s,1,R(`#1b2a4a`,`#2c1f4a`,t/c));let t=ri(r/140+l%17,Math.max(1,s-2)),n=ri(r/190+l%11,Math.max(1,c-2)),i=Math.floor(r/900+l)%4;H(e,a+t,o+n,2,2,[`#7fd0ff`,`#ff9ad5`,`#9be59b`,`#ffd36b`][i]);break}case`code`:{H(e,a,o,s,c,`#1d2130`),H(e,a,o,Math.min(2,s),c,`#252a3c`);let t=Math.floor(c/2),n=Math.floor(r/420+l%50);for(let i=0;i<t;i++){let u=Br(l,n+i),d=o+i*2+1;if(d>=o+c)break;H(e,a,d,1,1,`#4a5170`);let f=a+3+u%4,p=1+(u>>>3)%3;if((u>>>7)%7!=0){for(let t=0;t<p&&f<a+s-1;t++){let n=1+(u>>>9+t*4)%4;H(e,f,d,Math.min(n,a+s-1-f),1,Hr[(u>>>5+t*3)%Hr.length]),f+=n+1}i===t-1&&Math.floor(r/500)%2==0&&f<a+s&&H(e,f,d,1,1,`#f8f8f2`)}}break}case`terminal`:{H(e,a,o,s,c,`#0c120f`);let t=Math.floor((c-1)/2),n=Math.floor(r/260)+l%40,i=e=>2+Br(l,e)%Math.max(2,s-4),u=Math.max(2,s-4)+3,d=Math.floor(n/u),f=Math.min(i(d),n-d*u);for(let n=0;n<t;n++){let c=d-(t-1)+n;if(c<0)continue;let l=o+1+n*2,u=c===d?f:i(c);H(e,a+1,l,1,1,`#5cff7a`),H(e,a+3,l,Math.min(u,s-4),1,c===d?`#8ef0a0`:`#3fae5c`),c===d&&Math.floor(r/450)%2==0&&H(e,a+3+Math.min(u,s-5),l,1,1,`#d6ffe0`)}break}case`browser`:{H(e,a,o,s,c,`#f3f5f8`),H(e,a,o,s,2,`#d5dbe4`),H(e,a+1,o,1,1,`#ff6b6b`),s>6&&H(e,a+3,o,1,1,`#f7c948`),s>8&&H(e,a+5,o+1,s-6,1,`#ffffff`);let t=Math.floor(r/900+l%9)%4,n=[`#5b8fe0`,`#4cae6a`,`#e2604f`,`#8d66cf`][l%4],i=o+3;for(let r=0;r<c-3;r++){let o=r+t,c=i+r;o%6<3?o%12<3?H(e,a+1,c,Math.max(1,Math.floor(s*.45)),1,n):H(e,a+1,c,Math.max(1,s-2-o%5),1,o%6==0?`#9aa5b5`:`#c8cfd9`):o%6==3&&(H(e,a+1,c,Math.floor(s/2)-1,2,R(n,`#ffffff`,.55)),H(e,a+Math.floor(s/2)+1,c,Math.ceil(s/2)-2,1,`#c8cfd9`))}break}case`search`:{H(e,a,o,s,c,`#ffffff`),H(e,a+1,o+1,s-2,2,`#e3e8ef`),H(e,a+2,o+1,Math.max(1,s-6),1,`#ffffff`),H(e,a+s-3,o+1,1,1,`#3f7fd8`),H(e,a+s-2,o+2,1,1,`#3f7fd8`);let t=Math.floor(r/700+l%5)%3;for(let n=0;n<3;n++){let r=o+4+n*3;if(r+1>=o+c)break;n===t&&H(e,a,r-1,s,3,`#eef4ff`),H(e,a+1,r,Math.max(1,s-4-(l+n)%4),1,`#3f7fd8`),H(e,a+1,r+1,Math.max(1,s-6+(l+n)%3),1,`#b6bfcc`)}break}case`chat`:{H(e,a,o,s,c,`#eef1f6`);let t=Math.floor(r/1100+l%13),n=Math.floor(c/3);for(let r=0;r<n;r++){let i=t+r,u=(Br(l,i)&1)==1,d=Math.max(3,Math.min(s-3,4+(Br(l,i)>>>2)%Math.max(1,s-5))),f=o+c-3-(n-1-r)*3;f<o||H(e,u?a+s-1-d:a+1,f,d,2,u?`#5b8fe0`:`#d6dce6`)}let i=Math.floor(r/250)%3;for(let t=0;t<3;t++)H(e,a+2+t*2,o+1,1,1,t===i?`#5b6b85`:`#b8c2d2`);break}case`docs`:{H(e,a,o,s,c,`#e9edf2`),H(e,a+1,o,s-2,c,`#ffffff`);let t=Math.floor(r/1500+l%7)%3;H(e,a+2,o+1,Math.max(1,Math.floor(s*.5)),1,`#2b2f3b`);for(let n=0;n<c-3;n++){let r=n+t,i=o+3+n;r%4!=3&&H(e,a+2,i,Math.max(1,s-4-Br(l,r)%4),1,r%4==0?`#7d8796`:`#b9c1cd`)}break}case`tasks`:{H(e,a,o,s,c,`#fffaf0`);let t=Math.floor((c-1)/2),n=Math.floor(r/900+l%6)%(t+2);for(let r=0;r<t;r++){let t=o+1+r*2,i=r<n;H(e,a+1,t,1,1,i?`#3fae5c`:`#b9c1cd`),H(e,a+3,t,Math.max(1,s-5-(l+r)%3),1,i?`#a8d8b3`:`#8b95a5`)}break}case`progress`:{H(e,a,o,s,c,`#0b1210`),H(e,a,o+c-1,s,1,`#0f1916`);let t=c<9;H(e,a+1,o+1,1,1,`#5cff7a`),H(e,a+3,o+1,Math.max(1,Math.min(s-5,4+Br(l,1)%Math.max(1,s-7))),1,`#3c8f57`),c>=13&&(H(e,a+3,o+3,Math.max(1,Math.min(s-5,3+Br(l,2)%Math.max(1,s-6))),1,`#2a5c3c`),H(e,a+3,o+5,Math.max(1,Math.min(s-5,2+Br(l,3)%Math.max(1,s-6))),1,`#2a5c3c`));let n=t?o+3:c>=13?o+c-7:o+3,i=t?1:2,u=Math.max(1,s-4);H(e,a+1,n,1,i,`#7d8ea0`),H(e,a+s-2,n,1,i,`#7d8ea0`),H(e,a+2,n,u,i,`#163322`);let d=3400+l%5*300,f=Vr((r+l%997*37)/d),p=f<.85?Math.floor(f/.85*(u+1)):u,m=f>=.85;if(p>0){let t=m&&Math.floor(r/160)%2==0;H(e,a+2,n,p,i,t?`#b9ffca`:`#3ccf63`),i>1&&H(e,a+2,n,p,1,t?`#e4ffe9`:`#7cf09a`),m||H(e,a+1+p,n,1,i,`#d8ffe2`)}let h=t?o+c-3:o+c-4;if(h+2<o+c){let t=[[1,0],[2,0],[2,1],[2,2],[1,2],[0,2],[0,1],[0,0]],n=Math.floor(r/110+l%8)%8;for(let r=0;r<8;r++){let i=(n-r+8)%8,o=i===0?`#9ff3ff`:i===1?`#4fb8d6`:i===2?`#2b6f86`:`#173a45`;H(e,a+1+t[r][0],h+t[r][1],1,1,o)}let i=Math.floor(r/420+l%3)%4;for(let t=0;t<i&&5+t*2<s-2;t++)H(e,a+5+t*2,h+2,1,1,`#3c8f57`);Math.floor(r/500)%2==0&&a+11<a+s&&H(e,a+11,h+1,1,2,`#d6ffe0`)}break}case`show`:{let t=l%3;t===0?Xr(e,a,o,s,c,r,l):t===1?$r(e,a,o,s,c,r,l):ei(e,a,o,s,c,r,l);break}case`game`:l%2==0?ti(e,a,o,s,c,r,l):ni(e,a,o,s,c,r,l);break;case`alert`:{let t=Math.floor(r/380)%2==0;H(e,a,o,s,c,t?`#f2b33d`:`#8a5a12`);let n=a+Math.floor(s/2),i=o+Math.floor(c/2),l=t?`#3a2a08`:`#f7d27a`;H(e,n,i-2,1,3,l),H(e,n,i+2,1,1,l),c>=9&&(H(e,n-1,i-3,3,1,l),H(e,n,i-4,1,1,l));break}}}var Wr={G:[`###`,`#..`,`#.#`,`#.#`,`###`],O:[`###`,`#.#`,`#.#`,`#.#`,`###`],L:[`#..`,`#..`,`#..`,`#..`,`###`],K:[`#.#`,`##.`,`#..`,`##.`,`#.#`]};function Gr(e,t,n,r,i){for(let a=0;a<t.length;a++){let o=Wr[t[a]];if(o)for(let t=0;t<o.length;t++){let s=o[t],c=0;for(;c<s.length;){if(s[c]!==`#`){c++;continue}let o=c;for(;o<s.length&&s[o]===`#`;)o++;H(e,n+a*4+c,r+t,o-c,1,i),c=o}}}}function Kr(e,t,n,r,i,a,o){let s=t.length*4-1,c=n+Math.floor((i-s)/2),l=r+Math.floor((a-5)/2);H(e,c-2,l-1,s+4,7,`rgba(12,16,28,0.78)`),Gr(e,t,c,l,o)}var qr=7e3,Jr=.8;function Yr(e,t){let n=Math.floor((e+t%997*13)/qr);return{lance:n,progress:Vr((e+t%997*13)/qr),right:(Br(t,n)&1)==1,period:qr,goalAt:Jr}}function Xr(e,t,n,r,i,a,o){let{lance:s,progress:c}=Yr(a,o);H(e,t,n,r,i,`#3f9a4a`);for(let a=0;a*4<r;a+=2)H(e,t+a*4,n,4,i,`#48a855`);let l=t+Math.floor(r/2),u=n+Math.floor(i/2);H(e,l,n,1,i,`#cfeccd`),i>=9&&(H(e,l-2,u-1,1,3,`#cfeccd`),H(e,l+2,u-1,1,3,`#cfeccd`),H(e,l-1,u-2,3,1,`#cfeccd`),H(e,l-1,u+2,3,1,`#cfeccd`));let d=Math.max(3,Math.floor(i/3));H(e,t,u-Math.floor(d/2),1,d,`#ffffff`),H(e,t+r-1,u-Math.floor(d/2),1,d,`#ffffff`);let f=Yr(a,o).right,p=Math.min(1,c/.8),m=p*p*(3-2*p),h=Math.floor(r/2)-1,g=l+Math.round((f?1:-1)*h*m),_=u+Math.round(Math.sin(p*Math.PI*3+o%7)*Math.max(1,(i-6)/3)*(1-m));for(let t=0;t<6;t++){let s=t<3,c=Br(o+t*31,7),u=l+(s?-1:1)*Math.floor(r/2*(.25+t%3*.22)),d=n+2+Math.floor((t%3+.5)*((i-4)/3)),f=.35+c%5*.08,p=Math.round(Math.sin(a/(420+c%300)+t)*1.2);H(e,Math.round(u+(g-u)*f)+p,Math.round(d+(_-d)*f*.6)-1,1,2,s?`#e8454a`:`#3d7ce0`)}if(H(e,g,_+1,1,1,`rgba(10,40,10,0.45)`),H(e,g,_,1,1,`#ffffff`),r>=16&&i>=9){let r=[0,0];for(let e=s-s%4;e<s;e++)r[Br(o,e)&1]++;H(e,t+1,n+1,11,3,`rgba(12,16,28,0.8)`),H(e,t+2,n+2,1,1,`#e8454a`);for(let i=0;i<r[0];i++)H(e,t+4+i,n+2,1,1,`#ffffff`);H(e,t+9,n+2,1,1,`#3d7ce0`);for(let i=0;i<r[1];i++)H(e,t+8-i-1,n+2,1,1,`#9fc4ff`)}if(c>=.8){let o=Math.floor(a/180)%2==0?`#ffd84d`:`#ffffff`;H(e,t,n,r,1,o),H(e,t,n+i-1,r,1,o),H(e,t,n,1,i,o),H(e,t+r-1,n,1,i,o),r>=15&&i>=9&&Kr(e,`GOL`,t,n,r,i,o)}}function Zr(e,t,n,r,i,a,o,s,c){let l=6*r,u=7*r,d=t-Math.floor(l/2),f=n-Math.floor(u/2);o&&H(e,d-r,f,l+2*r,u+2*r,a),H(e,d,f+r,l,u-r,i),H(e,d+r,f+u,l-2*r,r,i),H(e,d,f-r,l,2*r,a),o||H(e,d,f+r,r,2*r,a);let p=s===0?r:0;H(e,d+r+p,f+3*r,r,r,`#2b2236`),H(e,d+4*r+p-r,f+3*r,r,r,`#2b2236`),c&&(H(e,d+r-(r>1?0:1)+p,f+4*r+ +(r>1),r,1,`#f08a96`),H(e,d+4*r+p-r+(r>1?0:1),f+4*r+ +(r>1),r,1,`#f08a96`)),H(e,d+2*r+p,f+5*r,Math.max(1,r+Math.floor(r/2)),Math.max(1,Math.floor(r/2)),`#b4475a`)}function Qr(e,t,n,r){H(e,t,n,1,1,r),H(e,t+2,n,1,1,r),H(e,t,n+1,3,1,r),H(e,t+1,n+2,1,1,r)}function $r(e,t,n,r,i,a,o){let s=Math.floor((a+o%97*31)/2600)%4,c=[`#c98a6a`,`#b77a62`,`#d6a27c`,`#8f6f9e`][o%4];H(e,t,n,r,i,c),H(e,t,n+i-Math.max(2,Math.floor(i/5)),r,Math.max(2,Math.floor(i/5)),R(c,`#2b2236`,.35)),H(e,t+r-Math.floor(r/3),n+1,Math.floor(r/4),Math.floor(i/2),`#ffd59a`),H(e,t+r-Math.floor(r/3)+Math.floor(r/8),n+1,1,Math.floor(i/2),R(c,`#2b2236`,.2));let l=i>=13?2:1,u={skin:`#f2c3a0`,hair:`#5a2f24`},d={skin:`#c98f68`,hair:`#2b2530`},f=n+Math.floor(i/2)+ +(l>1);if(s===0)Zr(e,t+Math.floor(r/2),f,l,u.skin,u.hair,!0,0,!0);else if(s===1)Zr(e,t+Math.floor(r/2),f,l,d.skin,d.hair,!1,1,!1);else{let o=r>=34?l:1;if(Zr(e,t+Math.floor(r*.3),f,o,u.skin,u.hair,!0,0,s===3),Zr(e,t+Math.floor(r*.7),f,o,d.skin,d.hair,!1,1,!1),s===3)for(let o=0;o<2;o++){let s=Vr((a+o*700)/1400);Qr(e,t+Math.floor(r/2)-1+(o?1:-1),n+i-3-Math.floor(s*(i-2)),o?`#ff7aa8`:`#ff4f7e`)}}}function ei(e,t,n,r,i,a,o){H(e,t,n,r,i,`#7fd3ff`),H(e,t,n,r,Math.floor(i/3),`#9fe0ff`);let s=Math.max(2,Math.floor(i/4));H(e,t,n+i-s,r,s,`#6cc04a`),H(e,t,n+i-s,r,1,`#8ee070`),H(e,t+r-4,n+1,3,3,`#ffd84d`),H(e,t+r-3,n+2,1,1,`#fff2a8`);for(let i=0;i<2;i++){let s=t+r-1-Math.floor(Vr(a/(9e3+i*4e3)+i*.5+o%5*.1)*(r+8)),c=n+1+i*3;H(e,s,c+1,5,2,`#ffffff`),H(e,s+1,c,3,1,`#ffffff`)}let c=Vr(a/5200+o%11*.09),l=n+i-s,u=Math.abs(Math.sin(a/260%Math.PI))*Math.max(2,i/3),d=t+Math.floor(c*(r+6))-3,f=l-4-Math.round(u);H(e,d,f,4,4,`#ff7ab8`),H(e,d+1,f+1,1,1,`#2b2236`),H(e,d+3,f+1,1,1,`#2b2236`),H(e,d+1,f+3,2,1,`#d84a8a`);let p=d-7,m=l-3-Math.round(Math.abs(Math.sin((a/260+1.2)%Math.PI))*Math.max(1,i/4));H(e,p,m,3,3,`#ffd84d`),H(e,p+2,m+1,1,1,`#2b2236`)}function ti(e,t,n,r,i,a,o){let s=Math.floor(i/2),c=[`#e8454a`,`#3d7ce0`];for(let l=0;l<2;l++){let u=n+l*(i-s),d=l===0?s:i-s;H(e,t,u,r,d,`#6a7280`),H(e,t,u,r,1,`#4caf50`),H(e,t,u+d-1,r,1,`#4caf50`);let f=.045+l*.006,p=Math.floor(a*f+o%13)%6,m=u+Math.floor(d/2);for(let n=-p;n<r;n+=6)H(e,t+n,m,3,1,`#f4f4f0`);let h=Math.floor(a*f*.8+l*9)%(r+6);H(e,t+r-h,u,2,1,`#2e7d32`);let g=Math.sin(a/2300+o%9+l*Math.PI),_=t+Math.floor(r*.3)+Math.round(g*Math.max(1,r/8)),v=m-1+(Math.floor(a/130+l)%2==0?0:+(d>=6));H(e,_,v,4,2,c[l]),H(e,_+2,v,1,1,`#cfe6ff`),H(e,_,v+2<=u+d-2?v+2:v+1,1,1,`#1d2029`),H(e,_+3,v+2<=u+d-2?v+2:v+1,1,1,`#1d2029`)}H(e,t,n+s-+(i%2==0),r,1,`#11141c`)}function ni(e,t,n,r,i,a,o){let s=9e3,c=a+o%991*17,l=Math.floor(c/s),u=Vr(c/s);H(e,t,n,r,i,`#3b2a6b`),H(e,t,n+Math.floor(i/3),r,Math.floor(i/3),`#4b3784`);let d=Math.max(2,Math.floor(i/4));H(e,t,n+i-d,r,d,`#7a4f2a`),H(e,t,n+i-d,r,1,`#a8723f`);let f=Br(o,l)&1,p=Math.max(3,Math.floor(r/2)-2),m=Math.min(1,u/.82),h=e=>Math.max(0,1-m*(e===f?1:.55));for(let i=0;i<2;i++){let a=i===0?t+1:t+r-1-p;H(e,a,n+1,p,2,`#5a1d2a`);let o=Math.round(p*h(i));o>0&&H(e,i===0?a:a+p-o,n+1,o,2,h(i)>.35?`#ffd84d`:`#ff6b4a`)}let g=n+i-d,_=Math.max(3,Math.round(r*(.18+.12*Math.abs(Math.sin(c/900))))),v=t+Math.floor(r/2),y=Br(o,Math.floor(c/300))%3,b=u>=.82;for(let t=0;t<2;t++){let n=t===0?1:-1,r=t===0?v-_-2:v+_,i=b&&t===f,a=t===0?`#e8454a`:`#3d7ce0`,o=!b&&y===1-t;if(i){H(e,r-1,g-2,4,2,a),H(e,t===0?r-3:r+3,g-2,2,2,`#f2c3a0`);continue}let s=Math.floor(c/220+t)%2;H(e,r,g-7+s,2,2,o?`#ffffff`:`#f2c3a0`),H(e,r,g-5+s,2,3,o?`#ffffff`:a),H(e,r,g-2,1,2,`#2b2530`),H(e,r+1,g-2,1,2,`#2b2530`);let l=!b&&y===t;H(e,n>0?r+2:r-(l?3:1),g-5+s,l?3:1,1,`#f2c3a0`)}b&&Math.floor(c/200)%2==0&&r>=12&&i>=9&&Kr(e,`KO`,t,n,r,i,`#ffd84d`)}function ri(e,t){let n=Vr(e/(t*2))*t*2;return Math.floor(n<t?n:t*2-n)}var ii={pending:[`#ffe27a`,`#ffd0a8`],in_progress:[`#8fd0ff`,`#a9e0ff`],completed:[`#9be59b`,`#b8efb0`]};function ai(e,t,n,r){let i=Math.round(t.x),a=Math.round(t.y),o=Math.round(t.w),s=Math.round(t.h);zr(i,a,o,s);let c=Math.floor(o/3),l=[`#f2b33d`,`#3f7fd8`,`#3fae5c`];for(let t=0;t<3;t++)H(e,i+t*c+1,a,c-2,1,l[t]),t>0&&H(e,i+t*c-1,a+2,1,s-3,`#e1e6ec`);let u=[`pending`,`in_progress`,`completed`],d=c>=11?2:1,f=[0,0,0];for(let t of n){let n=u.indexOf(t.status);if(n<0)continue;let o=f[n]++,l=i+n*c+1+o%d*5,p=a+2+Math.floor(o/d)*4;if(p+3>a+s){o%d===0&&H(e,i+n*c+Math.floor(c/2)-1,a+s-1,3,1,`#9aa4b2`);continue}let m=ii[t.status][o%2];H(e,l,p,4,3,m),H(e,l,p+2,4,1,R(m,`#7a6a4a`,.25)),H(e,l+1,p+1,2,1,R(m,`#2b2f3b`,.35)),t.status===`completed`&&H(e,l+3,p,1,1,`#2e8a46`),t.status===`in_progress`&&Math.floor(r/600+o)%2==0&&H(e,l,p,4,1,`#e8f6ff`)}}var oi=[[0,`#0b1230`,`#1f2b57`],[4.6,`#0e1838`,`#28335f`],[5.6,`#38397a`,`#e48a6c`],[6.6,`#6ea6df`,`#f5c99c`],[8,`#79b8eb`,`#d2ebfa`],[16,`#70b0e8`,`#d8edf8`],[17.4,`#5f86c8`,`#f5b37c`],[18.4,`#4a4f96`,`#ef8a68`],[19.4,`#26295f`,`#7a4e86`],[20.4,`#111b42`,`#2b3565`],[24,`#0b1230`,`#1f2b57`]];function si(e){let t=(e%24+24)%24,n=0;for(;n<oi.length-2&&oi[n+1][0]<=t;)n++;let[r,i,a]=oi[n],[o,s,c]=oi[n+1],l=(t-r)/Math.max(.001,o-r),u=t<5||t>20?1:t<6.2?Math.max(0,(6.2-t)/1.2):t>19?Math.min(1,(t-19)/1.2):0,d=t>7&&t<17?1:t>=6&&t<=7?t-6:t>=17&&t<=18.5?(18.5-t)/1.5:0;return{top:R(i,s,l),bottom:R(a,c,l),night:u,day:d}}function ci(e,t,n,r,i){let a=Math.round(t.x),o=Math.round(t.y),s=Math.round(t.w),c=Math.round(t.h);if(s<=0||c<=0)return;zr(a,o,s,c);let l=i>>>0,u=si(n);for(let t=0;t<c;t++)H(e,a,o+t,s,1,R(u.top,u.bottom,t/Math.max(1,c-1)));if(u.night>.3){for(let t=0;t<7;t++){let n=Br(l,t+101);H(e,a+n%s,o+(n>>>8)%Math.max(1,Math.floor(c*.55)),1,1,Math.floor(r/600+t)%5==0?`#8090c0`:`#f2f4ff`)}let t=a+Math.floor(s*.72);H(e,t,o+2,3,3,`#f4efd2`),H(e,t+2,o+2,1,1,u.top),H(e,t,o+4,1,1,`#d9d2ad`)}let d=(n%24+24)%24;if(d>5.6&&d<19){let t=(d-5.6)/13.4,n=a+Math.floor(t*(s-3)),r=o+Math.floor((1-Math.sin(t*Math.PI))*(c*.55))+1,i=u.day<.7;H(e,n-1,r,5,3,i?`rgba(255,190,120,0.35)`:`rgba(255,250,210,0.35)`),H(e,n,r,3,3,i?`#ffcf86`:`#fff6c8`)}if(u.night<.8){let t=u.day>.5?`rgba(255,255,255,0.9)`:`rgba(255,214,190,0.75)`;for(let n=0;n<2;n++){let i=Br(l,n+7),c=s+12,u=a-6+Math.floor(Vr(r/1e3*(.35+n*.2)/c+i%100/100)*c),d=o+2+n*3+(i>>>4)%2,f=5+i%3;for(let n=0;n<f;n++){let r=u+n;r<a||r>=a+s||(H(e,r,d+1,1,1,t),n>0&&n<f-1&&H(e,r,d,1,1,t))}}}let f=R(`#8ea8c6`,`#1a2138`,Math.max(u.night,1-u.day)*.9),p=R(`#b3c6dc`,`#262f4d`,Math.max(u.night,1-u.day)*.9),m=a,h=0;for(;m<a+s;){let t=Br(l,h+300),n=3+t%4,i=3+(t>>>4)%Math.max(2,Math.floor(c*.42)),d=(t>>>9)%3==0,g=Math.min(n,a+s-m);if(H(e,m,o+c-i-(d?2:0),g,i+(d?2:0),d?p:f),u.night>.2)for(let t=o+c-i+1;t<o+c-1;t+=2)for(let n=m+1;n<m+g-1;n+=2)Br(l+n*31,t)%3==0&&H(e,n,t,1,1,Math.floor(r/3e3+n+t)%17==0?`#c99a40`:`#f7d77a`);else if(!d&&n>3)for(let t=o+c-i+1;t<o+c-1;t+=2)H(e,m+1,t,g-2,1,R(f,`#e6f0fa`,.35));m+=n,h++}}function li(e,t,n){zr(Math.round(t.x),Math.round(t.y),Math.round(t.w),Math.round(t.h));let r=t.x+t.w/2,i=t.y+t.h/2,a=n.getSeconds(),o=n.getMinutes()+a/60,s=n.getHours()%12+o/60,c=(t,n,a)=>{let o=t-Math.PI/2,s=Math.ceil(n*2),c=-999,l=-999;for(let t=1;t<=s;t++){let u=n*t/s,d=Math.floor(r+Math.cos(o)*u),f=Math.floor(i+Math.sin(o)*u);(d!==c||f!==l)&&(H(e,d,f,1,1,a),c=d,l=f)}},l=Math.min(t.w,t.h);c(s/12*Math.PI*2,l*.26,`#2b2f3b`),c(o/60*Math.PI*2,l*.4,`#3a3f4b`),c(a/60*Math.PI*2,l*.38,`rgba(224,90,90,0.85)`),H(e,Math.floor(r),Math.floor(i),1,1,`#e05a5a`)}function U(e,t,n,r=4,i=3){let a=new Cn(e*16+r*2,n+t*16+i);return a.ox=r,a.oy=n,{buf:a,ax:r+e*16/2,ay:n+t*16}}function ui(e,t=2){let n=new Cn(e*16+t*2,38);return n.ox=t,n.oy=36,{buf:n,ax:t+e*16/2,ay:36}}function di(e,t,n,r,i){return{x:t+e.buf.ox,y:n+e.buf.oy,w:r,h:i}}function fi(e){let t=e.buf.bounds();if(!t)return e;let n=e.buf.crop(t.x,t.y,t.w,t.h),r;if(e.rects){r={};for(let[n,i]of Object.entries(e.rects))r[n]={x:i.x-t.x,y:i.y-t.y,w:i.w,h:i.h}}return{buf:n,ax:e.ax-t.x,ay:e.ay-t.y,rects:r}}var W={oak:z(`#d9b88e`,.06),oakDark:z(`#b88c5e`,.06),white:z(`#e9e8e4`,.045),walnut:z(`#7a5a45`,.065),steel:z(`#b9c0ca`,.06),steelDark:z(`#6d7583`,.07),graphite:z(`#474d5c`,.065),plastic:z(`#e4e6ea`,.045),stone:z(`#e8e6e1`,.04),terracotta:z(`#c9714a`,.07),ceramic:z(`#eeebe4`,.05),leaf:z(`#4c9a55`,.08),leafDark:z(`#2f7044`,.07),cardboard:z(`#c99a5e`,.06),blueFabric:z(`#4f78b8`,.07),orange:z(`#ec8a3c`,.07)},pi=[`#3f7fd8`,`#ec8a3c`,`#4cae6a`,`#e05a5a`,`#f2c14e`,`#8d66cf`,`#36b0b0`,`#e47aa8`],mi=`#22324f`;function hi(e,t=0){return d((e*2654435761^t*40503^1540483477)>>>0)}function gi(e,t){return t[Math.floor(e()*t.length)%t.length]}function _i(e,t,n,r,i,a){e.rect(t,n,r,i,a.lt),i>2&&e.hline(t,t+r-1,n,a.base),e.hline(t,t+r-1,n+i-1,a.hi)}function vi(e,t,n,r,i,a){e.rect(t,n,r,i,a.base),e.hline(t,t+r-1,n+i-1,a.dk),e.vline(t+r-1,n,n+i-1,a.dk),i>1&&e.hline(t,t+r-1,n,a.base)}function yi(e,t,n,r,i,a,o,s=!1){let c=hi(o,7);if(s){for(let o=t+2;o<t+r-1;o+=3+Math.floor(c()*2)){let t=n+Math.floor(c()*i),r=2+Math.floor(c()*(i-1));for(let s=t;s<Math.min(n+i,t+r);s++)e.set(o,s,a.base)}return}for(let o=n+1;o<n+i-1;o+=2+Math.floor(c()*2)){let n=t+Math.floor(c()*r),i=3+Math.floor(c()*(r/2));for(let s=n;s<Math.min(t+r,n+i);s++)e.set(s,o,a.base)}}function G(e,t,n,r,i,a=.2){let o=`rgba(28,32,52,${a})`,s=`rgba(28,32,52,${a*.55})`;for(let a=n;a<n+i;a++)for(let c=t;c<t+r;c++){if((c===t||c===t+r-1)&&(a===n||a===n+i-1))continue;let l=c===t||c===t+r-1||a===n+i-1;e.under(c,a,l?s:o)}}function bi(e,t,n,r,i,a){for(let o=n;o<n+i;o++)for(let n=t;n<t+r;n++)e.under(n,o,a)}function xi(e,t,n,r,i,a={}){let o=a.alpha??.42;if(e.rect(t,n,r,i,`rgba(168,212,238,${o})`),a.streaks===!1)return;let s=a.period??9;for(let o=-i+(a.offset??0);o<r;o+=s)for(let a=0;a<i;a++){let s=t+o+(i-1-a),c=n+a;s>=t&&s<t+r&&e.set(s,c,`rgba(255,255,255,0.42)`),s+1>=t&&s+1<t+r&&e.set(s+1,c,`rgba(255,255,255,0.22)`)}e.hline(t,t+r-1,n,`rgba(255,255,255,0.35)`)}var Si=`rgba(60,40,40,0.2)`,Ci=`rgba(40,46,70,0.3)`;function wi(e,t,n,r){e.hline(t+1,t+3,n+3,Si),e.hline(t,t+2,n,`#f4f2ee`),e.set(t+1,n,`#6b4226`),e.rect(t,n+1,3,2,r),e.set(t,n+1,L(r,.12)),e.set(t+2,n+2,L(r,-.12)),e.set(t+3,n+1,L(r,-.08)),e.set(t+3,n+2,L(r,-.15))}function Ti(e,t,n,r=6,i=4,a=`light`){let o=a===`onLight`;e.hline(t+1,t+r,n+i,o?Ci:Si),o&&e.vline(t+r,n,n+i-1,Ci),e.rect(t+1,n-1,r,i,o?`#c4bfb2`:`#dedad0`),e.rect(t,n,r,i,o?`#fbfaf6`:`#f8f7f3`),e.hline(t,t+r-1,n+i-1,o?`#b9b3a6`:`#d6d2c8`),o&&e.vline(t+r-1,n,n+i-1,`#cfcabd`);for(let a=1;a<i-1;a++)e.hline(t+1,t+1+Math.max(1,r-3-a%2),n+a,o?`#93a0b4`:`#b9c2d0`)}function Ei(e,t,n,r=10,i=`light`){let a=i===`dark`?{base:`#3d4250`,key:`#5a6070`,edge:`#2a2e38`,sh:Si}:i===`onLight`?{base:`#b9c0cc`,key:`#e4e8ee`,edge:`#7d8696`,sh:Ci}:{base:`#d9dce2`,key:`#f4f5f7`,edge:`#a9aeb8`,sh:Si};e.hline(t+1,t+r,n+3,a.sh),e.rect(t,n,r,3,a.base);for(let i=0;i<r-1;i+=2)e.set(t+1+i,n,a.key),e.set(t+i,n+1,a.key);e.hline(t,t+r-1,n+2,a.edge),i===`onLight`&&(e.vline(t,n,n+2,`#a3abb8`),e.vline(t+r-1,n,n+2,a.edge))}function Di(e,t,n,r=`light`){let i=r===`onLight`,a=r===`dark`;e.hline(t+1,t+2,n+2,i?Ci:Si),i&&e.set(t+2,n+1,Ci),e.rect(t,n,2,2,a?`#3d4250`:i?`#c3c9d3`:`#eceef1`),e.set(t+1,n+1,a?`#2a2e38`:i?`#7d8696`:`#b4b9c2`),i&&e.set(t,n,`#e4e8ee`)}function Oi(e,t,n,r=16,i=11){e.hline(t+3,t+r-2,n+i+3,Si),e.rect(t,n,r,i,`#2c313d`),e.hline(t,t+r-1,n,`#3e4554`),e.vline(t,n,n+i-1,`#363c4a`),e.hline(t,t+r-1,n+i-1,`#232732`);let a=t+1,o=n+1,s=r-2,c=i-2;e.rect(a,o,s,c,mi),e.rect(a,o,s,1,`#2a3d5f`);for(let t=0;t<c;t++)e.set(a+s-3-t,o+t,`#2f4569`);e.set(t+r-2,n+i-1,`#5fd07a`);let l=t+Math.floor(r/2)-1;return e.rect(l,n+i,2,2,`#4a5060`),e.rect(l-2,n+i+2,6,1,`#5b6272`),e.set(l-2,n+i+2,`#6b7282`),{x:a,y:o,w:s,h:c}}function ki(e,t,n,r){let{x:i,y:a,w:o,h:s}=t,c=hi(r,41);if(n===`sheet`){e.rect(i,a,o,s,`#b4c0d2`),e.hline(i,i+o-1,a,`#5f86c4`),e.vline(i,a+1,a+s-1,`#9aa8bd`);for(let t=a+2;t<a+s;t+=2)e.hline(i+1,i+o-1,t,`#a2afc3`);for(let t=i+4;t<i+o;t+=4)e.vline(t,a+1,a+s-1,`#a2afc3`);for(let t=0;t<3;t++){let t=i+1+4*Math.floor(c()*Math.max(1,Math.floor((o-1)/4))),n=a+1+2*Math.floor(c()*Math.max(1,Math.floor((s-1)/2)));e.rect(t,n,Math.min(3,i+o-t),1,gi(c,[`#6fa784`,`#d29b58`,`#7d9ad0`]))}return}if(n===`chart`){e.rect(i,a,o,s,`#22304a`),e.hline(i+1,i+Math.max(1,Math.floor(o/2)),a+1,`#6d7f9e`);let t=a+s-1;e.hline(i,i+o-1,t,`#3d4f70`);let n=[`#4a86c8`,`#4fae7a`,`#d09a4a`];for(let r=i+1,a=0;r<i+o-1;r+=2,a++){let i=Math.max(1,Math.min(s-3,1+Math.floor(c()*(s-3))+Math.floor(a/2)));e.vline(r,t-i,t-1,n[a%n.length])}return}let l=[`#a0628e`,`#4f8fa6`,`#a8a35f`,`#4f9c68`,`#8a72b0`,`#b08156`];e.rect(i,a,o,s,`#232a3d`),e.vline(i,a,a+s-1,`#2c3449`);for(let t=a+1;t<a+s;t+=2){let n=i+2+Math.floor(c()*3),r=1+Math.floor(c()*3);for(let a=0;a<r&&n<i+o-1;a++){let r=Math.min(1+Math.floor(c()*4),i+o-1-n);e.hline(n,n+r-1,t,gi(c,l)),n+=r+1}}}function Ai(e,t,n,r=16,i=10,a=`light`){let o=a===`mid`?{hi:`#b4bcc8`,lt:`#a3abb8`,base:`#8f98a6`,dk:`#747d8c`,line:`#454c5a`,stand:`#6b7383`,foot:`#596170`}:{hi:`#e6eaf0`,lt:`#d8dee6`,base:`#c9d0da`,dk:`#aab3c0`,line:`#5b6577`,stand:`#9aa3b0`,foot:`#7d8696`},s=t+Math.floor(r/2);e.hline(t+2,t+r-1,n+i+3,Ci),e.rect(s-4,n+i+1,8,2,o.foot),e.hline(s-4,s+3,n+i+1,o.stand),e.set(s-4,n+i+2,o.line),e.set(s+3,n+i+2,o.line),e.rect(s-1,n+i-1,2,3,o.stand),e.vline(s,n+i-1,n+i+1,o.dk),e.rect(t,n,r,i,o.base),e.hline(t+1,t+r-2,n+1,o.lt),e.vline(t+1,n+1,n+i-2,o.lt),e.vline(t+r-2,n+1,n+i-2,o.dk),e.hline(t+1,t+r-2,n+i-2,o.dk),e.hline(t,t+r-1,n,o.hi),e.vline(t,n+1,n+i-1,o.line),e.vline(t+r-1,n+1,n+i-1,o.line),e.hline(t,t+r-1,n+i-1,o.line),e.set(t,n,o.lt),e.set(t+r-1,n,o.dk);for(let i=t+3;i<=t+r-4;i+=2)e.set(i,n+2,o.dk);e.rect(s-3,n+4,6,Math.max(2,i-6),o.lt),e.hline(s-3,s+2,n+4,o.hi),e.hline(s-3,s+2,n+4+Math.max(2,i-6)-1,o.dk),e.vline(s+2,n+5,n+4+Math.max(2,i-6)-1,o.dk),e.set(s-1,n+5,a===`mid`?`#cfd5de`:`#f6f8fb`),e.set(s,n+5,a===`mid`?`#cfd5de`:`#f6f8fb`),e.vline(s+2,n+i,n+i+2,o.line)}function ji(e,t,n){e.set(t,n-2,`#e05a5a`),e.set(t+1,n-3,`#3f7fd8`),e.set(t+2,n-2,`#f2c14e`),e.rect(t,n-1,3,3,`#5b6272`),e.set(t,n-1,`#7a8292`)}function Mi(e,t,n){e.rect(t,n,4,3,`#e3e1db`),e.set(t+3,n+1,`#c2bfb7`),e.set(t+3,n+2,`#c2bfb7`),e.set(t+1,n-1,`#6fbf6a`),e.set(t+2,n-1,`#4c9a55`),e.set(t,n-2,`#6fbf6a`),e.set(t+3,n-2,`#4c9a55`),e.set(t+1,n-3,`#8fd68a`),e.set(t+2,n-2,`#3e8a4c`)}function Ni(e,t,n){e.rect(t,n,4,4,`#3a3f4b`),e.rect(t+1,n+1,2,2,`#8fc8f0`),e.set(t+1,n+2,`#6fbf6a`)}function Pi(e,t,n,r,i,a){e.rect(t,n,r,i,a),e.vline(t,n,n+i-1,L(a,.1)),e.vline(t+r-1,n,n+i-1,L(a,-.12)),i>4&&e.hline(t,t+r-1,n+1,L(a,.22)),i>6&&r>1&&e.hline(t,t+r-1,n+i-3,L(a,.22))}function Fi(e,t,n,r,i,a,o){let s=hi(o,3);e.ellipse(t,n+.5,r,i,a.dd);let c=[],l=Math.max(1.6,Math.min(r,i)*.55);for(let e=-i+l*.6;e<=i-l*.4;e+=l*1.05)for(let a=-r+l*.6;a<=r-l*.4;a+=l*1.15){let o=a+(s()-.5)*l*.7,u=e+(s()-.5)*l*.6;(o/r)**2+(u/i)**2>.82||c.push([t+o,n+u,l*(.85+s()*.35)])}c.sort((e,t)=>e[1]-t[1]);for(let[o,s,l]of c){let c=(s-n)/i,u=(t-o)/r,d=c>.35?a.dk:c>-.2||u<-.4?a.base:a.lt;for(let t=Math.floor(s-l);t<=Math.ceil(s+l);t++)for(let n=Math.floor(o-l);n<=Math.ceil(o+l);n++){let r=(n+.5-o)/l,i=(t+.5-s)/(l*.9),c=r*r+i*i;if(c>1)continue;let u=d;c>.4&&r+i*1.3<-.75?u=d===a.lt?a.hi:d===a.base?a.lt:a.base:c>.5&&r*.4+i>.7&&(u=d===a.lt?a.base:a.dd),e.set(n,t,u)}}}function Ii(e,t,n,r,i,a,o,s=`monstera`){let c=Math.hypot(r-t,i-n),l=(r-t)/c,u=(i-n)/c,d=-u,f=l,p=Math.ceil(c*3),m=e=>a/2*Math.sin(Math.PI*Math.min(1,e)**.7),h=(a,s)=>{for(let r=0;r<=p;r++){let i=r/p,o=m(i)+a;for(let r=-o;r<=o;r+=.4)e.set(Math.round(t+l*c*i+d*r),Math.round(n+u*c*i+f*r),s(r))}a>0&&e.set(Math.round(r+l*a),Math.round(i+u*a),o.dd)};if(h(.9,()=>o.dd),h(0,e=>d*e+f*e<0?o.lt:o.base),e.line(Math.round(t),Math.round(n),Math.round(t+l*c*.92),Math.round(n+u*c*.92),o.dk),e.set(Math.round(t+l*c*.3+d*-m(.3)*.5),Math.round(n+u*c*.3+f*-m(.3)*.5),o.hi),s===`none`)return;let g=s===`monstera`?[[.42,1],[.6,-1],[.76,1]]:Array.from({length:Math.floor(c/1.2)},(e,t)=>[.18+t*1.2/c,t%2?1:-1]).filter(([e])=>e<.95);for(let[r,i]of g){let a=m(r);for(let p=a*.35;p<=a+.5;p+=.4){let a=Math.round(t+l*c*(r+.04)+d*p*i),m=Math.round(n+u*c*(r+.04)+f*p*i);s===`pinnate`?e.clear(a,m):e.set(a,m,o.dd)}}}function Li(e,t,n,r,i,a,o,s){let c=Math.hypot(r-t,i-n),l=Math.ceil(c*2),u=-(i-n)/c,d=(r-t)/c;for(let c=0;c<=l;c++){let f=c/l,p=a*Math.sin(Math.PI*Math.min(1,f*1.15))*.5,m=t+(r-t)*f,h=n+(i-n)*f;for(let t=-p;t<=p;t+=.5)e.set(Math.round(m+u*t),Math.round(h+d*t),t<0===s?o.lt:o.base)}e.line(t,n,Math.round(t+(r-t)*.85),Math.round(n+(i-n)*.85),o.dk)}function Ri(e,t,n,r,i,a=W.terracotta){e.rect(t,n,r,2,a.lt),e.hline(t,t+r-1,n,a.hi),e.hline(t+1,t+r-2,n+1,L(a.dd,-.1));for(let o=2;o<i;o++){let s=+(o>=i-2);e.hline(t+s,t+r-1-s,n+o,a.base),e.set(t+s,n+o,a.lt),e.set(t+r-1-s,n+o,a.dk),o===i-1&&e.hline(t+s,t+r-1-s,n+o,a.dk)}}var zi=z(`#d8b98f`,.06),Bi=z(`#eceae5`,.04);function Vi(e,t=16){for(let n=-e.oy;n<e.h-e.oy;n++)e.clear(-1,n),e.clear(t,n)}function Hi(e,t){if(vi(e,0,5,16,11,zi),e.vline(0,5,15,zi.lt),e.vline(15,5,13,zi.dd),e.rect(1,14,14,2,`#5a4a3c`),e.hline(1,14,14,`#43372d`),t===`drawers`){for(let t of[8,11])e.hline(1,14,t,zi.dd),e.hline(1,14,t+1,zi.lt);for(let t of[6,9,12])e.rect(6,t,4,1,`#8b939f`)}else t===`doors`?(e.vline(7,6,13,zi.dd),e.vline(8,6,13,zi.lt),e.rect(5,8,1,3,`#8b939f`),e.rect(10,8,1,3,`#8b939f`)):(e.rect(12,8,1,3,`#8b939f`),e.hline(1,14,6,zi.lt));_i(e,0,-3,16,7,Bi),e.hline(0,15,4,Bi.dk),e.hline(0,15,3,Bi.hi);for(let[t,n]of[[3,-1],[11,1],[7,0]])e.set(t,n,Bi.base)}function Ui(e){let t=U(1,1,6);return Hi(t.buf,e===`drawers`?`drawers`:`plain`),t.buf.outline(),Vi(t.buf),G(t.buf,0,14,16,3,.2),{base:t}}function Wi(){let e=U(1,1,10),t=e.buf;return Hi(t,`doors`),t.rect(3,-1,10,4,`#aeb6c2`),t.rect(4,0,8,3,`#7d8592`),t.hline(4,11,0,`#5d6573`),t.set(8,2,`#3d4350`),t.hline(3,12,-1,`#d3d8df`),t.rect(7,-6,2,5,`#c3cad4`),t.hline(7,10,-7,`#e3e7ec`),t.set(10,-6,`#c3cad4`),t.set(9,-7,`#ffffff`),t.rect(5,-3,1,2,`#c3cad4`),t.outline(),Vi(t),G(t,0,14,16,3,.2),{base:e}}function Gi(e){let t=U(1,1,18),n=t.buf;Hi(n,`drawers`);let r=e>=1,i=z(`#3a3f4b`,.06),a=z(`#c3cad4`,.06);if(_i(n,2,-15,12,3,a),n.rect(2,-12,12,13,i.base),n.vline(2,-12,0,i.lt),n.vline(13,-12,0,i.dd),n.rect(3,-11,10,2,`#22262f`),n.set(4,-10,r?`#5fd07a`:`#3b4a3f`),n.set(6,-10,r?`#f2c14e`:`#4a4535`),n.rect(9,-11,3,2,r?`#7fd0ff`:`#2a3a52`),n.rect(5,-7,6,2,a.base),n.hline(5,10,-7,a.hi),n.rect(7,-5,2,1,a.dk),n.rect(4,0,8,1,a.dk),n.hline(4,11,-1,a.base),n.rect(6,-3,4,3,`#f4f2ee`),n.set(10,-2,`#d6d2c8`),n.hline(6,9,-3,r?`#6b4226`:`#f4f2ee`),r&&(n.vline(7,-4,-3,`#7a4a2a`),n.set(8,-4,`#9a6a3e`)),n.rect(10,-18,3,3,`rgba(120,80,50,0.9)`),n.hline(10,12,-18,`rgba(240,240,240,0.8)`),n.outline(),Vi(n),G(n,0,14,16,3,.2),r)for(let[e,t,r]of[[12,-17,.55],[13,-18,.45],[12,-19,.35]])n.set(e,t,`rgba(255,255,255,${r})`);return{base:t}}function Ki(){let e=U(1,1,12),t=e.buf;Hi(t,`plain`);let n=z(`#e8eaee`,.05);return _i(t,1,-11,14,3,n),vi(t,1,-8,14,9,n),t.rect(2,-7,9,6,`#2a303c`),t.hline(2,10,-7,`#3d4656`),t.line(4,-7,8,-2,`rgba(255,255,255,0.12)`),t.rect(12,-7,2,2,`#1f2a1f`),t.set(12,-7,`#7be08a`),t.set(13,-7,`#7be08a`),t.set(12,-4,`#9aa2ae`),t.set(13,-4,`#9aa2ae`),t.set(12,-3,`#9aa2ae`),t.set(13,-3,`#9aa2ae`),t.outline(),Vi(t),G(t,0,14,16,3,.2),{base:e}}function qi(){let e=U(1,1,24),t=e.buf,n=z(`#dfe3e9`,.05);return _i(t,0,-23,16,3,n),vi(t,0,-20,16,34,n),t.vline(0,-20,13,n.hi),t.rect(1,14,14,2,`#4a505c`),t.hline(0,15,-9,n.dd),t.hline(0,15,-8,n.lt),t.rect(12,-17,2,6,`#9aa2ae`),t.vline(12,-17,-12,`#c3cad4`),t.rect(12,-5,2,9,`#9aa2ae`),t.vline(12,-5,3,`#c3cad4`),t.rect(3,-4,4,5,`#fbf4c0`),t.hline(4,6,-2,`#c9b77a`),t.hline(4,5,0,`#c9b77a`),t.set(5,-5,`#e05a5a`),t.set(8,4,`#3f7fd8`),t.set(4,6,`#4cae6a`),t.set(3,-15,`#f2c14e`),t.rect(6,-16,3,3,`#e47aa8`),t.outline(),G(t,0,13,16,4,.24),{base:e}}function Ji(){let e=U(1,1,24),t=e.buf,n=z(`#c94a52`,.07);_i(t,0,-23,16,3,n),vi(t,0,-20,16,36,n),t.vline(0,-20,15,n.lt),t.rect(2,-18,9,22,`#fff7e0`);let r=hi(7,61),i=[`#e05a5a`,`#f2c14e`,`#3f7fd8`,`#4cae6a`,`#ec8a3c`,`#8d66cf`,`#e47aa8`];for(let e=0;e<5;e++){let n=-17+e*4;for(let e=0;e<3;e++){let a=gi(r,i);t.rect(3+e*3,n,2,3,a),t.set(3+e*3,n,L(a,.2))}t.hline(2,10,n+3,`#c9b98a`)}xi(t,2,-18,9,22,{alpha:.18}),t.rect(12,-16,3,12,`#2f333d`),t.rect(13,-15,1,2,`#7fd0ff`);for(let e=0;e<4;e++)t.set(13,-11+e*2,`#d9dde3`);return t.rect(12,-2,3,2,`#22262f`),t.rect(2,7,9,4,`#22262f`),t.hline(2,10,7,`#3a3f4b`),t.outline(),G(t,0,13,16,4,.26),e.rects={glow:di(e,2,-18,9,22)},{base:e}}function Yi(){let e=U(1,1,4),t=e.buf;t.ellipse(8,14.5,3.5,1.3,`#3a3f4b`),t.rect(7,7,2,7,`#4a505c`),t.vline(7,7,13,`#6b7282`);let n=z(`#f2efe8`,.05);return t.ellipse(8,5.5,7,3.5,n.dk),t.ellipse(8,4.8,7,3.2,n.lt),t.set(4,3,n.hi),t.set(5,3,n.hi),t.rect(7,2,2,2,`#8fc8f0`),t.set(7,1,`#4cae6a`),t.set(8,0,`#f26d8a`),t.set(8,1,`#4cae6a`),t.outline(),G(t,3,13,10,3,.22),{base:e}}var Xi=z(`#e0a84a`,.07);function Zi(e){let t=e??`down`,n=U(1,1,10),r=n.buf,i=`#3a3f4b`;for(let e of[4,11])r.vline(e,9,15,i);for(let e of[5,10])r.vline(e,9,13,`#5a6070`);let a=()=>{r.rect(3,5,10,4,Xi.lt),r.hline(3,12,5,Xi.hi),r.hline(3,12,8,Xi.dk),r.hline(3,12,9,Xi.dd)},o=(e,t,n,i,a)=>{r.rect(e,t,n,i,a.base),r.hline(e,e+n-1,t,a.hi),r.vline(e,t,t+i-1,a.lt),r.vline(e+n-1,t,t+i-1,a.dk)};if(t===`down`){for(let e of[4,11])r.vline(e,-3,5,i);return o(3,-6,10,5,Xi),a(),r.outline(),G(r,2,13,12,3,.2),{base:n}}if(t===`up`){a(),r.outline();let e=U(1,1,10),t=e.buf;for(let e of[4,11])t.vline(e,6,10,i);return t.rect(3,3,10,5,Xi.base),t.hline(3,12,3,Xi.hi),t.hline(3,12,7,Xi.dk),t.vline(12,3,7,Xi.dk),t.outline(),{base:n,front:e}}a();let s=t===`left`?11:3;return r.vline(s+1,0,8,i),o(s,-6,2,12,Xi),r.outline(),{base:n}}var K=z(`#5b7fbd`,.07),Qi=z(`#ee8d3e`,.07);function $i(e,t,n){e.rect(t,n,6,5,Qi.base),e.hline(t+1,t+4,n,Qi.hi),e.vline(t,n+1,n+3,Qi.lt),e.vline(t+5,n+1,n+4,Qi.dk),e.hline(t+1,t+5,n+4,Qi.dk),e.set(t+2,n+2,Qi.dk)}function ea(e,t,n,r,i,a,o=1){e.rect(t,n,r,i,a.base),e.rect(t,n,r,o,a.lt),e.hline(t+1,t+r-2,n,a.hi),e.hline(t,t+r-1,n+i-1,a.dk),e.vline(t+r-1,n+1,n+i-1,a.dk),e.vline(t,n+1,n+i-2,a.lt),e.set(t,n,a.base),e.set(t+r-1,n,a.dk),e.set(t,n+i-1,a.dk)}function ta(e,t,n,r,i){e.rect(t,n+2,r,i-n-2,K.base),e.rect(t,n,r,3,K.lt),e.hline(t+1,t+r-2,n,K.hi),e.hline(t,t+r-1,n+3,K.dk),e.vline(t,n+3,i,K.lt),e.vline(t+r-1,n+1,i,K.dk),e.hline(t,t+r-1,i,K.dd),e.clear(t,n),e.clear(t+r-1,n)}function na(e,t,n){for(let r of t)e.rect(r,n,2,2,`#5a4232`),e.set(r,n,`#7a5a42`)}function ra(e){let t=e===`up`,n=U(3,1,14),r=n.buf;if(!t){r.rect(5,-11,38,13,K.dk),r.hline(6,41,-11,K.base);for(let e=0;e<3;e++)ea(r,6+e*12,-10,12,11,K,2);r.hline(6,41,1,K.dd);for(let e=0;e<3;e++)ea(r,6+e*12,2,12,7,z(K.lt,.06),4);return r.rect(5,9,38,5,K.dk),r.hline(5,42,9,K.base),r.hline(5,42,13,K.dd),na(r,[7,39],14),ta(r,0,-5,6,13),ta(r,42,-5,6,13),na(r,[1,45],14),$i(r,7,-5),$i(r,35,-5),r.outline(),G(r,-1,13,50,4,.24),{base:n}}ia(r,5,42),aa(r,8,-3),aa(r,34,-3),ta(r,0,-7,6,13),ta(r,42,-7,6,13),r.outline(),G(r,-1,13,50,4,.24);let i=U(3,1,14),a=i.buf;return oa(a,0,47),sa(a,[2,23,44],14),a.outline(),{base:n,front:i}}function ia(e,t,n){let r=z(K.lt,.06);e.rect(t,-3,n-t+1,5,r.base),e.hline(t,n,-3,K.base),e.hline(t,n,-2,r.lt)}function aa(e,t,n){e.rect(t,n,6,4,Qi.base),e.hline(t+1,t+4,n,Qi.hi),e.vline(t,n+1,n+3,Qi.lt),e.vline(t+5,n+1,n+3,Qi.dk),e.set(t,n,Qi.lt),e.set(t+5,n,Qi.dk)}function oa(e,t,n){let r=K.dk,i=K.dd;e.hline(t+3,n-3,1,K.lt),e.hline(t+1,n-1,2,K.base),e.hline(t+4,t+9,2,K.lt),e.hline(t,n,3,K.base),e.set(t+2,1,K.base),e.set(n-2,1,K.base),e.hline(t,n,4,i),e.rect(t,5,n-t+1,7,r),e.hline(t,n,5,R(r,K.base,.45)),e.hline(t,n,6,R(r,K.base,.2)),e.vline(t,4,12,K.base),e.vline(n,3,12,i),e.hline(t,n,12,i),e.hline(t,n,13,L(i,-.05))}function sa(e,t,n){for(let r of t)e.rect(r,n,2,2,`#3b2d24`),e.set(r,n,`#54402f`)}function ca(e){let t=e??`down`,n=U(1,1,14),r=n.buf;if(t===`down`||t===`up`){if(t===`down`)return r.rect(3,-10,10,12,K.dk),ea(r,3,-9,10,10,K,2),ea(r,3,2,10,7,z(K.lt,.06),4),r.rect(3,9,10,5,K.dk),r.hline(3,12,9,K.base),ta(r,0,-4,4,13),ta(r,12,-4,4,13),na(r,[1,13],14),r.outline(),G(r,-1,13,18,4,.24),{base:n};ia(r,3,12),ta(r,0,-6,4,13),ta(r,12,-6,4,13),r.outline(),G(r,-1,13,18,4,.24);let e=U(1,1,14),i=e.buf;return oa(i,0,15),sa(i,[1,13],14),i.outline(),{base:n,front:e}}let i=t===`left`?11:0;return ea(r,1,2,14,8,z(K.lt,.06),5),r.rect(1,9,14,5,K.dk),r.hline(1,14,9,K.base),r.rect(i,-10,5,24,K.base),r.rect(i,-10,5,2,K.lt),r.hline(i+1,i+3,-10,K.hi),r.vline(i,-8,13,K.lt),r.vline(i+4,-8,13,K.dk),r.clear(i,-10),r.clear(i+4,-10),r.hline(i,i+4,13,K.dd),na(r,[1,13],14),r.outline(),G(r,-1,13,18,4,.24),{base:n}}function la(e){let t=U(2,1,6),n=t.buf,r=z(`#5d4637`,.06);for(let e of[2,28])n.rect(e,9,2,5,r.dd);_i(n,1,1,30,8,r),yi(n,2,2,28,6,r,e),n.hline(1,30,9,r.base),n.hline(1,30,10,r.dk),n.ellipse(11,4,4,2,`#f4f2ee`),n.ellipse(11,4.6,3,1.3,`#d6d2c8`);for(let[e,t,r]of[[9,2,`#ee8d3e`],[11,2,`#e05a5a`],[13,3,`#ee8d3e`],[10,3,`#7cc45a`]])n.rect(e,t,2,2,r),n.set(e,t,L(r,.2));return n.rect(19,3,8,5,`#3f7fd8`),n.rect(20,2,7,5,`#f4f2ee`),n.rect(21,3,4,2,`#e05a5a`),n.hline(21,25,6,`#b9c2d0`),e%2&&wi(n,4,4,`#f2c14e`),n.outline(),G(n,0,12,32,4,.22),{base:t}}function ua(){let e=U(3,2,8),t=e.buf,n=z(`#2f72b8`,.07);for(let e of[4,42])t.rect(e,22,2,9,`#3a3f4b`),t.vline(e,22,30,`#5a6070`);t.rect(22,22,4,7,`#3a3f4b`),t.rect(0,-4,48,25,n.lt),t.hline(0,47,20,n.dk),t.hline(0,47,21,n.dd),t.rect(0,22,48,1,`#2a2e38`),t.hline(0,47,-4,`#f4f6f8`),t.hline(0,47,19,`#f4f6f8`),t.vline(0,-4,19,`#f4f6f8`),t.vline(47,-4,19,`#f4f6f8`),t.hline(1,46,7,`rgba(244,246,248,0.8)`);for(let e=-8;e<=18;e++)t.set(23,e,e%2?`rgba(240,244,248,0.55)`:`rgba(40,46,60,0.45)`),t.set(24,e,`rgba(40,46,60,0.35)`);return t.hline(22,25,-9,`#3a3f4b`),t.hline(22,25,19,`#3a3f4b`),t.vline(22,-9,15,`#f4f6f8`),t.outline(),G(t,0,27,48,5,.22),{base:e}}var da={red:`#d65454`,blue:`#4f78c8`,yellow:`#e8b83f`,green:`#4fae6a`};function fa(e){let t=z(da[e??`red`]??da.red,.08),n=U(1,1,6),r=n.buf;return r.ellipse(8,9,7.5,6,t.dk),r.ellipse(7.6,8,7,5.5,t.base),r.ellipse(7.2,6.5,5,3.5,t.lt),r.ellipse(8,7.5,3.5,2,t.base),r.set(4,4,t.hi),r.set(5,3,t.hi),r.set(6,3,t.hi),r.hline(4,12,14,t.dd),r.outline(),G(r,0,12,16,4,.24),{base:n}}function pa(){let e=U(1,1,24),t=e.buf,n=z(`#5b3f9a`,.07);vi(t,1,-20,14,36,n),t.vline(1,-20,15,n.lt),t.rect(1,-22,14,4,`#f2c14e`),t.hline(1,14,-22,`#fff2b0`);for(let e of[3,5,8,10,12])t.set(e,-20,`#e05a5a`);t.rect(2,-17,12,9,`#1a1f2e`);let r={x:3,y:-16,w:10,h:7};t.rect(r.x,r.y,r.w,r.h,`#14213d`),t.rect(5,-13,2,2,`#7be08a`),t.rect(9,-15,2,1,`#ff79c6`),t.set(8,-11,`#f2c14e`),t.rect(1,-7,14,4,n.hi),t.hline(1,14,-4,n.dk),t.rect(4,-7,2,2,`#e05a5a`),t.set(4,-7,`#ff9a9a`),t.vline(5,-5,-4,`#2a2e38`);for(let[e,n]of[[9,`#3f7fd8`],[11,`#f2c14e`],[13,`#4cae6a`]])t.set(e,-6,n);return t.rect(5,2,6,6,n.dd),t.set(6,4,`#f2a03d`),t.set(9,4,`#f2a03d`),t.line(2,13,6,9,`#e47aa8`),t.line(3,13,7,9,`#36b0b0`),t.outline(),G(t,0,13,16,4,.26),e.rects={screen:di(e,r.x,r.y,r.w,r.h)},{base:e}}function ma(e){let t=e>=1,n=z(`#a9c4cf`,.06),r=z(`#c3cad4`,.06),i=U(2,2,26,3,4),a=i.buf,o=z(`#f6f6f3`,.045);a.rect(11,-7,10,6,o.base),a.hline(11,20,-7,o.hi),a.hline(11,20,-2,o.dk),a.rect(14,-6,4,1,`#c9ced6`),a.ellipse(16,3,5.5,4,o.dk),a.ellipse(16,2.5,5,3.6,o.lt),a.ellipse(16,3,3,2.2,`#cfd8e0`),a.ellipse(16,3.2,2,1.4,`#a9c9de`),a.rect(3,2,3,3,`#ffffff`),a.set(5,4,`#d9dde3`),a.vline(3,2,4,`#9aa2ae`);for(let e of[0,29])a.rect(e,-22,3,34,n.base),a.vline(e,-22,11,n.lt),a.vline(e+2,-22,11,n.dk),a.hline(e,e+2,-22,r.hi);a.outline(),bi(a,2,0,28,12,`rgba(30,34,52,0.12)`);let s=U(2,2,26,3,4),c=s.buf;c.rect(0,10,32,20,n.base),c.rect(0,9,32,2,r.lt),c.hline(0,31,9,r.hi),c.vline(0,11,29,n.lt),c.vline(31,11,29,n.dk),c.hline(0,31,29,n.dk);for(let e of[1,30])c.rect(e,30,1,2,`#9aa2ae`);return t?(c.rect(7,12,18,17,n.lt),c.vline(7,12,28,n.dk),c.vline(24,12,28,n.dd),c.hline(7,24,12,n.hi),c.rect(21,18,2,3,`#5a6070`),c.rect(21,15,2,2,`#e05a5a`)):(c.rect(19,12,6,17,`#3a4250`),c.rect(20,13,4,15,`#5a6577`),c.rect(7,12,12,17,n.lt),c.vline(7,12,28,n.dk),c.vline(18,12,28,n.dk),c.hline(7,18,12,n.hi),c.rect(16,18,2,3,`#5a6070`),c.rect(21,15,2,2,`#5fd07a`)),c.outline(),{base:i,front:s}}function ha(){let e=U(1,1,10),t=e.buf,n=z(`#e9e8e4`,.05);return vi(t,1,4,14,12,n),t.vline(7,5,14,n.dd),t.vline(8,5,14,n.lt),t.rect(5,8,1,3,`#9aa2ae`),t.rect(10,8,1,3,`#9aa2ae`),_i(t,0,-3,16,7,z(`#d7dbe1`,.04)),t.ellipse(8,.5,5,2.6,`#f8f8f6`),t.ellipse(8,.8,4,1.8,`#dfe5ea`),t.set(8,1,`#7d8592`),t.rect(7,-5,2,3,`#c3cad4`),t.set(7,-5,`#ffffff`),t.hline(7,9,-6,`#d3d8df`),t.rect(12,-4,2,3,`#f2c14e`),t.set(12,-5,`#5a6070`),t.outline(),G(t,0,14,16,3,.2),{base:e}}function ga(e){let t=U(3,1,16),n=t.buf,r=W.oak,i=z(`#efede8`,.04);return _i(n,1,-10,46,6,W.white),Ai(n,8,-15,13,7),Ri(n,38,-13,5,4,W.ceramic),Fi(n,40.5,-16,3.5,3,W.leaf,e+1),vi(n,0,-2,48,18,r),yi(n,1,-1,46,14,r,e,!0),n.rect(0,5,48,3,`#3f7fd8`),n.hline(0,47,5,`#6aa0ec`),n.hline(0,47,7,`#2d62b3`),n.rect(0,14,48,2,r.dd),_i(n,-1,-6,50,5,i),n.hline(-1,48,-2,i.dk),n.rect(30,-6,4,2,`#d9a42e`),n.set(31,-7,`#f2c14e`),n.set(32,-7,`#f2c14e`),Ti(n,4,-5,7,3),n.line(14,-4,18,-5,`#3a3f4b`),n.outline(),G(n,-1,13,50,4,.24),{base:t}}function _a(){let e=U(2,1,10),t=e.buf,n=W.oak,r=`#3a3f4b`;for(let e of[2,29])t.vline(e,-6,15,r),t.vline(e+1,8,15,`#5a6070`);t.hline(2,30,13,r);for(let e of[-6,-3])t.rect(1,e,30,2,n.base),t.hline(1,30,e,n.lt);for(let e of[2,5])t.rect(0,e,32,3,n.lt),t.hline(0,31,e,n.hi),t.hline(0,31,e+2,n.dk);return t.rect(0,8,32,1,n.dd),t.outline(),G(t,0,13,32,3,.22),{base:e}}function va(e){switch(e){case`white`:return{top:W.white,edge:z(`#d7d6d1`,.05),legs:W.steel,ped:z(`#dcdbd6`,.05)};case`dark`:return{top:W.walnut,edge:z(`#5f4535`,.06),legs:W.graphite,ped:z(`#5a4334`,.06)};default:return{top:W.oak,edge:W.oakDark,legs:z(`#e9e8e4`,.05),ped:z(`#e6e4de`,.05)}}}var ya=[`#e2604f`,`#3f7fd8`,`#f2c14e`,`#4cae6a`,`#f4f2ee`,`#8d66cf`];function ba(e){bi(e,3,8,26,7,`rgba(30,34,52,0.2)`),G(e,-1,13,34,4,.2)}function xa(e,t,n,r){let i=e.buf;r&&(vi(i,1,8,30,6,t.ped),i.hline(1,30,8,t.ped.dk),i.hline(2,29,11,t.ped.lt));for(let e of[0,29])i.rect(e,8,3,8,t.legs.base),i.vline(e,8,15,t.legs.lt),i.vline(e+2,8,15,t.legs.dk),i.hline(e,e+2,15,t.legs.dd);r||(vi(i,19,8,10,8,t.ped),i.hline(19,28,11,t.ped.dk),i.hline(19,28,12,t.ped.lt),i.hline(22,25,9,t.ped.dd),i.hline(22,25,13,t.ped.dd)),_i(i,0,-6,32,12,t.top),yi(i,1,-5,30,10,t.top,n),i.hline(0,31,6,t.edge.base),i.hline(0,31,7,t.edge.dk),i.set(0,6,t.edge.lt)}function Sa(e,t,n){let r=e.buf,i=hi(t,11),a=t%6,o=gi(i,ya),s,c;switch(a){case 1:s=Oi(r,2,-17,16,11),c=Oi(r,18,-16,13,10),ki(r,c,`sheet`,t),Ei(r,6,-1,11,n),Di(r,20,0,n),wi(r,26,-2,o);break;case 2:s=Oi(r,5,-17,16,11),r.rect(22,-9,9,6,`#3a404d`),r.hline(22,30,-9,`#4d5464`),c={x:23,y:-8,w:7,h:4},ki(r,c,`ide`,t),r.rect(21,-3,11,2,`#c9ced6`),r.hline(21,31,-2,`#9aa1ad`),r.hline(22,31,-1,n===`onLight`?`rgba(40,46,70,0.3)`:`rgba(60,40,40,0.2)`),Ei(r,8,-1,10,n),Mi(r,1,-3);break;case 3:s=Oi(r,8,-17,16,11),r.rect(22,-15,2,2,`#f7d154`),r.rect(9,-15,2,2,`#ff9fb2`),Ei(r,11,-1,10,n),Di(r,23,0,n),Ni(r,2,-5),Ti(r,24,-4,6,4,n),wi(r,3,0,o);break;case 4:s=Oi(r,4,-17,15,11),c=Oi(r,19,-17,12,10),ki(r,c,`chart`,t),Ei(r,7,-1,11,n),Di(r,21,0,n),Ti(r,1,-2,5,4,n);break;case 5:s=Oi(r,8,-17,16,11),Ei(r,11,-1,10,n),Di(r,23,0,n),r.hline(2,6,-4,`#3a3f4b`),r.set(1,-3,`#3a3f4b`),r.set(7,-3,`#3a3f4b`),r.rect(1,-2,2,2,`#e2604f`),r.rect(6,-2,2,2,`#e2604f`),wi(r,26,-3,o),ji(r,28,2);break;default:s=Oi(r,8,-17,16,11),Ei(r,11,-1,10,n),Di(r,23,0,n),wi(r,3,-2,o),Ti(r,25,-4,6,4,n),Mi(r,26,2)}return{screen:s,screen2:c}}function Ca(e){return e===`white`?`onLight`:`light`}function wa(e){let t=U(2,1,20),n=Math.max(0,Math.floor(e));for(let e=0;e<n;e++)Ti(t.buf,22+e%2,-3-e,7,4,`onLight`);return t}function Ta(e,t){let n=U(2,1,20);xa(n,va(e),t,!1);let r=Sa(n,t,Ca(e));return n.buf.outline(),ba(n.buf),n.rects={screen:di(n,r.screen.x,r.screen.y,r.screen.w,r.screen.h)},r.screen2&&(n.rects.screen2=di(n,r.screen2.x,r.screen2.y,r.screen2.w,r.screen2.h)),{base:n}}function Ea(e,t){let n=U(2,1,12),r=va(e),i=n.buf;xa(n,r,t,!0);let a=hi(t,12),o=t%4,s=gi(a,ya),c=Ca(e),l=e===`dark`?`mid`:`light`;return o===1?(Ai(i,2,-7,15,10,l),Ai(i,17,-6,13,9,l)):(Ai(i,8,-7,16,10,l),o===2?Mi(i,26,0):Ti(i,25,-1,6,4,c),o===3?Ni(i,2,-3):wi(i,2,0,s)),i.outline(),ba(i),{base:n}}var Da={black:`#41465a`,blue:`#3f62a3`,red:`#b44a4a`,green:`#3f8a62`,gray:`#8b929e`};function Oa(e){return z(Da[e??`black`]??Da.black,.07)}function ka(e){let t=`#565d6b`,n=`#23262e`;e.hline(3,12,13,t),e.hline(5,10,14,t),e.set(3,13,`#6c7382`);for(let[t,r]of[[2,14],[13,14],[4,15],[11,15]])e.set(t,r,n),e.set(t+(t<8?1:-1),r,n);e.rect(7,9,2,4,`#a3aab6`),e.vline(8,9,12,`#7d8592`)}function Aa(e){let t=Oa(e),n=U(1,1,6),r=n.buf;ka(r),r.rect(2,4,12,6,t.lt),r.hline(3,12,4,t.hi),r.hline(2,13,8,t.base),r.hline(2,13,9,t.dk),r.set(2,4,t.base),r.set(13,4,t.base),r.outline(),G(r,1,13,14,3,.22);let i=U(1,1,6),a=i.buf;return a.rect(4,7,8,6,t.base),a.hline(5,10,6,t.lt),a.hline(4,11,7,t.lt),a.set(5,7,t.hi),a.set(6,7,t.hi),a.vline(4,8,11,t.lt),a.vline(11,7,12,t.dk),a.hline(5,10,9,t.dk),a.hline(5,10,10,t.dk),a.hline(4,11,12,t.dd),a.rect(7,13,2,1,`#4a505c`),a.outline(),{base:n,front:i}}function ja(e){let t=Oa(e),n=U(1,1,10),r=n.buf;ka(r),r.rect(3,-6,10,10,t.base),r.hline(4,11,-7,t.lt),r.rect(4,-5,8,7,t.lt),r.hline(5,10,-5,t.hi),r.vline(12,-6,3,t.dk),r.hline(3,12,3,t.dd),r.rect(7,4,2,2,`#4a505c`),r.rect(2,5,12,5,t.lt),r.hline(3,12,5,t.hi),r.hline(2,13,9,t.dk),r.hline(2,13,10,t.dd);for(let e of[1,13])r.rect(e,3,2,5,`#3a3f4b`),r.set(e,3,`#5a6070`);return r.outline(),G(r,1,13,14,3,.22),{base:n}}function Ma(e){let t=U(2,1,22),n=t.buf,r=W.oak,i=hi(e,21);_i(n,0,-21,32,3,r),n.rect(0,-18,32,34,r.dk),n.rect(2,-17,28,31,L(r.dd,-.12)),n.vline(0,-18,15,r.lt),n.vline(1,-18,15,r.base),n.vline(30,-18,15,r.base),n.vline(31,-18,15,r.dd);let a=[-8,3,15];for(let e of a)n.hline(1,30,e,r.lt),n.hline(1,30,e+1,r.dk);return n.hline(0,31,15,r.dd),a.forEach((t,r)=>{let a=t-1,o=3;for(;o<29;){let t=i();if(t<.12&&o<25)Ri(n,o,a-3,4,4,W.ceramic),Fi(n,o+2,a-5,2.5,2,W.leaf,e+o+r*7),o+=5;else if(t<.2&&o<24){let e=gi(i,[`#e9e4d6`,`#c9a46e`,`#9fb6cf`]);n.rect(o,a-4,5,5,e),n.hline(o,o+4,a-4,L(e,.1)),n.rect(o+1,a-2,3,1,L(e,-.2)),o+=6}else if(t<.26&&o<26)n.rect(o+1,a-4,3,2,`#f2c14e`),n.set(o,a-4,`#d9a42e`),n.set(o+4,a-4,`#d9a42e`),n.set(o+2,a-2,`#d9a42e`),n.rect(o+1,a-1,3,2,`#6b4a32`),o+=6;else{let e=2+Math.floor(i()*4);for(let t=0;t<e&&o<29;t++){let e=1+Math.floor(i()*2),t=6+Math.floor(i()*4);Pi(n,o,a-t+1,e,t,gi(i,pi)),o+=e}i()<.3&&o<26?(n.line(o,a,o+3,a-6,gi(i,pi),1),n.line(o+1,a,o+4,a-6,gi(i,pi),1),o+=5):o+=1}}}),n.outline(),G(n,-1,13,34,4,.22),{base:t}}function Na(e){let t=U(1,1,22),n=t.buf,r=z(`#ecebe6`,.05),i=hi(e,23);_i(n,0,-21,16,3,r),n.rect(0,-18,16,34,r.dk),n.rect(1,-17,14,31,`#7d8592`),n.vline(0,-18,15,r.lt),n.vline(15,-18,15,r.dd);let a=[-8,3,15];for(let e of a)n.hline(1,14,e,r.lt),n.hline(1,14,e+1,r.dk);let o=[-17,-6,5],s=[`#3f7fd8`,`#ec8a3c`,`#4cae6a`,`#3f7fd8`,`#ec8a3c`,`#e05a5a`,`#f2c14e`];return o.forEach((e,t)=>{let r=a[t]-1,o=r-e+1;if(t===2&&i()<.6){n.rect(2,r-6,6,7,W.cardboard.base),n.hline(2,7,r-6,W.cardboard.lt),n.rect(3,r-4,4,2,`#f4efe2`),n.rect(8,r-5,6,6,W.cardboard.dk),n.hline(8,13,r-5,W.cardboard.base),n.rect(9,r-3,4,2,`#f4efe2`);return}let c=2;for(;c<14;){let e=gi(i,s),t=Math.min(o-1,8+Math.floor(i()*2));n.rect(c,r-t+1,2,t,e),n.vline(c,r-t+1,r,L(e,.1)),n.set(c,r-t+3,`#f4f2ee`),n.set(c+1,r-t+3,`#f4f2ee`),n.set(c+1,r-1,L(e,-.2)),c+=2,i()<.12&&(c+=1)}}),n.outline(),G(n,0,13,16,4,.22),{base:t}}function Pa(){let e=U(1,1,8),t=e.buf,n=z(`#c3c9d2`,.06);_i(t,1,-7,14,4,n),vi(t,1,-3,14,19,n);for(let e of[3,9])t.hline(1,14,e,n.dd),t.hline(1,14,e+1,n.lt);for(let e of[-1,5,11])t.rect(6,e,4,1,`#7d8592`),t.rect(6,e+1,4,1,`#eef1f5`),t.set(5,e+1,`#9aa2ae`);return t.set(2,-3,n.hi),Mi(t,9,-9),t.outline(),G(t,0,13,16,4,.22),{base:e}}function Fa(){let e=U(1,1,14),t=e.buf,n=z(`#dfe2e7`,.05),r=z(`#7b8391`,.06);vi(t,0,2,16,14,n);for(let e of[6,10])t.hline(1,14,e,n.dd),t.rect(6,e+1,4,1,r.base);return _i(t,0,-11,16,6,n),t.rect(1,-10,14,3,`#f4f5f7`),t.hline(1,14,-8,`#c9ced6`),vi(t,0,-5,16,7,n),t.rect(10,-10,5,3,r.base),t.rect(11,-9,3,1,`#7fd0ff`),t.set(14,-8,`#5fd07a`),t.rect(2,-4,9,2,`#3d4350`),t.rect(3,-5,7,2,`#fbfbf8`),t.hline(3,9,-3,`#e3e1da`),t.set(13,-2,`#5fd07a`),t.outline(),G(t,-1,13,18,4,.22),{base:e}}function Ia(){let e=U(1,1,2),t=e.buf,n=z(`#8a96a8`,.07);for(let e=7;e<=15;e++){let r=+(e>13);t.hline(4+r,11-r,e,n.base),t.set(4+r,e,n.lt),t.set(11-r,e,n.dk)}return t.hline(5,10,15,n.dk),t.ellipse(8,6.5,4.5,2,n.lt),t.ellipse(8,6.6,3.5,1.3,`#3b4150`),t.rect(6,5,3,2,`#f4f2ee`),t.set(8,5,`#d8d4ca`),t.set(9,6,`#f7d154`),t.outline(),G(t,3,14,10,2,.22),{base:e}}function La(e,t){let n=U(1,1,10),r=n.buf,i=e??`fern`;if(i===`succulent`){Ri(r,4,9,8,7,W.ceramic),r.rect(5,9,6,1,`#5b4636`);let e=z(`#7fbf9f`,.08);[[3,8,6,5],[13,8,10,5],[5,5,7,3],[11,5,9,3],[8,3,8,6],[4,7,8,6],[12,7,8,6]].forEach(([t,n,i,a],o)=>Li(r,i,a+2,t,n,3,o<2?z(e.dk,.08):e,!0)),r.set(8,5,e.hi),r.set(7,6,e.lt)}else if(i===`flower`){Ri(r,4,9,8,7,W.terracotta),r.rect(5,9,6,1,`#5b4636`);let e=W.leaf;for(let[t,n]of[[2,6],[14,5],[5,2],[11,2],[8,4]])Li(r,8,9,t,n,3,e,t<8);let n=gi(hi(t,5),[`#f26d8a`,`#f2c14e`,`#ffffff`,`#b07ae8`]);for(let[e,t]of[[4,1],[10,0],[7,3],[12,4],[3,5]])r.set(e,t,n),r.set(e+1,t,L(n,.12)),r.set(e,t+1,L(n,-.12)),r.set(e+1,t+1,`#f7d154`)}else{Ri(r,4,9,8,7,W.terracotta),r.rect(5,9,6,1,`#5b4636`);let e=W.leaf;[[0,7,0],[16,7,0],[2,1,1],[14,1,0],[5,-3,1],[11,-3,1],[8,-5,1],[-1,11,0],[17,11,0]].forEach(([t,n,i])=>Li(r,8,9,t,n,2.6,i?e:z(e.dk,.07),t<8)),r.set(8,-5,e.hi)}return r.outline(),G(r,3,14,10,2,.24),{base:n}}function Ra(e,t){let n=U(1,1,24,6),r=n.buf,i=e??`ficus`;if(i===`bonsai`){let e=W.walnut;_i(r,1,7,14,3,e),vi(r,1,10,14,3,e);for(let t of[2,12])r.rect(t,13,2,3,e.dd);let n=z(`#4f6a8f`,.07);r.rect(3,4,10,1,n.lt),r.rect(3,5,10,2,n.base),r.hline(4,11,4,`#5b4636`),r.vline(12,5,6,n.dk),r.hline(4,11,6,n.dk);let i=z(`#7a5a40`,.08);r.line(7,4,6,0,i.base,2),r.line(6,0,9,-4,i.base,2),r.line(9,-4,8,-8,i.base,1),r.line(8,-3,4,-5,i.base,1),r.line(9,-5,12,-6,i.base,1),r.set(6,3,i.dk),r.set(9,4,i.lt),r.set(5,4,i.lt),Fi(r,4,-6.5,3.6,2.2,W.leafDark,t+3),Fi(r,12.5,-7.5,3.2,2,W.leafDark,t+4),Fi(r,8.5,-10.5,4,2.4,W.leaf,t+5)}else if(i===`palm`){Ri(r,3,6,10,10,W.ceramic),r.rect(4,6,8,1,`#5b4636`);let e=W.leaf,t=z(W.leaf.dk,.07);for(let e of[6,8,10])r.line(8,6,e,-4,`#86a04f`,1);let n=[[7,-3,-2,-20,t],[9,-3,17,-19,t],[7,-2,-5,-8,e],[9,-2,21,-8,e],[8,-3,8,-23,e]];for(let[e,t,i,a,o]of n)Ii(r,e,t,i,a,6,o,`pinnate`)}else if(i===`monstera`){Ri(r,3,6,10,10,W.terracotta),r.rect(4,6,8,1,`#5b4636`);let e=z(`#43995a`,.08),t=z(`#2f7a45`,.08),n=[[7,-7,1,-17,9,t],[9,-7,16,-16,9,t],[8,-6,9,-21,9,e],[6,1,-3,-6,9,e],[10,1,19,-5,9,e],[8,3,6,-5,7,t]];for(let[e,t]of n)r.line(8,6,e,t,`#2f6b3d`);for(let[e,t,i,a,o,s]of n)Ii(r,e,t,i,a,o,s,`monstera`)}else{Ri(r,3,6,10,10,W.ceramic),r.rect(4,6,8,1,`#5b4636`);let e=`#7a5a3c`;r.line(8,6,8,-4,e,1),r.line(7,6,7,0,`#8e6b48`,1),r.line(8,-1,5,-5,e,1),r.line(8,-3,11,-6,e,1),Fi(r,8,-10,7,5.5,W.leafDark,t+7),Fi(r,6,-13,4.6,3.6,W.leaf,t+8),Fi(r,11.5,-9,3.8,3.2,W.leaf,t+9),Fi(r,4,-7,3.2,2.6,W.leaf,t+10)}return r.outline(),G(r,2,14,12,3,.24),{base:n}}function za(e){let t=e??`h`,n=U(1,1,22,2),r=n.buf,i=z(`#f1f1ee`,.045),a=z(`#c3cad4`,.06);if(t===`v`){[`#aab2be`,`#fbfbf9`,`#f0f0ec`,`#dce9f3`,`rgba(130,190,230,0.75)`,`#e1e1dc`,`#d0d0cb`,`#9aa2ae`].forEach((e,t)=>r.vline(4+t,-16,15,e));for(let e=-16;e<16;e+=7)r.set(8,e,`rgba(255,255,255,0.8)`);return bi(r,12,-16,2,32,`rgba(30,34,52,0.12)`),{base:n}}if(t===`end`)return _i(r,4,3,8,4,i),vi(r,4,7,8,9,i),r.hline(4,11,13,R(i.dk,`#9aa2ae`,.5)),r.rect(6,-18,4,22,a.base),r.vline(6,-18,3,a.hi),r.vline(9,-18,3,a.dk),r.hline(6,9,-18,a.hi),r.outline(),G(r,3,13,10,4,.2),{base:n};r.rect(0,-14,16,20,`#000000`),r.rect(0,-17,16,3,a.lt),r.hline(0,15,-17,a.hi),r.hline(0,15,-15,a.dk),_i(r,0,6,16,3,i),vi(r,0,9,16,7,i),r.hline(0,15,14,R(i.dk,`#9aa2ae`,.5)),r.outline(),r.clearRect(0,-14,16,20),r.rect(0,-14,16,20,`rgba(172,214,238,0.34)`),r.rect(0,-14,16,3,`rgba(255,255,255,0.22)`);for(let e=0;e<20;e++){let t=13-Math.floor(e*.6);r.set(t,-14+e,`rgba(255,255,255,0.3)`),r.set(t-2,-14+e,`rgba(255,255,255,0.14)`)}r.vline(0,-14,5,`rgba(195,202,212,0.85)`),r.hline(0,15,5,`rgba(120,150,175,0.35)`);for(let e=0;e<r.h;e++)r.clear(-1,e-r.oy),r.clear(16,e-r.oy);return G(r,0,14,16,3,.16),{base:n}}function Ba(e){let t=U(3,2,10),n=t.buf,r=W.white,i=hi(e,31);for(let e of[2,43])n.rect(e,21,3,11,W.steel.base),n.vline(e,21,31,W.steel.lt),n.vline(e+2,21,31,W.steel.dk);_i(n,0,-4,48,24,r),n.hline(0,47,20,r.base),n.hline(0,47,21,r.dk),n.rect(4,2,40,10,W.oak.lt),n.hline(4,43,2,W.oak.base),n.hline(4,43,11,W.oak.hi),yi(n,4,3,40,8,W.oak,e),n.rect(21,5,6,3,`#3a404d`),n.rect(22,5,4,1,`#5a6070`),n.set(24,6,`#5fd07a`);let a=(t,r,i)=>{i===`down`?(n.rect(t,r,9,5,`#3a404d`),n.hline(t,t+8,r,`#4d5464`),ki(n,{x:t+1,y:r+1,w:7,h:3},t<20?`ide`:`sheet`,e+t),n.rect(t-1,r+5,11,2,`#c9ced6`),n.hline(t-1,t+9,r+6,`#9aa1ad`)):(n.rect(t-1,r,11,2,`#c9ced6`),n.rect(t,r+2,9,4,`#aeb5c0`),n.hline(t,t+8,r+2,`#d6dbe2`),n.set(t+4,r+4,`#eef1f5`))};return a(6,-3,`down`),a(32,13,`up`),e%2==0?a(34,-3,`down`):Ti(n,34,-1,7,5),Ti(n,8,14,6,4),wi(n,18,14,gi(i,ya)),n.rect(29,-1,2,3,`rgba(190,225,245,0.9)`),n.set(29,-1,`#ffffff`),n.rect(16,-2,2,3,`rgba(190,225,245,0.9)`),n.set(16,-2,`#ffffff`),n.outline(),G(n,-1,28,50,5,.22),bi(n,4,22,40,8,`rgba(30,34,52,0.16)`),{base:t}}function Va(){let e=U(1,1,2),t=e.buf;t.ellipse(8,14.5,4,1.4,`#5b6272`),t.rect(7,8,2,6,`#9aa1ad`),t.vline(8,8,13,`#737b89`),t.hline(5,10,11,`#9aa1ad`);let n=z(`#3f7fd8`,.07);return t.ellipse(8,6,5.5,3,n.dk),t.ellipse(8,5.4,5.5,2.6,n.lt),t.set(5,4,n.hi),t.set(6,4,n.hi),t.outline(),G(t,3,13,10,3,.22),{base:e}}function Ha(){let e=U(1,1,26),t=e.buf;t.ellipse(8,14,4,1.5,`#3a3f4b`),t.hline(6,9,13,`#5a6070`),t.vline(8,-17,13,`#4a505c`),t.vline(7,-17,13,`#6b7282`);let n=z(`#f3e6c8`,.05);for(let e=0;e<7;e++){let r=3+Math.floor(e/2);t.hline(8-r,7+r,-24+e,e===0?n.hi:n.lt),t.set(8-r,-24+e,n.hi),t.set(7+r,-24+e,n.dk)}return t.hline(3,12,-17,n.dk),t.hline(5,10,-16,`#fff6d8`),t.outline(),G(t,3,13,10,3,.22),e.rects={glow:di(e,4,-20,8,6)},{base:e}}function Ua(){let e=U(1,1,20),t=e.buf,n=z(`#eceef1`,.05);_i(t,3,-5,10,3,n),vi(t,3,-2,10,18,n),t.vline(3,-2,15,n.hi),t.rect(5,1,2,2,`#4a86d8`),t.rect(9,1,2,2,`#e05a5a`),t.set(5,1,`#8ab8f0`),t.set(9,1,`#f08a8a`),t.rect(4,5,8,2,`#c3c9d2`),t.hline(5,10,5,`#9aa2ae`),t.rect(4,8,8,7,n.base),t.hline(4,11,8,n.dk),t.rect(10,11,1,2,`#9aa2ae`),t.rect(5,-6,6,1,`#5b8fd0`);for(let e=-17;e<=-7;e++){let n=+(e<-15);t.hline(4+n,11-n,e,`rgba(92,170,240,0.78)`)}return t.rect(6,-19,4,2,`#3f74c0`),t.vline(5,-15,-8,`rgba(255,255,255,0.65)`),t.vline(6,-14,-9,`rgba(255,255,255,0.3)`),t.hline(5,10,-12,`rgba(60,120,200,0.6)`),t.vline(10,-15,-8,`rgba(40,90,170,0.55)`),t.rect(13,-1,2,6,`#f4f6f8`),t.set(14,-1,`#c9ced6`),t.outline(),G(t,1,13,14,4,.22),{base:e}}function Wa(e,t,n,r,i){for(let a=n+1;a<=n+i;a++)e.under(t+r,a,`rgba(30,34,52,0.16)`);for(let a=t+1;a<=t+r;a++)e.under(a,n+i,`rgba(30,34,52,0.16)`)}function Ga(){let e=ui(3),t=e.buf,n=z(`#c3cad4`,.06);t.rect(2,-27,44,19,n.base),t.hline(2,45,-27,n.hi),t.vline(2,-27,-9,n.lt),t.vline(45,-27,-9,n.dk),t.hline(2,45,-9,n.dk),t.rect(3,-26,42,17,`#fbfcfd`),t.line(32,-26,26,-10,`rgba(210,225,240,0.5)`),t.line(35,-26,29,-10,`rgba(210,225,240,0.35)`),t.rect(5,-8,38,2,n.base),t.hline(5,42,-8,n.lt);for(let[e,n]of[[0,`#e05a5a`],[3,`#3f7fd8`],[6,`#2b2f3b`],[9,`#4cae6a`]])t.rect(10+e,-9,2,1,n);return t.rect(32,-10,5,2,`#3a3f4b`),t.hline(32,36,-10,`#f2efe6`),t.outline(),Wa(t,1,-28,46,22),e.rects={board:di(e,4,-25,40,15)},{base:e}}function Ka(){let e=ui(2),t=e.buf,n=z(`#f4f4f1`,.05);t.rect(2,-27,28,2,n.lt),t.rect(2,-10,28,2,n.base),t.rect(2,-27,2,19,n.lt),t.rect(28,-27,2,19,n.base),t.hline(2,29,-27,n.hi),t.vline(29,-27,-9,n.dk),t.rect(15,-25,2,15,n.base),t.vline(16,-25,-11,n.dk),t.hline(4,27,-25,`rgba(40,50,70,0.25)`);for(let e of[3,16])t.line(4+e+6,-25,4+e,-11,`rgba(255,255,255,0.28)`),t.line(4+e+7,-25,4+e+1,-11,`rgba(255,255,255,0.16)`);return t.rect(1,-8,30,2,n.lt),t.hline(1,30,-8,n.hi),t.hline(1,30,-7,n.dk),t.outline(),Wa(t,1,-27,30,22),e.rects={glass:di(e,4,-25,24,15)},{base:e}}function qa(){let e=ui(1),t=e.buf,n=-21.5;t.ellipse(8,n,6.5,6.5,`#3a3f4b`),t.ellipse(8,n,5.5,5.5,`#fbfbf8`),t.ellipse(7,-22.5,3,3,`#ffffff`);for(let[e,r]of[[0,-5],[5,0],[0,4],[-5,0]])t.set(Math.floor(8+e),Math.floor(n+r),`#5a6070`);return t.outline(),Wa(t,1,-29,14,14),e.rects={face:di(e,3,-27,10,10)},{base:e}}function Ja(e){let t=ui(1),n=t.buf;switch(n.rect(2,-28,12,16,`#2f3440`),e??`code`){case`coffee`:n.rect(3,-27,10,14,`#f2d7b0`),n.rect(3,-17,10,4,`#c98a52`),wi(n,6,-22,`#e2604f`),n.set(7,-24,`#ffffff`),n.set(8,-25,`#ffffff`),n.set(7,-26,`#ffffff`),n.hline(5,10,-15,`#f4efe2`);break;case`rocket`:n.rect(3,-27,10,14,`#24325a`);for(let[e,t]of[[1,2],[8,1],[6,5],[2,9],[9,8]])n.set(3+e,-27+t,`#f7e7a1`);n.rect(7,-24,2,6,`#f4f2ee`),n.set(7,-25,`#e05a5a`),n.set(8,-25,`#e05a5a`),n.set(7,-22,`#5bc0de`),n.set(6,-19,`#e05a5a`),n.set(9,-19,`#e05a5a`),n.rect(7,-18,2,2,`#f2a03d`),n.set(7,-16,`#f7d154`),n.hline(3,12,-14,`#3b4a7a`);break;case`cat`:{n.rect(3,-27,10,14,`#f7c9d4`);let e=`#3a3f4b`;n.set(5,-23,e),n.set(10,-23,e),n.rect(5,-22,6,5,e),n.set(6,-20,`#f7d154`),n.set(9,-20,`#f7d154`),n.set(7,-19,`#e47aa8`),n.set(8,-19,`#e47aa8`),n.hline(4,11,-15,`#e47aa8`);break}case`bug`:{n.rect(3,-27,10,14,`#f7d154`);let e=`#3a3f4b`;n.rect(6,-22,4,5,`#4cae6a`),n.vline(8,-22,-18,e),n.rect(7,-24,2,2,e);for(let t of[5,7,9])n.set(5,-27+t,e),n.set(10,-27+t,e);n.line(4,-26,11,-15,`#e05a5a`);break}case`ship_it`:n.rect(3,-27,10,14,`#bfe3f2`),n.rect(3,-18,10,5,`#3f7fd8`),n.hline(3,12,-18,`#8fc8f0`),n.rect(5,-20,6,2,`#e05a5a`),n.hline(6,9,-18,`#a83232`),n.vline(8,-26,-21,`#6b4a32`),n.rect(9,-25,3,2,`#f4f2ee`),n.set(4,-25,`#f7d154`);break;default:{n.rect(3,-27,10,14,`#1f2433`);let e=[`#ff79c6`,`#8be9fd`,`#f1fa8c`,`#50fa7b`,`#bd93f9`];for(let t=0;t<6;t++)n.hline(4+t%3,5+t*3%5+2,-26+t*2,e[t%e.length]);break}}return n.outline(),Wa(n,1,-29,14,18),{base:t}}function Ya(e){let t=ui(2),n=t.buf,r=z(`#c89b5c`,.07);n.rect(3,-27,26,17,r.base),n.hline(3,28,-27,r.hi),n.vline(3,-27,-11,r.lt),n.vline(28,-27,-11,r.dk),n.hline(3,28,-11,r.dk);let i=hi(e,41)()<.5;for(let e=0;e<13;e++)n.hline(5,26,-25+e,L(i?`#f6c48a`:`#9fd3f0`,-e*.012));n.ellipse(20,-22,2,2,i?`#fff2c2`:`#fffbe6`);let a=i?`#7a5a8a`:`#5a7fa8`;for(let t=0;t<22;t++){let r=Math.round(3+2.5*Math.sin(t*.55+e)+1.5*Math.sin(t*1.3));n.vline(5+t,-16-r,-16,a),n.set(5+t,-16-r,L(a,.15))}return n.rect(5,-16,22,4,i?`#4f8a6a`:`#3f7fb0`),n.hline(8,14,-15,`rgba(255,255,255,0.5)`),n.outline(),Wa(n,2,-28,28,19),t.rects={art:di(t,5,-25,22,13)},{base:t}}function Xa(){let e=ui(2),t=e.buf;return t.rect(1,-27,30,18,`#23262f`),t.hline(1,30,-27,`#3a3f4b`),t.hline(1,30,-10,`#15171d`),t.rect(2,-26,28,15,`#151b26`),t.line(21,-26,13,-12,`rgba(255,255,255,0.08)`),t.line(23,-26,15,-12,`rgba(255,255,255,0.05)`),t.set(28,-11,`#e05a5a`),t.outline(),Wa(t,0,-28,32,20),e.rects={tv:di(e,2,-26,28,15)},{base:e}}function Za(e){let t=ui(1),n=t.buf,r=(e??`on`)===`on`;return n.rect(6,-19,5,7,`#f6f6f3`),n.hline(6,10,-19,`#ffffff`),n.vline(10,-19,-13,`#d3d6dc`),n.hline(6,10,-13,`#c9cdd4`),n.rect(7,-17,3,3,r?`#e9ebee`:`#d5d8de`),n.hline(7,9,r?-17:-15,r?`#ffffff`:`#b9bec7`),n.hline(7,9,r?-15:-17,r?`#c3c8d0`:`#f4f5f7`),n.set(8,-18,r?`#7be08a`:`#9aa1ad`),n.outline(),{base:t}}function Qa(e){let t=ui(2,2),n=t.buf,r=Math.max(0,Math.min(4,Math.round(e))),i=z(`#aeb6c2`,.06),a=z(`#c9d0d9`,.05);n.rect(0,-28,32,28,i.base),n.hline(0,31,-28,i.hi),n.vline(0,-28,-1,i.lt),n.vline(31,-28,-1,i.dk),n.rect(10,-27,12,3,`#22262f`);let o=r>0;n.set(13,-26,o?`#5fd07a`:`#3b4a3f`),n.set(12,-25,o?`#5fd07a`:`#3b4a3f`),n.set(14,-25,o?`#5fd07a`:`#3b4a3f`),n.rect(16,-26,4,1,o?`#f2c14e`:`#4a4535`),n.rect(3,-23,26,23,`#f3e2bf`),n.rect(3,-23,26,3,`#fff3d6`),n.rect(5,-20,22,16,`#e4caa0`),n.hline(5,26,-11,`#b9c0ca`),n.rect(3,-4,26,4,`#b89a72`),n.hline(3,28,-4,`#a5865f`);let s=r*3,c=(e,t)=>{if(!(t<=0)){n.rect(e,-23,t,23,a.base),n.hline(e,e+t-1,-23,a.hi),n.vline(e,-23,-1,a.lt),n.vline(e+t-1,-23,-1,a.dk);for(let r=2;r<t-1;r+=4)n.vline(e+r,-21,-3,`rgba(255,255,255,0.18)`)}};return c(3,13-s),c(16+s,13-s),r===0&&n.vline(16,-23,-1,a.dd),n.rect(29,-15,2,4,`#22262f`),n.set(29,-14,o?`#f2c14e`:`#6b7282`),n.set(29,-12,`#6b7282`),n.outline(),{base:t}}function $a(){let e=ui(2,3),t=e.buf,n=z(`#f2f1ed`,.05);return t.rect(-2,-27,3,27,n.base),t.vline(-2,-27,-1,n.hi),t.vline(0,-26,-1,n.dk),t.rect(31,-27,3,27,n.base),t.vline(31,-26,-1,n.dk),t.vline(33,-27,-1,n.dd),t.rect(-2,-30,36,3,n.lt),t.hline(-2,33,-30,n.hi),t.hline(1,30,-27,`rgba(30,34,52,0.35)`),t.outline(),{base:e}}function eo(){let e=ui(3),t=e.buf,n=z(`#3a4256`,.07);return t.rect(3,-28,42,11,n.base),t.hline(3,44,-28,n.lt),t.hline(3,44,-18,n.dd),t.rect(4,-27,40,9,`#f7f3e8`),t.hline(4,43,-27,`#ffffff`),t.hline(4,43,-19,`#e6e0cf`),t.set(5,-26,`#b9c0ca`),t.set(42,-26,`#b9c0ca`),t.set(5,-20,`#b9c0ca`),t.set(42,-20,`#b9c0ca`),t.outline(),Wa(t,2,-29,44,13),e.rects={sign:di(e,7,-26,34,7)},{base:e}}function to(){let e=ui(1),t=e.buf,n=z(`#c3cad4`,.06);return t.rect(2,-28,12,14,n.base),t.hline(2,13,-28,n.hi),t.vline(13,-28,-15,n.dk),t.rect(3,-27,10,12,`#cfe6f2`),xi(t,3,-27,10,12,{alpha:.5}),t.line(10,-27,5,-16,`rgba(255,255,255,0.75)`),t.outline(),Wa(t,1,-29,14,16),e.rects={glass:di(e,3,-27,10,12)},{base:e}}function no(e){let t=ui(2),n=t.buf,r=hi(e,51),i=W.oak,a=e=>{n.rect(1,e,30,2,i.lt),n.hline(1,30,e,i.hi),n.hline(1,30,e+1,i.dk);for(let t of[4,26])n.rect(t,e+2,2,2,`#5a6070`)};a(-19),a(-9);let o=3,s=3+Math.floor(r()*3);for(let e=0;e<s;e++){let e=1+Math.floor(r()*2),t=5+Math.floor(r()*3);Pi(n,o,-19-t,e,t,gi(r,pi)),o+=e}n.line(o,-20,o+3,-25,gi(r,pi)),n.line(o+1,-20,o+4,-25,gi(r,pi)),Ri(n,21,-23,5,4,W.ceramic),Fi(n,23.5,-25,3,2.2,W.leaf,e+2),n.line(22,-23,20,-20,W.leaf.dk),n.line(25,-23,27,-19,W.leaf.base);let c=e%3;if(c===0)n.rect(3,-14,6,5,`#e9e4d6`),n.hline(3,8,-14,`#f7f3e8`),n.rect(4,-12,4,1,`#c9bfa6`),n.rect(11,-13,3,2,`#f2c14e`),n.set(10,-13,`#d9a42e`),n.set(14,-13,`#d9a42e`),n.set(12,-11,`#d9a42e`),n.rect(11,-10,3,1,`#6b4a32`),wi(n,18,-13,`#3f7fd8`),Mi(n,24,-12);else if(c===1){for(let e=0;e<4;e++)Pi(n,4+e*2,-16,2,7,gi(r,pi));n.rect(14,-13,7,4,`#c99a5e`),n.hline(14,20,-13,`#dcb27a`),n.rect(23,-15,4,6,`#3a3f4b`),n.rect(24,-14,2,2,`#8fc8f0`)}else{Mi(n,4,-12),n.rect(10,-15,5,6,`#f4f2ee`),n.rect(11,-14,3,3,`#e47aa8`);for(let e=0;e<3;e++)Pi(n,18+e*2,-15+e%2,2,6-e%2,gi(r,pi))}return n.outline(),{base:t}}var ro={desk:6,desk_back:4,bookshelf:4,binder_shelf:4,meeting_table:2,shelf_wall:3,painting:2,coffee_table:2,plant_small:3,plant_tall:3};function io(e,t,n,r){let i=on[e],a=i.variants?t&&i.variants.includes(t)?t:i.variants[0]:void 0,o=i.states??1,s=Math.max(0,Math.min(o-1,Math.floor(n??0))),c=ro[e]??1;return{variant:a,state:s,vseed:c>1?(Math.floor(r??0)%c+c)%c:0}}function ao(e,t,n,r){switch(e){case`desk`:return Ta(t,r);case`desk_back`:return Ea(t,r);case`office_chair`:return Aa(t);case`office_chair_front`:return ja(t);case`bookshelf`:return Ma(r);case`filing_cabinet`:return Pa();case`printer`:return Fa();case`trash_bin`:return Ia();case`plant_small`:return La(t,r);case`plant_tall`:return Ra(t,r);case`glass_partition`:return za(t);case`binder_shelf`:return Na(r);case`meeting_table`:return Ba(r);case`stool`:return Va();case`floor_lamp`:return Ha();case`water_cooler`:return Ua();case`whiteboard`:return Ga();case`window`:return Ka();case`clock`:return qa();case`poster`:return Ja(t);case`painting`:return Ya(r);case`tv`:return Xa();case`light_switch`:return Za(t);case`elevator`:return Qa(n);case`door_frame`:return $a();case`sign`:return eo();case`mirror`:return to();case`shelf_wall`:return no(r);case`counter`:return Ui(t);case`counter_sink`:return Wi();case`coffee_machine`:return Gi(n);case`microwave`:return Ki();case`fridge`:return qi();case`vending_machine`:return Ji();case`cafe_table`:return Yi();case`cafe_chair`:return Zi(t);case`sofa`:return ra(t);case`armchair`:return ca(t);case`coffee_table`:return la(r);case`pingpong_table`:return ua();case`beanbag`:return fa(t);case`arcade`:return pa();case`toilet_stall`:return ma(n);case`sink`:return ha();case`reception_desk`:return ga(r);case`bench`:return _a()}}function oo(e,t,n,r){let i=io(e,t,n,r),a=ao(e,i.variant,i.state,i.vseed);return{base:fi(a.base),front:a.front?fi(a.front):void 0}}var so={t:`#e6b37a`,c:`#c48a52`,C:`#8f5d36`,g:`#e4f3fc`,w:`#ffffff`,G:`#a6c9e3`,s:`#f5c451`,S:`#d6952a`},co={alert:{rows:[`....o....`,`...oyo...`,`...yky...`,`..yykyy..`,`..yykyy..`,`.yyykyyy.`,`.yyyyyyy.`,`yyyykyyyy`,`ddddddddd`],pal:{o:`#fff2a8`,y:`#f7c843`,k:`#4a3510`,d:`#d9a12a`}},question:{rows:[`..bbbbb..`,`.bbwwwbb.`,`bbwbbbwbb`,`bbbbbbwbb`,`bbbbbwbbb`,`bbbbwbbbb`,`bbbbbbbbb`,`.bbbwbbb.`,`..ddddd..`],pal:{b:`#4f8fe6`,w:`#ffffff`,d:`#3466b8`}},zzz:{rows:[`.....zzzz`,`.......z.`,`......z..`,`zzz..zzzz`,`..z......`,`.z.......`,`zzz......`],pal:{z:`#cfe3ff`}},check:{rows:[`..ggggg..`,`.ggggggg.`,`gggggggwg`,`ggggggwwg`,`gwggggwgg`,`gwwggwwgg`,`ggwwwwggg`,`.ggwwggg.`,`..ddddd..`],pal:{g:`#45b866`,w:`#ffffff`,d:`#2f8a4a`}},heart:{rows:[`.rr...rr.`,`rhrr.rrrr`,`rhrrrrrrr`,`rrrrrrrrr`,`.rrrrrrd.`,`..rrrrd..`,`...rrd...`,`....d....`],pal:{r:`#ef5a6f`,h:`#ffb3bf`,d:`#c23a50`}},coffee:{rows:[`..s..s...`,`.s..s....`,`..s..s...`,`wwwwwww..`,`wccccchhh`,`wrrrrrw.h`,`wrrrrrwhh`,`wwwwwww..`,`.ddddd...`],pal:{s:`#e6ecf5`,w:`#f4f2ee`,c:`#6b4226`,r:`#e2604f`,h:`#d6d2c8`,d:`#b9b3a6`}},music:{rows:[`...nnnnnn`,`...nhhhhn`,`...n....n`,`...n....n`,`...n....n`,`.nnn..nnn`,`nnnn.nnnn`,`.nn...nn.`],pal:{n:`#8d66cf`,h:`#b89aea`}},idea:{rows:[`..yyyyy..`,`.yhhyyyy.`,`yhhyyyyyy`,`yhyyyyyyy`,`yyyyyyyyd`,`.yyyyyyd.`,`..yyyyd..`,`..ggggg..`,`...ggg...`],pal:{y:`#ffd84d`,h:`#fff4b8`,d:`#e0b12e`,g:`#9aa2ae`}},sweat:{rows:[`...b...`,`...b...`,`..bbb..`,`.bwbbb.`,`.bwbbb.`,`bbbbbbb`,`.bbbbd.`,`..ddd..`],pal:{b:`#6fc3f2`,w:`#e6f6ff`,d:`#3f9ad6`}},star:{rows:[`....y....`,`...yhy...`,`...yhy...`,`yyyyhyyyy`,`.yyyyyyy.`,`..yyyyy..`,`..yyyyy..`,`.yyd.dyy.`,`.yd...dy.`],pal:{y:`#ffcf3f`,h:`#fff2a8`,d:`#d99e1f`}},lightning:{rows:[`....yyy`,`...yyy.`,`..yyy..`,`.yyyyyy`,`...yyy.`,`..yyy..`,`.yyd...`,`.yd....`,`yd.....`],pal:{y:`#ffd84d`,d:`#e0a62e`}},chat:{rows:[`.wwwwwwww.`,`wwwwwwwwww`,`wwkwwkwwkw`,`wwwwwwwwww`,`.wwwwwwww.`,`..ww......`,`.w........`],pal:{w:`#ffffff`,k:`#5b6b85`}},box:{rows:[`.hhhtthhh.`,`hhhhtthhhh`,`ccccttcccc`,`cccctttccd`,`ccccccccdd`,`cccllllccd`,`ccccccccdd`,`.ddddddddd`],pal:{h:`#e2b47a`,c:`#c99a5e`,t:`#f1dfb6`,l:`#8b6a43`,d:`#a87b45`}},hourglass:{rows:[`tcccccccC`,`CCCCCCCCC`,`.wgggggG.`,`.wsssssG.`,`..wsssG..`,`...gSG...`,`..wgsgG..`,`.wggsggG.`,`.wgsssSG.`,`tcccccccC`,`CCCCCCCCC`],pal:so},hourglass_flip:{rows:[`tc.......tc`,`tcw.....Gtc`,`tcwg...gGtc`,`tcggg.ggGtc`,`tcsssSggGtc`,`tcsss.ggGtc`,`tcSs...sStc`,`tcS.....Stc`,`tc.......tc`],pal:{...so,t:`#d9a46c`,c:`#a8723f`}},cobweb:{rows:[`wwwwwwwwwwww`,`wf...w....w.`,`w.f..w....w.`,`w..fw.....w.`,`w..wf....w..`,`www..f...w..`,`w.....f.w...`,`w......w....`,`w.....w.l.l.`,`w...ww.lkKkl`,`wwww....eke.`,`w......l...l`],pal:{w:`#ffffff`,f:`#d3dbe5`,k:`#3a3346`,K:`#6f6287`,e:`#fff7d6`,l:`#55496a`},outlineAlpha:.6,holeOutlineAlpha:.14},storm:{rows:[`...hHHh....`,`.hhHHHHhhh.`,`hhHhhhhhhcc`,`cccccccccdd`,`.dddddddddd`,`......yo..b`,`.b...yo...B`,`.B..yyyyo..`,`......yo...`,`.b...yo....`,`.B...o.....`],pal:{h:`#8d97ab`,H:`#b3bccc`,c:`#6b7489`,d:`#4f566a`,y:`#ffd84d`,o:`#e3a530`,b:`#9fd2f6`,B:`#5a9fd8`}},wave:{rows:[`..s.s.s..`,`..s.s.s.s`,`..s.s.s.s`,`s.sssssss`,`sssssssss`,`.sssssssd`,`..ssssssd`,`...ssssd.`],pal:{s:`#ffd2a8`,d:`#e0a87a`}},coin:{rows:[`..yyyy..`,`.yhwyyy.`,`yhyKKyyd`,`yhKyyyyd`,`yhKyyyyd`,`yyyKKyyd`,`.yyyyydd`,`..dddd..`],pal:{y:`#ffcf3f`,h:`#fff2a8`,w:`#ffffff`,K:`#d4931c`,d:`#c98a1c`}},sparkle:{rows:[`....y....`,`....y....`,`...yhy...`,`..yhwhy..`,`yyhwwwhyy`,`..yhwhy..`,`...yhy...`,`....y....`,`....y....`],pal:{y:`#ffe07a`,h:`#fff6c8`,w:`#ffffff`}},trophy:{rows:[`yhhhyyyyd`,`yhwhyyydy`,`y.hhyyd.y`,`.yhhyyd.y`,`..hyyyd..`,`...yyd...`,`....y....`,`..bbbbb..`,`.BBBBBBB.`],pal:{y:`#ffcf3f`,h:`#fff2a8`,w:`#ffffff`,d:`#d99e1f`,b:`#a8723f`,B:`#7a4f2a`}},hand_rock:{rows:[`.LL.LL.LL.`,`LsskssksSS`,`LsskssksSS`,`LssssssssS`,`LTTTTTsssS`,`.TTTTTssS.`,`..SSSSSS..`],pal:{L:`#ffe0c4`,s:`#f6c9a2`,S:`#d99d72`,k:`#c48660`,T:`#ecb68b`}},hand_paper:{rows:[`..L.L....`,`.LsLsL...`,`.LsLsLs..`,`.LsLsLs..`,`LLsssss..`,`sLssssss.`,`.sssssSS.`,`..ssssS..`,`..SSSS...`],pal:{L:`#ffe0c4`,s:`#f6c9a2`,S:`#d99d72`}},hand_scissors:{rows:[`.L...L...`,`.Ls..Ls..`,`..Ls.Ls..`,`..LsLs...`,`.LLsssk..`,`.LsksksS.`,`.sssssSS.`,`..SSSSS..`],pal:{L:`#ffe0c4`,s:`#f6c9a2`,S:`#d99d72`,k:`#c48660`}}};Object.keys(co);function lo(e){let t=co[e],n=Math.max(...t.rows.map(e=>e.length)),r=t.rows.length,i=new Cn(n+2,r+2);i.stamp(t.rows,1,1,t.pal);let a=t.outlineAlpha!==void 0||t.holeOutlineAlpha!==void 0?i.data.slice():null;if(i.outline(),a){let e=uo(t.outlineAlpha??1),n=uo(t.holeOutlineAlpha??t.outlineAlpha??1),r=fo(a,i.w,i.h);for(let t=0;t<i.w*i.h;t++){let o=t*4+3;a[o]===0&&i.data[o]>0&&(i.data[o]=r[t]?e:n)}}return{buf:i,ax:Math.floor((n+2)/2),ay:r+2}}function uo(e){return Math.round(Math.max(0,Math.min(1,e))*255)}function fo(e,t,n){let r=new Uint8Array(t*n),i=[],a=(a,o)=>{if(a<0||o<0||a>=t||o>=n)return;let s=o*t+a;r[s]||e[s*4+3]!==0||(r[s]=1,i.push(s))};for(let e=0;e<t;e++)a(e,0),a(e,n-1);for(let e=0;e<n;e++)a(0,e),a(t-1,e);for(;i.length;){let e=i.pop(),n=e%t,r=(e-n)/t;a(n+1,r),a(n-1,r),a(n,r+1),a(n,r-1)}return r}var po=128;function mo(e,t,n=0,r=0){let i=Math.imul(e|0,2654435761)^Math.imul(t|0,2246822519)^Math.imul(n|0,3266489917)^Math.imul(r|0,668265263);return i^=i>>>15,i=Math.imul(i,739982445),i^=i>>>12,i=Math.imul(i,695872825),i^=i>>>15,i>>>0}function ho(e,t,n=0,r=0){return mo(e,t,n,r)/4294967296}function go(e,t,n,r){let i=Math.floor(e/n),a=Math.floor(t/n),o=e/n-i,s=t/n-a,c=o*o*(3-2*o),l=s*s*(3-2*s),u=ho(i,a,0,r),d=ho(i+1,a,0,r),f=ho(i,a+1,0,r),p=ho(i+1,a+1,0,r);return u+(d-u)*c+(f-u)*l+(u-d-f+p)*c*l}function _o(e,t,n,r){let i=new Cn(po,po),a=t*po,o=n*po;switch(e){case`wood`:xo(i,a,o,r.seed);break;case`concrete`:Do(i,a,o,r.seed);break;case`marble`:jo(i,a,o,r.seed);break;case`sidewalk`:No(i,a,o,r.seed);break;default:for(let a=0;a<8;a++)for(let o=0;o<8;o++)i.ox=o*16,i.oy=a*16,vo(i,e,t*8+o,n*8+a,r);i.ox=0,i.oy=0}return i}function vo(e,t,n,r,i){let a=e=>ho(n,r,e,i.seed);switch(t){case`carpet`:{let t=i.tint??`#c9d1dc`,o=i.tint2??L(t,-.03),s=n+r&1,c=R(t,o,s?.55:.15);e.rect(0,0,16,16,c);let l=L(c,-.018);for(let t=1;t<15;t+=3)for(let n=1;n<15;n++)(n+t)%4!=0&&(s?e.set(n,t,l):e.set(t,n,l));for(let t=0;t<3;t++)e.set(Math.floor(a(t)*14)+1,Math.floor(a(t+9)*14)+1,L(c,t%2?.03:-.035));e.hline(0,15,15,L(c,-.06)),e.vline(15,0,15,L(c,-.06)),e.hline(0,14,0,L(c,.025)),e.vline(0,0,14,L(c,.025));break}case`tile_check`:for(let t=0;t<2;t++)for(let i=0;i<2;i++){let o=(i+t+n+r)%2?`#d2d8de`:`#f2ede4`;e.rect(i*8,t*8,8,8,o),e.hline(i*8,i*8+6,t*8,L(o,.02)),e.hline(i*8,i*8+7,t*8+7,L(o,-.045)),e.vline(i*8+7,t*8,t*8+7,L(o,-.045)),a(i+t*2)<.3&&e.set(i*8+2+Math.floor(a(5)*4),t*8+2+Math.floor(a(6)*4),L(o,-.02))}break;case`tile_white`:{let t=`#d3dae1`;e.rect(0,0,16,16,`#eef2f5`);for(let n=0;n<2;n++)e.hline(0,15,n*8+7,t),e.vline(n*8+7,0,15,t);for(let t=0;t<2;t++)for(let n=0;n<2;n++)e.hline(n*8,n*8+2,t*8,`#fbfcfd`);a(1)<.4&&e.set(Math.floor(a(2)*14),Math.floor(a(3)*14),`#e4eaef`);break}case`grass`:{let t=z(`#6cab57`,.045),o=go(n*16,r*16,48,i.seed+5),s=R(t.dk,t.lt,o);e.rect(0,0,16,16,s);for(let t=0;t<12;t++){let n=Math.floor(a(t)*16),r=Math.floor(a(t+20)*16),i=a(t+40)<.5?L(s,.05):L(s,-.05);e.set(n,r,i),a(t+60)<.5&&e.set(n,r-1,L(i,.03))}for(let n=0;n<2;n++){let r=2+Math.floor(a(n+80)*12),i=3+Math.floor(a(n+90)*11);e.set(r,i,t.dd),e.set(r-1,i-1,t.dk),e.set(r+1,i-1,t.dk),e.set(r,i-2,t.lt)}if(a(99)<.12){let t=3+Math.floor(a(100)*10),n=3+Math.floor(a(101)*10),r=[`#ffffff`,`#f7d154`,`#f28fb0`,`#b9a2f0`][Math.floor(a(102)*4)];e.set(t,n,r),e.set(t+1,n,r),e.set(t,n-1,r),e.set(t+1,n+1,`#f2c14e`)}break}case`street`:{let t=R(`#4b4f58`,`#565a63`,go(n*16,r*16,64,i.seed+9));e.rect(0,0,16,16,t);for(let t=0;t<14;t++)e.set(Math.floor(a(t)*16),Math.floor(a(t+30)*16),a(t+60)<.5?`#5f636c`:`#43464e`);break}default:e.rect(0,0,16,16,`#dcdedf`)}}function yo(e){return ln(e)}var bo=[`#c99668`,`#c48f61`,`#cf9f72`,`#c6925f`].map(e=>[e,L(e,.03),L(e,-.075),L(e,-.03),L(e,-.1),L(e,.03),L(e,-.12)].map(yo));function xo(e,t,n,r){for(let i=0;i<po;i++){let a=n+i,o=Math.floor(a/4),s=a-o*4,c=mo(o,0,1,r)%48;for(let n=0;n<po;n++){let a=t+n+c,l=Math.floor(a/48),u=a-l*48,d=mo(o,l,2,r),f=bo[d%bo.length],p=0;u===0?p=4:s===3?p=2:s===0?p=u===1?5:1:s===2&&u===10+(d>>>12)%20&&(d>>>20)%5==0?p=6:s===1+(d>>>5)%2&&(u+(d>>>8))%23<7?p=3:u===1&&(p=5),e.put(n,i,f[p])}}}var So=16,Co=Array.from({length:So},(e,t)=>yo(R(`#d6d9dc`,`#e4e6e8`,t/15))),wo=Co.map(e=>yo(L(`rgb(${e[0]},${e[1]},${e[2]})`,.02))),To=yo(`#c8cdd2`),Eo=[yo(`#cdd1d5`),yo(`#eceeef`)];function Do(e,t,n,r){for(let i=0;i<po;i++)for(let a=0;a<po;a++){let o=t+a,s=n+i,c=o&31,l=s&31;if(c===31||l===31){e.put(a,i,To);continue}let u=mo(o,s,3,r)%61;if(u<2){e.put(a,i,Eo[u]);continue}let d=go(o,s,26,r)*.6+go(o,s,7,r+3)*.4,f=Math.min(15,Math.floor(d*So));e.put(a,i,c===0||l===0?wo[f]:Co[f])}}var Oo=Array.from({length:So},(e,t)=>yo(R(`#ebe8e3`,`#f5f3f0`,t/15))),ko=[yo(`#e2e3e6`),yo(`#cfd2d7`)],Ao=yo(`#d6d3ce`);function jo(e,t,n,r){for(let i=0;i<po;i++)for(let a=0;a<po;a++){let o=t+a,s=n+i;if((o&31)==31||(s&31)==31){e.put(a,i,Ao);continue}let c=mo(o>>5,s>>5,4,r),l=c%1e3/1e3,u=(c>>>12)%5<2?Math.sin(o*.08+s*(.14+l*.1)+go(o,s,14,r+12)*2.4+l*6.28):0;u>.997?e.put(a,i,ko[1]):u>.986?e.put(a,i,ko[0]):e.put(a,i,Oo[Math.min(15,Math.floor(go(o,s,20,r+11)*So))])}}var Mo=[`#d3cdc2`,`#cfc8bc`,`#d8d2c8`].map(e=>[e,`#b8b1a5`,L(e,.03),L(e,-.05)].map(yo));function No(e,t,n,r){for(let i=0;i<po;i++)for(let a=0;a<po;a++){let o=t+a,s=n+i,c=s>>3,l=c&1?8:0,u=o+l&15,d=s&7,f=Mo[mo(o+l>>4,c,5,r)%Mo.length],p=0;d===7||u===15?p=1:d===0||u===0?p=2:mo(o,s,6,r)%41==0&&(p=3),e.put(a,i,f[p])}}function Po(e,t,n,r){let i=hi(t,91);for(let t=0;t<n;t++)e.set(Math.floor(i()*16),Math.floor(i()*16*2),r[Math.floor(i()*r.length)])}var Fo=32;function Io(e){return R(e.exterior?`#4a4f5c`:`#3d4356`,e.base,.1)}function Lo(e,t,n){let r=new Cn(16,Fo),i=e.base,a=e.pattern??`plain`,o=e.trim??L(i,-.16),s=Io(e),c=Fo-4-3,l=hi(t*31+n,43);for(let e=0;e<c;e++)r.hline(0,15,4+e,L(i,.02-e/c*.035));switch(a){case`stripes`:{let e=L(i,-.035);for(let t=0;t<16;t+=4)r.rect(t,4,2,c,e);for(let e=1;e<16;e+=4)r.vline(e,4,4+c-1,L(i,-.02));break}case`tiles`:{let e=L(i,-.09);for(let t=4;t<4+c;t++)(t-4)%6==5&&r.hline(0,15,t,e);for(let t=0;t<c;t+=6){let n=Math.floor(t/6)%2*4;for(let i=n;i<24;i+=8)r.vline((i+7)%16,4+t,Math.min(4+c-1,4+t+4),e);r.hline(0,15,4+t,L(i,.035))}break}case`wood_panel`:{let e=z(R(`#b98a5e`,i,.15),.04),t=4+Math.floor(c*.45);r.rect(0,t,16,4+c-t,e.base);for(let n=0;n<16;n+=4)r.vline(n,t,4+c-1,e.dk),r.vline(n+1,t+1,4+c-1,e.lt);r.hline(0,15,t-1,e.hi),r.hline(0,15,t,e.lt),r.hline(0,15,t+1,e.dk);break}case`brick`:{let e=z(i,.035),t=R(i,`#e9e4dc`,.5);for(let n=0;n*4<c;n++){let i=4+n*4,a=n%2?4:0;for(let n=-8;n<16;n+=8){let o=n+a,s=[e.lt,e.base,e.base,e.dk][Math.floor(l()*4)];for(let e=Math.max(0,o);e<Math.min(16,o+7);e++)for(let t=i;t<Math.min(4+c,i+3);t++)r.set(e,t,t===i?L(s,.03):s);o+7>=0&&o+7<16&&r.vline(o+7,i,Math.min(4+c-1,i+2),t)}i+3<4+c&&r.hline(0,15,i+3,t)}break}case`glass`:r.clearRect(0,4,16,c),r.rect(0,4,16,c,`rgba(175,215,238,0.38)`),r.vline(0,4,4+c-1,`rgba(195,202,212,0.95)`),r.hline(0,15,4,`rgba(255,255,255,0.45)`);for(let e=0;e<c;e++){let t=n*5+11-e&15;r.set(t,4+e,`rgba(255,255,255,0.35)`),r.set(t+1&15,4+e,`rgba(255,255,255,0.18)`)}break;case`marble`:{let e=R(`#c9cdd3`,i,.25);r.rect(0,4,16,c,e);for(let e=0;e<2;e++){let t=l()*16;for(let n=0;n<c;n++)r.set(Math.floor(t)&15,4+n,e?`rgba(120,126,138,0.4)`:`rgba(250,250,252,0.55)`),t+=(l()-.35)*1.4}for(let e=0;e<8;e++)r.set(Math.floor(l()*16),4+Math.floor(l()*c),l()<.5?`#d8dbe0`:`#b8bdc6`);r.hline(0,15,4+Math.floor(c/2),`rgba(120,126,138,0.35)`),n%2==1&&r.vline(15,4,4+c-1,`rgba(120,126,138,0.35)`);break}case`plain`:e.exterior&&Po(r,t*13+n,5,[L(i,-.03),L(i,.03)])}a!==`glass`&&r.hline(0,15,4,L(i,-.06)),r.rect(0,0,16,4,s),r.hline(0,15,0,L(s,.08)),r.hline(0,15,3,L(s,-.06));let u=Fo-3;return r.rect(0,u,16,3,o),r.hline(0,15,u,L(o,.08)),r.hline(0,15,Fo-1,L(o,-.08)),r}function Ro(e,t){let n=new Cn(16,16),r=Io(e);n.rect(0,0,16,6,r),n.hline(0,15,0,L(r,.08)),n.hline(0,15,5,L(r,-.05));let i=L(e.base,-.05);n.rect(0,6,16,10,i),n.hline(0,15,6,L(i,-.06));let a=e.trim??L(e.base,-.16);if(n.rect(0,14,16,2,a),n.hline(0,15,14,L(a,.06)),e.pattern===`brick`||e.exterior)for(let e=8;e<14;e+=3)n.hline(0,15,e,L(i,-.035));return t%4==3&&n.set(15,7,L(i,-.03)),n}function zo(e,t,n,r){let i=new Cn(e,t),a=z(n,.06),o=`#efe6d2`,s=e-2;for(let n=2;n<t-2;n+=2)i.set(0,n,o),i.set(e-1,n,o);i.rect(1,0,s-1+1,t,a.dk),i.rect(2,1,s-1-1,t-2,a.base),i.rect(3,2,s-1-3,1,a.hi),i.rect(3,t-3,s-1-3,1,a.hi),i.rect(3,2,1,t-4,a.hi),i.rect(s-2,2,1,t-4,a.hi);let c=s-1-5,l=t-6,u=Math.abs(r)%3;for(let e=0;e<l;e++)for(let t=0;t<c;t++){let n=a.lt;if(u===0){let r=(Math.abs((t+3)%8-4)+Math.abs((e+3)%8-4))%8;r===4?n=a.base:r===0&&(n=a.hi)}else u===1?e%6==0?n=a.base:e%6==3&&(n=L(a.lt,.03)):(t*7+e*13)%11==0&&(n=a.base);i.set(4+t,3+e,n)}for(let[e,n]of[[1,0],[s,0],[1,t-1],[s,t-1]])i.clear(e,n);return i}var Bo=[{carpet:`#c9d1dc`,carpet2:`#bdc6d3`,wall:{base:`#eef1f4`,trim:`#9fb0c4`,pattern:`plain`},accent:`#3f7fd8`,deskVariant:`white`,chairVariant:`blue`},{carpet:`#dbcfba`,carpet2:`#d0c2ab`,wall:{base:`#f6f0e5`,trim:`#b99f7a`,pattern:`stripes`},accent:`#ec8a3c`,deskVariant:`wood`,chairVariant:`black`},{carpet:`#c4cfbb`,carpet2:`#b8c5af`,wall:{base:`#f1f3ea`,trim:`#93a487`,pattern:`wood_panel`},accent:`#4cae6a`,deskVariant:`wood`,chairVariant:`green`},{carpet:`#cdc8de`,carpet2:`#c2bbd5`,wall:{base:`#f3f1f8`,trim:`#a59cc4`,pattern:`plain`},accent:`#8d66cf`,deskVariant:`white`,chairVariant:`gray`},{carpet:`#e4cdbe`,carpet2:`#dbc1b0`,wall:{base:`#f8f1eb`,trim:`#c99a83`,pattern:`plain`},accent:`#e2604f`,deskVariant:`wood`,chairVariant:`red`},{carpet:`#bfd9d2`,carpet2:`#b2cfc7`,wall:{base:`#eef6f4`,trim:`#7fb3a6`,pattern:`stripes`},accent:`#36b0b0`,deskVariant:`white`,chairVariant:`green`},{carpet:`#aab1bd`,carpet2:`#9fa7b4`,wall:{base:`#e8eaee`,trim:`#6d7583`,pattern:`brick`},accent:`#f2c14e`,deskVariant:`dark`,chairVariant:`black`},{carpet:`#e0cad2`,carpet2:`#d6bdc6`,wall:{base:`#f9f2f4`,trim:`#c08ea0`,pattern:`stripes`},accent:`#e47aa8`,deskVariant:`white`,chairVariant:`black`},{carpet:`#c0d2e7`,carpet2:`#b3c7e0`,wall:{base:`#eef4fa`,trim:`#8aa6c8`,pattern:`wood_panel`},accent:`#5b8fe0`,deskVariant:`wood`,chairVariant:`blue`},{carpet:`#d1c5b8`,carpet2:`#c5b8aa`,wall:{base:`#f4efe8`,trim:`#8a6a52`,pattern:`wood_panel`},accent:`#c9713f`,deskVariant:`dark`,chairVariant:`gray`}];Bo.length;function Vo(e){let t=Bo.length,n=Bo[(Math.floor(e)%t+t)%t];return{...n,wall:{...n.wall}}}var Ho=Jt({CHARACTER_SHEET:()=>Ss,FURNITURE:()=>on,TILE:()=>16,agentAppearance:()=>is,appearanceFromSeed:()=>rs,avatarCanvas:()=>cs,characterSprite:()=>ss,defaultLookApplies:()=>Ye,deskPaperStack:()=>us,drawBoard:()=>ai,drawClock:()=>li,drawFloor:()=>ms,drawRug:()=>hs,drawScreen:()=>Ur,drawSouthWall:()=>xs,drawWallFace:()=>ys,drawWallTop:()=>bs,drawWindowView:()=>ci,editorConflict:()=>b,editorOptions:()=>Te,fitToOptions:()=>re,footballLance:()=>Yr,furnitureSprites:()=>ls,hash32:()=>c,iconSprite:()=>ds,mergeParts:()=>ns,poseFrameCount:()=>as,poseFrameDuration:()=>os,roomTheme:()=>fs});function Uo(e){let t=document.createElement(`canvas`);t.width=Math.max(1,e.w),t.height=Math.max(1,e.h);let n=t.getContext(`2d`);return n&&e.w>0&&e.h>0&&n.putImageData(new ImageData(e.data,e.w,e.h),0,0),t}function Wo(e){return{canvas:Uo(e.buf),ax:e.ax,ay:e.ay,rects:e.rects}}var Go=class{limit;map=new Map;constructor(e){this.limit=e}get(e,t){let n=this.map.get(e);return n===void 0&&(this.map.size>=this.limit&&this.map.clear(),n=t(),this.map.set(e,n)),n}},Ko=new Go(3e4),qo=new Go(4e3),Jo=new Go(2e3),Yo=new Go(1500),Xo=new Go(64),Zo=new Go(16),Qo=new Go(2e3),$o=new Go(512),es=new WeakMap;function ts(e){let t=es.get(e);return t||(t=lt(e),es.set(e,t)),t}function ns(e,t){if(!e&&!t)return;let n={};for(let r of D){let i=e?.[r]===void 0?t?.[r]:e[r];i!==void 0&&(n[r]=i)}return Object.keys(n).length?n:void 0}function rs(e,t={}){let n=ns(t.parts,t.defaultParts);return we(e,{...t,parts:n})}function is(e,t,n={appearanceFromSeed:rs}){let r=Ye(e,t)?t?.parts:void 0;return n.appearanceFromSeed(e.seed,{look:e.look,sub:e.kind===`sub`,parts:e.parts,defaultParts:r})}function as(e){return An[e]??1}function os(e){return jn[e]??500}function ss(e){let t=as(e.pose),n=(Math.floor(e.frame)%t+t)%t,r=In(e.pose,e.seated),i=`${ts(e.appearance)}|${e.dir}|${e.pose}|${n}|${e.held??`none`}|${+!!r}|${e.costume??`none`}|${e.appearance.face===`led_mask`?e.led??`idle`:``}`;return Ko.get(i,()=>Wo(Pr({...e,frame:n,seated:r})))}function cs(e,t={}){let n=Math.max(1,Math.round(t.scale??3)),r=`${e}|${t.look??`-`}|${+!!t.sub}|${n}|${k(t.parts)}`;return Qo.get(r,()=>{let r=Pr({appearance:we(e,t),dir:`down`,pose:`stand`,frame:0}).buf.crop(2,2,20,20),i=new Cn(r.w*n,r.h*n);for(let e=0;e<i.h;e++)for(let t=0;t<i.w;t++){let a=(Math.floor(e/n)*r.w+Math.floor(t/n))*4,o=(e*i.w+t)*4;i.data[o]=r.data[a],i.data[o+1]=r.data[a+1],i.data[o+2]=r.data[a+2],i.data[o+3]=r.data[a+3]}return Uo(i)})}function ls(e,t,n,r={}){let i=io(e,t,n,r.seed),a=`${e}|${i.variant??`-`}|${i.state}|${i.vseed}`;return qo.get(a,()=>{let t=oo(e,i.variant,i.state,i.vseed);return{base:Wo(t.base),front:t.front?Wo(t.front):void 0}})}function us(e){let t=Math.max(0,Math.min(8,Math.floor(e)));return Zo.get(String(t),()=>Wo(wa(t)))}function ds(e){return Xo.get(e,()=>Wo(lo(e)))}function fs(e){return Vo(e)}function ps(e,t,n){let r=Math.imul(t|0,2654435761)^Math.imul(n|0,2246822519)^Math.imul(e|0,3266489917);return r^=r>>>15,r=Math.imul(r,739982445),r^=r>>>12,r>>>0}function ms(e,t,n,r,i,a,o){let s=Math.floor(n/po),c=Math.floor(r/po),l=Math.ceil((n+i)/po),u=Math.ceil((r+a)/po);for(let d=c;d<u;d++)for(let c=s;c<l;c++){let s=`f|${t}|${o.seed}|${o.tint??``}|${o.tint2??``}|${c}|${d}`,l=Yo.get(s,()=>Uo(_o(t,c,d,o))),u=c*po,f=d*po,p=Math.max(0,n-u),m=Math.max(0,r-f),h=Math.min(po,n+i-u),g=Math.min(po,r+a-f);h<=p||g<=m||e.drawImage(l,p,m,h-p,g-m,u+p,f+m,h-p,g-m)}}function hs(e,t,n,r,i,a,o){let s=Math.max(4,Math.round(r)),c=Math.max(4,Math.round(i)),l=`${s}|${c}|${a}|${o}`,u=$o.get(l,()=>Uo(zo(s,c,a,o)));e.drawImage(u,Math.round(t),Math.round(n))}function gs(e){return`${e.base}|${e.trim??``}|${e.pattern??`plain`}|${+!!e.exterior}`}function _s(e,t,n){let r=[[e,e+t]];for(let e of n??[]){let t=[];for(let[n,i]of r){let r=e.x,a=e.x+e.w;if(a<=n||r>=i){t.push([n,i]);continue}r>n&&t.push([n,r]),a<i&&t.push([a,i])}r=t}return r}function vs(e,t,n,r,i,a){for(let o=Math.floor(t/16);o*16<n;o++){let s=o*16,c=Math.max(0,t-s),l=Math.min(16,n-s);l<=c||e.drawImage(a(o),c,0,l-c,i,s+c,r,l-c,i)}}function ys(e,t,n,r,i,a={}){let o=gs(i),s=e=>{let t=ps(7,e,0)%4,n=e&1;return Jo.get(`w|${o}|${t}|${n}`,()=>Uo(Lo(i,t,n)))},c=_s(t,r,a.doorways),l=L(i.base,-.14),u=L(i.base,.04),d=Io(i);for(let[i,a]of c)vs(e,i,a,n,Fo,s),a<t+r&&(e.fillStyle=l,e.fillRect(a-2,n+4,2,Fo-4),e.fillStyle=L(d,-.08),e.fillRect(a-1,n,1,4)),i>t&&(e.fillStyle=u,e.fillRect(i,n+4,1,Fo-4),e.fillStyle=l,e.fillRect(i+1,n+4,1,Fo-4),e.fillStyle=L(d,.06),e.fillRect(i,n,1,4))}function bs(e,t,n,r,i,a){let o=Io(a);e.fillStyle=o,e.fillRect(t,n,r,i),e.fillStyle=L(o,.08),e.fillRect(t,n,r,1),r>2&&e.fillRect(t,n,1,i),e.fillStyle=L(o,-.06),i>2&&e.fillRect(t,n+i-1,r,1),r>2&&e.fillRect(t+r-1,n,1,i)}function xs(e,t,n,r,i,a={}){let o=gs(i),s=e=>{let t=e&3;return Jo.get(`s|${o}|${t}`,()=>Uo(Ro(i,t)))},c=Io(i);for(let[i,o]of _s(t,r,a.doorways))vs(e,i,o,n,16,s),o<t+r&&(e.fillStyle=L(c,-.08),e.fillRect(o-1,n,1,16)),i>t&&(e.fillStyle=L(c,.08),e.fillRect(i,n,1,16))}var Ss={w:24,h:34};function Cs(e){return e.filter(e=>e.status===`open`)}function ws(e){return e>0?e===1?1:e<=3?2:e<=6?3:e<=12?4:5:0}function Ts(e){return e>0?e>99?`99+`:String(e):``}function Es(e){return e.arrived?.status===`open`}function Ds(e,t){let n=e.arrived;return!n||n.status!==`open`||!t.ownerRoomVisible||t.reducedMotion?null:n.from.kind===`agent`&&t.hasAgent(n.from.agentId)?{kind:`agent`,agentId:n.from.agentId}:{kind:`courier`}}var Os={url:`/assets/emoji/sheet.png`,width:192,height:120,cell:10},ks={"🪙":{x:1,y:1,w:10,h:10},"⏳":{x:13,y:1,w:10,h:10},"✅":{x:25,y:1,w:10,h:10},"❤":{x:37,y:1,w:10,h:10},"🎉":{x:49,y:1,w:10,h:10},"🌿":{x:61,y:1,w:10,h:10},"💬":{x:73,y:1,w:10,h:10},"✋":{x:85,y:1,w:10,h:10},"👀":{x:97,y:1,w:10,h:10},"✏":{x:109,y:1,w:10,h:10},"☕":{x:121,y:1,w:10,h:10},"❌":{x:133,y:1,w:10,h:10},"📺":{x:145,y:1,w:10,h:10},"😂":{x:157,y:1,w:10,h:10},"🏓":{x:169,y:1,w:10,h:10},"🗒":{x:181,y:1,w:10,h:10},"🚫":{x:1,y:13,w:10,h:10},"💻":{x:13,y:13,w:10,h:10},"🔎":{x:25,y:13,w:10,h:10},"🌐":{x:37,y:13,w:10,h:10},"🎮":{x:49,y:13,w:10,h:10},"🚀":{x:61,y:13,w:10,h:10},"🚪":{x:73,y:13,w:10,h:10},"👋":{x:85,y:13,w:10,h:10},"😎":{x:97,y:13,w:10,h:10},"📦":{x:109,y:13,w:10,h:10},"📝":{x:121,y:13,w:10,h:10},"👥":{x:133,y:13,w:10,h:10},"⚠":{x:145,y:13,w:10,h:10},"✊":{x:157,y:13,w:10,h:10},"💄":{x:169,y:13,w:10,h:10},"🚨":{x:181,y:13,w:10,h:10},"🏙":{x:1,y:25,w:10,h:10},"🔐":{x:13,y:25,w:10,h:10},"⚽":{x:25,y:25,w:10,h:10},"✨":{x:37,y:25,w:10,h:10},"🧭":{x:49,y:25,w:10,h:10},"📨":{x:61,y:25,w:10,h:10},"🛑":{x:73,y:25,w:10,h:10},"⏸":{x:85,y:25,w:10,h:10},"💔":{x:97,y:25,w:10,h:10},"🏢":{x:109,y:25,w:10,h:10},"💰":{x:121,y:25,w:10,h:10},"😱":{x:133,y:25,w:10,h:10},"🏆":{x:145,y:25,w:10,h:10},"⌨":{x:157,y:25,w:10,h:10},"🏗":{x:169,y:25,w:10,h:10},"🔍":{x:181,y:25,w:10,h:10},"📖":{x:1,y:37,w:10,h:10},"😴":{x:13,y:37,w:10,h:10},"📬":{x:25,y:37,w:10,h:10},"🎆":{x:37,y:37,w:10,h:10},"🎲":{x:49,y:37,w:10,h:10},"👾":{x:61,y:37,w:10,h:10},"😅":{x:73,y:37,w:10,h:10},"🤝":{x:85,y:37,w:10,h:10},"❓":{x:97,y:37,w:10,h:10},"⬇":{x:109,y:37,w:10,h:10},"🔀":{x:121,y:37,w:10,h:10},"📂":{x:133,y:37,w:10,h:10},"🔌":{x:145,y:37,w:10,h:10},"🖼":{x:157,y:37,w:10,h:10},"💭":{x:169,y:37,w:10,h:10},"🧪":{x:181,y:37,w:10,h:10},"🍿":{x:1,y:49,w:10,h:10},"🕸":{x:13,y:49,w:10,h:10},"📮":{x:25,y:49,w:10,h:10},"👁":{x:37,y:49,w:10,h:10},"🛠":{x:49,y:49,w:10,h:10},"🌙":{x:61,y:49,w:10,h:10},"🙈":{x:73,y:49,w:10,h:10},"❔":{x:85,y:49,w:10,h:10},"✌":{x:97,y:49,w:10,h:10},"😏":{x:109,y:49,w:10,h:10},"😍":{x:121,y:49,w:10,h:10},"😭":{x:133,y:49,w:10,h:10},"📚":{x:145,y:49,w:10,h:10},"🍀":{x:157,y:49,w:10,h:10},"🏃":{x:169,y:49,w:10,h:10},"⭐":{x:181,y:49,w:10,h:10},"🥱":{x:1,y:61,w:10,h:10},"⚙":{x:13,y:61,w:10,h:10},"🏷":{x:25,y:61,w:10,h:10},"🐙":{x:37,y:61,w:10,h:10},"🧹":{x:49,y:61,w:10,h:10},"🗄":{x:61,y:61,w:10,h:10},"🔁":{x:73,y:61,w:10,h:10},"✉":{x:85,y:61,w:10,h:10},"📟":{x:97,y:61,w:10,h:10},"📡":{x:109,y:61,w:10,h:10},"🌧":{x:121,y:61,w:10,h:10},"🪑":{x:133,y:61,w:10,h:10},"💛":{x:145,y:61,w:10,h:10},"⚔":{x:157,y:61,w:10,h:10},"🚶":{x:169,y:61,w:10,h:10},"🔒":{x:181,y:61,w:10,h:10},"😄":{x:1,y:73,w:10,h:10},"😩":{x:13,y:73,w:10,h:10},"😤":{x:25,y:73,w:10,h:10},"🏎":{x:37,y:73,w:10,h:10},"💥":{x:49,y:73,w:10,h:10},"💋":{x:61,y:73,w:10,h:10},"🤫":{x:73,y:73,w:10,h:10},"🍕":{x:85,y:73,w:10,h:10},"😈":{x:97,y:73,w:10,h:10},"🐛":{x:109,y:73,w:10,h:10},"🏖":{x:121,y:73,w:10,h:10},"😮":{x:133,y:73,w:10,h:10},"☀":{x:145,y:73,w:10,h:10},"🍽":{x:157,y:73,w:10,h:10},"💅":{x:169,y:73,w:10,h:10},"🗑":{x:181,y:73,w:10,h:10},"🔧":{x:1,y:85,w:10,h:10},"⬆":{x:13,y:85,w:10,h:10},"🍒":{x:25,y:85,w:10,h:10},"🐳":{x:37,y:85,w:10,h:10},"☁":{x:49,y:85,w:10,h:10},"🔢":{x:61,y:85,w:10,h:10},"📜":{x:73,y:85,w:10,h:10},"🗂":{x:85,y:85,w:10,h:10},"🖥":{x:97,y:85,w:10,h:10},"🕒":{x:109,y:85,w:10,h:10},"🤖":{x:121,y:85,w:10,h:10},"📋":{x:133,y:85,w:10,h:10},"📸":{x:145,y:85,w:10,h:10},"🖱":{x:157,y:85,w:10,h:10},"📄":{x:169,y:85,w:10,h:10},"📕":{x:181,y:85,w:10,h:10},"📓":{x:1,y:97,w:10,h:10},"📤":{x:13,y:97,w:10,h:10},"🧩":{x:25,y:97,w:10,h:10},"🧰":{x:37,y:97,w:10,h:10},"⏰":{x:49,y:97,w:10,h:10},"📣":{x:61,y:97,w:10,h:10},"🧽":{x:73,y:97,w:10,h:10},"📥":{x:85,y:97,w:10,h:10},"👍":{x:97,y:97,w:10,h:10},"🙏":{x:109,y:97,w:10,h:10},"🙋":{x:121,y:97,w:10,h:10},"👏":{x:133,y:97,w:10,h:10},"👣":{x:145,y:97,w:10,h:10},"💪":{x:157,y:97,w:10,h:10},"💖":{x:169,y:97,w:10,h:10},"🤬":{x:181,y:97,w:10,h:10},"🎭":{x:1,y:109,w:10,h:10},"📢":{x:13,y:109,w:10,h:10},"🏚":{x:25,y:109,w:10,h:10},"🗣":{x:37,y:109,w:10,h:10}},As=65039,js=8205,Ms=e=>e>=127995&&e<=127999,Ns=e=>e>=127462&&e<=127487;function Ps(e,t){let n=t+1;for(Ns(e[t])&&n<e.length&&Ns(e[n])&&n++;;){for(;n<e.length&&(e[n]===As||Ms(e[n]));)n++;if(e[n]===js&&n+1<e.length)n+=2;else break}return n}var Fs=e=>String.fromCodePoint(...e.filter(e=>e!==As));function Is(e,t=ks){let n=[],r=``,i=()=>{r&&n.push({text:r}),r=``},a=Array.from(e,e=>e.codePointAt(0));for(let e=0;e<a.length;){if(a[e]<128){r+=String.fromCodePoint(a[e++]);continue}let o=Ps(a,e),s=a.slice(e,o),c=t[Fs(s)];c?(i(),n.push({emoji:String.fromCodePoint(...s),sprite:c})):r+=String.fromCodePoint(...s),e=o}return i(),n}function Ls(e,t,n){let r=Math.max(2,Math.round(n*1.3/e.h));return{scale:r,width:e.w*r,height:e.h*r,bgX:-e.x*r,bgY:-e.y*r,bgW:t.width*r,bgH:t.height*r}}var Rs=!0,zs=()=>Rs;function Bs(e){Rs=e,typeof document<`u`&&document.documentElement.classList.toggle(`px-emoji-off`,!e)}var Vs=/[^\x00-\x7f]/;function Hs(e,t,n=14){let r=Ls(t,Os,n),i=document.createElement(`span`);return i.className=`px-emoji`,i.setAttribute(`role`,`img`),i.setAttribute(`aria-label`,e),i.setAttribute(`style`,`width:${r.width}px;height:${r.height}px;background-position:${r.bgX}px ${r.bgY}px;background-size:${r.bgW}px ${r.bgH}px`),i.textContent=e,i}function Us(e,t,n=14){if(!Vs.test(t)){e.textContent=t;return}let r=Is(t);if(!r.some(e=>`emoji`in e)){e.textContent=t;return}e.textContent=``;for(let t of r)e.append(`emoji`in t?Hs(t.emoji,t.sprite,n):t.text)}function Ws(e){let t=/(\d+(?:\.\d+)?)px/.exec(e);return t?Number(t[1]):12}function Gs(e,t=Os.cell){return Math.max(1,Math.floor(e/t))*t}function Ks(e,t,n,r=ks){let i=Is(e,r);if(!i.some(e=>`emoji`in e))return t(e);let a=Gs(n)+2,o=0;for(let e of i)o+=`emoji`in e?a:t(e.text);return o}var qs=null;function Js(){qs||typeof Image>`u`||(qs=new Image,qs.src=Os.url)}function Ys(){return zs()?(Js(),qs&&qs.complete&&qs.naturalWidth>0?qs:null):null}var Xs=()=>+!!Ys();function Zs(e,t){let n=t=>e.measureText(t).width;return Ys()?Ks(t,n,Ws(e.font)):n(t)}function Qs(e,t,n,r,i=`fill`){let a=(t,n)=>i===`fill`?e.fillText(t,n,r):e.strokeText(t,n,r),o=Ys(),s=o?Is(t):[];if(!o||!s.some(e=>`emoji`in e))return a(t,n);let c=Ws(e.font),l=Gs(c),u=Ks(t,t=>e.measureText(t).width,c),d=e.textAlign,f=d===`center`?n-u/2:d===`right`||d===`end`?n-u:n,p=e.textBaseline,m=Math.round(p===`middle`?r-l/2:p===`top`||p===`hanging`?r:p===`bottom`||p===`ideographic`?r-l:r-l+l*.15),h=e.imageSmoothingEnabled;e.textAlign=`left`,e.imageSmoothingEnabled=!1;for(let t of s)`emoji`in t?(f+=1,i===`fill`&&e.drawImage(o,t.sprite.x,t.sprite.y,t.sprite.w,t.sprite.h,Math.round(f),m,l,l),f+=l+1):(a(t.text,f),f+=e.measureText(t.text).width);e.imageSmoothingEnabled=h,e.textAlign=d}var $s=`ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif`,ec=`800 11.5px ${$s}`,tc=22,nc=900,rc=42,ic;function ac(){return ic===void 0&&(ic=typeof matchMedia==`function`?matchMedia(`(prefers-reduced-motion: reduce)`):null),!!ic?.matches}function oc(e,t){return Math.max(0,Math.min(1,(t-e.start)/300,(e.end-t)/600))}function sc(e,t){let n=document.createElement(`canvas`);n.width=e[0].length,n.height=e.length;let r=n.getContext(`2d`);return e.forEach((e,n)=>{for(let i=0;i<e.length;i++){let a=t[e[i]];a&&(r.fillStyle=a,r.fillRect(i,n,1,1))}}),n}var cc=[[`..kkkkk..`,`.kRbwbrk.`,`kRRbwbRrk`,`kRRbwbRrk`,`kRRRRRRrk`,`kmmmmmmmk`,`kMMMMMMMk`,`.kkkkkkk.`],[`..kkkkk..`,`.kRRRwbk.`,`kRRRRRwbk`,`kRRRRRwbk`,`kRRRRRRrk`,`kmmmmmmmk`,`kMMMMMMMk`,`.kkkkkkk.`],[`..kkkkk..`,`.kddddek.`,`kdddddddk`,`kdddddddk`,`kdddddeek`,`kmmmmmmmk`,`kMMMMMMMk`,`.kkkkkkk.`],[`..kkkkk..`,`.kbwRRrk.`,`kbwRRRRrk`,`kbwRRRRrk`,`kRRRRRRrk`,`kmmmmmmmk`,`kMMMMMMMk`,`.kkkkkkk.`]],lc={k:`#3a1012`,R:`#ff3b3b`,r:`#c4161f`,b:`#ff9a9a`,w:`#fff4f4`,d:`#9b161d`,e:`#6d0d12`,m:`#8d96a6`,M:`#5c6372`},uc=[`.kkkkkkk.`,`krrrrrrrk`,`krrrwrrrk`,`krrrwrrrk`,`krrrwrrrk`,`krrrrrrrk`,`krrrwrrrk`,`krrrrrrrk`,`.kkkkkkk.`,`...krk...`,`....k....`],dc={k:`#4a0d10`,r:`#e5383b`,w:`#ffffff`},fc=null,pc=null;function mc(){return fc??=cc.map(e=>sc(e,lc))}function hc(){return pc??=sc(uc,dc)}function gc(e){return Math.min(3,Math.floor(((e+.125)%1+1)%1*4))}function _c(e){return Math.max(0,Math.cos(e*Math.PI*2))}var vc=new Map;function yc(e){let t=vc.get(e);if(t)return t;t=document.createElement(`canvas`),t.width=e,t.height=e;let n=t.getContext(`2d`),r=n.createRadialGradient(e/2,e/2,0,e/2,e/2,e/2);return r.addColorStop(0,`rgba(255,36,48,0.75)`),r.addColorStop(.45,`rgba(255,36,48,0.3)`),r.addColorStop(1,`rgba(255,36,48,0)`),n.fillStyle=r,n.fillRect(0,0,e,e),vc.set(e,t),t}function bc(e){return{room:{x:e.x*16,y:e.y*16,w:e.w*16,h:e.h*16},floor:{x:(e.x+.5)*16,y:(e.y+2)*16,w:(e.w-1)*16,h:(e.h-3)*16}}}var xc=class{acc=new Map;visibleRoom(e,t,n){let r=e.rooms.get(t.roomId);if(!r||!r.present||r.phase===`dismantling`)return null;let i=bc(r.layout.rect),a=i.room;return a.x>n.x1||a.x+a.w<n.x0||a.y-8>n.y1||a.y+a.h<n.y0?null:i}drawFloor(e,t,n,r){if(!t.roomFx.active.size)return;let i=ac();for(let a of t.roomFx.active.values()){if(a.kind!==`alarm`||n>=a.end)continue;let o=this.visibleRoom(t,a,r);if(!o)continue;let s=i?.5:.5+.5*Math.sin((n-a.start)/1100*Math.PI*2),c=o.floor;e.globalAlpha=oc(a,n)*(.08+.09*s),e.fillStyle=`#ff2a36`,e.fillRect(c.x,c.y,c.w,c.h)}e.globalAlpha=1}emit(e,t,n,r,i){if(!t.roomFx.active.size){this.acc.size&&this.acc.clear();return}let a=ac();for(let[o,s]of t.roomFx.active){if(s.kind!==`party`||n>=s.end||a){this.acc.delete(o);continue}let c=this.visibleRoom(t,s,i);if(!c)continue;let l=Math.min(1,(s.end-n)/2e3)*(n-s.start<1500?1.6:1),u=(this.acc.get(o)??0)+Math.min(.1,r)*rc*l,d=c.floor,f=c.room.y+4;for(;u>=1;){--u;let t=f+Math.random()*6;e.confettiFall(d.x+2+Math.random()*(d.w-4),t,d.y+d.h-4-t)}this.acc.set(o,u)}for(let e of this.acc.keys())t.roomFx.active.has(e)||this.acc.delete(e)}drawLights(e,t,n,r,i){if(!t.roomFx.active.size)return;let a=ac();for(let o of t.roomFx.active.values()){if(o.kind!==`alarm`||r>=o.end)continue;let s=oc(o,r),c=this.visibleRoom(t,o,i);c&&this.drawBeacons(e,c,r-o.start,s,a);let l=o.agentId?n.get(o.agentId):void 0;if(l?.visible){let t=hc(),n=a?0:Math.round(Math.abs(Math.sin((r-o.start)/260))*2);e.globalAlpha=s,e.drawImage(t,Math.round(l.x+4),Math.round(l.y-t.height-1-n)),e.globalAlpha=1}}}drawBeacons(e,t,n,r,i){let a=mc(),o=t.room,s=t.floor,c=[o.x+4,o.x+o.w-4],l=i?0:n/nc,u=e=>i?.6:_c(l+e*.5);if(!i){e.save(),e.beginPath(),e.rect(o.x,o.y,o.w,o.h),e.clip();let t=yc(128),n=s.x+s.w/2,i=s.y+s.h/2;for(let a=0;a<2;a++){let o=l*Math.PI*2+a*Math.PI;e.globalAlpha=.3*r,e.drawImage(t,Math.round(n+Math.cos(o)*s.w*.3-64),Math.round(i+Math.sin(o)*s.h*.3-64))}e.restore()}let d=yc(48);for(let[t,n]of c.entries())e.globalAlpha=(.25+.75*u(t))*r,e.drawImage(d,Math.round(n-24),Math.round(o.y+3-24));e.globalAlpha=r;for(let[t,n]of c.entries()){let r=a[i?0:gc(l+t*.5)],s=Math.round(n-r.width/2),c=Math.round(o.y+7-r.height);if(e.drawImage(r,s,c),!i&&u(t)>.75){e.fillStyle=`#ff6b6b`;let t=c+2;e.fillRect(s-4,t,3,1),e.fillRect(s+r.width+1,t,3,1),e.fillRect(s-2,t-3,1,1),e.fillRect(s-3,t-4,1,1),e.fillRect(s+r.width+1,t-3,1,1),e.fillRect(s+r.width+2,t-4,1,1),e.fillRect(s+Math.floor(r.width/2),c-3,1,2)}}e.globalAlpha=1}};function Sc(e,t,n,r,i,a,o,s){let c=oc(t,a);if(c<=0)return null;let l=ac(),u=t.kind===`party`,d=u?`🎉`:`🚨`,f=l?0:Math.max(0,1-(a-t.start)/260),p=!l&&u?Math.sin((a-t.start)/320)*1.5:0,m=Math.round(r-f*10+p),h=i>=70?o(ec,`${d} ${t.text}`,i-24-12):``;e.save(),e.globalAlpha=c,e.font=ec,e.textBaseline=`middle`,e.textAlign=`center`;let g=l?0:.5+.5*Math.sin((a-t.start)/700*Math.PI*2),_=u?`#ffcf3a`:g>.5?`#ef3340`:`#c8202e`,v=u?`#c98a12`:`#7a0d16`,y=u?`#3a2606`:`#ffffff`;if(!h||h===`…`)return e.fillStyle=`rgba(16,20,32,0.25)`,e.beginPath(),e.arc(n,m+11+1.5,11,0,Math.PI*2),e.fill(),e.fillStyle=_,e.beginPath(),e.arc(n,m+11,11,0,Math.PI*2),e.fill(),e.font=`13px ${$s}`,Qs(e,d,n,m+11+1),e.restore(),{x:n-11,y:m,w:22,h:22};let b=s(ec,h),x=Math.round(b+24+12),S=Math.round(n-x/2),C=tc,w=t=>{e.beginPath(),e.moveTo(S,m+t),e.lineTo(S+x,m+t),e.lineTo(S+x-6,m+t+C/2),e.lineTo(S+x,m+t+C),e.lineTo(S,m+t+C),e.lineTo(S+6,m+t+C/2),e.closePath()};if(e.fillStyle=`rgba(16,20,32,0.28)`,w(2),e.fill(),e.fillStyle=v,w(1),e.fill(),e.fillStyle=_,w(0),e.fill(),u){let t=[`#ff4d6d`,`#3fa7ff`,`#3ddc84`,`#b06bff`];for(let n=0,r=S+6+6;r<S+x-6-6;n++,r+=9)e.fillStyle=t[n%t.length],e.beginPath(),e.moveTo(r-3,m),e.lineTo(r+3,m),e.lineTo(r,m+4),e.closePath(),e.fill()}return e.fillStyle=y,Qs(e,h,Math.round(n),m+C/2+1),e.restore(),{x:S,y:m,w:x,h:C}}var Cc=51.2,wc=96,Tc=8,Ec=2600,Dc=2200,Oc=8e3,kc=.25,Ac=class{area;seq=0;constructor(e,t,n){this.area={id:e,kind:t,rect:n,floors:[],rugs:[],walls:[],wallItems:[],furniture:[],spots:[],walkable:[]}}get x0(){return this.area.rect.x}get y0(){return this.area.rect.y}px(e){return(this.x0+e)*16}py(e){return(this.y0+e)*16}floor(e,t,n,r,i,a,o,s){return this.area.floors.push({kind:e,x:this.px(t),y:this.py(n),w:r*16,h:i*16,seed:a,tint:o,tint2:s}),this}rug(e,t,n,r,i,a){return this.area.rugs.push({x:Math.round(this.px(e)),y:Math.round(this.py(t)),w:Math.round(n*16),h:Math.round(r*16),color:i,seed:a}),this}face(e,t,n,r=[],i=0){return this.area.walls.push({kind:`face`,x:this.px(e),y:this.py(i),w:t*16,style:n,doorways:this.doors(r)}),this}south(e,t,n,r,i=[]){return this.area.walls.push({kind:`south`,x:this.px(e),y:this.py(n),w:t*16,style:r,doorways:this.doors(i)}),this}cap(e,t,n,r,i){return this.area.walls.push({kind:`cap`,x:this.px(e),y:this.py(t),w:n*16,h:r*16,style:i}),this}doors(e){return e.length?e.map(e=>({x:this.px(e.lx),w:e.w*16})):void 0}wall(e,t,n,r={}){let i=`${this.area.id}#w${this.seq++}:${e}`;return this.area.wallItems.push({id:i,kind:e,variant:n,cx:Math.round(this.px(t)),baseY:this.py(r.ly??2),on:r.on??`face`,order:r.order??.5}),i}furn(e,t,n,r,i={}){let a=`${this.area.id}#f${this.seq++}:${e}`,o={id:a,kind:e,variant:r,tx:this.x0+t,ty:this.y0+n,dx:i.dx,dy:i.dy,order:i.order??.5,seat:i.seat};return this.area.furniture.push(o),a}spot(e,t,n,r,i={}){let a=this.x0+t,o=this.y0+n,s={id:`${this.area.id}#s${this.seq++}:${e}`,kind:e,areaId:this.area.id,tx:a,ty:o,x:i.x??a*16+Tc+(i.dx??0),y:i.y??o*16+11+(i.dy??0),dir:r,seated:i.seated,furnitureId:i.furnitureId,sortY:i.sortY,group:i.group,deskId:i.deskId,rank:i.rank,side:i.side};return this.area.spots.push(s),s}seat(e,t,n,r,i,a,o={}){let s=o.noFurniture?o.furnitureId:this.furn(t,n,r,a,{dx:o.dx,order:o.order}),c=this.py(r+1);return this.spot(e,n,r,i,{...o,furnitureId:s,seated:!0,x:this.px(n)+8+(o.dx??0),y:c-3+(o.dy??0),sortY:c+kc})}walk(e,t,n,r){return this.area.walkable.push({x:this.x0+e,y:this.y0+t,w:n,h:r}),this}block(e,t,n,r){return(this.area.blocked??=[]).push({x:this.x0+e,y:this.y0+t,w:n,h:r}),this}build(){return this.area}};function jc(e){let t=on[e];return t.mount===`floor`&&t.blocks}function Mc(e){let t=on[e];return t.mount===`floor`&&!!t.seat}function Nc(e){return Math.max(0,e)+1}function Pc(e){return 2+Math.floor(Nc(e)/2)}function Fc(e){return Nc(e)%2==0?`north`:`south`}function Ic(){return Lc(2,`north`)}function Lc(e,t){return{x:e*16,y:t===`north`?0:17,w:16,h:12}}function Rc(e){return Lc(Pc(e),Fc(e))}function zc(e,t){return(e-2)*2+(t===`north`?0:1)-1}function Bc(e){let t=0;for(let n of e)t=Math.max(t,Math.floor(Nc(n)/2));return 2+t+1}function Vc(e){return{x:0,y:0,w:e*16,h:29}}function Hc(e,t,n){return t>=e.x&&n>=e.y&&t<e.x+e.w&&n<e.y+e.h}var Uc=`core:recepcao`,Wc=`core:banheiros`,Gc=`core:copa`,Kc=`core:lounge`,qc=`core:meu-escritorio`,Jc=5,Yc=Ic(),Xc={reception:{base:`#e9e5dc`,trim:`#a88e6c`,pattern:`wood_panel`},restroom:{base:`#dce8ee`,trim:`#8fb0c0`,pattern:`tiles`},cafe:{base:`#eef0ee`,trim:`#9aa6ad`,pattern:`plain`},cafeSplash:{base:`#d9dcdf`,trim:`#8d969e`,pattern:`marble`},lounge:{base:`#e6e2ea`,trim:`#8f8aa3`,pattern:`plain`},glass:{base:`#cfe6f0`,trim:`#9fb9c6`,pattern:`glass`},office:{base:`#e3e7ee`,trim:`#7d8fab`,pattern:`plain`}},Zc=[3,6.5];function Qc(){let e=new Ac(Uc,`reception`,{x:0,y:0,w:16,h:12}),t=Xc.reception;e.floor(`marble`,0,0,16,12,101),e.rug(1.5,2.2,6.5,2.6,`#3d5a80`,102),e.rug(8.6,6.4,5.2,3.2,`#b65f3a`,103),e.face(.5,15,t),e.cap(0,0,.5,12,t),e.cap(15.5,0,.5,12,t),Zc.forEach((t,n)=>{e.wall(`elevator`,t,void 0,{order:.2+n*.1});let r=Math.floor(t-.5);e.spot(`elevator`,r,2,`up`,{x:e.px(t),y:e.py(2)+2,group:`elevator:${n}`})}),e.wall(`sign`,11,void 0,{order:.9}),e.wall(`clock`,8.15,void 0,{order:.7}),e.wall(`painting`,14.25,void 0,{order:.6}),e.furn(`plant_tall`,1,2,`monstera`,{order:.2}),e.furn(`plant_tall`,14,4,`ficus`,{order:.21}),e.furn(`reception_desk`,9,5,void 0,{order:.4}),e.furn(`plant_small`,12,5,`flower`,{order:.45}),e.furn(`filing_cabinet`,8,5,void 0,{order:.42}),e.seat(`armchair`,`armchair`,9,8,`right`,`right`,{order:.6}),e.furn(`coffee_table`,10,8,void 0,{order:.58}),e.seat(`armchair`,`armchair`,12,8,`left`,`left`,{order:.61}),e.furn(`plant_tall`,14,9,`palm`,{order:.22});let n=e.furn(`bench`,2,7,void 0,{order:.5});for(let t=0;t<2;t++)e.seat(`bench`,`bench`,2+t,7,`down`,void 0,{noFurniture:!0,furnitureId:n});e.furn(`plant_small`,4,7,`fern`,{order:.52}),e.furn(`water_cooler`,1,7,void 0,{order:.53}),e.spot(`water`,1,8,`up`,{dy:-3});for(let t of[1,2,3,12,13,14])e.furn(`glass_partition`,t,11,`h`,{order:.15});e.walk(1,2,14,10),e.spot(`talk`,6,9,`right`,{group:`talk:recepcao`,dx:-1}),e.spot(`talk`,7,9,`left`,{group:`talk:recepcao`,dx:1});let r=e.build();return r.shade=void 0,r}function $c(){let e=new Ac(Wc,`restroom`,{x:0,y:17,w:16,h:12}),t=Xc.restroom;e.floor(`tile_white`,0,0,16,12,201),e.rug(2,3.15,3,.85,`#6fa3b8`,202),e.face(.5,15,t,[{lx:7,w:2}]),e.wall(`door_frame`,8,void 0,{order:.05}),e.south(.5,15,11,{...t,exterior:!0}),e.cap(0,0,.5,12,t),e.cap(15.5,0,.5,12,t),e.walk(1,2,14,9),e.walk(7,0,2,2),e.area.door={x:7,y:17,w:2,h:2};for(let t=0;t<3;t++)e.wall(`mirror`,2.5+t,void 0,{order:.3}),e.furn(`sink`,2+t,2,void 0,{order:.35}),e.spot(`sink`,2+t,3,`up`,{dy:-3});e.furn(`trash_bin`,5,2,void 0,{order:.4}),e.furn(`plant_small`,1,2,`fern`,{order:.2}),e.wall(`clock`,6,void 0,{order:.5});for(let t=0;t<3;t++){let n=9+t*2,r=e.furn(`toilet_stall`,n,2,void 0,{order:.3+t*.05});e.spot(`stall`,n,4,`up`,{furnitureId:r,x:e.px(n+1),y:e.py(4)-3,sortY:e.py(4)-.5})}e.wall(`poster`,1.5,`cat`,{order:.5}),e.furn(`plant_small`,14,6,`succulent`,{order:.2}),e.furn(`plant_tall`,1,10,`ficus`,{order:.21}),e.furn(`plant_tall`,14,10,`monstera`,{order:.22});let n=e.furn(`bench`,3,9,void 0,{order:.5});for(let t=0;t<2;t++)e.seat(`bench`,`bench`,3+t,9,`down`,void 0,{noFurniture:!0,furnitureId:n});return e.furn(`trash_bin`,9,10,void 0,{order:.6}),e.rug(2.5,9.9,3,.9,`#9cc3cf`,203),e.furn(`plant_small`,1,6,`flower`,{order:.24}),e.furn(`plant_small`,12,10,`fern`,{order:.25}),e.build()}function el(){let e=new Ac(Gc,`cafe`,{x:16,y:0,w:16,h:12}),t=Xc.cafe;e.floor(`tile_check`,0,0,16,12,301),e.face(.5,9,Xc.cafeSplash),e.face(9.5,6,t),e.cap(0,0,.5,12,t),e.cap(15.5,0,.5,12,t),e.furn(`fridge`,1,2,void 0,{order:.2}),e.spot(`fridge`,1,3,`up`,{dy:-3}),e.furn(`counter`,2,2,`drawers`,{order:.22}),e.furn(`counter_sink`,3,2,void 0,{order:.24}),e.spot(`sink`,3,3,`up`,{dy:-3}),e.furn(`counter`,4,2,`plain`,{order:.26});for(let t of[5,6]){let n=e.furn(`coffee_machine`,t,2,void 0,{order:.28});e.spot(`coffee`,t,3,`up`,{dy:-3,furnitureId:n})}e.furn(`microwave`,7,2,void 0,{order:.3}),e.furn(`counter`,8,2,`drawers`,{order:.32}),e.wall(`shelf_wall`,3,void 0,{order:.4}),e.wall(`poster`,5.5,`coffee`,{order:.45}),e.wall(`clock`,7.5,void 0,{order:.6});let n=e.furn(`vending_machine`,9,2,void 0,{order:.34});e.spot(`snack`,9,3,`up`,{dy:-3,furnitureId:n}),e.furn(`water_cooler`,10,2,void 0,{order:.36}),e.spot(`water`,10,3,`up`,{dy:-3}),e.wall(`window`,12,void 0,{order:.4}),e.wall(`window`,14.25,void 0,{order:.45}),e.spot(`window`,11,2,`up`,{dx:8,dy:1}),e.spot(`window`,13,2,`up`,{dx:12,dy:1}),e.rug(2.6,4.15,8.8,3.7,`#b98a5e`,302),e.furn(`meeting_table`,4,5,void 0,{order:.5}),e.furn(`meeting_table`,7,5,void 0,{order:.51});for(let t=0;t<6;t++){let n=4+t;e.seat(`cafe_seat`,`cafe_chair`,n,4,`down`,`down`,{order:.55+t*.01}),e.seat(`cafe_seat`,`cafe_chair`,n,7,`up`,`up`,{order:.62+t*.01})}e.furn(`plant_small`,3,5,`flower`,{order:.52});for(let[t,n,r]of[[12,5,0],[12,8,1]])e.furn(`cafe_table`,t,n,void 0,{order:.7+r*.03}),e.seat(`cafe_seat`,`cafe_chair`,t-1,n,`right`,`right`,{order:.72+r*.03}),e.seat(`cafe_seat`,`cafe_chair`,t+1,n,`left`,`left`,{order:.73+r*.03});e.furn(`plant_tall`,1,10,`monstera`,{order:.2}),e.furn(`plant_tall`,14,10,`ficus`,{order:.21}),e.furn(`trash_bin`,1,6,void 0,{order:.6});for(let t of[1,2,3,4,5,10,11,12,13,14])e.furn(`glass_partition`,t,11,`h`,{order:.15});return e.walk(1,2,14,10),e.spot(`talk`,7,9,`right`,{group:`talk:copa`,dx:-1}),e.spot(`talk`,8,9,`left`,{group:`talk:copa`,dx:1}),e.area.shade=void 0,e.build()}function tl(){let e=new Ac(Kc,`lounge`,{x:16,y:17,w:16,h:12}),t=Xc.lounge;e.floor(`wood`,0,0,16,12,401),e.rug(1.5,3.2,7,5.2,`#4f8a5b`,402),e.rug(9.2,4.6,5.6,4.4,`#d7c8a8`,403),e.face(.5,6.5,t),e.face(10,5.5,Xc.glass),e.south(.5,15,11,{...t,exterior:!0}),e.cap(0,0,.5,12,t),e.cap(15.5,0,.5,12,t),e.walk(1,2,14,9),e.walk(7,0,3,2),e.area.door={x:23,y:17,w:3,h:2},e.wall(`tv`,4.5,void 0,{order:.4}),e.wall(`painting`,1.75,void 0,{order:.5});let n=e.furn(`sofa`,3,6,`up`,{order:.5});for(let t=0;t<3;t++)e.seat(`sofa`,`sofa`,3+t,6,`up`,`up`,{noFurniture:!0,furnitureId:n});e.furn(`coffee_table`,3,4,void 0,{dx:8,order:.45}),e.block(5,4,1,1),e.seat(`armchair`,`armchair`,2,4,`right`,`right`,{order:.55}),e.seat(`armchair`,`armchair`,6,4,`left`,`left`,{order:.56}),e.furn(`pingpong_table`,10,6,void 0,{order:.4});let r=e.py(7)+5,i=e.py(8)+kc;e.spot(`pingpong`,9,7,`right`,{x:e.px(10)-8,y:r,group:`pingpong`,sortY:i}),e.spot(`pingpong`,13,7,`left`,{x:e.px(13)+8,y:r,group:`pingpong`,sortY:i});for(let t of[13,14])e.furn(`arcade`,t,2,void 0,{order:.3}),e.spot(`arcade`,t,3,`up`,{dy:-3});return e.furn(`bookshelf`,10,2,void 0,{order:.3}),e.spot(`shelf`,10,3,`up`,{dx:8,dy:-2}),e.furn(`binder_shelf`,12,2,void 0,{order:.31}),e.furn(`plant_small`,1,2,`fern`,{order:.2}),e.furn(`plant_tall`,6,2,`palm`,{order:.21}),e.furn(`printer`,1,10,void 0,{order:.3}),e.furn(`floor_lamp`,1,7,void 0,{order:.32}),e.furn(`plant_tall`,14,10,`monstera`,{order:.22}),[`red`,`blue`,`yellow`].forEach((t,n)=>{e.seat(`beanbag`,`beanbag`,6+n*2,9,`down`,t,{order:.6+n*.02})}),e.spot(`talk`,11,9,`right`,{group:`talk:lounge`,dx:-1}),e.spot(`talk`,12,9,`left`,{group:`talk:lounge`,dx:1}),e.spot(`watch`,10,5,`down`,{group:`watch:pingpong`,dx:2}),e.spot(`watch`,12,5,`down`,{group:`watch:pingpong`,dx:-2}),e.build()}function nl(){let e=new Ac(qc,`office`,Ic()),t=Xc.office;e.floor(`wood`,0,0,16,12,601),e.rug(4.5,4.2,7,4.6,`#3d5a80`,602),e.face(.5,15,t),e.cap(0,0,.5,12,t),e.cap(15.5,0,.5,12,t),e.wall(`window`,5,void 0,{order:.4}),e.wall(`sign`,8,void 0,{order:.9}),e.wall(`painting`,10.5,void 0,{order:.6}),e.furn(`bookshelf`,1,2,void 0,{order:.2}),e.furn(`binder_shelf`,12,2,void 0,{order:.21}),e.furn(`filing_cabinet`,13,2,void 0,{order:.22});let n=e.furn(`desk`,7,5,`white`,{order:.4});e.seat(`player_desk`,`office_chair`,7,6,`up`,`blue`,{dx:8,deskId:n,side:`S`,order:.6}),e.furn(`plant_tall`,1,9,`monstera`,{order:.23}),e.furn(`plant_tall`,14,9,`ficus`,{order:.24}),e.furn(`plant_small`,3,4,`flower`,{order:.5}),e.furn(`floor_lamp`,13,5,void 0,{order:.3}),e.furn(`trash_bin`,12,8,void 0,{order:.6});let r=Jc;for(let t=1;t<=14;t++)t!==r&&e.furn(`glass_partition`,t,11,`h`,{order:.15});e.walk(1,2,14,10),e.spot(`player_door`,r,12,`right`);for(let t=0;t<6;t++)e.spot(`queue`,6+t,12,`left`,{rank:t,group:`queue:meu-escritorio`});let i=e.build();return i.shade=void 0,i}function rl(e){return e.kind===`main`?e.favoriteRoomId??e.roomId:e.roomId}var il=class{id;info;appearance;lookSig=``;rng;x=0;y=0;tx=0;ty=0;dir=`down`;pose=`stand`;held=`none`;seated=!1;alpha=1;visible=!0;sortY=null;animT=0;mode=`idle`;queue=[];step=null;stepT=0;stepStarted=!1;replan=!1;errand=!1;homeSpot=null;atSpot=null;tempSpots=[];roomId;annexId=null;leaving=!1;gone=!1;arriving=!1;missingSince=null;nextOutingAt=0;gathering=null;nextSocialAt=0;hiddenUntil=0;inside=!1;thinkAt=0;delivered=!1;stallUntil=0;enterFrom=null;standTile=null;speedK;lane;offX=0;offY=0;icon=null;iconUntil=0;iconAt=0;bubbleText=null;bubbleIcon=``;bubbleAt=0;bubbleUntil=0;chatEmoji=``;chatUntil=0;sayText=``;sayAt=0;sayUntil=0;lastActivityId=null;activityChangedAt=0;shellSince=0;shellCount=0;shellLabel=``;shellStage=null;shellEnteredAt=0;shellText=``;shellTextKey=-1;reactUntil=0;shellDoneAt=0;popcornAt=0;constructor(e,t){this.id=e.id,this.info=e,this.appearance=t,this.roomId=rl(e),this.rng=d((e.seed^2654435769)>>>0);let n=d((e.seed^1374496675)>>>0);this.speedK=.92+n()*.16,this.lane=Math.round((n()*2-1)*3.5)}updateLane(e){let t=this.pose===`walk`||this.pose===`run`,n=this.dir===`left`||this.dir===`right`,r=t&&!n?this.lane:0,i=t&&n?this.lane*.6:0,a=Math.min(1,e*5);this.offX+=(r-this.offX)*a,this.offY+=(i-this.offY)*a,Math.abs(this.offX)<.05&&(this.offX=0),Math.abs(this.offY)<.05&&(this.offY=0)}placeAtTile(e,t){this.tx=e,this.ty=t,this.x=e*16+Tc,this.y=t*16+11}setPose(e,t=`none`){this.pose!==e&&(this.pose=e,this.animT=0),this.held=t}setIcon(e,t,n){this.icon=e,this.iconAt=n,this.iconUntil=e?n+t:0}showBubble(e,t,n,r){this.bubbleIcon=e,this.bubbleText=t,this.bubbleAt=r,this.bubbleUntil=r+n}depth(){return this.sortY??this.y}};function al(e,t,n){return Math.abs(e)<.01&&Math.abs(t)<.01?n:Math.abs(e)>=Math.abs(t)?e>0?`right`:`left`:t>0?`down`:`up`}function ol(e,t,n,r){return al(n-e,r-t,`down`)}var sl=`@courier`,cl=45e3,ll=3,ul=4242;function dl(e,t){return{id:`${sl}:${e}`,kind:`main`,provider:`claude`,roomId:Uc,name:a(`Mensageiro`),look:`m`,role:a(`Mensageiro`),sessionId:`${sl}:${e}`,account:``,status:`idle`,recent:[],tasks:[],startedAt:t,lastEventAt:t,statusSince:t,stats:{toolCalls:0,tokensIn:0,tokensOut:0,subagents:0},seed:ul}}var fl=class{sim;open=0;shown=0;couriers=[];deadline=0;serial=0;constructor(e){this.sim=e}set(e){this.open=e,(this.deadline===0||e<this.shown)&&(this.shown=e)}dropTile(){let e=this.sim.spots.ofKind(`player_desk`)[0];if(!e)return null;let t=e.tx+1;return this.sim.building.grid.walkable(t,e.ty)?{tx:t,ty:e.ty}:null}holdBack(e){this.shown=Math.max(0,this.open-1),this.deadline=e+cl}drop(){this.deadline=0,this.shown=this.open}errandAborted(){this.drop()}agentErrand(e,t){let n=this.sim.chars.get(e),r=this.dropTile();if(!n||!r||n.gone||n.leaving||n.inside||n.arriving||n.gathering||!n.homeSpot||!this.sim.spots.get(n.homeSpot)||n.mode===`wait`||n.mode===`leave`||n.mode===`deliver`||n.step&&!this.sim.interruptible(n.step))return!1;this.sim.clearPlan(n);let i=[];return n.atSpot&&i.push({t:`exit`}),i.push({t:`go`,tx:r.tx,ty:r.ty,held:`papers`,dir:`up`},{t:`act`,pose:`stand`,held:`papers`,ms:700,dir:`up`},{t:`do`,fn:()=>{n.errand=!1,this.drop()}},{t:`act`,pose:`stand`,held:`none`,ms:450,dir:`up`}),n.queue.push(...i),n.errand=!0,this.sim.pushHome(n,`none`),this.holdBack(t),!0}courierErrand(e){let t=this.sim.spots.ofKind(`player_door`)[0],n=this.dropTile();if(!t||!n||this.couriers.length>=ll)return!1;let r=dl(this.serial++,e),i;try{i=new il(r,this.sim.art.appearanceFromSeed(r.seed,{look:r.look,sub:!1}))}catch{return!1}return i.placeAtTile(t.tx,t.ty),i.queue.push({t:`go`,tx:n.tx,ty:n.ty,held:`papers`,dir:`up`},{t:`act`,pose:`stand`,held:`papers`,ms:700,dir:`up`},{t:`do`,fn:()=>this.drop()},{t:`act`,pose:`stand`,held:`none`,ms:450,dir:`up`},{t:`go`,tx:t.tx,ty:t.ty},{t:`remove`}),this.couriers.push(i),this.holdBack(e),!0}update(e,t){this.deadline&&t>=this.deadline&&this.drop();for(let n of this.couriers)n.animT+=e*1e3,this.sim.stepActor(n,e,t),!n.step&&!n.queue.length&&!n.gone&&n.setPose(`stand`);for(let e=this.couriers.length-1;e>=0;e--)this.couriers[e].gone&&this.couriers.splice(e,1)}};function pl(e){return new Promise(t=>{let n=new Image;n.decoding=`async`,n.onload=()=>t(n.naturalWidth>0?n:null),n.onerror=()=>t(null),n.src=`/assets/${e.replace(/^\/+/,``)}`})}function ml(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.file==`string`&&t.file.length>0&&!t.file.includes(`..`)}async function hl(e){try{let t=await fetch(`/assets/manifest.json`,{signal:e,cache:`no-cache`});if(!t.ok||!(t.headers.get(`content-type`)??``).includes(`json`))return null;let n=await t.json(),r=[],i=Array.isArray(n.wallArt)?n.wallArt:[],a=await Promise.all(i.map(e=>ml(e)?pl(e.file):Promise.resolve(null))),o=await Promise.all(i.map(e=>ml(e.framed)?pl(e.framed.file):Promise.resolve(null)));i.forEach((e,t)=>{let n=a[t];if(!n||e.kind!==`painting`&&e.kind!==`poster`)return;let i=n.naturalWidth,s=n.naturalHeight,c=typeof e.tiles==`number`&&e.tiles>0?e.tiles:e.kind===`poster`?1:i>40?4:2,l=o[t];r.push({id:String(e.id),kind:e.kind,img:n,w:i,h:s,tiles:c,variant:typeof e.variant==`string`?e.variant:void 0,framed:l?{img:l,w:l.naturalWidth,h:l.naturalHeight}:void 0})});let s=async e=>{if(!ml(e))return;let t=await pl(e.file);return t?{img:t,w:t.naturalWidth,h:t.naturalHeight}:void 0},[c,l]=await Promise.all([s(n.brand?.signage),s(n.brand?.mark)]);return!r.length&&!c&&!l?null:{wallArt:r,signage:c,mark:l}}catch{return null}}var gl={top:34,bottom:10,side:16};function _l(e,t,n,r){let i=gl,a={x:e.x-8,y:e.y-24,w:e.w+16,h:e.h+56},o=Math.max(80,t-r.left-r.right-2*i.side),s=Math.max(80,n-r.top-r.bottom-i.top-i.bottom);return{zoom:Math.min(o/a.w,s/a.h),cx:a.x+a.w/2,cy:a.y+a.h/2,dy:(i.top-i.bottom)/2}}var vl=e=>e<.5?4*e*e*e:1-(-2*e+2)**3/2,yl=class{x=0;y=0;zoom=2;viewW=800;viewH=600;dpr=1;minZoom=1;bounds={x:0,y:0,w:800,h:600};follow=null;insets={top:0,right:0,bottom:0,left:0};anim=null;freeZoom=!1;setView(e,t,n){this.viewW=Math.max(1,e),this.viewH=Math.max(1,t),this.dpr=n||1}get animating(){return this.anim!==null}levels(){let e=Math.min(this.minZoom,1),t=new Set;for(let e=1;e<=6*this.dpr;e++)t.add(Math.round(e/this.dpr*1e3)/1e3);for(let e=4;e<=12;e++)t.add(e/2);let n=[...t].filter(t=>t>=e-1e-6&&t<=6+1e-6).sort((e,t)=>e-t);return(!n.length||n[0]>e+1e-6)&&n.unshift(e),n}snapZoom(e,t=`nearest`){let n=this.levels();if(t===`down`){let t=n[0];for(let r of n)r<=e+1e-6&&(t=r);return t}if(t===`up`){for(let t of n)if(t>=e-1e-6)return t;return n[n.length-1]}let r=n[0];for(let t of n)Math.abs(t-e)<Math.abs(r-e)&&(r=t);return r}stepZoom(e){let t=this.levels(),n=this.anim?this.anim.tz:this.zoom,r=0;for(let e=0;e<t.length;e++)Math.abs(t[e]-n)<Math.abs(t[r]-n)&&(r=e);return t[Math.max(0,Math.min(t.length-1,r+e))]}animateTo(e,t,n,r,i=400){let a=Math.max(Math.min(this.minZoom,1),Math.min(6,n));this.anim={fx:this.x,fy:this.y,fz:this.zoom,tx:e,ty:t,tz:a,t0:r,dur:i}}stop(){this.anim=null}panBy(e,t){this.anim=null,this.x-=e/this.zoom,this.y-=t/this.zoom,this.clamp()}zoomAt(e,t,n,r,i=!0){let a=Math.max(Math.min(this.minZoom,1),Math.min(6,e)),o=this.x+(t-this.viewW/2)/this.zoom,s=this.y+(n-this.viewH/2)/this.zoom,c=o-(t-this.viewW/2)/a,l=s-(n-this.viewH/2)/a;i?this.animateTo(c,l,a,r,160):(this.anim=null,this.x=c,this.y=l,this.zoom=a,this.freeZoom=!0,this.clamp())}settle(e){this.freeZoom&&(this.freeZoom=!1,this.zoomAt(this.snapZoom(this.zoom),this.viewW/2,this.viewH/2,e,!0))}update(e,t,n){if(this.anim){let t=this.anim,n=Math.min(1,(e-t.t0)/t.dur),r=vl(n);this.zoom=t.fz+(t.tz-t.fz)*r,this.x=t.fx+(t.tx-t.fx)*r,this.y=t.fy+(t.ty-t.fy)*r,n>=1&&(this.anim=null)}else if(t){let e=1-Math.exp(-n*6);this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e}this.clamp()}clamp(){let e=this.bounds,t=this.zoom,n=this.insets,r=(-this.viewW/2+n.left)/t,i=(this.viewW/2-n.right)/t,a=(-this.viewH/2+n.top)/t,o=(this.viewH/2-n.bottom)/t;this.x=e.w<=i-r?e.x+e.w/2-(r+i)/2:Math.max(e.x-r,Math.min(e.x+e.w-i,this.x)),this.y=e.h<=o-a?e.y+e.h/2-(a+o)/2:Math.max(e.y-a,Math.min(e.y+e.h-o,this.y))}transform(){let e=this.zoom*this.dpr;return{scale:e,ox:Math.round(this.viewW*this.dpr/2-this.x*e),oy:Math.round(this.viewH*this.dpr/2-this.y*e)}}worldToScreen(e,t){let{scale:n,ox:r,oy:i}=this.transform();return{x:(e*n+r)/this.dpr,y:(t*n+i)/this.dpr}}screenToWorld(e,t){let{scale:n,ox:r,oy:i}=this.transform();return{x:(e*this.dpr-r)/n,y:(t*this.dpr-i)/n}}fitZoom(e,t=24){let n=Math.max(80,this.viewW-this.insets.left-this.insets.right),r=Math.max(80,this.viewH-this.insets.top-this.insets.bottom);return Math.min((n-t*2)/e.w,(r-t*2)/e.h)}centerFor(e,t,n){return{x:e-(this.insets.left-this.insets.right)/2/n,y:t-(this.insets.top-this.insets.bottom)/2/n}}},bl=18e4,xl=6e5,Sl=15e5,Cl=15e3,wl=25e3,Tl=2500,El=1300,Dl=18e3,Ol=32e3,kl=4e3,Al=6e3,jl=3e4,Ml=4e3,Nl=150,Pl=400;function Fl(e){return e>=15e5?`nap`:e>=6e5?`cobweb`:e>=18e4?`restless`:`popcorn`}function Il(e){return e<6e5?0:e>=12e5?2:1}function Ll(e){return Math.floor(e/1200)%2?`hourglass_flip`:`hourglass`}function Rl(e,t){return!t||e.background===!1}function zl(e,t){if(!e)return null;let n=null;for(let r of e)Rl(r,t)&&Number.isFinite(r.startedAt)&&(!n||r.startedAt<n.startedAt)&&(n=r);return n}function Bl(e,t){if(!e)return 0;let n=0;for(let r of e)Rl(r,t)&&n++;return n}function Vl(e,t){let n=zl(e,!0);return!!n&&t-n.startedAt>1e4}function Hl(e){let t=zl(e.shells,e.status!==`shell`);return t?t.startedAt:e.statusSince}function Ul(e){let t=e.status!==`shell`,n=zl(e.shells,t);return n?.label?.trim()||(n?.kind===`monitor`?a(`Monitorando um processo`):a(t?`Comando no terminal`:`Comando em segundo plano`))}function Wl(e){let t=e.activity?.tool===`ShellDone`?e.activity:null,n=e.recent;if(n)for(let e=n.length-1;e>=0;e--){let r=n[e];r.tool===`ShellDone`&&(!t||r.at>t.at)&&(t=r)}return t}function Gl(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t} s`;let n=Math.floor(t/60);if(n<60)return`${n} min`;let r=Math.floor(n/60),i=n%60;return`${r} h ${i<10?`0`:``}${i}`}function Kl(e){let t=Math.max(0,Math.floor(e/1e3));return t<60?t:60+Math.floor(t/60)}function ql(e,t){return`${e} · ${Gl(t)}`}function Jl(e,t=0){if(e<0)return 0;if(e<6e3)return Yl(e,Al);let n=(t%jl+jl)%jl,r=e-jl-n;if(r<0)return 0;let i=r%jl;return i<4e3?Yl(i,Ml):0}function Yl(e,t){return Math.max(0,Math.min(1,e/Nl,(t-e)/Pl))}function Xl(e,t,n){let r=(e^Math.imul(t+1,2654435761)^Math.imul(n,2246822519))>>>0;return r^=r>>>16,r=Math.imul(r,2146121005),r^=r>>>15,r=Math.imul(r,2221713035),r^=r>>>16,(r>>>0)/4294967296}function Zl(e,t,n,r,i,a,o,s,c){if(e<t||e>=n)return-1;let l=t+r;for(let t=0;l<=e&&t<1e4;t++){if(e<l+o)return(e-l)/o;l+=i+Xl(s,t,c)*(a-i)}return-1}function Ql(e,t){return Zl(e,bl,xl,Tl,Cl,wl,800,t,1)}function $l(e,t){return Zl(e,xl,Sl,kl,Dl,Ol,El,t,2)}var eu=[`up`,`right`,`down`,`left`];function tu(e,t){return e<0?t:eu[(eu.indexOf(t)+Math.min(3,Math.floor(e*4))+1)%4]}var nu=[`Lia`,`Otávio`,`Bruna`,`Caio`,`Iara`,`Rui`,`Nina`,`Davi`,`Tais`,`Ivo`];function ru(e,t,n,r){let i=0,a=()=>Date.now(),o=()=>e.reapply(a()),s=()=>{let t=new Set([...e.rooms.values()].map(e=>e.slot));for(let n of e.injected.rooms)t.add(n.slot);let n=0;for(;t.has(n);)n++;return n},l=e=>{let t=a();return{look:i%2?`f`:`m`,role:e.kind===`main`?`Agente principal`:`Explore`,status:`working`,recent:[],tasks:e.kind===`main`?[{id:`1`,title:`Testar o mundo`,status:`in_progress`},{id:`2`,title:`Revisar`,status:`pending`}]:[],startedAt:t,lastEventAt:t,statusSince:t,stats:{toolCalls:0,tokensIn:0,tokensOut:0,subagents:0},seed:c(e.id),activity:{id:`dbg-act-${++i}`,kind:`edit`,icon:`✏️`,text:`Editando world.ts`,at:t},...e}},u=e=>e.map(e=>({id:e.id??`bdbg${(++i).toString(36)}`,label:e.label??`Rodar a suíte de testes`,command:e.command??`npm test`,startedAt:e.startedAt??a()-(e.ageMinutes??0)*6e4-(e.ageSeconds??0)*1e3,background:e.background??!0,kind:e.kind??`shell`})),d=(e,t)=>e===`waiting`||e===`offline`||e===`done`?e:t.some(e=>e.background)?`shell`:t.length?`working`:e===`shell`?`idle`:e,p=(t,n)=>{let r=e.injected.agents.findIndex(e=>e.id===t);if(r>=0){let t={...e.injected.agents[r]};return n(t),e.injected.agents[r]=t,!0}let i=e.chars.get(t);if(!i)return!1;let a={...i.info};n(a);let o={...e.agentPatches.get(t)};for(let e of[`status`,`statusSince`,`shells`,`activity`])a[e]!==i.info[e]&&Object.assign(o,{[e]:a[e]});return e.agentPatches.set(t,o),!0},m=(e,t)=>{let n=d(e.status,t);n!==e.status&&(e.statusSince=a()),e.status=n,e.shells=t;let r=zl(t,!1);n===`shell`&&r&&(e.statusSince=Math.min(e.statusSince,r.startedAt))};return{state:()=>({cols:e.building.cols,camera:{x:Math.round(n.x),y:Math.round(n.y),zoom:n.zoom},rooms:[...e.rooms.values()].map(t=>({id:t.id,name:t.info.name,slot:t.slot,phase:t.phase,listed:t.listed,lightOn:t.lightOn,light:Math.round(t.light(a())*100)/100,occupants:e.occupants(t)})),chars:[...e.chars.values()].map(e=>({id:e.id,name:e.info.name,kind:e.info.kind,status:e.info.status,mode:e.mode,step:e.step?.t??null,queue:e.queue.map(e=>e.t),tile:[e.tx,e.ty],room:e.roomId,spot:e.atSpot,leaving:e.leaving,pose:e.pose,held:e.held,dir:e.dir,icon:e.icon,shell:e.mode===`shell`?{stage:e.shellStage,count:e.shellCount,label:e.shellLabel,ageMin:Math.round((a()-e.shellSince)/6e4*10)/10}:null}))}),spawnSession:(t={})=>{let n=t.project??`projeto-teste-${i+1}`,r=[...e.rooms.values()].map(e=>e.info).find(e=>e.name===n)??e.injected.rooms.find(e=>e.name===n);if(!r){let t=`/debug/${n}`;r={id:t,name:n,path:t,slot:s(),seed:c(t),createdAt:a()},e.injected.rooms.push(r)}let d=++i,f=`dbg-sess-${d}`,p=t.account??[...e.accounts.keys()][d%Math.max(1,e.accounts.size)]??`.claude`,h=l({id:`dbg:${d}`,kind:`main`,name:t.name??nu[d%nu.length],roomId:r.id,account:p,sessionId:f,status:t.status??`working`,title:`Sessão de teste ${d}`});if(t.shell){let e=t.shell,n=Math.max(1,Math.floor(e.count??1)),r=[];for(let t=0;t<n;t++)r.push({label:t===0?e.label:`${e.label??`Rodar a suíte de testes`} (${t+1})`,command:e.command,ageMinutes:Math.max(0,(e.ageMinutes??0)-t*.5),background:e.background??!0,kind:e.kind});m(h,u(r)),h.activity={id:`dbg-act-${++i}`,kind:`run`,icon:`💻`,text:`Rodando em segundo plano`,tool:`Bash`,at:a()}}e.injected.agents.push(h);for(let n=0;n<(t.subs??0);n++){let t=++i;e.injected.agents.push(l({id:`${f}:sub${t}`,kind:`sub`,parentId:h.id,name:nu[t%nu.length],roomId:r.id,account:p,sessionId:f,title:`Investigar o bug`}))}return o(),h.id},setStatus:(t,n,r)=>{let s=e.injected.agents.findIndex(e=>e.id===t);if(s<0)return;let c={...e.injected.agents[s]};e.injected.agents[s]=c,c.status=n,c.statusSince=a(),c.waitingFor=n===`waiting`?r??`aprovar uma permissão`:void 0,c.activity={id:`dbg-act-${++i}`,kind:n===`idle`||n===`done`?`done`:n===`waiting`?`wait`:`run`,icon:n===`idle`||n===`done`?`✅`:n===`waiting`?`✋`:`💻`,text:n===`idle`||n===`done`?`Concluiu`:n===`waiting`?`Precisa de você`:`Rodando testes`,at:a()},o()},endSession:t=>{let n=e.injected.agents.find(e=>e.id===t);e.injected.agents=e.injected.agents.filter(e=>e.id!==t&&e.parentId!==t),n&&!e.injected.agents.some(e=>e.roomId===n.roomId)&&(e.injected.rooms=e.injected.rooms.filter(e=>e.id!==n.roomId)),o()},closeSession:t=>{e.forcedOffline.add(t);for(let n of e.chars.values())n.info.parentId===t&&e.forcedOffline.add(n.id);o()},closeRoom:t=>{for(let n of e.chars.values())n.roomId===t&&e.forcedOffline.add(n.id);e.hiddenRooms.add(t),o()},reset:()=>{e.agentPatches.clear(),e.forcedOffline.clear(),e.hiddenRooms.clear(),e.injected.agents=[],e.injected.rooms=[],o()},setHour:e=>{t.hourOverride=e},lookAt:(e,t,i)=>{r(),n.follow=null,n.stop(),n.x=e*16,n.y=t*16,i&&(n.zoom=i),n.clamp()},lookAtRoom:(t,i=2.5)=>{let a=[...e.rooms.values()].find(e=>e.id===t||e.info.name===t);if(!a)return;let o=a.layout.rect;r(),n.follow=null,n.stop(),n.x=(o.x+o.w/2)*16,n.y=(o.y+o.h/2)*16,n.zoom=i,n.clamp()},fastForward:()=>e.fastForward(a()),wanderNow:()=>{for(let t of e.chars.values())t.nextOutingAt=1},socialize:(t,n)=>(e.fastForward(a()),e.social.force(t,a(),n)),gatherings:()=>[...e.social.gatherings].map(t=>({kind:t.kind,phase:t.phase,program:t.program,bet:t.bet,score:t.score,members:t.members.map(t=>({name:e.chars.get(t.id)?.info.name??t.id,role:t.role,arrived:t.arrived,left:t.left,pose:t.pose}))})),coins:(t,n)=>{let r=e.social.wallets.get(t);return r?(n>0?e.social.wallets.credit(t,n,`🛠️`,`Ajuste (depuração)`,a()):r.coins=Math.max(0,r.coins+n),r.coins):0},setShells:(e,t)=>{p(e,e=>m(e,u(t)))&&o()},ageShells:(t,n)=>{let r=t*6e4;if(!Number.isFinite(r)||!r)return;let i=n?[n]:[...e.injected.agents.map(e=>e.id),...e.agentPatches.keys()];for(let e of i)p(e,e=>{e.shells?.length&&(e.shells=e.shells.map(e=>({...e,startedAt:e.startedAt-r})),e.status===`shell`&&(e.statusSince-=r))});o()},finishShell:(e,t=`completed`,n={})=>{let r=t===`completed`;p(e,e=>{let o=[...e.shells??[]].sort((e,t)=>e.startedAt-t.startedAt),s=n.all?o:o.slice(0,1),c=n.all?[]:o.slice(1),l=a(),u=s[0]?l-s[0].startedAt:void 0,d=r?`ok`:t===`killed`?`killed`:`failed`,p=s.map(e=>e.command??e.label).join(` | `)||void 0,m={id:`dbg-act-${++i}`,at:l,...f.shellDone(s[0]?.label,d,u,p)};r&&u!==void 0&&(m.durationMs=u),e.activity=m,e.recent=[...e.recent??[],m].slice(-30),e.shells=c;let h=c.some(e=>e.background)?`shell`:c.length?`working`:n.then??`working`;h!==e.status&&(e.status=h,e.statusSince=l)})&&o()},roomEffect:(t,n,r={})=>{let i=[...e.rooms.values()].find(e=>e.id===t||e.info.name===t);if(!i)return;if(!n){e.roomFx.active.delete(i.id);return}let o=a(),s=r.text??(n===`party`?`PR #12 mergeado!`:`CI falhou (main)`),c=r.agentId??[...e.chars.values()].find(e=>e.roomId===i.id&&!e.leaving)?.id,l=o+(n===`party`?12e3:36e5);e.roomFx.active.set(i.id,{roomId:i.id,kind:n,text:s,agentId:c,key:o,start:o,end:l,cheered:new Set,sticky:!0})},sim:e,camera:n}}var iu={attend:null,talk:null,lastAt:0};function au(e,t){if(t.at<=e.lastAt)return e;let n={agentId:t.agentId,screenId:t.screenId,at:t.at};switch(t.kind){case`open`:return{...e,attend:n,lastAt:t.at};case`send`:return{...e,attend:n,talk:{agentId:t.agentId,at:t.at},lastAt:t.at};case`close`:{let n=e.attend?.screenId===t.screenId&&e.attend.agentId===t.agentId;return{...e,attend:n?null:e.attend,lastAt:t.at}}case`decide`:return{...e,lastAt:t.at}}}function ou(e,t){let n=e.attend?.agentId;return n!==void 0&&t.has(n)?n:null}var su=15e3,cu={coffeeMs:3e5,napMs:12e5};function lu(e,t){return e===null||e<t.coffeeMs?`here`:e>=t.napMs?`nap`:`coffee`}var uu=class{last=null;pending=null;lastReturnTo=-1/0;feed(e,t){this.last={idleMs:e.idleMs,receivedAt:t},e.returned&&e.returned.to>this.lastReturnTo&&(this.lastReturnTo=e.returned.to,this.pending=e.returned)}stale(e){return!!this.last&&e-this.last.receivedAt>15e4}idleMs(e){return!this.last||this.last.idleMs===null||this.stale(e)?null:this.last.idleMs+Math.max(0,e-this.last.receivedAt)}takeReturned(){let e=this.pending;return this.pending=null,e}},du=class{sink;opts;state=iu;tracker=new uu;current=`here`;constructor(e,t){this.sink=e,this.opts=t}get stage(){return this.current}get attention(){return this.state}onAttention(e,t){let n=au(this.state,e);n!==this.state&&(this.state=n,this.sink.noteAttention(e,t),this.sink.setAttention(n,t),this.refreshStage(t))}onPresence(e,t){this.tracker.feed(e,t);let n=this.tracker.takeReturned();if(n&&n.to-n.from>=this.opts.thresholds().coffeeMs){let e=this.opts.toLocal??(e=>e);this.sink.returned({from:e(n.from),to:e(n.to)},t)}this.refreshStage(t)}tick(e){this.refreshStage(e)}refreshStage(e){if(!this.state.attend&&this.tracker.stale(e))return;let t=this.state.attend?`here`:lu(this.tracker.idleMs(e),this.opts.thresholds());t!==this.current&&(this.current=t,this.sink.setAway(t,e))}};function fu(e,t,n,r){let i=null,a=-1/0,o=null;for(let[s,c]of e)if(c.visible&&!(t.x<c.bx-n||t.x>c.bx+c.bw+n||t.y<c.by-n||t.y>c.by+c.bh+n)){if(s===r.playerId){o=s;continue}c.depth>a&&(a=c.depth,i=s)}return i??(r.inOwnOffice?o:null)}function pu(e,t){return e&&e.type===`agent`&&e.id===t?null:e}var mu=5,hu=90;function gu(e){if(e?.closest?.(`dialog, [popover], [role="dialog"], [aria-modal="true"]`))return!0;if(typeof document>`u`)return!1;if(document.querySelector(`dialog[open], :not(dialog)[aria-modal="true"]`))return!0;try{return!!document.querySelector(`:popover-open`)}catch{return!1}}function _u(e,t,n){let r=new Map,i=0,a=0,o=!1,s=null,c=0,l=null,u={t:0,x:0,y:0};e.style.touchAction=`none`,e.style.cursor=`grab`;let d=t=>{let n=e.getBoundingClientRect();return{x:t.clientX-n.left,y:t.clientY-n.top}},f=c=>{if(c.button!==0&&c.pointerType===`mouse`)return;let l=d(c);r.set(c.pointerId,l);try{e.setPointerCapture(c.pointerId)}catch{}if(r.size===1)i=l.x,a=l.y,o=!1;else if(r.size===2){let[e,i]=[...r.values()];s={dist:Math.hypot(e.x-i.x,e.y-i.y)||1,zoom:t.zoom,cx:(e.x+i.x)/2,cy:(e.y+i.y)/2},o=!0,n.interact()}},p=c=>{let l=d(c),u=r.get(c.pointerId);if(!u){c.pointerType===`mouse`&&n.hover(l.x,l.y,!0);return}if(r.set(c.pointerId,l),s&&r.size>=2){let[e,n]=[...r.values()],i=Math.hypot(e.x-n.x,e.y-n.y)||1,a=(e.x+n.x)/2,o=(e.y+n.y)/2;t.panBy(a-s.cx,o-s.cy),t.zoomAt(s.zoom*(i/s.dist),a,o,Date.now(),!1),s.cx=a,s.cy=o;return}!o&&Math.hypot(l.x-i,l.y-a)>mu&&(o=!0,e.style.cursor=`grabbing`,n.interact()),o&&t.panBy(l.x-u.x,l.y-u.y)},m=i=>{let a=d(i);if(!r.delete(i.pointerId))return;if(s&&r.size<2){s=null,t.settle(Date.now());return}if(r.size>0)return;if(e.style.cursor=`grab`,o){o=!1;return}let c=n.pick(a.x,a.y);if(i.pointerType!==`mouse`){let e=performance.now();if(e-u.t<320&&Math.hypot(a.x-u.x,a.y-u.y)<24){n.doubleClick(c),u={t:0,x:0,y:0};return}u={t:e,x:a.x,y:a.y}}n.click(c,a)},h=t=>{r.delete(t.pointerId),r.size<2&&(s=null),r.size||(o=!1,e.style.cursor=`grab`)},g=()=>n.hover(0,0,!1),_=e=>{let t=d(e);n.doubleClick(n.pick(t.x,t.y))},v=e=>{e.preventDefault();let r=d(e);n.interact();let i=e.deltaMode===1?e.deltaY*33:e.deltaMode===2?e.deltaY*400:e.deltaY;if(e.ctrlKey){t.zoomAt(t.zoom*Math.exp(-i*.012),r.x,r.y,Date.now(),!1),l&&clearTimeout(l),l=setTimeout(()=>t.settle(Date.now()),180);return}c+=i,Math.abs(c)>=50&&(n.zoomStep(c<0?1:-1,r.x,r.y),c=0)},y=e=>{if(e.defaultPrevented||e.ctrlKey||e.metaKey||e.altKey||n.active&&!n.active()||n.keys&&!n.keys())return;let r=e.target;if(r&&(r.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(r.tagName)||r.getAttribute?.(`role`)===`radio`)||gu(r))return;let i=0,a=0;switch(e.key){case`ArrowLeft`:case`a`:case`A`:i=hu;break;case`ArrowRight`:case`d`:case`D`:i=-90;break;case`ArrowUp`:case`w`:case`W`:a=hu;break;case`ArrowDown`:case`s`:case`S`:a=-90;break;case`+`:case`=`:n.zoomStep(1),e.preventDefault();return;case`-`:case`_`:n.zoomStep(-1),e.preventDefault();return;case`0`:n.overview(),e.preventDefault();return;default:return}e.preventDefault(),n.interact(),t.panBy(i,a)};return e.addEventListener(`pointerdown`,f),e.addEventListener(`pointermove`,p),e.addEventListener(`pointerup`,m),e.addEventListener(`pointercancel`,h),e.addEventListener(`pointerleave`,g),e.addEventListener(`dblclick`,_),e.addEventListener(`wheel`,v,{passive:!1}),window.addEventListener(`keydown`,y),()=>{e.removeEventListener(`pointerdown`,f),e.removeEventListener(`pointermove`,p),e.removeEventListener(`pointerup`,m),e.removeEventListener(`pointercancel`,h),e.removeEventListener(`pointerleave`,g),e.removeEventListener(`dblclick`,_),e.removeEventListener(`wheel`,v),window.removeEventListener(`keydown`,y),l&&clearTimeout(l)}}function vu(e){return!Number.isFinite(e)||e<=0?0:Math.min(16,Math.max(1,Math.round(Math.sqrt(e)*.75)))}function yu(e,t){return t?{...e,serverTime:e.serverTime+t,agents:e.agents.map(e=>{let n={...e,statusSince:e.statusSince+t};return e.shells&&(n.shells=e.shells.map(e=>({...e,startedAt:e.startedAt+t}))),n})}:e}function bu(e){return e.filter(e=>e.status===`waiting`).sort((e,t)=>e.statusSince-t.statusSince)}function xu(e){return bu(e).map(e=>({agentId:e.id,since:e.permission?.createdAt??e.statusSince,kind:e.permission?`stamp`:`terminal`})).sort((e,t)=>e.since-t.since||(e.agentId<t.agentId?-1:+(e.agentId>t.agentId)))}function Su(e,t){let n=e.slice(0,Math.max(0,t));return{queued:n,overflow:e.length-n.length}}function Cu(e){return e>0?a(`+{0} esperando`,[e]):null}function wu(e,t){return e.kind===`terminal`?{text:a(`responder no terminal`),stamp:null}:{text:a(`aguardando resposta`),stamp:t}}function Tu(e){return e===`allow`||e===`answer`?`green`:e===`deny`?`red`:null}var Eu=class{entries=new Map;note(e,t){if(e.kind!==`decide`)return;let n=Tu(e.verdict);n&&this.entries.set(e.agentId,{stamp:n,receivedAt:t})}take(e,t){let n=this.entries.get(e);return n?(this.entries.delete(e),t-n.receivedAt<=5e3?n.stamp:null):null}prune(e){for(let[t,n]of this.entries)e-n.receivedAt>5e3&&this.entries.delete(t)}get size(){return this.entries.size}},Du=e=>e<0?0:e>1?1:e;function Ou(e){return 1+2.70158*(e-1)**3+1.70158*(e-1)**2}function ku(e){return 2.70158*e*e*e-1.70158*e*e}function Au(e){return 1-(1-e)**3}var ju={floor:1,walls:1,sign:1,mode:`none`,p:1};function Mu(e,t){return e===`building`?{floor:Du(t/.4),walls:Au(Du((t-.22)/.3)),sign:Au(Du((t-.84)/.16)),mode:`build`,p:t}:e===`dismantling`?{floor:1-Du((t-.7)/.3),walls:1-Du((t-.47)/.25),sign:1-Du(t/.15),mode:`dismantle`,p:t}:ju}function Nu(e,t){if(e.mode===`build`){let n=Du((e.p-(.48+t*.36))/.13);return n<=0?0:n>=1?1:Math.max(0,Ou(n))}if(e.mode===`dismantle`){let n=Du((e.p-(1-t)*.33)/.12);return n<=0?1:n>=1?0:Math.max(0,1-ku(n))}return 1}function Pu(e,t,n,r){return(e+t*.8)/(n+r*.8)}function Fu(e,t,n,r){let i=Math.max(0,Math.min(n,t.w-16)),a=Math.max(0,e.x),o=Math.min(t.w,e.x+e.w),s=Math.max(0,e.y),c=Math.min(t.h,e.y+e.h),l=o>a?(a+o)/2:e.x+e.w/2,u=c>s?(s+c)/2:e.y+e.h/2,d=i/2;return{cx:Math.round(Math.min(Math.max(l,d+8),Math.max(d+8,t.w-d-8))),top:Math.round(Math.min(Math.max(u-r/2,8),Math.max(8,t.h-r-8))),maxW:i}}var Iu=`ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif`,Lu=`600 10.5px ${Iu}`,Ru=`500 11.5px ${Iu}`,zu=`500 10.5px ${Iu}`,Bu=`800 12px ${Iu}`,Vu=`700 8px ${Iu}`,Hu=`700 8px ${Iu}`,Uu=`700 12px ${Iu}`,Wu=`600 11px ${Iu}`,Gu=`600 9.5px ${Iu}`,Ku=e=>`700 ${e}px ${Iu}`,qu=20,Ju=15,Yu=4e3,Xu=14,Zu=1,Qu=4,$u={"core:recepcao":a(`Recepção`),"core:banheiros":a(`Banheiros`),"core:copa":a(`Copa`),"core:lounge":a(`Lounge`),"core:meu-escritorio":a(`Meu escritório`)},ed=17,td=`#161b26`,nd=`CODEX`;function rd(e,t,n,r,i,a){e.beginPath(),e.moveTo(t+a,n),e.lineTo(t+r-a,n),e.lineTo(t+r,n+a),e.lineTo(t+r,n+i-a),e.lineTo(t+r-a,n+i),e.lineTo(t+a,n+i),e.lineTo(t,n+i-a),e.lineTo(t,n+a),e.closePath()}function id(e,t,n,r,i){if(e.beginPath(),e.arc(t,n,r,0,Math.PI*2),i.provider===`codex`){e.fillStyle=td,e.fill(),e.lineWidth=Math.max(1.2,r*.55),e.strokeStyle=i.color,e.beginPath(),e.arc(t,n,r-e.lineWidth/2,0,Math.PI*2),e.stroke();return}e.fillStyle=i.color,e.fill()}function ad(e){let t=/^#?([0-9a-f]{6})$/i.exec(e);if(!t)return .5;let n=parseInt(t[1],16);return(.2126*(n>>16&255)+.7152*(n>>8&255)+.0722*(n&255))/255}function od(e){return e.icon===`storm`?16:e.mode===`wait`||e.mode===`shell`||e.icon?13:0}function sd(e){let t=(e??``).trim().replace(/^precisa de você:?\s*/i,``);return t?t.charAt(0).toUpperCase()+t.slice(1):a(`Responder no terminal`)}function cd(e){return e.player?e.selected||e.hovered:e.selected||e.hovered||e.waiting||e.showAll||e.visitor}function ld(e,t,n){let r=e.map((e,t)=>t).sort((t,n)=>e[n].prio-e[t].prio||e[n].changedAt-e[t].changedAt),i=new Set,a=new Map;for(let o of r){if(i.size>=n)break;let r=a.get(e[o].room)??0;r>=t||(a.set(e[o].room,r+1),i.add(o))}return i}var ud={green:`#2e9e5b`,red:`#d03a3a`},dd=class{ctx;sim;renderer;camera;widths=new Map;fitted=new Map;placed=[];items=[];bubblePool=[];labelPool=[];nb=0;nl=0;rationIn=[];rationIdx=[];k=1;ox=0;oy=0;zoom=1;constructor(e,t,n,r){this.ctx=e,this.sim=t,this.renderer=n,this.camera=r,Js()}resetCaches(){this.widths.clear(),this.fitted.clear()}measure(e,t){let n=`${Xs()}|${e}|${t}`,r=this.widths.get(n);return r===void 0&&(this.widths.size>4e3&&this.widths.clear(),this.ctx.font=e,r=Zs(this.ctx,t),this.widths.set(n,r)),r}fit(e,t,n){let r=`${Xs()}|${e}|${n}|${t}`,i=this.fitted.get(r);if(i!==void 0)return i;this.fitted.size>2e3&&this.fitted.clear();let a=t;if(this.measure(e,t)>n){let r=0,i=t.length;for(;r<i;){let a=r+i+1>>1;this.measure(e,`${t.slice(0,a).trimEnd()}…`)<=n?r=a:i=a-1}a=r>0?`${t.slice(0,r).trimEnd()}…`:``}return this.fitted.set(r,a),a}sx(e){return e*this.k+this.ox}sy(e){return e*this.k+this.oy}overlaps(e,t,n,r){let i=this.placed;for(let a=0;a<i.length;a+=4)if(e<i[a]+i[a+2]&&e+n>i[a]&&t<i[a+1]+i[a+3]&&t+r>i[a+1])return!0;return!1}place(e,t,n,r){this.placed.push(e,t,n,r)}draw(e,t,n){let{ctx:r,camera:i}=this,a=i.dpr;r.setTransform(a,0,0,a,0,0),r.textBaseline=`middle`,this.placed.length=0;let o=i.transform();this.k=o.scale/a,this.ox=o.ox/a,this.oy=o.oy/a,this.nb=0,this.nl=0;let s=this.zoom=i.zoom,c=i.viewW,l=i.viewH;if(n.room)for(let t of this.sim.rooms.values()){if(t.id!==n.room&&t.annexOf!==n.room||!t.present)continue;let i=t.layout.rect,a=this.sx(i.x*16),o=this.sy(i.y*16),s=this.sx((i.x+i.w)*16),c=this.sy((i.y+i.h)*16);r.save(),r.strokeStyle=t.theme.accent,r.lineWidth=2.5,r.globalAlpha=.85+Math.sin(e/300)*.15,r.beginPath(),r.roundRect(a-2,o-2,s-a+4,c-o+4,6),r.stroke(),r.restore()}this.drawRoomTexts(e,s),this.drawFxBanners(e,s),this.drawIntrusionBanner(e),this.drawQueue();let u=this.items;u.length=0;let d=this.renderer.heads,f=t.showNames&&s>=.99;for(let r of this.sim.people()){let i=d.get(r.id);if(!i||!i.visible)continue;let a=this.sx(i.x),o=this.sy(i.y);if(a<-120||a>c+120||o<-60||o>l+80)continue;let p=n.agent===r.id,m=n.hover===r.id,h=r===this.sim.visitor,g=cd({selected:p,hovered:m,waiting:r.mode===`wait`,showAll:f,visitor:h,player:r===this.sim.player?.ch}),_=g&&this.labelAbove(r),v=this.bubbleFor(r,i,e,t,p,m);if(v&&(v.extraLift=_?18:0,u.push(v)),g){let e=p?100:m?95:h?92:r.mode===`wait`?90:r.info.kind===`main`?50:40,t=this.labelPool[this.nl];t?(t.ch=r,t.head=i,t.prio=e,t.above=_):this.labelPool[this.nl]=t={type:`label`,ch:r,head:i,prio:e,above:_,compact:!1,x:0,y:0,w:0,h:0},t.compact=s<2.5&&!p&&!m,this.nl++,u.push(t)}}this.ration(s),u.sort((e,t)=>t.prio-e.prio||(e.type===t.type?e.head.feetY-t.head.feetY:e.type===`bubble`?-1:1));let p=0;for(let e of u)(e.type===`bubble`?this.placeBubble(e):this.placeLabel(e))&&(u[p++]=e);u.length=p;for(let t=u.length-1;t>=0;t--){let r=u[t];r.type===`bubble`?this.drawBubble(r,e):this.drawLabel(r,n)}this.drawChats(e),this.drawFloaters(e),r.textBaseline=`alphabetic`}drawQueue(){let e=this.sim.player;if(!e?.ch)return;let{ctx:t}=this,n=this.k;for(let r of e.queueSlots().keys()){let i=this.renderer.heads.get(r),a=e.queueEntry(r);if(!i||!i.visible||!a)continue;let o=this.sim.stamps.get(r),s=wu(a,o?.color??null),c=26*n,l=15*n,u=this.sx(i.bx+i.bw)+1,d=this.sy(i.by+i.bh*.45);if(t.save(),t.fillStyle=`rgba(0,0,0,0.18)`,t.fillRect(u+1,d+1,c,l),t.fillStyle=`#fbf7ea`,t.fillRect(u,d,c,l),t.strokeStyle=`#b9ae92`,t.lineWidth=1,t.strokeRect(u+.5,d+.5,c-1,l-1),t.beginPath(),t.rect(u+1,d+1,c-2,l-2),t.clip(),t.textAlign=`left`,n>=2){let e=`600 ${Math.max(6,Math.round(3.6*n))}px system-ui, sans-serif`;t.font=e,t.fillStyle=`#3a3426`,Qs(t,this.fit(e,s.text,c-4),u+2,d+l*.3)}else t.fillStyle=`#c9bfa4`,t.fillRect(u+3,d+l*.28,c-6,1),t.fillRect(u+3,d+l*.5,c*.6,1);if(s.stamp&&o){let e=Math.min(1,Math.max(0,1-(o.until-this.sim.now)/900)),r=l*.3*(1.6-.6*Math.min(1,e*3));t.globalAlpha=Math.min(1,e*4),t.strokeStyle=t.fillStyle=ud[s.stamp],t.lineWidth=Math.max(1.5,n*.8),t.beginPath(),t.arc(u+c*.72,d+l*.68,r,0,Math.PI*2),t.stroke(),t.globalAlpha*=.25,t.fill()}t.restore()}let r=Cu(this.sim.queueOverflow);if(!r)return;let i=this.sim.spots.ofKind(`queue`).reduce((e,t)=>!e||(t.rank??0)>(e.rank??0)?t:e,null);if(!i)return;let a=`700 ${Math.max(9,Math.round(4.2*n))}px system-ui, sans-serif`;t.save(),t.font=a,t.textAlign=`center`;let o=Zs(t,r)+8,s=Math.max(13,6.4*n),c=this.sx(i.tx*16+8),l=this.sy(i.ty*16)-s-4*n;t.fillStyle=`#7a5a34`,t.fillRect(c-1,l+s,2,4*n),t.fillStyle=`#f0d9a6`,t.fillRect(c-o/2,l,o,s),t.strokeStyle=`#7a5a34`,t.lineWidth=1.5,t.strokeRect(c-o/2+.5,l+.5,o-1,s-1),t.fillStyle=`#3a2a14`,t.textBaseline=`middle`,Qs(t,r,c,l+s/2+.5),t.restore()}labelAbove(e){if(!e.seated||e.dir!==`down`||!e.atSpot)return!1;let t=this.sim.spots.get(e.atSpot);return!!t&&t.kind===`desk`}ration(e){let t=this.items;if(e<.6){let e=0;for(let n of t){if(n.type===`bubble`){if(n.tone===`info`&&n.prio<75||n.tone===`say`)continue;n.chip=!0}t[e++]=n}t.length=e;return}if(e>=1.8)return;let n=this.rationIn,r=this.rationIdx;n.length=0,r.length=0;for(let e of t){if(e.type!==`bubble`||e.tone!==`info`&&e.tone!==`shell`&&e.tone!==`say`||e.prio>=75)continue;let t=e.ch;n.push({room:`${Math.floor(t.tx/16)}:${t.ty<12?`n`:t.ty<17?`c`:`s`}`,prio:e.prio,changedAt:e.changedAt}),r.push(e)}if(!r.length)return;let i=ld(n,Zu,Qu);for(let e=0;e<r.length;e++)i.has(e)||(r[e].chip=!0)}drawRoomTexts(e,t){let{camera:n}=this,r=this.ctx,i=n.viewW,a=n.viewH,o=256*t;for(let n of this.renderer.areas.values()){let s=n.room,c=n.layout.rect,l=s?Mu(s.phase,s.progress(e)):null,u=this.renderer.signRect(n),d=s?Dt(s.info,this.sim.machines):null,f=d?d.tag?`${d.text} (${d.tag})`:d.text:n.id===`core:recepcao`?`Busybits`:null,p=!!d?.dim,m=!!u&&u.h*t>=Xu;if(m&&u&&f&&(!l||l.sign>=1)){let e=this.sx(u.x),o=this.sy(u.y),c=u.w*t,l=u.h*t;e+c>0&&e<i&&o+l>0&&o<a&&(r.save(),p&&(r.globalAlpha=.5),this.drawSignText(f,e,o,c,l,this.renderer.signIsDark(n),s?.accounts??[]),r.restore(),this.place(e,o,c,l))}if(s?m:t>=1.4)continue;let h=this.sx((c.x+c.w/2)*16),g=this.sy(c.y*16+6);if(!(h<-200||h>i+200||g<-40||g>a+40)){if(s){if(!s.present||s.ghost||l&&l.walls<.6)continue;this.drawRoomPill(f??s.info.name,h,g,o-8,s.accounts,this.countIn(s.id),s.theme.accent,s.lightOn,p)}else $u[n.id]&&this.drawCorePill($u[n.id],h,g,o-8)}}}iconLift(e){let t=od(e);return this.sim.roomFx.active.size&&this.sim.roomFx.alarmOwner(e.id,this.sim.now)?Math.max(t,13):t}drawFxBanners(e,t){let n=this.sim.roomFx.active;if(!n.size)return;let{camera:r}=this;for(let i of n.values()){let n=this.sim.rooms.get(i.roomId);if(!n||!n.present||e>=i.end)continue;let a=n.layout.rect,o=this.sx((a.x+a.w/2)*16),s=this.sy((a.y+2)*16)+4;if(o<-200||o>r.viewW+200||s<-40||s>r.viewH+40)continue;let c=Sc(this.ctx,i,o,s,a.w*16*t-12,e,(e,t,n)=>this.fit(e,t,n),(e,t)=>this.measure(e,t));c&&this.place(c.x,c.y,c.w,c.h)}}drawIntrusionBanner(e){let t=this.sim.intrusionEffect;if(!t||e>=t.end)return;let{camera:n}=this,r=this.sim.building.rect,i=Fu({x:this.sx(r.x*16),y:this.sy(r.y*16),w:r.w*16*n.zoom,h:r.h*16*n.zoom},{w:n.viewW,h:n.viewH},460,22),a={roomId:``,kind:`alarm`,text:t.text.replace(/^🚨\s*/u,``),key:t.key,start:t.start,end:t.end,cheered:new Set},o=Sc(this.ctx,a,i.cx,i.top,i.maxW,e,(e,t,n)=>this.fit(e,t,n),(e,t)=>this.measure(e,t));o&&this.place(o.x,o.y,o.w,o.h)}countIn(e){return this.sim.countIn(e)}drawSignText(e,t,n,r,i,a,o){let{ctx:s}=this,c=Math.min(18,Math.max(7,Math.floor(i*.72))),l=Ku(c);for(;c>7&&this.measure(l,e)>r-4;)c--,l=Ku(c);let u=this.fit(l,e,r-4);s.font=l,s.textAlign=`center`;let d=Math.round(t+r/2),f=Math.round(n+i/2)+.5;s.fillStyle=a?`rgba(0,0,0,0.35)`:`rgba(255,255,255,0.45)`,Qs(s,u,d,f+1),s.fillStyle=a?`#f5f1e6`:`#26303e`,Qs(s,u,d,f),s.textAlign=`left`;let p=Math.max(2.5,Math.min(4,i*.22)),m=t+r+p+3;for(let e of o){let t=this.sim.accounts.get(e);t&&(id(s,m,n+i/2,p,t),s.beginPath(),s.arc(m,n+i/2,p,0,Math.PI*2),s.lineWidth=1,s.strokeStyle=`rgba(20,24,36,0.65)`,s.stroke(),m+=p*2+2)}}drawRoomPill(e,t,n,r,i,a,o,s,c=!1){let{ctx:l}=this,u=i.filter(e=>this.sim.accounts.has(e)),d=a>0?String(a):``,f=d?this.measure(Lu,d)+14:0,p=this.fit(Uu,e,Math.min(180,r-(18+u.length*10+f)));if(p.length<Math.min(7,e.length)){let t=this.fit(Uu,e,r-18);t.length>=4&&(p=t,u=[],d=``,f=0)}let m=18+u.length*10+f,h=p!==e&&p.length<4,g=h?0:this.measure(Uu,p),_=Math.round(h?Math.max(12,10+f+u.length*10):g+m),v=Math.round(t-_/2),y=Math.round(n-22-4);l.save(),l.globalAlpha=c?.5:s?1:.8,l.fillStyle=`rgba(16,20,32,0.28)`,l.beginPath(),l.roundRect(v,y+2,_,22,7),l.fill(),l.fillStyle=`rgba(22,27,40,0.9)`,l.beginPath(),l.roundRect(v,y,_,22,7),l.fill(),l.fillStyle=o,l.beginPath(),l.roundRect(v,y,4,22,[7,0,0,7]),l.fill();let b=v+10;h||(l.font=Uu,l.fillStyle=`#f3f5fa`,Qs(l,p,v+10,y+11+1),b=v+10+g+8);for(let e of u)id(l,b+3,y+11,3.5,this.sim.accounts.get(e)),b+=10;d&&(l.fillStyle=`rgba(255,255,255,0.14)`,l.beginPath(),l.roundRect(b+2,y+4,f-4,14,5),l.fill(),l.font=Lu,l.fillStyle=`#dfe5f2`,l.fillText(d,b+7,y+11+.5)),l.restore(),this.place(v,y,_,22)}drawCorePill(e,t,n,r){let{ctx:i}=this,a=this.measure(Wu,e)<=r-14?Wu:Gu,o=this.fit(a,e,r-14);if(o.length<3)return;let s=this.measure(a,o),c=Math.round(s+14),l=Math.round(t-c/2),u=Math.round(n-18-4);i.fillStyle=`rgba(22,27,40,0.62)`,i.beginPath(),i.roundRect(l,u,c,18,6),i.fill(),i.font=a,i.fillStyle=`#e8ecf5`,Qs(i,o,l+7,u+9+1),this.place(l,u,c,18)}takeBubble(e,t,n,r,i,a,o,s){let c=this.bubblePool[this.nb];return c?(c.ch=e,c.head=t,c.icon=n,c.text=r,c.tone=i,c.prio=a,c.alpha=o,c.chip=!1,c.extraLift=0,c.changedAt=s,c.lifted=!1):(c={type:`bubble`,ch:e,head:t,icon:n,text:r,tone:i,prio:a,alpha:o,chip:!1,extraLift:0,changedAt:s,x:0,y:0,w:0,h:0,fitted:``,lifted:!1},this.bubblePool[this.nb]=c),this.nb++,c}bubbleFor(e,t,n,r,i,o){if(r.bubbles===`none`)return null;if(e.mode===`wait`)return this.takeBubble(e,t,`✋`,this.sim.visit?a(`Esperando o dono`):sd(e.info.waitingFor),`alert`,100,1,n);if(e.bubbleText&&n<e.bubbleUntil){let r=Math.min(1,(n-e.bubbleAt)/150,(e.bubbleUntil-n)/400);return this.takeBubble(e,t,e.bubbleIcon,e.bubbleText,`deliver`,90,r,e.bubbleAt)}if(e.sayText&&n<e.sayUntil&&!e.leaving){let r=Math.min(1,(n-e.sayAt)/120,(e.sayUntil-n)/300);return this.takeBubble(e,t,fd(e.sayText),e.sayText,`say`,55,r,e.sayAt)}let s=e.info.activity;if(e.mode===`shell`&&e.shellSince>0&&!e.leaving){let a=this.shellBubble(e,t,n,r,i,o);if(a)return a}if(!s||e.leaving)return null;let c=n-e.activityChangedAt;if(i)return this.takeBubble(e,t,s.icon,s.text,`info`,80,1,e.activityChangedAt);if(o)return this.takeBubble(e,t,s.icon,s.text,`info`,75,1,e.activityChangedAt);if(r.bubbles===`all`&&e.mode===`work`)return this.takeBubble(e,t,s.icon,s.text,`info`,c<Yu?50:30,1,e.activityChangedAt);if(c<Yu&&e.activityChangedAt>0){let n=Math.min(1,c/150,(Yu-c)/500);return this.takeBubble(e,t,s.icon,s.text,`info`,50,n,e.activityChangedAt)}return null}shellBubble(e,t,n,r,i,a){if(n-e.activityChangedAt<Yu&&e.activityChangedAt>e.shellEnteredAt+500&&!i&&!a)return null;let o=this.shellText(e,n);if(i)return this.takeBubble(e,t,`⏳`,o,`shell`,80,1,e.shellEnteredAt);if(a)return this.takeBubble(e,t,`⏳`,o,`shell`,75,1,e.shellEnteredAt);if(r.bubbles===`all`)return this.takeBubble(e,t,`⏳`,o,`shell`,45,1,e.shellEnteredAt);let s=Jl(n-e.shellEnteredAt,Xl(e.info.seed,0,3)*9e3);return s>.01?this.takeBubble(e,t,`⏳`,o,`shell`,50,s,e.shellEnteredAt):null}shellText(e,t){if(this.sim.visit)return e.shellLabel;let n=t-e.shellSince,r=Kl(n);return(r!==e.shellTextKey||!e.shellText)&&(e.shellTextKey=r,e.shellText=ql(e.shellLabel,n)),e.shellText}layoutBubble(e){let{camera:t}=this,n=Math.max(1,this.iconLift(e.ch))*this.zoom+e.extraLift,r=this.sx(e.head.x),i=this.sy(e.head.y),a=e.tone===`say`,o=e.icon&&!a?this.measure(Ru,e.icon)+4:0;if(e.chip||!e.text)e.fitted=``,e.w=Math.round(Math.max(20,(a?this.measure(Ru,e.icon)+4:o)+10));else if(a)e.fitted=this.fit(zu,e.text,156),e.w=Math.round(Math.min(170,this.measure(zu,e.fitted)+14));else{let t=e.tone===`alert`?340:220;e.fitted=this.fit(Ru,e.text,t-16-o),e.w=Math.round(Math.min(t,this.measure(Ru,e.fitted)+o+14))}e.h=a&&!e.chip?ed:qu,e.x=Math.max(4,Math.min(t.viewW-e.w-4,Math.round(r-e.w/2))),e.y=Math.round(i-n-e.h-6)}placeBubble(e){if(this.layoutBubble(e),!this.overlaps(e.x,e.y,e.w,e.h))return this.place(e.x,e.y,e.w,e.h),!0;if(e.tone===`alert`){let t=e.y-e.h-6;return this.overlaps(e.x,t,e.w,e.h)||(e.y=t,e.lifted=!0),this.place(e.x,e.y,e.w,e.h),!0}return!e.chip&&(e.chip=!0,this.layoutBubble(e),!this.overlaps(e.x,e.y,e.w,e.h))&&(this.place(e.x,e.y,e.w,e.h),!0)}drawBubble(e,t){let{ctx:n}=this,{x:r,y:i,w:a,h:o}=e,s=this.sx(e.head.x),c=e.tone,l=c===`alert`?`#ffcf4a`:c===`deliver`?`#e2f0ff`:c===`shell`?`#1d2433`:c===`say`?`#ffffff`:`#fffdf8`,u=c===`alert`?`#c58f10`:c===`deliver`?`#7aa7d9`:c===`shell`?`#4b5d7e`:c===`say`?`rgba(40,48,66,0.38)`:`rgba(40,48,66,0.22)`,d=c===`alert`?`#3b2a00`:c===`deliver`?`#17324f`:c===`shell`?`#b9f6b4`:c===`say`?`#1d2330`:`#232a36`,f=c===`alert`?1+Math.sin(t/160)*.035:1;if(n.save(),n.globalAlpha=e.alpha,e.lifted){let e=Math.max(r+8,Math.min(r+a-8,Math.round(s)));n.strokeStyle=u,n.lineWidth=1.5,n.beginPath(),n.moveTo(e+.5,i+o),n.lineTo(e+.5,i+2*o+11),n.stroke()}f!==1&&(n.translate(s,i+o),n.scale(f,f),n.translate(-s,-(i+o)));let p=Math.max(r+8,Math.min(r+a-8,Math.round(s)));if(n.fillStyle=`rgba(16,20,32,0.22)`,n.beginPath(),n.roundRect(r,i+2,a,o,7),n.fill(),n.fillStyle=l,n.strokeStyle=u,n.lineWidth=1,n.beginPath(),n.roundRect(r+.5,i+.5,a-1,o-1,7),n.fill(),n.stroke(),n.beginPath(),n.moveTo(p-4.5,i+o-1),n.lineTo(p,i+o+5),n.lineTo(p+4.5,i+o-1),n.closePath(),n.fill(),n.beginPath(),n.moveTo(p-4.5,i+o-.5),n.lineTo(p,i+o+5),n.lineTo(p+4.5,i+o-.5),n.stroke(),n.fillStyle=l,n.fillRect(p-4,i+o-2,8,2),n.font=c===`say`&&!e.chip?zu:Ru,n.fillStyle=d,c===`say`&&!e.chip&&e.fitted)n.textAlign=`center`,Qs(n,e.fitted,r+a/2,i+o/2+1),n.textAlign=`left`;else if(e.chip||!e.fitted)n.textAlign=`center`,Qs(n,e.icon||`…`,r+a/2,i+o/2+1),n.textAlign=`left`;else{let t=r+7;e.icon&&(Qs(n,e.icon,t,i+o/2+1),t+=this.measure(Ru,e.icon)+4),Qs(n,e.fitted,t,i+o/2+1)}n.restore()}drawChats(e){let{ctx:t}=this;for(let n of this.sim.chars.values()){if(!n.chatEmoji||e>n.chatUntil)continue;let r=this.renderer.heads.get(n.id);if(!r||!r.visible)continue;let i=this.sx(r.x),a=this.sy(r.y),o=Math.min(1,(n.chatUntil-e)/300,1-(n.chatUntil-e-1e3)/200),s=n.dir===`left`?-1:1,c=Math.round(i+s*12),l=Math.round(a-16-(1-Math.min(1,o))*4);t.save(),t.globalAlpha=Math.max(0,Math.min(1,o)),t.fillStyle=`rgba(16,20,32,0.2)`,t.beginPath(),t.arc(c,l+1.5,12,0,Math.PI*2),t.fill(),t.fillStyle=`#ffffff`,t.beginPath(),t.arc(c,l,12,0,Math.PI*2),t.moveTo(c-s*4,l+12-2),t.lineTo(c-s*9,l+12+4),t.lineTo(c-s*1,l+12-1),t.fill(),t.font=`14px ${Iu}`,t.textAlign=`center`,Qs(t,n.chatEmoji,c,l+1),t.textAlign=`left`,t.restore()}}drawFloaters(e){let t=this.sim.social.floaters;if(!t.length||this.zoom<.6)return;let{ctx:n}=this;n.save(),n.font=Bu,n.textAlign=`center`,n.lineJoin=`round`;for(let r of t){let t=this.renderer.heads.get(r.charId);if(!t||!t.visible||e<r.at)continue;let i=Math.min(1,(e-r.at)/(r.until-r.at)),a=Math.round(this.sx(t.x)+10*this.zoom+12),o=Math.round(this.sy(t.y)+4*this.zoom-i*24);n.globalAlpha=i<.12?i/.12:Math.max(0,1-Math.max(0,i-.6)/.4),n.lineWidth=3,n.strokeStyle=`rgba(20,24,36,0.85)`,Qs(n,r.text,a,o,`stroke`),n.fillStyle=r.color,Qs(n,r.text,a,o)}n.restore()}labelWidth(e){let t=e.ch,n=this.sim.accounts.get(t.info.account);return{nameW:this.measure(Lu,xt(t.info,this.sim.machines)),chipW:n?13:0,badgeW:t===this.sim.visitor?this.measure(Hu,pd())+7:t.info.kind===`sub`&&!e.compact?this.measure(Hu,`SUB`)+7:0,codexW:t.info.provider===`codex`&&!e.compact?this.measure(Hu,nd)+7:0}}placeLabel(e){let{nameW:t,chipW:n,badgeW:r,codexW:i}=this.labelWidth(e),a=Math.round(t+10+n+(r?r+3:0)+(i?i+3:0)),o=Ju,s=Math.round(this.sx(e.head.x)-a/2),c=Math.round(this.sy(e.head.feetY)+3),l=this.iconLift(e.ch)*this.zoom,u=Math.round(this.sy(e.head.y)-l-o-3),d=e.above?u:c,f=e.above?c:u;if(e.w=a,e.h=o,e.x=s,!this.overlaps(s,d,a,o))e.y=d;else if(!this.overlaps(s,f,a,o))e.y=f;else if(e.prio>=90)e.y=d;else return!1;return this.place(e.x,e.y,a,o),!0}drawLabel(e,t){let{ctx:n}=this,r=e.ch,i=this.sim.accounts.get(r.info.account),a=r.info.kind===`sub`,o=r.info.provider===`codex`||i?.provider===`codex`,{nameW:s,chipW:c,badgeW:l,codexW:u}=this.labelWidth(e),{x:d,y:f,w:p,h:m}=e;n.fillStyle=t.agent===r.id?`rgba(18,96,140,0.95)`:r.mode===`wait`?`rgba(120,78,0,0.92)`:`rgba(22,26,38,0.82)`,n.beginPath(),n.roundRect(d,f,p,m,7.5),n.fill();let h=d+4;i&&o?(rd(n,h,f+m/2-5,10,10,2),n.fillStyle=td,n.fill(),n.lineWidth=1.5,n.strokeStyle=i.color,rd(n,h+.75,f+m/2-4.25,8.5,8.5,1.6),n.stroke(),n.font=Vu,n.textAlign=`center`,n.fillStyle=i.color,n.fillText(i.short.slice(0,1),h+5,f+m/2+.5),n.textAlign=`left`,h+=c):i&&(n.beginPath(),n.arc(h+5,f+m/2,5,0,Math.PI*2),n.fillStyle=i.color,n.fill(),n.font=Vu,n.textAlign=`center`,n.fillStyle=ad(i.color)>.62?`#1d2330`:`#ffffff`,n.fillText(i.short.slice(0,1),h+5,f+m/2+.5),n.textAlign=`left`,h+=c),n.font=Lu,n.fillStyle=`#f5f7fb`,n.fillText(xt(r.info,this.sim.machines),h+1,f+m/2+.5),h+=s+4,l?(n.fillStyle=r.appearance.lanyard??`#f2b33d`,n.beginPath(),n.roundRect(h,f+3,l,m-6,4),n.fill(),n.font=Hu,n.fillStyle=`#2a2000`,n.fillText(r===this.sim.visitor?pd():`SUB`,h+3.5,f+m/2+.5),h+=l+3):a&&(n.fillStyle=r.appearance.lanyard??`#f2b33d`,n.beginPath(),n.arc(d+p-3,f+3,2.5,0,Math.PI*2),n.fill()),u&&(n.fillStyle=`rgba(255,255,255,0.16)`,n.beginPath(),n.roundRect(h,f+3,u,m-6,3),n.fill(),n.font=Hu,n.fillStyle=`#e8ecf5`,n.fillText(nd,h+3.5,f+m/2+.5))}};function fd(e){let t=/\p{Extended_Pictographic}(?:\uFE0F)?/u.exec(e);return t?t[0]:`💬`}function pd(){return a(`visitante`).toLocaleUpperCase()}var md={base:`#cfc8bd`,trim:`#8a8174`,pattern:`brick`,exterior:!0};function hd(e){let t=e*16,n={x:-20,y:-16,w:t+20+20,h:69},r=e=>e*16,i=[],a=[],o=d(49374+e);i.push({kind:`grass`,x:r(n.x),y:r(n.y),w:r(n.w),h:r(n.h),seed:11}),i.push({kind:`sidewalk`,x:r(n.x),y:r(31),w:r(n.w),h:r(2),seed:12}),i.push({kind:`street`,x:r(n.x),y:r(33),w:r(n.w),h:r(5),seed:13}),i.push({kind:`sidewalk`,x:r(n.x),y:r(38),w:r(n.w),h:r(2),seed:14}),i.push({kind:`sidewalk`,x:r(-3),y:r(12),w:r(3),h:r(5),seed:15}),i.push({kind:`sidewalk`,x:r(-3),y:r(17),w:r(2),h:r(14),seed:16});for(let e=n.x+1;e<n.x+n.w-1;e+=4+Math.floor(o()*3))a.push({kind:o()<.25?`pine`:`tree`,x:r(e)+Math.floor(o()*8),y:r(-3)-Math.floor(o()*20),seed:Math.floor(o()*1e9)}),o()<.6&&a.push({kind:`bush`,x:r(e+2),y:r(-1)-2,seed:Math.floor(o()*1e9)});for(let[e,t]of[[-6,5],[-10,6],[-14,8]])for(let i=n.x+2;i<n.x+n.w-1;i+=t+Math.floor(o()*4))a.push({kind:o()<.3?`pine`:`tree`,x:r(i)+Math.floor(o()*8),y:r(e)-Math.floor(o()*12),seed:Math.floor(o()*1e9)});for(let e of[-1,1])for(let n of[0,7,13]){let i=e<0?-6-n:t+4+n;for(let s=1;s<29;s+=3+Math.floor(o()*3))e<0&&n===0&&s>=11&&s<=30||(a.push({kind:o()<.3?`pine`:`tree`,x:r(i+Math.floor(o()*5)),y:r(s+1),seed:Math.floor(o()*1e9)}),n===0&&o()<.5&&a.push({kind:`bush`,x:r(e<0?-2:t+1),y:r(s+2),seed:Math.floor(o()*1e9)}))}for(let e=0;e<t;e+=2){let t=Math.floor(e/16),n=e-t*16,i=t>=2&&(n===6||n===8)?zc(t,`south`):void 0;a.push({kind:e/2%3==1?`flowers`:`hedge`,x:r(e)+16,y:r(30)+10,seed:e*7+3,whenRoom:i})}for(let e=n.x+4;e<n.x+n.w;e+=10)a.push({kind:`lamp`,x:r(e),y:r(32)+6,seed:e});for(let e of[13,17,21])for(let t=n.x+3;t<n.x+n.w-2;t+=6+Math.floor(o()*5))a.push({kind:o()<.2?`pine`:`tree`,x:r(t)+Math.floor(o()*10),y:r(29+e)+Math.floor(o()*10),seed:Math.floor(o()*1e9)}),o()<.3&&a.push({kind:`bush`,x:r(t+3),y:r(29+e+1),seed:Math.floor(o()*1e9)});a.push({kind:`bench`,x:r(-4),y:r(15)+6,seed:1}),a.push({kind:`totem`,x:r(-3)+6,y:r(13),seed:2});let s=r(33),c=r(5);return{bounds:n,floors:i,props:a,lanes:[{y:s+Math.round(c*.36),dir:1},{y:s+Math.round(c*.86),dir:-1}],streetY:s,streetH:c}}function gd(e,t){let n=Pc(e),r=Fc(e),i=Lc(n,r),a=i.x*16,o=d(39549+e*31),s=[],c=[],l=[],u=[],f=e=>e*16,p=()=>Math.floor(o()*1e9),m=(t,n,r,o)=>{l.push({kind:`sidewalk`,x:a+f(t),y:f(i.y+n),w:f(r),h:f(o),seed:e+7}),l.push({kind:`wood`,x:a+f(t)+4,y:f(i.y+n)+4,w:f(r)-8,h:f(o)-8,seed:e+8})};if(r===`north`){s.push({kind:`face`,x:a,y:160,w:256,style:md}),[3,8,13].forEach((t,n)=>c.push({id:`shell:${e}:janela${n}`,kind:`window`,cx:a+t*16,baseY:192,on:`face`,order:0})),t&&s.push({kind:`cap`,x:a+256-8,y:160,w:8,h:32,style:md}),l.push({kind:`sidewalk`,x:a+f(7),y:f(i.y),w:f(2),h:f(3),seed:e}),m(3,3,10,5),u.push({kind:`parasol`,x:a+f(5.5),y:f(i.y+6)+4,seed:p(),slot:e}),u.push({kind:`parasol`,x:a+f(10.5),y:f(i.y+6)+4,seed:p(),slot:e}),u.push({kind:`bush`,x:a+f(3.5),y:f(i.y+3)+6,seed:p(),slot:e}),u.push({kind:`bush`,x:a+f(12.5),y:f(i.y+3)+6,seed:p(),slot:e});for(let t of[3,8,13])u.push({kind:`flowers`,x:a+f(t),y:f(i.y+9)+12,seed:e*3+t,slot:e});u.push({kind:`tree`,x:a+f(1)+4,y:f(i.y+3),seed:p(),slot:e}),u.push({kind:o()<.5?`pine`:`tree`,x:a+f(15)-4,y:f(i.y+3)+6,seed:p(),slot:e}),u.push({kind:`bush`,x:a+f(1)+8,y:f(i.y+8),seed:p(),slot:e}),u.push({kind:`bush`,x:a+f(15)-8,y:f(i.y+8),seed:p(),slot:e})}else{s.push({kind:`south`,x:a,y:272,w:256,style:md}),t&&s.push({kind:`cap`,x:a+256-8,y:272,w:8,h:16,style:md}),l.push({kind:`sidewalk`,x:a+f(7),y:f(i.y+1),w:f(2),h:f(i.h-1),seed:e}),u.push({kind:`paving`,x:a+f(7),y:f(29),seed:e,slot:e}),m(3,3.5,10,5),u.push({kind:`parasol`,x:a+f(5.5),y:f(i.y+6.5)+4,seed:p(),slot:e}),u.push({kind:`parasol`,x:a+f(10.5),y:f(i.y+6.5)+4,seed:p(),slot:e}),u.push({kind:`bush`,x:a+f(3.5),y:f(i.y+4)+4,seed:p(),slot:e}),u.push({kind:`bush`,x:a+f(12.5),y:f(i.y+4)+4,seed:p(),slot:e});for(let t of[3,13])u.push({kind:`flowers`,x:a+f(t),y:f(i.y+2),seed:e*3+t,slot:e});u.push({kind:`bench`,x:a+f(4),y:f(i.y+10)+6,seed:e,slot:e}),u.push({kind:`bench`,x:a+f(12),y:f(i.y+10)+6,seed:e+1,slot:e}),u.push({kind:`tree`,x:a+f(1)+6,y:f(i.y+11),seed:p(),slot:e}),u.push({kind:o()<.5?`pine`:`tree`,x:a+f(15)-6,y:f(i.y+11)+4,seed:p(),slot:e}),u.push({kind:`rock`,x:a+f(14),y:f(i.y+2)+4,seed:e+3,slot:e})}return{slot:e,rect:i,walls:s,windows:c,floors:l,props:u}}function _d(e,t){return t.missing||e===`offline`?`leave`:e===`done`?t.kind===`sub`?`deliver`:`idle`:t.kind===`sub`&&t.parentGone?`leave`:e===`waiting`?`wait`:e===`shell`?`shell`:e===`working`?t.now!==void 0&&Vl(t.shells,t.now)?`shell`:`work`:`idle`}function vd(e){switch(e){case`edit`:case`write`:case`think`:return`code`;case`run`:case`test`:case`git`:return`terminal`;case`web`:case`browser`:case`mcp`:return`browser`;case`search`:return`search`;case`read`:case`respond`:case`compact`:return`docs`;case`plan`:return`tasks`;case`communicate`:case`ask`:case`prompt`:case`delegate`:return`chat`;case`wait`:case`error`:return`alert`;case`skill`:return`tasks`;case`done`:return`idle`;default:return`code`}}var yd={coffee:18,water:12,bathroom:8,lounge:12,pingpong:9,talk:13,window:7,shelf:6,stretch:8,arcade:5,snack:5,mirror:3,phone:6};function bd(e,t={},n=yd){let r=0;for(let e of Object.keys(yd))t[e]!==!1&&(r+=n[e]);if(r<=0)return null;let i=e()*r;for(let e of Object.keys(yd))if(t[e]!==!1&&(i-=n[e],i<0))return e;return null}var xd={calm:[16e3,42e3],normal:[6e3,2e4],lively:[3e3,1e4]};function Sd(e,t){let[n,r]=xd[t]??xd.normal;return n+e()*(r-n)}function Cd(e,t,n){return e===`idle`&&n-t>6e5}function wd(e,t,n,r=!0){let i=e.filter(e=>e.kind===`desk`&&t(e.id)).sort((e,t)=>(e.rank??99)-(t.rank??99));if(i.length)return i[0];for(let n of r?[`stool`,`nook`,`stand`]:[`stool`,`nook`]){let r=e.find(e=>e.kind===n&&t(e.id));if(r)return r}return null}function Td(e,t){return t===`wait`?e>2:t===`work`?e>12:t===`shell`&&e>20}function Ed(e){let t=0;for(let n of e)(n.kind===`desk`||n.kind===`stool`||n.kind===`nook`)&&t++;return t}function Dd(e){return e.annexId??e.roomId}function Od(e,t,n){for(let r of n)if(r.id!==t&&Dd(r)===e&&!r.leaving)return!1;return!0}function kd(e,t){return!e.listed&&e.occupants===0&&!e.lightOn&&e.dark&&e.unlistedForMs>=t}function Ad(e,t){let n=Math.max(0,t);return e?n<70?.75:n<160?.1:n<220?.9:n<330?.25:Math.min(1,.25+(n-330)/220):n<60?.55:n<120?.95:Math.max(0,.95*(1-(n-120)/480))}var jd={a:`010101111101101`,b:`110101110101110`,c:`011100100100011`,d:`110101101101110`,e:`111100110100111`,f:`111100110100100`,g:`011100101101011`,h:`101101111101101`,i:`111010010010111`,j:`001001001101010`,k:`101101110101101`,l:`100100100100111`,m:`101111111101101`,n:`110101101101101`,o:`010101101101010`,p:`110101110100100`,q:`010101101110011`,r:`110101110101101`,s:`011100010001110`,t:`111010010010010`,u:`101101101101111`,v:`101101101101010`,w:`101101111111101`,x:`101101010101101`,y:`101101010010010`,z:`111001010100111`,0:`111101101101111`,1:`010110010010111`,2:`110001010100111`,3:`110001010001110`,4:`101101111001001`,5:`111100110001110`,6:`011100111101111`,7:`111001010010010`,8:`111101111101111`,9:`111101111001110`,_:`000000000000111`,"-":`000000111000000`,"#":`101111101111101`,".":`000000000000010`,"(":`010100100100010`,")":`010001001001010`,"/":`001001010100100`," ":`000000000000000`,":":`000010000010000`,",":`000000000010100`,"×":`000101010101000`,"—":`000000111000000`,">":`100010001010100`,"<":`001010100010001`,"+":`000010111010000`},Md={acute:{dy:-3,rows:[`001`,`010`]},grave:{dy:-3,rows:[`100`,`010`]},circ:{dy:-3,rows:[`010`,`101`]},tilde:{dy:-3,rows:[`011`,`110`]},cedilla:{dy:5,rows:[`010`,`110`]}},Nd={á:[`a`,`acute`],à:[`a`,`grave`],â:[`a`,`circ`],ã:[`a`,`tilde`],é:[`e`,`acute`],ê:[`e`,`circ`],í:[`i`,`acute`],ó:[`o`,`acute`],ô:[`o`,`circ`],õ:[`o`,`tilde`],ú:[`u`,`acute`],ç:[`c`,`cedilla`]};function Pd(e){return Math.max(0,[...e].length*4-1)}function Fd(e,t,n,r,i){e.fillStyle=i;let a=n;for(let n of t.toLowerCase()){let t=Nd[n],i=jd[t?t[0]:n]??jd[` `];for(let t=0;t<15;t++)i[t]===`1`&&e.fillRect(a+t%3,r+Math.floor(t/3),1,1);if(t){let n=Md[t[1]];n.rows.forEach((t,i)=>{for(let o=0;o<3;o++)t[o]===`1`&&e.fillRect(a+o,r+n.dy+i,1,1)})}a+=4}return a-n}function Id(e){switch(e){case`working`:return`work`;case`waiting`:case`waiting-background`:return`wait`;case`done`:return`done`;default:return`idle`}}var Ld=13.5,Rd=22.5,zd=[255,255,255],Bd=[244,220,184],Vd=[255,222,184],Hd=[138,144,180],Ud=[[0,1,0,[70,84,140]],[4.5,1,0,[72,86,142]],[5.25,.86,.25,[104,100,156]],[5.9,.56,.8,[190,146,168]],[6.5,.2,1,[255,208,174]],[7.25,0,.35,[255,238,220]],[8,0,0,zd],[16.25,0,0,zd],[17.25,.04,.45,[255,236,206]],[18,.24,1,[255,202,162]],[18.6,.55,.75,[194,148,164]],[19.25,.85,.3,[110,108,162]],[20,1,0,[80,96,150]],[24,1,0,[70,84,140]]],Wd=(e,t,n)=>e<t?t:e>n?n:e;function Gd(e){return Number.isFinite(e)?(e%24+24)%24:0}function Kd(e,t,n){let r=Wd(n,0,1);return[Math.round(e[0]+(t[0]-e[0])*r),Math.round(e[1]+(t[1]-e[1])*r),Math.round(e[2]+(t[2]-e[2])*r)]}function qd(e){let t=Gd(e);return t<5?`madrugada`:t<7?`amanhecer`:t<17?`dia`:t<19?`entardecer`:`noite`}function Jd(e){let t=Gd(e),n=0;for(;n<Ud.length-2&&Ud[n+1][0]<=t;)n++;let[r,i,a,o]=Ud[n],[s,c,l,u]=Ud[n+1],d=(t-r)/Math.max(1e-6,s-r),f=i+(c-i)*d,p=a+(l-a)*d,m=Kd(o,u,d),h=Kd(Kd(zd,Bd,f),Vd,p*(1-f)*.55),g=Kd(zd,Hd,f);return{hour:t,phase:qd(t),night:f,warm:p,outside:m,inside:h,dim:g}}function Yd(e){return e.night<.005&&e.outside[0]>=254&&e.outside[1]>=254&&e.outside[2]>=254&&e.inside[2]>=254}function Xd(e,t,n){let r=Wd(n,0,1);if(r>=1)return t;let i=(e,t)=>e+(t-e)*r;return{hour:t.hour,phase:t.phase,night:i(e.night,t.night),warm:i(e.warm,t.warm),outside:Kd(e.outside,t.outside,r),inside:Kd(e.inside,t.inside,r),dim:Kd(e.dim,t.dim,r)}}function Zd(e,t){let n=Math.abs(e.night-t.night)*255+Math.abs(e.warm-t.warm)*255;for(let r=0;r<3;r++)n+=Math.abs(e.outside[r]-t.outside[r])+Math.abs(e.inside[r]-t.inside[r])+Math.abs(e.dim[r]-t.dim[r]);return n}function Qd(e){let t=Gd(e);if(t<=6.1||t>=18.4)return null;let n=Wd((t-6)/12,0,1),r=Wd(18+(1-Math.sin(n*Math.PI))*70,18,88),i=Wd(-Math.cos(n*Math.PI)*.9,-.9,.9),a=Math.min(Wd((t-6.1)/.6,0,1),Wd((18.4-t)/.6,0,1)),o=Math.max(0,1-Math.abs(t-7.2)/1.6,1-Math.abs(t-17.2)/1.6);return{len:Math.round(r),skew:i,alpha:a*(.12+.2*o)}}function $d(e){if(!e)return null;let t;try{t=new URLSearchParams(e).get(`hora`)}catch{return null}if(t===null)return null;let n=/^\s*(\d{1,2})(?:\s*[:h]\s*(\d{2})?)?\s*$/i.exec(t);if(!n)return null;let r=Number(n[1]),i=n[2]===void 0?0:Number(n[2]);return r>24||i>59||r===24&&i>0?null:Gd(r+i/60)}function ef(e,t,n){return t!==null&&Number.isFinite(t)?Gd(t):e===`day`?Ld:e===`night`?Rd:n.getHours()+n.getMinutes()/60+n.getSeconds()/3600}function tf(e){return e.daylight===`auto`||e.daylight===`day`||e.daylight===`night`?e.daylight:e.dayNight?`auto`:`day`}function nf(e){return`rgb(${e[0]},${e[1]},${e[2]})`}var rf=new Map;function af(e,t){let n=document.createElement(`canvas`);n.width=e,n.height=t;let r=n.getContext(`2d`);return r.imageSmoothingEnabled=!1,[n,r]}function of(e){let t=parseInt(e.slice(1),16);return[t>>16&255,t>>8&255,t&255]}var sf=class{ctx;w;h;data;constructor(e,t,n){this.ctx=e,this.w=t,this.h=n,this.data=e.getImageData(0,0,t,n)}set(e,t,n,r=255){if(e<0||t<0||e>=this.w||t>=this.h)return;let[i,a,o]=of(n),s=(t*this.w+e)*4;this.data.data[s]=i,this.data.data[s+1]=a,this.data.data[s+2]=o,this.data.data[s+3]=r}alpha(e,t){return e<0||t<0||e>=this.w||t>=this.h?0:this.data.data[(t*this.w+e)*4+3]}flush(){this.ctx.putImageData(this.data,0,0)}};function cf(e,t,n,r,i,a=.22){e.fillStyle=`rgba(28,36,52,${a})`;for(let a=-i;a<=i;a++){let o=Math.round(r*Math.sqrt(Math.max(0,1-a*a/(i*i))));e.fillRect(t-o,n+a,o*2,1)}}function lf(e,t,n,r,i,a,o){let s=[[n,r,i]];for(let e=0;e<4;e++){let e=t()*Math.PI*2,a=i*(.35+t()*.35);s.push([n+Math.cos(e)*a,r+Math.sin(e)*a*.8,i*(.55+t()*.25)])}let c=(e,t)=>s.some(([n,r,i])=>(e-n)**2+(t-r)**2<=i*i),l=Math.floor(n-i*1.8),u=Math.ceil(n+i*1.8),d=Math.floor(r-i*1.6),f=Math.ceil(r+i*1.6);for(let s=d;s<=f;s++)for(let d=l;d<=u;d++){if(!c(d+.5,s+.5))continue;if(!c(d-.5,s+.5)||!c(d+1.5,s+.5)||!c(d+.5,s-.5)||!c(d+.5,s+1.5)){e.set(d,s,o);continue}let l=(d-n)/i,u=(s-r)/i,f=-l*.45-u*.75+(t()-.5)*.55,p=f>.55?3:f>.05?2:+(f>-.5);e.set(d,s,a[p])}}function uf(e){let t=d(e),[n,r]=af(36,48);cf(r,18,45,12,3,.25);let i=new sf(r,36,48);for(let e=30;e<46;e++)for(let t=16;t<21;t++){let n=t===16?`#8a6243`:t===20?`#4a3222`:`#6b4a32`;i.set(t,e,n)}i.set(15,45,`#4a3222`),i.set(21,45,`#4a3222`);let a=[[`#2f6a43`,`#3f8550`,`#5aa45d`,`#86c873`],[`#356b3c`,`#4b8a45`,`#6aa956`,`#9fcf74`],[`#2c6250`,`#3a7e5f`,`#53a071`,`#82c489`]];return lf(i,t,18,18,11+Math.floor(t()*3),a[Math.floor(t()*a.length)],`#25463a`),i.flush(),{canvas:n,ax:18,ay:45}}function df(e){let t=d(e),[n,r]=af(28,48);cf(r,14,45,9,3,.25);let i=new sf(r,28,48);for(let e=38;e<46;e++)for(let t=12;t<16;t++)i.set(t,e,t===12?`#8a6243`:t===15?`#4a3222`:`#6b4a32`);let a=[`#24533f`,`#2f6b4f`,`#3f8a5f`,`#62ab79`];for(let e=0;e<4;e++){let n=4+e*8,r=n+14;for(let o=n;o<r;o++){let s=Math.round((o-n)/(r-n)*(5+e*2.2));for(let e=14-s;e<=14+s;e++){let c=e===14-s||e===14+s||o===r-1,l=(14-e)/(s+1)-(o-n)/(r-n)+(t()-.5)*.5;i.set(e,o,c?`#1d3f33`:a[l>.5?3:l>-.1?2:+(l>-.6)])}}}return i.flush(),{canvas:n,ax:14,ay:45}}function ff(e){let t=d(e),[n,r]=af(22,16);cf(r,11,14,9,2,.22);let i=new sf(r,22,16);if(lf(i,t,11,9,6,[`#34663f`,`#47864c`,`#62a45a`,`#8cc66f`],`#264a36`),t()<.6){let e=[`#f2d14b`,`#f28aa5`,`#ffffff`][Math.floor(t()*3)];for(let n=0;n<4;n++)i.set(6+Math.floor(t()*10),5+Math.floor(t()*6),e)}return i.flush(),{canvas:n,ax:11,ay:14}}function pf(e){let t=d(e),[n,r]=af(30,14),i=new sf(r,30,14);for(let e=4;e<13;e++)for(let t=1;t<29;t++){let n=e===4||e===12||t===1||t===28;i.set(t,e,n?e===12?`#8d8a82`:`#b9b5aa`:`#6a4b35`)}let a=[`#e8574a`,`#f2c94c`,`#f08bb0`,`#ffffff`,`#9b7be0`];for(let e=0;e<26;e++){let e=3+Math.floor(t()*24),n=2+Math.floor(t()*9);i.set(e,n+1,`#3f8550`),i.set(e,n,t()<.75?a[Math.floor(t()*a.length)]:`#5aa45d`)}return i.flush(),{canvas:n,ax:15,ay:13}}function mf(e){let t=d(e),[n,r]=af(34,16);cf(r,17,14,15,2,.2);let i=new sf(r,34,16);for(let e=3;e<14;e++)for(let n=1;n<33;n++){let r=e===3?2:+(e===4);if(n<1+r||n>32-r)continue;let a=e===3||e===13||n===1+r||n===32-r,o=-(e-3)/10+(t()-.5)*.6;i.set(n,e,a?`#264a36`:o>0?`#6aa956`:o>-.4?`#4b8a45`:`#356b3c`)}return i.flush(),{canvas:n,ax:17,ay:14}}function hf(){let[e,t]=af(10,36);return cf(t,5,34,4,1,.25),t.fillStyle=`#2e3648`,t.fillRect(4,6,2,28),t.fillStyle=`#4a5468`,t.fillRect(4,6,1,28),t.fillStyle=`#2e3648`,t.fillRect(1,2,8,5),t.fillStyle=`#ffe9a8`,t.fillRect(2,4,6,2),t.fillStyle=`#fff6d6`,t.fillRect(3,4,2,1),t.fillStyle=`#3a4152`,t.fillRect(3,32,4,2),{canvas:e,ax:5,ay:34}}function gf(){let[e,t]=af(26,14);return cf(t,13,12,11,2,.22),t.fillStyle=`#2e3648`,t.fillRect(3,8,2,4),t.fillRect(21,8,2,4),t.fillStyle=`#7a5232`,t.fillRect(1,1,24,3),t.fillRect(1,6,24,3),t.fillStyle=`#a0703f`,t.fillRect(1,1,24,1),t.fillRect(1,6,24,1),t.fillStyle=`#5b3c25`,t.fillRect(1,8,24,1),t.fillRect(1,3,24,1),{canvas:e,ax:13,ay:12}}function _f(e){let t=d(e),[n,r]=af(16,12),i=new sf(r,16,12);return lf(i,t,8,7,4,[`#7d8590`,`#959da8`,`#b3bac4`,`#d3d8de`],`#4d5562`),i.flush(),{canvas:n,ax:8,ay:11}}function vf(e){let[t,n]=af(32,34),r=[[`#e8574a`,`#f6efe2`,`#a83a33`],[`#2fb3a3`,`#f6efe2`,`#1f8579`],[`#f2b33d`,`#fbf4e4`,`#c88a1f`]],[i,a,o]=r[e%r.length];cf(n,16,29,12,3,.24),n.fillStyle=`#5b3c25`,n.fillRect(2,24,6,5),n.fillRect(24,24,6,5),n.fillStyle=`#a0703f`,n.fillRect(2,24,6,2),n.fillRect(24,24,6,2),n.fillStyle=`#d8dde3`,n.fillRect(10,24,12,5),n.fillStyle=`#f4f6f8`,n.fillRect(10,24,12,2),n.fillStyle=`#8d96a3`,n.fillRect(10,28,12,1),n.fillStyle=`#4a5468`,n.fillRect(15,11,2,14);let s=new sf(n,32,34),c=15.5;for(let e=0;e<=15;e++)for(let t=0;t<32;t++){let n=(t-c)/14.5,r=(e-8)/7.5,l=Math.abs(n)+Math.abs(r)*.55+Math.hypot(n,r)*.45;if(l>1)continue;let u=Math.atan2(e-8,t-c),d=Math.floor((u+Math.PI)/(Math.PI*2)*8)%2,f=l>.86,p=e<7;s.set(t,e,f?o:d?p?`#ffffff`:a:p?i:o)}return s.set(15,8,`#2e3648`),s.set(16,8,`#2e3648`),s.flush(),{canvas:t,ax:16,ay:29}}function yf(){let[e,t]=af(14,34);return cf(t,7,32,6,1.5,.25),t.fillStyle=`#141b30`,t.fillRect(2,2,10,30),t.fillStyle=`#1c2541`,t.fillRect(3,3,8,28),t.fillStyle=`#2a355a`,t.fillRect(3,3,1,28),t.fillStyle=`#f2a33a`,t.fillRect(3,5,8,2),t.fillStyle=`#f5f1e6`,t.fillRect(4,11,1,6),t.fillRect(8,11,1,6),t.fillRect(5,13,3,1),t.fillStyle=`#f2a33a`,t.fillRect(5,19,1,6),t.fillRect(6,21,2,1),t.fillRect(8,22,1,2),t.fillRect(6,24,2,1),t.fillStyle=`#8d96a3`,t.fillRect(1,31,12,2),{canvas:e,ax:7,ay:32}}function bf(e){let t=e.kind===`lamp`||e.kind===`bench`||e.kind===`totem`?e.kind:`${e.kind}:${e.seed%7}`,n=rf.get(t);if(n)return n;switch(e.kind){case`tree`:n=uf(e.seed%7);break;case`pine`:n=df(e.seed%7);break;case`bush`:n=ff(e.seed%7);break;case`flowers`:n=pf(e.seed%7);break;case`hedge`:n=mf(e.seed%7);break;case`lamp`:n=hf();break;case`bench`:n=gf();break;case`rock`:n=_f(e.seed%7);break;case`parasol`:n=vf(e.seed%7);break;case`totem`:n=yf();break;default:n={canvas:af(1,1)[0],ax:0,ay:0}}return rf.set(t,n),n}var xf=[[`#d9534a`,`#a83a33`,`#f08a80`],[`#3f7fd8`,`#2c5ea6`,`#7fb0f0`],[`#f2f2ee`,`#c4c6c8`,`#ffffff`],[`#f2b33d`,`#c88a1f`,`#ffd889`],[`#2fb3a3`,`#1f8579`,`#79dccf`],[`#4a5468`,`#323a4a`,`#76819a`]];function Sf(e,t){let n=`car:${e%xf.length}:${+!!t}`,r=rf.get(n);if(r)return r;let[i,a,o]=xf[e%xf.length],[s,c]=af(36,20);t&&(c.translate(36,0),c.scale(-1,1)),cf(c,18,17,16,2,.3);let l=`#2e3648`;c.fillStyle=l,c.fillRect(2,8,32,8),c.fillRect(8,3,18,6),c.fillStyle=i,c.fillRect(3,9,30,6),c.fillRect(9,4,16,5),c.fillStyle=o,c.fillRect(3,9,30,1),c.fillRect(9,4,16,1),c.fillStyle=a,c.fillRect(3,13,30,2),c.fillStyle=`#3a5f86`,c.fillRect(10,5,6,3),c.fillRect(18,5,6,3),c.fillStyle=`#9cc7ec`,c.fillRect(10,5,2,1),c.fillRect(18,5,2,1),c.fillStyle=`#fff3c4`,c.fillRect(32,10,2,2),c.fillStyle=`#e04a3a`,c.fillRect(2,10,1,2);for(let e of[7,25])c.fillStyle=l,c.fillRect(e,13,5,5),c.fillStyle=`#6b7385`,c.fillRect(e+1,14,3,3),c.fillStyle=`#9aa3b5`,c.fillRect(e+2,15,1,1);let u={canvas:s,ax:18,ay:17};return rf.set(n,u),u}function Cf(){let e=rf.get(`shadow`);if(e)return e;let[t,n]=af(14,6);cf(n,7,3,6,2,.28);let r={canvas:t,ax:7,ay:3};return rf.set(`shadow`,r),r}function wf(e,t=64){let n=`glow:${e}:${t}`,r=rf.get(n);if(r)return r.canvas;let[i,a]=af(t,t),o=a.createRadialGradient(t/2,t/2,0,t/2,t/2,t/2),[s,c,l]=of(e);return o.addColorStop(0,`rgba(${s},${c},${l},0.9)`),o.addColorStop(.4,`rgba(${s},${c},${l},0.35)`),o.addColorStop(1,`rgba(${s},${c},${l},0)`),a.fillStyle=o,a.fillRect(0,0,t,t),rf.set(n,{canvas:i,ax:t/2,ay:t/2}),i}function Tf(e){let t=new Cn(40,64),n=(e,n,r,i,a)=>t.rect(e,n,r,i,a);if(e===`tree`){t.shadow(20,59,17,3,`#252c39`,.22),n(17,49,6,9,`#80573d`);for(let e=0;e<4;e++){let t=13+e*8,r=6+e*3;n(20-r,t,r*2+1,9,`#245644`),n(22-r,t,r*2-4,6,`#387956`),n(22-r,t+1,r-1,3,`#4d9361`)}t.vline(20,5,13,`#ffe0a0`),t.hline(16,24,9,`#ffe0a0`),n(18,7,5,5,`#ffc45d`);for(let[e,r]of[[16,20],[24,24],[13,31],[25,36],[9,42],[20,43],[31,44]])n(e,r,3,3,`#e05250`),t.set(e,r,`#ffb27b`);for(let[e,t]of[[21,17],[15,26],[23,30],[15,38],[26,42],[11,47]])n(e,t,2,2,`#ffe8b2`);n(3,52,10,8,`#a82d42`),n(6,51,2,9,`#e5c17b`),n(3,54,10,1,`#e5c17b`),n(26,51,10,9,`#e6b357`),n(30,50,2,10,`#b33549`),n(26,54,10,1,`#b33549`)}else if(e===`gift`)t.shadow(20,59,9,2,`#252c39`,.2),n(11,49,17,11,`#bf3849`),n(11,49,17,3,`#e35a58`),n(18,49,3,11,`#efd1a0`),n(11,54,17,2,`#efd1a0`),n(14,46,5,3,`#e8b860`),n(21,46,5,3,`#e8b860`);else if(e===`pumpkin`)t.shadow(20,59,11,2,`#252c39`,.2),n(18,41,3,6,`#557342`),n(11,46,18,14,`#c56832`),n(8,49,24,8,`#e18b39`),n(13,46,4,13,`#f0a647`),n(23,47,3,12,`#f0a647`),n(12,50,4,3,`#523347`),n(24,50,4,3,`#523347`),n(17,56,7,2,`#523347`),t.set(13,51,`#ffd680`),t.set(25,51,`#ffd680`),t.hline(18,22,56,`#ffd680`);else if(e===`ghost`){n(15,39,10,3,`#e0dae9`),n(12,42,16,15,`#e0dae9`),n(14,41,11,15,`#fff4ed`),n(10,47,4,4,`#e0dae9`),n(26,47,4,4,`#e0dae9`);for(let e of[12,18,24])n(e,56,4,3,`#e0dae9`);n(16,46,2,3,`#574563`),n(23,46,2,3,`#574563`),n(19,51,3,2,`#574563`)}else if(e===`wreath`){n(12,39,16,4,`#347653`),n(10,43,5,10,`#245644`),n(25,43,5,10,`#347653`),n(13,53,15,4,`#245644`);for(let[e,t]of[[14,41],[26,47],[12,50],[23,54]])n(e,t,2,2,`#e45c58`);n(15,55,4,4,`#c93945`),n(21,55,4,4,`#c93945`),n(19,54,2,4,`#f07368`)}else n(18,51,5,6,`#47344f`),n(10,50,9,4,`#47344f`),n(22,50,9,4,`#47344f`),n(7,48,4,4,`#47344f`),n(30,48,4,4,`#47344f`),n(13,53,3,3,`#47344f`),n(25,53,3,3,`#47344f`),t.set(19,52,`#f5b95f`),t.set(21,52,`#f5b95f`);return t.outline(),{buf:t,ax:20,ay:60}}var Ef=new Map;function Df(e){let t=Ef.get(e);if(!t){let{buf:n,ax:r,ay:i}=Tf(e),a=document.createElement(`canvas`);a.width=n.w,a.height=n.h,a.getContext(`2d`).putImageData(new ImageData(n.data,n.w,n.h),0,0),Ef.set(e,t={canvas:a,ax:r,ay:i})}return t}function Of(e,t){if(e===`christmas`)return`santa`;if(e===`halloween`)return[`witch`,`pumpkin`,`vampire`][(t>>>0)%3]}function kf(e,t,n,r){if(e===`none`||n.kind===`restroom`)return null;if(t===`plant_tall`){let t=n.furniture.find(e=>e.kind===`plant_tall`);return!t||c(t.id)!==r?null:Df(e===`christmas`?`tree`:r%3==0?`ghost`:`pumpkin`)}return t===`plant_small`?Df(e===`christmas`?`gift`:`pumpkin`):null}function Af(e,t){return e===`christmas`?`#a93649`:e===`halloween`?`#60416f`:t}function jf(e,t){return e===`none`||t.pattern===`glass`?t:{...t,base:R(t.base,e===`christmas`?`#ffe3b4`:`#bc97d1`,.18),trim:e===`christmas`?`#4e7756`:`#725486`}}function Mf(e,t,n){if(t===`none`)return;let r=Math.round(n.x),i=Math.round(n.y),a=Math.floor(n.w),o=Math.floor(n.h);if(!(a<25||o<16)){e.save(),e.fillStyle=t===`christmas`?`#ddb66e`:`#e5a457`,e.fillRect(r+4,i+4,a-8,1),e.fillRect(r+4,i+o-5,a-8,1);for(let n=r+14;n<r+a-10;n+=28){let r=Math.round(i+o/2);if(t===`christmas`){e.fillRect(n-4,r,9,1),e.fillRect(n,r-4,1,9);for(let t of[-2,2])e.fillRect(n+t,r+t,1,1),e.fillRect(n+t,r-t,1,1)}else e.fillRect(n-3,r-2,7,5),e.fillRect(n,r-4,1,2),e.fillStyle=`#60416f`,e.fillRect(n-2,r-1,1,1),e.fillRect(n+2,r-1,1,1),e.fillStyle=`#e5a457`}e.restore()}}function Nf(e,t,n){if(t===`none`||n.kind!==`face`)return;e.save();let r=Math.round(n.x+3),i=Math.floor(n.x+n.w-3),a=Math.round(n.y+5);for(let o=r;o<i;o++){if(n.doorways?.some(e=>o>=e.x-1&&o<e.x+e.w+1))continue;let i=Math.round(Math.sin((o-r)%48/48*Math.PI)*3);e.fillStyle=t===`christmas`?`#347653`:`#584068`,e.fillRect(o,a+i,1,t===`christmas`?3:1),(o-r)%12==6&&(e.fillStyle=t===`christmas`?`#f5d491`:`#eea24d`,e.fillRect(o,a+i+3,2,3),e.fillStyle=t===`christmas`?`#fff0be`:`#ffd78a`,e.fillRect(o,a+i+3,1,1))}if(t===`halloween`){e.strokeStyle=`#d6bfdd`,e.lineWidth=1;for(let t of[1,-1]){let n=t===1?r:i;e.beginPath();for(let[r,i]of[[15,0],[13,7],[7,13],[0,15]])e.moveTo(n,a+2),e.lineTo(n+t*r,a+2+i);for(let r of[5,10,15])e.moveTo(n+t*r,a+2),e.lineTo(n+t*Math.round(r*.7),a+2+Math.round(r*.7)),e.lineTo(n,a+2+r);e.stroke()}if(n.w>90){let t=Df(`bat`);e.drawImage(t.canvas,Math.round(n.x+n.w/2-t.ax),a+18-t.ay)}}e.restore()}function Pf(e,t,n,r){if(t===`none`)return;let i=Df(t===`christmas`?`wreath`:`bat`);e.drawImage(i.canvas,Math.round(n-i.ax),Math.round(r-19-i.ay))}var Ff=new Map;function If(e){let t=Ff.get(e);if(!t){t=document.createElement(`canvas`),t.width=t.height=34;let n=t.getContext(`2d`),r=n.createRadialGradient(17,17,1,17,17,17);r.addColorStop(0,e===`christmas`?`#ffd58b`:`#d8a5ed`),r.addColorStop(1,`rgba(255,220,180,0)`),n.fillStyle=r,n.fillRect(0,0,34,34),Ff.set(e,t)}return t}function Lf(e,t,n,r){if(!(t===`none`||r<=.01)){e.save();for(let i of n.walls)if(i.kind===`face`){e.save(),e.beginPath(),e.rect(i.x,i.y+4,i.w,27),e.clip();for(let n=i.x+14;n<i.x+i.w-6;n+=24)i.doorways?.some(e=>n>=e.x-10&&n<=e.x+e.w+10)||(e.globalAlpha=r*.3,e.drawImage(If(t),Math.round(n-17),i.y-8),e.globalAlpha=r*.85,e.fillStyle=t===`christmas`?`#ffe4a9`:`#ffd181`,e.fillRect(Math.round(n),i.y+9,2,2));e.restore()}e.restore()}}function Rf(e,t,n,r,i){if(t===`christmas`){e.save(),e.beginPath(),e.rect(n.x,n.y,n.w,n.h),e.clip(),e.fillStyle=`#edf3f3`,e.globalAlpha*=.7,e.fillRect(n.x,n.y+n.h-2,n.w,2);for(let t=0;t<12;t++){let a=((i>>>0)+t*17)%Math.max(1,Math.floor(n.w)),o=(Math.floor(r/180)+t*11)%Math.max(1,Math.floor(n.h));e.fillRect(Math.floor(n.x+a),Math.floor(n.y+o),1,1)}e.restore()}}var zf=new Set([`window`,`clock`,`whiteboard`,`tv`,`elevator`,`light_switch`,`sign`,`mirror`]);function Bf(e,t){let n=document.createElement(`canvas`);n.width=Math.max(1,Math.ceil(e)),n.height=Math.max(1,Math.ceil(t));let r=n.getContext(`2d`);return r.imageSmoothingEnabled=!1,[n,r]}function Vf(e,t,n=0){let r=t.states[n];if(r!==void 0)return r;let i=null;try{i=e.furnitureSprites(t.kind,t.variant,n,{seed:t.seed})??null,i&&!i.base?.canvas&&(i=null)}catch{i=null}return t.states[n]=i,i}var Hf=new WeakMap;function Uf(e){let t=Hf.get(e);if(t)return t;let n={x:0,y:0,w:e.width,h:e.height};try{let t=e.getContext(`2d`);if(t&&e.width>0&&e.height>0){let r=t.getImageData(0,0,e.width,e.height).data,i=e.width,a=e.height,o=-1,s=-1;for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++)r[(t*e.width+n)*4+3]>16&&(n<i&&(i=n),n>o&&(o=n),t<a&&(a=t),t>s&&(s=t));o>=0&&(n={x:i,y:a,w:o-i+1,h:s-a+1})}}catch{}return Hf.set(e,n),n}function Wf(e,t){if(e.on===`south`){let n=Uf(t.canvas),r=e.baseY-16;return{x:Math.round(e.cx-(n.x+n.w/2)),y:Math.round(r+9-(n.y+n.h/2))}}return{x:Math.round(e.cx-t.ax),y:Math.round(e.baseY-t.ay)}}function Gf(e,t,n,r,i){try{let a=e.furnitureSprites(t,n,r,{seed:i});return a&&a.base?.canvas?a:null}catch{return null}}function Kf(e,t,n){try{n.kind===`face`?e.drawWallFace(t,n.x,n.y,n.w,n.style,n.doorways?{doorways:n.doorways}:void 0):n.kind===`south`?e.drawSouthWall(t,n.x,n.y,n.w,n.style,n.doorways?{doorways:n.doorways}:void 0):e.drawWallTop(t,n.x,n.y,n.w,n.h,n.style)}catch{t.fillStyle=n.style.base,t.fillRect(n.x,n.y,n.w,n.kind===`face`?32:n.kind===`south`?16:n.h)}}var qf=28;function Jf(e,t,n,r,i){if(!e)return null;let a=e.wallArt.filter(e=>e.kind===t&&e.tiles===n);if(t===`poster`&&r){let e=a.filter(e=>e.variant===r);e.length&&(a=e)}return a.length?a[(i>>>0)%a.length]:null}function Yf(e,t,n){let r=n.framed??(n.kind===`poster`?n:null);if(!r)return!1;let i=Math.round(t.cx-r.w/2),a=t.baseY-qf;return e.fillStyle=`rgba(30,34,52,0.16)`,e.fillRect(i+r.w,a+1,1,r.h),e.fillRect(i+1,a+r.h,r.w,1),e.drawImage(r.img,i,a),!0}function Xf(e,t,n,r,i){let a=t.rects?.art;if(!a){let e=Uf(t.canvas);a={x:e.x+2,y:e.y+2,w:e.w-4,h:e.h-4}}if(a.w<=2||a.h<=2)return;let o=Math.min(i.w,a.w),s=Math.min(i.h,a.h),c=Math.floor((i.w-o)/2),l=Math.floor((i.h-s)/2);e.drawImage(i.img,c,l,o,s,n+a.x+Math.floor((a.w-o)/2),r+a.y+Math.floor((a.h-s)/2),o,s)}function Zf(e,t,n){let r=/^#?([0-9a-f]{6})$/i.exec(n.trim());if(!r)return;let i=parseInt(r[1],16),a=e=>Math.round(255+(e-255)*.1);e.save(),e.globalCompositeOperation=`multiply`,e.fillStyle=`rgb(${a(i>>16&255)},${a(i>>8&255)},${a(i&255)})`,e.fillRect(t.x,t.y,t.w,t.h),e.restore()}function Qf(e,t,n,r,i=`none`){let a=t.rect,o={x:a.x*16,y:a.y*16,w:a.w*16,h:a.h*16},[s,l]=Bf(o.w,o.h);l.translate(-o.x,-o.y);for(let n of t.floors)try{e.drawFloor(l,n.kind,n.x,n.y,n.w,n.h,{seed:n.seed,tint:n.tint,tint2:n.tint2})}catch{l.fillStyle=`#d9dde2`,l.fillRect(n.x,n.y,n.w,n.h)}t.floorTint&&Zf(l,o,t.floorTint);for(let n of t.rugs){let t=Af(i,n.color);try{e.drawRug(l,n.x,n.y,n.w,n.h,t,n.seed)}catch{l.fillStyle=t,l.fillRect(n.x,n.y,n.w,n.h)}Mf(l,i,n)}let[u,d]=Bf(o.w,o.h+16);d.translate(-o.x,-o.y+16);let f={face:0,south:1,cap:2};for(let n of[...t.walls].sort((e,t)=>f[e.kind]-f[t.kind]))Kf(e,d,{...n,style:jf(i,n.style)});for(let e of t.walls)Nf(d,i,e);let p=[],m;for(let n of t.wallItems){let i=$f(n,t.id);if(zf.has(n.kind)){n.kind===`sign`?m=i:p.push(i);continue}let a=n.kind===`painting`||n.kind===`poster`?Jf(r,n.kind,n.kind===`poster`?1:n.variant===`wide`?4:2,n.variant,i.seed):null;if(a&&i.on===`face`&&Yf(d,i,a))continue;let o=Gf(e,n.kind,n.variant===`wide`?void 0:n.variant,0,i.seed);if(!o)continue;let s=Wf(i,o.base);d.drawImage(o.base.canvas,s.x,s.y),a&&n.kind===`painting`&&Xf(d,o.base,s.x,s.y,a)}let h=t.furniture.map(e=>{let n=on[e.kind],r=(e.tx+n.footprint.w/2)*16+(e.dx??0),i=(e.ty+n.footprint.h)*16+(e.dy??0);return{id:e.id,kind:e.kind,variant:e.variant,seed:c(e.id),ax:r,ay:i,order:e.order,areaId:t.id,seatSpot:t.spots.find(t=>t.deskId===e.id)?.id,states:[]}});return{id:t.id,layout:t,room:n,px:o,floor:s,walls:u,furniture:h,wallItems:p,sign:m,version:n?.version??0}}function $f(e,t){return{id:e.id,kind:e.kind,variant:e.variant,seed:c(e.id),cx:e.cx,baseY:e.baseY,on:e.on,order:e.order,areaId:t}}function ep(e,t,n,r){for(let r of n)try{e.drawFloor(t,r.kind,r.x,r.y,r.w,r.h,{seed:r.seed,tint:r.tint,tint2:r.tint2})}catch{t.fillStyle=`#9fc77f`,t.fillRect(r.x,r.y,r.w,r.h)}for(let n of r)Kf(e,t,n)}var tp=2,np=1200,rp=250,ip=[255,236,196],ap=[255,214,150],op=[196,222,255],sp=[236,190,255],cp=26,lp=new Map;function up(e,t){let n=`${e.join(`,`)}:${t}`,r=lp.get(n);if(r)return r;r=document.createElement(`canvas`),r.width=t,r.height=t;let i=r.getContext(`2d`),a=i.createRadialGradient(t/2,t/2,0,t/2,t/2,t/2),[o,s,c]=e;return a.addColorStop(0,`rgba(${o},${s},${c},1)`),a.addColorStop(.35,`rgba(${o},${s},${c},0.8)`),a.addColorStop(.7,`rgba(${o},${s},${c},0.3)`),a.addColorStop(1,`rgba(${o},${s},${c},0)`),i.fillStyle=a,i.fillRect(0,0,t,t),lp.set(n,r),r}var dp=null;function fp(){if(dp)return dp;dp=document.createElement(`canvas`),dp.width=64,dp.height=64;let e=dp.getContext(`2d`),t=e.createRadialGradient(32,28.8,0,32,28.8,39.68);return t.addColorStop(0,`rgb(255,255,255)`),t.addColorStop(.5,`rgb(252,248,242)`),t.addColorStop(1,`rgb(212,196,176)`),e.fillStyle=t,e.fillRect(0,0,64,64),dp}var pp=new Map;function mp(e){let t=e.join(`,`),n=pp.get(t);if(n)return n;n=document.createElement(`canvas`),n.width=8,n.height=64;let r=n.getContext(`2d`),i=r.createLinearGradient(0,0,0,64);return i.addColorStop(0,`rgba(${e[0]},${e[1]},${e[2]},0.9)`),i.addColorStop(.55,`rgba(${e[0]},${e[1]},${e[2]},0.55)`),i.addColorStop(1,`rgba(${e[0]},${e[1]},${e[2]},0)`),r.fillStyle=i,r.fillRect(0,0,8,64),r.globalCompositeOperation=`destination-out`,r.fillStyle=`rgba(0,0,0,0.45)`,r.fillRect(0,0,1,64),r.fillRect(7,0,1,64),pp.set(t,n),n}var hp=()=>{try{return typeof matchMedia==`function`&&matchMedia(`(prefers-reduced-motion: reduce)`).matches}catch{return!1}},gp=class{art;sim;ambient=Jd(12);target=this.ambient;calcAt=-1e9;lastNow=0;mode=null;override=null;map=null;mapCtx=null;mapKey=``;mapX=0;mapY=0;coreLevel=new Map;coreBusy=new Map;occAt=0;flies=[];fliesFor=null;reduced=hp();reducedAt=0;constructor(e,t){this.art=e,this.sim=t}update(e,t,n,r){let i=ef(t,n,r),a=t!==this.mode||n!==this.override;if(e-this.reducedAt>5e3&&(this.reducedAt=e,this.reduced=hp()),a||e-this.calcAt>=4e3){let r=this.mode===null;this.mode=t,this.override=n,this.calcAt=e,this.target=Jd(i),(r||this.reduced)&&(this.ambient=this.target)}let o=Math.max(0,Math.min(250,e-this.lastNow));return this.lastNow=e,this.ambient!==this.target&&(this.ambient=this.reduced?this.target:Xd(this.ambient,this.target,o/np*3),Zd(this.ambient,this.target)<3&&(this.ambient=this.target)),i}get night(){return this.ambient.night}drawAmbient(e,t,n,r,i){let a=this.ambient;if(this.updateOccupancy(t,r,i),Yd(a))return;let o=this.ensureMap(t,r);if(!o)return;let s=this.mapX,c=this.mapY,l=s+o.width*tp,u=c+o.height*tp;e.save(),e.globalCompositeOperation=`multiply`;let d=Math.max(0,Math.floor((n.x0-s)/tp)-1),f=Math.max(0,Math.floor((n.y0-c)/tp)-1),p=Math.min(o.width,Math.ceil((n.x1-s)/tp)+1),m=Math.min(o.height,Math.ceil((n.y1-c)/tp)+1);p>d&&m>f&&e.drawImage(o,d,f,p-d,m-f,s+d*tp,c+f*tp,(p-d)*tp,(m-f)*tp),e.fillStyle=nf(a.outside);let h=n.x1-n.x0+4;n.y0<c&&e.fillRect(n.x0-2,n.y0-2,h,c-n.y0+2),n.y1>u&&e.fillRect(n.x0-2,u,h,n.y1-u+2);let g=Math.max(n.y0-2,c),_=Math.min(n.y1+2,u);_>g&&(n.x0<s&&e.fillRect(n.x0-2,g,s-n.x0+2,_-g),n.x1>l&&e.fillRect(l,g,n.x1-l+2,_-g)),e.restore()}updateOccupancy(e,t,n){if(t-this.occAt>=rp){this.occAt=t;for(let t of e.areas.values())!t.room&&this.presenceLit(t)&&this.coreBusy.set(t.id,this.someoneIn(t.layout.rect))}let r=this.reduced?1:Math.min(1,n*3.5);for(let[e,t]of this.coreBusy){let n=this.coreLevel.get(e)??+!!t,i=+!!t;this.coreLevel.set(e,Math.abs(i-n)<.02?i:n+(i-n)*r)}}presenceLit(e){let t=e.layout.kind;return t===`cafe`||t===`lounge`||t===`restroom`}someoneIn(e){for(let t of this.sim.chars.values())if(!(t.gone||t.inside)&&t.tx>=e.x&&t.ty>=e.y&&t.tx<e.x+e.w&&t.ty<e.y+e.h)return!0;return!1}areaLight(e,t){let n=e.room;if(n){let e=n.phase===`building`||n.phase===`dismantling`?Mu(n.phase,n.progress(t)).floor:1;return{lit:n.light(t),cover:e}}return this.presenceLit(e)?{lit:this.coreLevel.get(e.id)??0,cover:1}:{lit:1,cover:1}}areaColor(e,t,n){let r=this.ambient,i;return i=e.room?Kd(zd,r.inside,t):e.layout.kind===`corridor`?Kd(r.inside,r.dim,.18):Kd(r.dim,r.inside,t),n>=1?i:Kd(r.outside,i,n)}ensureMap(e,t){let n=e.exterior.bounds,r=Math.ceil(n.w*16/tp),i=Math.ceil(n.h*16/tp);if(!this.map||this.map.width!==r||this.map.height!==i){try{this.map=document.createElement(`canvas`),this.map.width=r,this.map.height=i,this.mapCtx=this.map.getContext(`2d`)}catch{this.map=null,this.mapCtx=null}this.mapKey=``}if(!this.map||!this.mapCtx)return null;this.mapX=n.x*16,this.mapY=n.y*16;let a=this.lightKey(e,t);return a!==this.mapKey&&(this.mapKey=a,this.paintMap(this.mapCtx,e,t)),this.map}lightKey(e,t){let n=this.ambient,r=`${Math.round(n.night*200)}|${n.outside.join(`,`)}|${n.inside.join(`,`)}|${n.dim.join(`,`)}|${this.sim.building.cols}`;for(let n of e.areas.values()){let{lit:e,cover:i}=this.areaLight(n,t);r+=`|${n.id}:${Math.round(e*24)}:${Math.round(i*20)}`}for(let t of e.shells)e.roomInSlot(t.slot)&&(r+=`|s${t.slot}`);return r}paintMap(e,t,n){let r=this.ambient,i=r.night;e.setTransform(1,0,0,1,0,0),e.globalCompositeOperation=`source-over`,e.globalAlpha=1,e.fillStyle=nf(r.outside),e.fillRect(0,0,this.map.width,this.map.height),e.setTransform(1/tp,0,0,1/tp,-this.mapX/tp,-this.mapY/tp);let a=nf(Kd(r.inside,r.dim,.18));for(let n of t.shells){if(t.roomInSlot(n.slot))continue;let r=n.rect;e.fillStyle=a,r.y===0?e.fillRect(r.x*16,(r.y+r.h-2)*16,r.w*16,32):e.fillRect(r.x*16,r.y*16,r.w*16,16)}let o=new Map;for(let r of t.areas.values()){let t=this.areaLight(r,n);if(t.cover<=.01)continue;o.set(r,r.room?t.lit*t.cover:this.presenceLit(r)?.4+.6*t.lit:1);let s=r.px,c=r.room?r.layout.shade:void 0;c&&t.cover>=1?(e.fillStyle=a,e.fillRect(s.x,s.y,s.w,s.h),e.fillStyle=nf(this.areaColor(r,t.lit,t.cover)),e.fillRect(c.x,c.y,c.w,c.h)):(e.fillStyle=nf(this.areaColor(r,t.lit,t.cover)),e.fillRect(s.x,s.y,s.w,s.h));let l=(r.room||this.presenceLit(r)?t.lit:r.layout.kind===`corridor`?0:1)*t.cover*i;if(l>.05){let t=c??s;e.globalCompositeOperation=`multiply`,e.globalAlpha=Math.min(1,l),e.drawImage(fp(),t.x,t.y,t.w,t.h),e.globalAlpha=1,e.globalCompositeOperation=`source-over`}}if(i<.12){e.setTransform(1,0,0,1,0,0);return}e.globalCompositeOperation=`lighten`;let s=up(ip,64),c=up(ap,64),l=up(op,48),u=up(sp,48),d=Math.min(1,(i-.12)/.5),f=(t,n,r,i,a,o)=>{o<=.01||(e.globalAlpha=Math.min(1,o),e.drawImage(t,n-i/2,r-a/2,i,a))};for(let[e,t]of o){if(!(!e.room||e.room.lightOn&&t>=.3))continue;let n=e.room?d*t:d;for(let t of e.furniture)t.kind===`floor_lamp`?f(s,t.ax,t.ay-6,92,66,n):t.kind===`vending_machine`?f(l,t.ax,t.ay+4,52,34,.9*n):t.kind===`arcade`&&f(u,t.ax,t.ay+4,44,30,.8*n)}for(let e of t.exterior.props)e.kind===`lamp`?(f(c,e.x,e.y+6,120,84,d),f(c,e.x,e.y-30,30,24,.7*d)):e.kind===`totem`&&f(l,e.x,e.y-4,34,22,.6*d);this.paintWindowSpill(t,o,d,f,c),e.globalAlpha=1,e.globalCompositeOperation=`source-over`,e.setTransform(1,0,0,1,0,0)}paintWindowSpill(e,t,n,r,i){let a=this.sim.building.cols*16*16;for(let[e,a]of t){if(a<.3)continue;let t=e.layout.rect;if(t.y===0)for(let t of e.wallItems)t.kind===`window`&&r(i,t.cx,-12,58,30,.55*n*a);else if(e.layout.kind!==`corridor`&&t.y+t.h>=29)for(let e of[.25,.75])r(i,(t.x+t.w*e)*16,480,96,30,.35*n*a)}r(i,-20,232,56,92,.6*n),r(i,a+20,232,56,92,.45*n);for(let t of e.shellWindows){let a=Number(t.areaId.slice(6));e.roomInSlot(a)||r(i,t.cx,t.baseY-32-14,52,28,.5*n)}}drawGlows(e,t,n,r){let i=this.ambient.night;e.save(),e.globalCompositeOperation=`lighter`;let a=wf(`#7fb8ff`,48),o=wf(`#ffcf7a`,64),s=(e,t,r)=>e>n.x0-r&&e<n.x1+r&&t>n.y0-r&&t<n.y1+r;for(let c of t.areas.values()){let l=c.px;if(l.x>n.x1+40||l.x+l.w<n.x0-40||l.y>n.y1+40||l.y+l.h<n.y0-40)continue;let u=c.room,d=u?1-u.light(r):0,f=Math.max(i,d);if(!(f<.2)){for(let n of c.furniture)if(s(n.ax,n.ay,40)){if(n.kind===`desk`||n.kind===`desk_back`){let r=t.deskScreen(n,c);if(r===`off`)continue;e.globalAlpha=(r===`idle`?.2:.35)*f,e.drawImage(a,Math.round(n.ax-24),Math.round(n.ay-34))}else if(n.kind===`floor_lamp`&&i>.2&&(!u||u.lightOn)){let t=this.lampHead(n);e.globalAlpha=.5*i,e.drawImage(o,Math.round(t.x-16),Math.round(t.y-16),32,32)}else(n.kind===`vending_machine`||n.kind===`arcade`)&&(e.globalAlpha=.25*f,e.drawImage(a,Math.round(n.ax-24),Math.round(n.ay-36)))}if(i>.2)for(let t of c.wallItems)t.kind===`tv`&&s(t.cx,t.baseY,60)&&(e.globalAlpha=.3*i,e.drawImage(a,Math.round(t.cx-28),Math.round(t.baseY-30),56,56))}}if(this.drawSunbeams(e,t,n),i>.2){for(let n of t.exterior.props)n.kind===`lamp`&&s(n.x,n.y,64)&&(e.globalAlpha=.6*i,e.drawImage(o,Math.round(n.x-14),Math.round(n.y-43),28,28));this.drawHeadlights(e,t,n,i),i>.6&&!this.reduced&&this.drawFireflies(e,t,n,r,(i-.6)/.4)}e.restore()}drawSunbeams(e,t,n){let r=Qd(this.ambient.hour);if(!r)return;let i=mp(Kd([255,226,160],[255,150,64],this.ambient.warm));e.globalCompositeOperation=`lighter`;let a=(t,a)=>{if(!(a.x>n.x1||a.x+a.w<n.x0||a.y>n.y1||a.y+a.h<n.y0)){e.save(),e.beginPath(),e.rect(a.x,a.y,a.w,a.h),e.clip(),e.globalAlpha=r.alpha;for(let n of t){let t=this.windowGlass(n);t&&(e.save(),e.transform(1,0,r.skew,1,t.x-r.skew*n.baseY,0),e.drawImage(i,0,n.baseY,t.w,r.len),e.restore())}e.restore()}};for(let e of t.areas.values()){if(e.layout.rect.y!==0||e.room&&e.room.phase!==`ready`)continue;let t=e.wallItems.filter(e=>e.kind===`window`);if(!t.length)continue;let n=e.px;a(t,{x:n.x,y:n.y+32,w:n.w,h:n.h-48})}for(let e of t.shells)e.rect.y!==0||t.roomInSlot(e.slot)||a(t.shellWindows.filter(t=>t.areaId===`shell:${e.slot}`),{x:e.rect.x*16,y:192,w:e.rect.w*16,h:80})}windowGlass(e){let t=Gf(this.art,`window`,e.variant,0,e.seed);if(!t)return null;let n=Wf(e,t.base),r=t.base.rects?.glass;return r?{x:n.x+r.x,w:r.w}:{x:n.x+3,w:t.base.canvas.width-6}}lampHead(e){let t=Vf(this.art,e)?.base,n=t?.rects?.glow;return t&&n?{x:e.ax-t.ax+n.x+n.w/2,y:e.ay-t.ay+n.y+n.h/2}:{x:e.ax,y:e.ay-33}}drawHeadlights(e,t,n,r){if(!t.cars.length)return;let i=wf(`#fff1c4`,64),a=wf(`#ff4a3a`,16);for(let o of t.cars){if(o.x<n.x0-80||o.x>n.x1+80||o.y<n.y0-30||o.y>n.y1+30)continue;let t=o.x+o.dir*16;e.globalAlpha=.55*r,e.drawImage(i,Math.round(t+(o.dir>0?0:-46)),Math.round(o.y-15),46,16),e.globalAlpha=.8*r,e.drawImage(a,Math.round(o.x-o.dir*16-4),Math.round(o.y-11),8,8)}}drawFireflies(e,t,n,r,i){this.fliesFor!==t.exterior&&this.seedFireflies(t.exterior);let a=wf(`#d8ff7a`,12),o=r/1e3;for(let t of this.flies){let r=t.x+Math.sin(o*t.sx+t.ph)*7,s=t.y+Math.cos(o*t.sy+t.ph*1.7)*4;if(r<n.x0-8||r>n.x1+8||s<n.y0-8||s>n.y1+8)continue;let c=Math.sin(o*t.blink+t.ph*3);if(c<=.2)continue;let l=((c-.2)/.8)**2*i;e.globalAlpha=.9*l,e.drawImage(a,Math.round(r-6),Math.round(s-6)),e.globalAlpha=l,e.fillStyle=`#f4ffc8`,e.fillRect(Math.round(r),Math.round(s),1,1)}}seedFireflies(e){this.fliesFor=e,this.flies=[];let t=d(61925+e.bounds.w),n=e.props.filter(e=>e.kind===`bush`||e.kind===`flowers`||e.kind===`tree`);if(n.length)for(let e=0;e<cp;e++){let e=n[Math.floor(t()*n.length)];this.flies.push({x:e.x+(t()-.5)*28,y:e.y-6-t()*14,ph:t()*Math.PI*2,sx:.25+t()*.35,sy:.3+t()*.4,blink:.6+t()*.9})}}},_p=[`#ff4d6d`,`#ffb11f`,`#ffe14d`,`#3ddc84`,`#3fa7ff`,`#b06bff`,`#ff7ad9`],vp=`#fff6dc`,yp=`#f2c75c`,bp=`#7cc4ff`,xp=`#ffcf3a`,Sp=`#c98a12`,Cp=`#fff6c2`,wp=[`#ffffff`,`#fff3a6`,`#ffd1f0`,`#bfe9ff`],Tp={0:260,1:150,2:0,3:240,4:-14},Ep={0:0,1:2.2,2:0,3:0,4:3},Dp=class{cap;n=0;x;y;vx;vy;age;life;ph;kind;color;constructor(e=600){this.cap=e,this.x=new Float32Array(e),this.y=new Float32Array(e),this.vx=new Float32Array(e),this.vy=new Float32Array(e),this.age=new Float32Array(e),this.life=new Float32Array(e),this.ph=new Float32Array(e),this.kind=new Uint8Array(e),this.color=new Uint8Array(e)}get count(){return this.n}spawn(e,t,n,r,i,a,o=0){if(this.n>=this.cap)return;let s=this.n++;this.kind[s]=e,this.x[s]=t,this.y[s]=n,this.vx[s]=r,this.vy[s]=i,this.age[s]=0,this.life[s]=Math.max(.01,a),this.ph[s]=Math.random()*6.283,this.color[s]=o}popcorn(e,t){let n=-(62+Math.random()*26);this.spawn(0,e+(Math.random()*4-2),t,Math.random()*28-14,n,-2*n/Tp[0]+.05)}confetti(e,t,n=42){for(let r=0;r<n;r++){let n=-Math.PI/2+(Math.random()-.5)*2.4,r=55+Math.random()*70;this.spawn(1,e+(Math.random()*6-3),t,Math.cos(n)*r,Math.sin(n)*r,1.3+Math.random()*.9,Math.floor(Math.random()*_p.length))}}confettiFall(e,t,n){this.spawn(1,e,t,Math.random()*24-12,8+Math.random()*16,Math.max(.3,n/34)*(.85+Math.random()*.3),Math.floor(Math.random()*_p.length))}rain(e,t,n){this.spawn(2,e,t,0,32,Math.max(.05,n/32))}coins(e,t,n,r,i=7){let a=Tp[3];for(let o=0;o<i;o++){let i=.55+o*.07+Math.random()*.06,s=n+(Math.random()*6-3),c=r+(Math.random()*3-1),l=e+(Math.random()*4-2);this.spawn(3,l,t,(s-l)/i,(c-t)/i-.5*a*i,i)}}sparkle(e,t,n=9){for(let r=0;r<n;r++){let i=r/n*Math.PI*2+Math.random()*.5,a=5+Math.random()*6;this.spawn(4,e+Math.cos(i)*a,t+Math.sin(i)*a*.8-6,Math.cos(i)*6,-10-Math.random()*8,.8+Math.random()*.6,Math.floor(Math.random()*wp.length))}}update(e){let t=Math.min(.1,Math.max(0,e)),n=0;for(;n<this.n;){if(this.age[n]+=t,this.age[n]>=this.life[n]){this.remove(n);continue}let e=this.kind[n];this.vy[n]+=Tp[e]*t,Ep[e]&&(this.vx[n]*=Math.max(0,1-Ep[e]*t)),e===1&&this.vy[n]>38&&(this.vy[n]=38),this.x[n]+=this.vx[n]*t,this.y[n]+=this.vy[n]*t,n++}}draw(e,t,n,r,i,a){if(this.n){for(let o=0;o<this.n;o++){let s=Math.round(this.x[o]),c=Math.round(this.y[o]);if(s<t-2||s>r+2||c<n-2||c>i+2)continue;let l=this.kind[o],u=1-this.age[o]/this.life[o];if(l===0)e.globalAlpha=1,e.fillStyle=vp,e.fillRect(s,c,2,2),e.fillStyle=yp,e.fillRect(s+1,c+1,1,1);else if(l===1){e.globalAlpha=Math.min(1,u*3.5),e.fillStyle=_p[this.color[o]%_p.length];let t=Math.sin(a/90+this.ph[o])>0;e.fillRect(s,c,t?2:1,t?1:2)}else l===3?(e.globalAlpha=1,Math.sin(a/70+this.ph[o])>-.3?(e.fillStyle=Sp,e.fillRect(s-1,c-1,3,3),e.fillStyle=xp,e.fillRect(s-1,c-1,2,2),e.fillStyle=Cp,e.fillRect(s-1,c-1,1,1)):(e.fillStyle=xp,e.fillRect(s,c-1,1,3))):l===4?(e.globalAlpha=Math.min(1,u*2.5),e.fillStyle=wp[this.color[o]%wp.length],Math.sin(a/90+this.ph[o])>0?(e.fillRect(s-1,c,3,1),e.fillRect(s,c-1,1,3)):e.fillRect(s,c,1,1)):(e.globalAlpha=.9,e.fillStyle=bp,e.fillRect(s,c,1,2))}e.globalAlpha=1}}clear(){this.n=0}remove(e){let t=--this.n;e!==t&&(this.x[e]=this.x[t],this.y[e]=this.y[t],this.vx[e]=this.vx[t],this.vy[e]=this.vy[t],this.age[e]=this.age[t],this.life[e]=this.life[t],this.ph[e]=this.ph[t],this.kind[e]=this.kind[t],this.color[e]=this.color[t])}},Op={"×":[`000`,`101`,`010`,`101`,`000`],"+":[`000`,`010`,`111`,`010`,`000`],0:[`111`,`101`,`101`,`101`,`111`],1:[`010`,`110`,`010`,`010`,`111`],2:[`110`,`001`,`010`,`100`,`111`],3:[`110`,`001`,`010`,`001`,`110`],4:[`101`,`101`,`111`,`001`,`001`],5:[`111`,`100`,`110`,`001`,`110`],6:[`011`,`100`,`111`,`101`,`111`],7:[`111`,`001`,`010`,`010`,`010`],8:[`111`,`101`,`111`,`101`,`111`],9:[`111`,`101`,`111`,`001`,`110`]},kp=`#2b3346`,Ap=`#151a26`,jp=`#ffe08a`,Mp=new Map;function Np(e,t){let n=document.createElement(`canvas`);n.width=e,n.height=t;let r=n.getContext(`2d`);return r.imageSmoothingEnabled=!1,{c:n,ctx:r}}function Pp(e){return e>9?`×9+`:`×${Math.max(0,Math.floor(e))}`}function Fp(e){let t=Math.min(10,Math.max(2,Math.floor(e))),n=Mp.get(t);if(n)return n;let r=[...Pp(t)],i=r.length*4-1+4,{c:a,ctx:o}=Np(i,9);o.fillStyle=Ap,o.fillRect(1,0,i-2,9),o.fillRect(0,1,i,7),o.fillStyle=kp,o.fillRect(1,1,i-2,7),o.fillStyle=jp;let s=2;for(let e of r){let t=Op[e];if(t)for(let e=0;e<5;e++)for(let n=0;n<3;n++)t[e][n]===`1`&&o.fillRect(s+n,2+e,1,1);s+=4}return n={canvas:a,ax:0,ay:9},Mp.set(t,n),n}var Ip=`#2a3142`,Lp={hourglass:{rows:[`oooooooo`,`.owwwwo.`,`.oyyyyo.`,`..oyyo..`,`...oo...`,`..owwo..`,`.owyywo.`,`.oyyyyo.`,`oooooooo`],pal:{o:`#8a5a2b`,w:`#e8f4ff`,y:`#ffd166`}},hourglass_flip:{rows:[`...oo...`,`..owwo..`,`.owwyyo.`,`oowyyyoo`,`o.oyyo.o`,`oowwwwoo`,`.owwwwo.`,`..owwo..`,`...oo...`],pal:{o:`#8a5a2b`,w:`#e8f4ff`,y:`#ffd166`}},cobweb:{rows:[`w....w....w.`,`.w...w...w..`,`..wwwwwww...`,`..w.w.w.w...`,`.wwwwwwwww..`,`..w.w.w.w...`,`...wwwwww...`,`....w.w.....`,`.....ww.....`,`......s.....`,`......s.....`,`.....kkk....`],pal:{w:`#e9eef7`,s:`#c9d1de`,k:`#2b2b33`},outline:!1},storm:{rows:[`...cccc....`,`.cccwwccc..`,`cwwwwwwwcc.`,`cwwwwwwwwwc`,`.cccccyccc.`,`.....yy....`,`....yy.....`,`.....y.....`],pal:{c:`#7d8799`,w:`#c3cad6`,y:`#ffd23f`}}},Rp=new Map;function zp(e){if(Rp.has(e))return Rp.get(e);let t=Lp[e],n=null;if(t&&typeof document<`u`){let e=Math.max(...t.rows.map(e=>e.length)),r=t.rows.length,{c:i,ctx:a}=Np(e+2,r+2);if(a.fillStyle=Ip,t.outline!==!1)for(let e=0;e<r;e++)for(let n=0;n<t.rows[e].length;n++)t.pal[t.rows[e][n]]&&a.fillRect(n,e,3,3);for(let e=0;e<r;e++)for(let n=0;n<t.rows[e].length;n++){let r=t.pal[t.rows[e][n]];r&&(a.fillStyle=r,a.fillRect(n+1,e+1,1,1))}n={canvas:i,ax:Math.floor((e+2)/2),ay:r+2}}return Rp.set(e,n),n}var Bp=[`browser`,`idle`,`chat`,`code`],Vp={down:0,up:-9,left:-5,right:5},Hp={down:11,up:8,left:9,right:9},Up=9,Wp=.2,Gp=`rgba(18,40,26,${Wp})`,Kp=class{canvas;art;sim;camera;ctx;areas=new Map;heads=new Map;exterior;shells=[];shellWindows=[];base=null;baseX=0;baseY=0;baseCols=-1;layoutVersion=-1;assetsVersion=0;builtAssetsVersion=0;cars=[];nextCarAt=0;ents=[];pool=[];date=new Date;icons=[];particles=new Dp;roomFx=new xc;dt=0;iconCount=0;elevatorVis=[];occupiedSlots=new Set;hourOverride=$d(typeof location>`u`?``:location.search);clock=()=>Date.now();lighting;assets=null;night=0;clearColor=`#7fae62`;grass=null;theme=`none`;constructor(e,t,n,r){this.canvas=e,this.art=t,this.sim=n,this.camera=r,this.ctx=e.getContext(`2d`,{alpha:!1}),this.exterior=hd(n.building.cols),this.lighting=new gp(t,n)}setAssets(e){this.assets=e,this.assetsVersion++}sync(e=`none`){let t=this.sim,n=e!==this.theme;this.theme=e;let r=this.builtAssetsVersion!==this.assetsVersion||n;if((this.baseCols!==t.building.cols||r)&&this.buildBase(),this.layoutVersion!==t.layoutVersion||r){this.layoutVersion=t.layoutVersion;let n=new Set;for(let i of[...t.building.core,t.building.corridor]){n.add(i.id);let t=this.areas.get(i.id);(!t||t.layout!==i||r)&&this.areas.set(i.id,Qf(this.art,i,void 0,this.assets,e))}for(let e of t.rooms.values())e.present&&n.add(e.id);for(let e of[...this.areas.keys()])n.has(e)||this.areas.delete(e);this.elevatorVis=this.areas.get(`core:recepcao`)?.wallItems.filter(e=>e.kind===`elevator`)??[]}this.occupiedSlots.clear();for(let n of t.rooms.values()){if(!n.present)continue;this.occupiedSlots.add(n.slot);let t=this.areas.get(n.id);!t||t.layout!==n.layout||t.version!==n.version||r?this.areas.set(n.id,Qf(this.art,n.layout,n,this.assets,e)):t.room=n}for(let[e,t]of this.areas)t.room&&!t.room.present&&this.areas.delete(e);this.builtAssetsVersion=this.assetsVersion}buildBase(){let e=this.sim.building.cols;this.baseCols=e,this.exterior=hd(e);let t=this.exterior.bounds;this.baseX=t.x*16,this.baseY=t.y*16;let n=document.createElement(`canvas`);n.width=t.w*16,n.height=t.h*16;let r=n.getContext(`2d`);r.imageSmoothingEnabled=!1,r.translate(-this.baseX,-this.baseY),ep(this.art,r,this.exterior.floors,[]);let i=this.exterior.streetY+Math.round(this.exterior.streetH/2)-1;r.fillStyle=`rgba(255,236,170,0.75)`;for(let e=this.baseX+4;e<this.baseX+n.width;e+=24)r.fillRect(e,i,12,2);this.shells=[],this.shellWindows=[];for(let t=2;t<e;t++)for(let n of[`north`,`south`]){let i=zc(t,n);if(i<0)continue;let a=gd(i,t===e-1);this.shells.push(a),ep(this.art,r,a.floors,a.walls);for(let e of a.windows)this.shellWindows.push($f(e,`shell:${a.slot}`))}this.desaturate(r);try{let e=document.createElement(`canvas`);e.width=128,e.height=128;let t=e.getContext(`2d`);t.imageSmoothingEnabled=!1;for(let[e,r]of[[0,0],[1,0],[0,1],[1,1]])t.setTransform(e?-1:1,0,0,r?-1:1,e?128:0,r?128:0),t.drawImage(n,0,0,64,64,0,0,64,64);t.setTransform(1,0,0,1,0,0);let r=t.getImageData(0,0,128,128).data,i=0,a=0,o=0;for(let e=0;e<r.length;e+=4)i+=r[e],a+=r[e+1],o+=r[e+2];let s=r.length/4,c=`rgb(${Math.round(i/s)},${Math.round(a/s)},${Math.round(o/s)})`;t.globalAlpha=.6,t.fillStyle=c,t.fillRect(0,0,128,128),t.globalAlpha=1,t.fillStyle=Gp,t.fillRect(0,0,128,128),this.grass=this.ctx.createPattern(e,`repeat`);let l=Wp;this.clearColor=`rgb(${Math.round(i/s*.8+18*l)},${Math.round(a/s*.8+40*l)},${Math.round(o/s*.8+26*l)})`}catch{this.grass=null,this.clearColor=`#6f9a5a`}this.finishBase(r,e),this.base=n}desaturate(e){let t=this.exterior.bounds;e.save();try{e.globalCompositeOperation=`saturation`,e.fillStyle=`rgba(128,128,128,0.16)`,e.fillRect(t.x*16,t.y*16,t.w*16,t.h*16)}catch{}e.restore()}finishBase(e,t){let n=this.exterior.bounds,r=n.x*16,i=n.y*16,a=n.w*16,o=n.h*16;e.save();let s=t*16,c=(e,t,n)=>{let r=Math.max(0,Math.min(1,(n-e)/Math.max(1e-6,t-e)));return r*r*(3-2*r)};try{let t=document.createElement(`canvas`);t.width=n.w,t.height=n.h;let l=t.getContext(`2d`),u=l.createImageData(n.w,n.h);for(let e=0;e<n.h;e++)for(let t=0;t<n.w;t++){let r=n.x+t+.5,i=n.y+e+.5,a=r<0?c(6,-n.x,-r):r>s?c(6,n.x+n.w-s,r-s):0,o=i<0?c(5,-n.y,-i):i>29?c(12,n.y+n.h-29,i-29):0,l=(e*n.w+t)*4;u.data[l]=18,u.data[l+1]=40,u.data[l+2]=26,u.data[l+3]=Math.round(Math.max(a,o)*Wp*255)}l.putImageData(u,0,0),e.imageSmoothingEnabled=!0,e.drawImage(t,r,i,a,o),e.imageSmoothingEnabled=!1}catch{}e.fillStyle=`#3f4652`,e.fillRect(-28,212,24,40),e.fillStyle=`#596170`,e.fillRect(-26,214,20,36),e.fillStyle=`#4b525f`;for(let t=216;t<248;t+=3)e.fillRect(-25,t,18,1);e.restore()}frame(e,t,n,r){let{ctx:i,camera:a}=this;this.date.setTime(this.clock()),this.dt=t,this.updateCars(e,t);let o=this.canvas.width,s=this.canvas.height;i.setTransform(1,0,0,1,0,0),i.imageSmoothingEnabled=!1,i.fillStyle=this.clearColor,i.fillRect(0,0,o,s);let{scale:c,ox:l,oy:u}=a.transform();i.setTransform(c,0,0,c,l,u);let d=-l/c,f=-u/c,p=d+o/c,m=f+s/c;if(this.grass&&this.base){let e=this.baseX+this.base.width,t=this.baseY+this.base.height;(d<this.baseX||f<this.baseY||p>e||m>t)&&(i.fillStyle=this.grass,i.save(),i.translate(this.baseX,this.baseY),i.fillRect(d-this.baseX-1,f-this.baseY-1,p-d+2,m-f+2),i.restore())}let h=(e,t,n,r)=>e<p&&e+n>d&&t<m&&t+r>f;if(this.base){let e=Math.max(0,Math.floor(d-this.baseX)-1),t=Math.max(0,Math.floor(f-this.baseY)-1),n=Math.min(this.base.width-e,Math.ceil(p-d)+3),r=Math.min(this.base.height-t,Math.ceil(m-f)+3);n>0&&r>0&&i.drawImage(this.base,e,t,n,r,this.baseX+e,this.baseY+t,n,r)}if(this.hourOverride!==null){let e=Math.round(this.hourOverride*60);this.date.setHours(Math.floor(e/60)%24,e%60)}let g=this.lighting.update(e,tf(n),this.hourOverride,this.date),_=e;for(let e of this.shellWindows){let t=Number(e.areaId.slice(6)),n=this.roomInSlot(t);n&&n.phase===`ready`||h(e.cx-24,e.baseY-40,48,44)&&this.drawWindow(e,g,_,1)}for(let t of this.areas.values()){let n=t.px;if(!h(n.x,n.y-16,n.w,n.h+16))continue;let r=t.room?Mu(t.room.phase,t.room.progress(e)):ju;this.drawFloor(t,r)}for(let t of this.areas.values()){let n=t.px;if(!h(n.x,n.y-16,n.w,n.h+16))continue;let r=t.room?Mu(t.room.phase,t.room.progress(e)):ju;this.drawWalls(t,r,e,g)}let v={x0:d,y0:f,x1:p,y1:m};this.roomFx.drawFloor(i,this.sim,e,v);let y=this.ents;y.length=0;let b=0,x=(e,t,n,r,i)=>{let a=this.pool[b];a?(a.k=e,a.y=t,a.ref=n,a.area=r,a.scale=i):this.pool[b]=a={k:e,y:t,ref:n,area:r,scale:i},b++,y.push(a)};for(let t of this.areas.values()){let n=t.px;if(!h(n.x-16,n.y-48,n.w+32,n.h+64))continue;let r=t.room?Mu(t.room.phase,t.room.progress(e)):ju;for(let n of t.furniture){let i=r.mode===`none`?1:Nu(r,n.order);i<=.01||h(n.ax-48,n.ay-64,96,68)&&(x(0,n.ay,n,t,i),Vf(this.art,n,this.furnState(n,e))?.front&&x(1,n.ay+.5,n,t,i))}}for(let t of this.sim.people()){let n=this.headOf(t);if(n.visible=!1,!(t.inside||t.alpha<=.01||e<t.hiddenUntil)){if(!h(t.x-24,t.y-48,48,56)){n.x=t.x,n.y=t.y-26,n.feetY=t.y;continue}x(2,t.depth(),t,null,1)}}for(let t of this.exterior.props){if(!h(t.x-24,t.y-56,48,60))continue;let n=1;if(t.whenRoom!==void 0){let r=this.roomInSlot(t.whenRoom);if(!r)continue;if(r.phase===`building`||r.phase===`dismantling`){let t=r.progress(e);if(n=r.phase===`building`?Math.min(1,t*3):1-Math.min(1,Math.max(0,(t-.75)*4)),n<=.02)continue}}x(3,t.y,t,null,n)}for(let t of this.shells){let n=this.roomInSlot(t.slot),r=1;if(n){if(n.phase!==`building`&&n.phase!==`dismantling`)continue;let t=n.progress(e);if(r=n.phase===`building`?1-Math.min(1,t*3):Math.min(1,Math.max(0,(t-.75)*4)),r<=.02)continue}for(let e of t.props)h(e.x-24,e.y-56,48,60)&&x(3,e.y,e,null,r)}for(let e of this.cars)h(e.x-24,e.y-24,48,28)&&x(4,e.y,e,null,1);y.sort((e,t)=>e.y-t.y||e.k-t.k),this.iconCount=0;for(let t of y)switch(t.k){case 0:this.drawFurniture(t.ref,t.area,t.scale,!1,e);break;case 1:this.drawFurniture(t.ref,t.area,t.scale,!0,e);break;case 2:this.drawCharacter(t.ref,e,r);break;case 3:this.drawProp(t.ref,t.scale);break;case 4:this.drawCar(t.ref)}if(this.drawPingPong(e),this.drawCobwebs(e),this.drainEffects(e),this.roomFx.emit(this.particles,this.sim,e,t,v),this.particles.update(t),this.particles.draw(i,d,f,p,m,e),this.night=this.lighting.night,this.drawLighting(e,d,f,p,m),this.theme!==`none`)for(let t of this.areas.values())t.room&&t.room.phase!==`ready`||h(t.px.x,t.px.y,t.px.w,t.px.h)&&Lf(i,this.theme,t.layout,t.room?t.room.light(e):1);this.roomFx.drawLights(i,this.sim,this.heads,e,v);for(let e=0;e<this.iconCount;e++){let t=this.icons[e],n=this.icon(t.name);if(!n)continue;i.globalAlpha=t.alpha;let r=Math.round(t.x-n.ax),a=Math.round(t.y-n.ay-t.bounce);if(i.drawImage(n.canvas,r,a),t.badge>1){let e=Fp(t.badge);i.drawImage(e.canvas,r+n.canvas.width-1,a+n.canvas.height-e.ay+1)}}i.globalAlpha=1}headOf(e){let t=this.heads.get(e.id);return t||this.heads.set(e.id,t={x:0,y:0,feetY:0,visible:!1,bx:0,by:0,bw:0,bh:0,depth:0}),t}pruneHeads(){for(let e of this.heads.keys())this.sim.person(e)||this.heads.delete(e)}roomInSlot(e){if(this.occupiedSlots.has(e)){for(let t of this.sim.rooms.values())if(t.slot===e&&t.present)return t}}drawFloor(e,t){let{ctx:n}=this,r=e.px;if(t.floor>=1){n.drawImage(e.floor,r.x,r.y);return}if(t.floor<=0)return;let i=e.layout.rect.w,a=e.layout.rect.h,o=t.floor*1.06;for(let t=0;t<a;t++)for(let s=0;s<i;s++)Pu(s,t,i,a)>o||n.drawImage(e.floor,s*16,t*16,16,16,r.x+s*16,r.y+t*16,16,16)}drawWalls(e,t,n,r){let{ctx:i}=this,a=e.px;if(t.walls<=0)return;let o=Math.round((1-t.walls)*10);t.walls<1&&(i.globalAlpha=t.walls),i.drawImage(e.walls,a.x,a.y-16+o);for(let t of e.wallItems)this.drawWallItem(e,t,n,r,o);if(i.globalAlpha=1,e.sign&&t.sign>0){let n=Math.round((1-t.sign)*-18);i.globalAlpha=t.sign,this.drawSign(e,e.sign,n),i.globalAlpha=1}}drawWallItem(e,t,n,r,i){let{ctx:a}=this;switch(t.kind){case`window`:this.drawWindow(t,r,n,1,i);return;case`elevator`:{let e=this.elevatorVis.indexOf(t),n=this.sim.elevators[e]?.state??0,r=Gf(this.art,`elevator`,t.variant,n,t.seed);if(!r)return;let o=Wf(t,r.base);a.drawImage(r.base.canvas,o.x,o.y+i),Pf(a,this.theme,t.cx,t.baseY+i);return}case`light_switch`:{let n=!e.room||e.room.lightOn,r=Gf(this.art,`light_switch`,n?`on`:`off`,0,t.seed);if(!r)return;let o=Wf(t,r.base);a.drawImage(r.base.canvas,o.x,o.y+i);return}case`clock`:{let e=Gf(this.art,`clock`,t.variant,0,t.seed);if(!e)return;let n=Wf(t,e.base);a.drawImage(e.base.canvas,n.x,n.y+i);let r=e.base.rects?.face;r&&this.safe(()=>this.art.drawClock(a,{x:n.x+r.x,y:n.y+i+r.y,w:r.w,h:r.h},this.date));return}case`whiteboard`:{let r=Gf(this.art,`whiteboard`,t.variant,0,t.seed);if(!r)return;let o=Wf(t,r.base);a.drawImage(r.base.canvas,o.x,o.y+i);let s=r.base.rects?.board;s&&this.safe(()=>this.art.drawBoard(a,{x:o.x+s.x,y:o.y+i+s.y,w:s.w,h:s.h},e.room?.board??[],n));return}case`tv`:{let e=Gf(this.art,`tv`,t.variant,0,t.seed);if(!e)return;let r=Wf(t,e.base);a.drawImage(e.base.canvas,r.x,r.y+i);let o=e.base.rects?.tv,s=this.sim.social.tvScreen(),c=s?s.mode:Bp[Math.floor(n/9e3)%Bp.length],l=s?s.seed:t.seed;o&&this.safe(()=>this.art.drawScreen(a,{x:r.x+o.x,y:r.y+i+o.y,w:o.w,h:o.h},c,n,l));return}case`mirror`:{let e=Gf(this.art,`mirror`,t.variant,0,t.seed);if(!e)return;let n=Wf(t,e.base);a.drawImage(e.base.canvas,n.x,n.y+i);let r=e.base.rects?.glass;r&&this.drawReflection(t,n.x+r.x,n.y+i+r.y,r.w,r.h);return}default:{let e=Gf(this.art,t.kind,t.variant,0,t.seed);if(!e)return;let n=Wf(t,e.base);a.drawImage(e.base.canvas,n.x,n.y+i)}}}drawWindow(e,t,n,r,i=0){let{ctx:a}=this,o=Gf(this.art,`window`,e.variant,0,e.seed);if(!o)return;let s=Wf(e,o.base),c=o.base.rects?.glass;if(!c){let e=Uf(o.base.canvas);c={x:e.x+2,y:e.y+2,w:e.w-4,h:e.h-4}}a.globalAlpha*=r,this.safe(()=>this.art.drawWindowView(a,{x:s.x+c.x,y:s.y+i+c.y,w:c.w,h:c.h},t,n,e.seed)),Rf(a,this.theme,{x:s.x+c.x,y:s.y+i+c.y,w:c.w,h:c.h},n,e.seed),a.drawImage(o.base.canvas,s.x,s.y+i)}drawSign(e,t,n){let{ctx:r}=this;if(!e.room&&this.assets?.signage&&e.id===`core:recepcao`){let e=this.assets.signage,i=Math.min(80/e.w,24/e.h),a=i>=1?Math.floor(i):i,o=Math.round(e.w*a),s=Math.round(e.h*a);r.save(),r.imageSmoothingEnabled=a<1,r.drawImage(e.img,Math.round(t.cx-o/2),Math.round(t.baseY-8-s)+n,o,s),r.restore();return}let i=Gf(this.art,`sign`,t.variant,0,t.seed);if(!i)return;let a=Wf(t,i.base);r.drawImage(i.base.canvas,a.x,a.y+n)}signRect(e){if(!e.sign||!e.room&&this.assets?.signage&&e.id===`core:recepcao`)return null;let t=Gf(this.art,`sign`,e.sign.variant,0,e.sign.seed);if(!t)return null;let n=Wf(e.sign,t.base),r=t.base.rects?.sign??(()=>{let e=Uf(t.base.canvas);return{x:e.x+3,y:e.y+3,w:e.w-6,h:e.h-6}})();return{x:n.x+r.x,y:n.y+r.y,w:r.w,h:r.h}}paintingRect(e){let t=this.areas.get(e),n=t?.layout.wallItems.find(e=>e.kind===`painting`);if(!t||!n)return null;let r=$f(n,t.id),i=Gf(this.art,`painting`,n.variant===`wide`?void 0:n.variant,0,r.seed);if(!i)return null;let a=Wf(r,i.base),o=Uf(i.base.canvas);return{x:a.x+o.x,y:a.y+o.y,w:o.w,h:o.h}}signIsDark(e){let t=e.sign?Gf(this.art,`sign`,e.sign.variant,0,e.sign.seed):null;if(!t)return!1;let n=t.base.canvas;if(n.__dark!==void 0)return n.__dark;let r=!1;try{let e=t.base.rects?.sign??{x:2,y:2,w:n.width-4,h:n.height-4},i=n.getContext(`2d`).getImageData(e.x,e.y,Math.max(1,e.w),Math.max(1,e.h)).data,a=0,o=0;for(let e=0;e<i.length;e+=4)i[e+3]<128||(a+=.2126*i[e]+.7152*i[e+1]+.0722*i[e+2],o++);r=o>0&&a/o<120}catch{r=!1}return n.__dark=r,r}furnState(e,t){return e.kind===`coffee_machine`?+((this.sim.machineUntil.get(e.id)??0)>t):e.kind===`toilet_stall`?+!!this.sim.stallBusy.has(e.id):0}drawFurniture(e,t,n,r,i){let{ctx:a}=this,o=this.furnState(e,i),s=Vf(this.art,e,o);if(!s)return;let c=r?s.front:kf(this.theme,e.kind,t.layout,e.seed)??s.base;if(!c)return;let l=Math.round(e.ax-c.ax),u=Math.round(e.ay-c.ay),d=n!==1;if(d&&(a.save(),a.translate(e.ax,e.ay),a.scale(n,n),a.translate(-e.ax,-e.ay)),a.drawImage(c.canvas,l,u),!r&&e.kind===`desk`&&e.areaId===`core:meu-escritorio`&&this.drawInboxStack(e),!r){if(e.kind===`desk`&&c.rects?.screen){let n=c.rects.screen,r=this.deskScreen(e,t);this.safe(()=>this.art.drawScreen(a,{x:l+n.x,y:u+n.y,w:n.w,h:n.h},r,i,e.seed))}else if(e.kind===`coffee_machine`&&o===1)this.drawSteam(e.ax,u+2,i,e.seed);else if(e.kind===`arcade`&&c.rects?.screen){let e=this.sim.social.arcadeSeed(),t=c.rects.screen;e!==null&&this.safe(()=>this.art.drawScreen(a,{x:l+t.x,y:u+t.y,w:t.w,h:t.h},`game`,i,e))}}d&&a.restore()}inboxRect=null;drawInboxStack(e){let t=this.sim.inbox.shown,n=ws(t);if(n===0){this.inboxRect=null;return}let r=this.art.deskPaperStack?.(n);if(!r)return;let{ctx:i}=this;i.drawImage(r.canvas,Math.round(e.ax-r.ax),Math.round(e.ay-r.ay));let a=e.ax-16+21,o=e.ay-16-3-n;this.inboxRect={x:a,y:o-2,w:11,h:9+n};let s=Ts(t),c=Pd(s)+2,l=Math.round(a+8-c/2),u=Math.round(o-8);i.fillStyle=`#d9483b`,i.fillRect(l,u,c,7),Fd(i,s,l+1,u+1,`#ffffff`)}deskScreen(e,t){let n=t.room;if(n&&n.light(this.sim.now)<.3)return`off`;let r=e.seatSpot?this.sim.spots.ownerOf(e.seatSpot):void 0,i=r?this.sim.chars.get(r):void 0;if(!i||i.leaving)return`off`;let a=i.atSpot===e.seatSpot;return i.mode===`wait`?`alert`:a?i.mode===`work`?vd(i.info.activity?.kind):i.mode===`shell`?`progress`:`idle`:`idle`}drawSteam(e,t,n,r){let{ctx:i}=this;i.fillStyle=`#ffffff`;for(let a=0;a<3;a++){let o=((n/900+a/3+r%7/7)%1+1)%1;i.globalAlpha=.75*(1-o);let s=Math.round(e-1+Math.sin(o*6+a*2)*1.5+(a-1)),c=Math.round(t-o*9);i.fillRect(s,c,1,2)}i.globalAlpha=1}drawCharacter(e,t,n){let{ctx:r}=this,i=this.headOf(e),a=Math.round(e.x+e.offX),o=Math.round(e.y+e.offY);if(r.globalAlpha=e.alpha,e.mode===`wait`&&this.drawAlertRing(a,o,t),n.agent===e.id?this.drawRing(a,o,`#7fe3ff`,t,!0):n.hover===e.id&&this.drawRing(a,o,`#ffffff`,t,!1),!e.seated){let e=Cf();r.drawImage(e.canvas,a-e.ax,o-e.ay)}let s=null,c=this.req;c.appearance=e.appearance,c.dir=e.dir,c.pose=e.pose,c.held=e.held,c.seated=e.seated,c.costume=Of(this.theme,e.info.seed),c.led=Id(e.info.status);try{s=this.charSprite(c,e.animT)}catch{s=null}if(!s&&(c.pose===`wait`||c.held===`popcorn`)){c.pose=c.pose===`wait`?`sit`:c.pose,c.held=`none`;try{s=this.charSprite(c,e.animT)}catch{s=null}}if(s){let e=a-s.ax,t=o-s.ay;r.drawImage(s.canvas,e,t);let n=Uf(s.canvas);i.bx=e+n.x,i.by=t+n.y,i.bw=n.w,i.bh=n.h,i.y=t+n.y}else i.bx=a-7,i.by=o-26,i.bw=14,i.bh=26,i.y=o-26;r.globalAlpha=1,i.x=a,i.feetY=o,i.visible=!0,i.depth=e.depth();let l=e.mode===`wait`?`alert`:e.icon,u=e.mode===`shell`&&e.shellSince>0&&!e.leaving,d=0;if(u&&(!l||l===`zzz`)&&(l=Ll(t),d=e.shellCount),l){let n=l===`alert`?Math.round(Math.abs(Math.sin(t/180))*4):l===`zzz`?Math.round(Math.sin(t/500)*1.5):l===`hourglass`||l===`hourglass_flip`?+(t%1200<110):Math.round(Math.max(0,1-(t-e.iconAt)/250)*4),r=l===`storm`?3:0;this.pushIcon(a,i.y-2-r,l,n,e.alpha,d),l===`storm`&&Math.random()<this.dt*24&&this.particles.rain(a-3+Math.floor(Math.random()*7),i.y-3-r,r+1)}if(u&&e.shellStage===`nap`&&e.pose===`sleep`&&this.pushIcon(a+10,i.y-13,`zzz`,Math.round(Math.sin(t/500)*1.5),e.alpha,0),u&&e.pose===`wait`&&e.held===`popcorn`&&s&&t>=e.popcornAt){e.popcornAt=t+450+Math.random()*1200;let n=a-1+(Vp[e.dir]??0),r=o-1-(Hp[e.dir]??10);this.particles.popcorn(n,r),Math.random()<.3&&this.particles.popcorn(n,r)}}pushIcon(e,t,n,r,i,a){if(this.iconCount>=256)return;let o=this.icons[this.iconCount];o||(this.icons[this.iconCount]=o={x:0,y:0,name:n,bounce:0,alpha:1,badge:0}),o.x=e,o.y=t,o.name=n,o.bounce=r,o.alpha=i,o.badge=a,this.iconCount++}charSprite(e,t){let{art:n}=this,r=Math.max(1,n.poseFrameCount(e.pose)||1),i=Math.max(30,n.poseFrameDuration(e.pose)||500);return e.frame=Math.floor(t/i)%r,n.characterSprite(e)}drawCobwebs(e){if(this.sim.visit)return;let{ctx:t}=this;for(let n of this.sim.chars.values()){if(n.mode!==`shell`||!n.shellSince||n.leaving||!n.seated||n.atSpot!==n.homeSpot)continue;let r=Il(e-n.shellSince);if(!r)continue;let i=this.heads.get(n.id);if(!i||!i.visible)continue;let a=this.icon(`cobweb`);if(!a)return;let o=!(n.info.seed&1),s=this.neighborAt(i,-1),c=this.neighborAt(i,1);(o?s&&!c:c&&!s)&&(o=!o),t.globalAlpha=n.alpha,this.drawWeb(a,i,o,r,o?s:c),n.shellStage===`nap`&&this.drawWeb(a,i,!o,1,o?c:s)}t.globalAlpha=1}neighborAt(e,t){for(let n of this.heads.values()){if(n===e||!n.visible||Math.abs(n.feetY-e.feetY)>10)continue;let r=(n.x-e.x)*t;if(r>0&&r<35.2)return!0}return!1}drawWeb(e,t,n,r,i){let{ctx:a}=this,o=e.canvas.width*r,s=e.canvas.height*r,c=i?Math.min(o-3*r,Up):o-3*r,l=Math.round(t.by+2);if(n){a.drawImage(e.canvas,Math.round(t.bx-c),l,o,s);return}let u=Math.round(t.bx+t.bw+c-o);a.save(),a.translate(u+o,l),a.scale(-1,1),a.drawImage(e.canvas,0,0,o,s),a.restore()}drainEffects(e){let t=this.sim.effects;for(let n=0;n<t.length;n++){let r=t[n],i=this.heads.get(r.charId);if(!(!i||!i.visible||e-r.at>1500)){if(r.kind===`confetti`)this.particles.confetti(i.x,i.y-4);else if(r.kind===`sparkle`)this.particles.sparkle(i.x,i.y+4);else if(r.kind===`coins`){let e=this.heads.get(r.toId);e&&e.visible&&this.particles.coins(i.x,i.y+2,e.x,e.y+2)}}}t.length=0}reflectReq={appearance:void 0,dir:`down`,pose:`stand`,frame:0,held:`none`,seated:!1};drawReflection(e,t,n,r,i){let{ctx:a}=this;for(let o of this.sim.chars.values()){if(o.inside||o.alpha<.5||o.dir!==`up`||o.seated||Math.abs(o.x-e.cx)>5)continue;let s=o.y-e.baseY;if(s<14||s>30)continue;let c=this.reflectReq;c.appearance=o.appearance,c.pose=o.pose===`groom`?`groom`:`stand`,c.held=o.pose===`groom`?o.held:`none`,c.seated=!1,c.costume=Of(this.theme,o.info.seed),c.led=Id(o.info.status);let l;try{l=this.charSprite(c,o.animT)}catch{return}a.save(),a.beginPath(),a.rect(t,n,r,i),a.clip(),a.globalAlpha=.8*o.alpha,a.drawImage(l.canvas,Math.round(t+r/2-l.ax),Math.round(n-6)),a.globalAlpha=.28,a.fillStyle=`#cfe6f2`,a.fillRect(t,n,r,i),a.restore();return}}req={appearance:void 0,dir:`down`,pose:`stand`,frame:0,held:`none`,seated:!1};drawRing(e,t,n,r,i){let{ctx:a}=this,o=i?1+Math.sin(r/220)*.08:1;a.save(),a.globalAlpha*=i?.95:.6,a.strokeStyle=n,a.lineWidth=1,a.beginPath(),a.ellipse(e,t,8*o,3.5*o,0,0,Math.PI*2),a.stroke(),a.restore()}drawAlertRing(e,t,n){let{ctx:r}=this,i=n%1100/1100;r.save(),r.strokeStyle=`#ffb11f`,r.lineWidth=1.5,r.globalAlpha*=.9*(1-i),r.beginPath(),r.ellipse(e,t,6+i*12,2.5+i*5,0,0,Math.PI*2),r.stroke(),r.restore()}drawProp(e,t){if(e.kind===`paving`){let n=this.pavingCanvas(e);t<1&&(this.ctx.globalAlpha=t),this.ctx.drawImage(n,e.x,e.y),this.ctx.globalAlpha=1;return}let n=bf(e);t<1&&(this.ctx.globalAlpha=t),this.ctx.drawImage(n.canvas,Math.round(e.x-n.ax),Math.round(e.y-n.ay)),this.ctx.globalAlpha=1}pavings=new Map;pavingCanvas(e){let t=`${e.x},${e.y}`,n=this.pavings.get(t);if(n)return n;n=document.createElement(`canvas`),n.width=32,n.height=32;let r=n.getContext(`2d`);return r.imageSmoothingEnabled=!1,r.translate(-e.x,-e.y),this.safe(()=>this.art.drawFloor(r,`sidewalk`,e.x,e.y,32,32,{seed:e.seed})),this.pavings.set(t,n),n}drawCar(e){let t=Sf(e.variant,e.dir<0);this.ctx.drawImage(t.canvas,Math.round(e.x-t.ax),Math.round(e.y-t.ay))}updateCars(e,t){let n=this.exterior.bounds,r=n.x*16-40,i=(n.x+n.w)*16+40;if(e>=this.nextCarAt){this.nextCarAt=e+4e3+Math.random()*9e3;let t=this.exterior.lanes[Math.floor(Math.random()*this.exterior.lanes.length)];t&&this.cars.push({x:t.dir>0?r:i,y:t.y,dir:t.dir,speed:38+Math.random()*30,variant:Math.floor(Math.random()*6)})}for(let e of this.cars)e.x+=e.dir*e.speed*Math.min(t,.1);this.cars.length&&(this.cars=this.cars.filter(e=>e.x>=r-10&&e.x<=i+10))}drawPingPong(e){let{ctx:t}=this;for(let n of this.sim.social.gatherings){if(n.kind!==`pingpong`||n.phase!==`run`)continue;let r,i;for(let e of n.members)e.role!==`player`||e.left||(r?i=this.sim.chars.get(e.id):r=this.sim.chars.get(e.id));if(!r||!i)continue;let a=r.x<i.x?r:i,o=r.x<i.x?i:r,s=1100,c=(e-n.startAt)%(s*2)/s,l=c<1?c:2-c,u=a.x+9+(o.x-a.x-18)*l,d=(a.y+o.y)/2-9,f=Math.sin(Math.PI*(l*2%1))*6;t.fillStyle=`rgba(30,40,60,0.35)`,t.fillRect(Math.round(u)-1,Math.round(d)+1,2,1),t.fillStyle=`#ffffff`,t.fillRect(Math.round(u)-1,Math.round(d-f)-1,2,2)}}icon(e){try{let t=this.art.iconSprite(e);if(t&&t.canvas.width>0)return t}catch{}return zp(e)}drawLighting(e,t,n,r,i){let{ctx:a}=this,o={x0:t,y0:n,x1:r,y1:i};this.lighting.drawAmbient(a,this,o,e,this.dt);let s=this.night;for(let t of this.areas.values()){let n=t.room;if(!n||!t.layout.shade)continue;let r=n.light(e),i=(n.phase===`building`?.5:.74)+.1*s,o=n.phase===`building`||n.phase===`dismantling`?Mu(n.phase,n.progress(e)).floor:1,c=(1-r)*i*o;if(c<=.01)continue;let l=t.layout.shade;a.fillStyle=`rgba(8,12,36,${c})`,a.fillRect(l.x,l.y,l.w,l.h)}this.lighting.drawGlows(a,this,o,e)}safe(e){try{e()}catch{}}},qp=class{w;h;version;cells;constructor(e,t,n=0){this.w=e,this.h=t,this.version=n,this.cells=new Uint8Array(e*t)}inside(e,t){return e>=0&&t>=0&&e<this.w&&t<this.h}get(e,t){return this.inside(e,t)?this.cells[t*this.w+e]:0}set(e,t,n){this.inside(e,t)&&(this.cells[t*this.w+e]=n)}walkable(e,t){return this.get(e,t)!==0}fill(e,t,n,r,i){for(let a=t;a<t+r;a++)for(let t=e;t<e+n;t++)this.set(t,a,i)}nearestWalkable(e,t,n=12){if(this.walkable(e,t))return{x:e,y:t};for(let r=1;r<=n;r++){let n=null,i=1/0;for(let a=-r;a<=r;a++)for(let o=-r;o<=r;o++){if(Math.max(Math.abs(o),Math.abs(a))!==r||!this.walkable(e+o,t+a))continue;let s=o*o+a*a;s<i&&(i=s,n={x:e+o,y:t+a})}if(n)return n}return null}reachableFrom(e,t){let n=new Uint8Array(this.w*this.h);if(!this.walkable(e,t))return n;let r=new Int32Array(this.w*this.h),i=0,a=0;for(r[a++]=t*this.w+e,n[t*this.w+e]=1;i<a;){let e=r[i++],t=e%this.w,o=(e-t)/this.w;for(let e=0;e<4;e++){let i=t+(e===0?1:e===1?-1:0),s=o+(e===2?1:e===3?-1:0);if(!this.walkable(i,s))continue;let c=s*this.w+i;n[c]||(n[c]=1,r[a++]=c)}}return n}},Jp=[[-1,0],[1,0]],Yp=[[0,1],[-1,1],[1,1],[0,-1],[-1,-1],[1,-1]];function Xp(e,t,n,r){let i=(i,a)=>{for(let[o,s]of i){let i=t.x+o,c=t.y+s;if(!e.inside(i,c)||e.get(i,c)!==1)continue;let l=c*e.w+i;if(!(n.has(l)||r.has(l)))return{x:i,y:c,tier:a}}return null};return i(Jp,`beside`)??i(Yp,`aisle`)}var Zp=`player:me`;function Qp(e,t){return{id:Zp,kind:`main`,provider:`claude`,roomId:Uc,name:e.name,look:e.look,...e.parts&&Object.keys(e.parts).length?{parts:e.parts}:{},role:a(`Eu`),sessionId:Zp,account:``,status:`idle`,recent:[],tasks:[],startedAt:t,lastEventAt:t,statusSince:t,stats:{toolCalls:0,tokensIn:0,tokensOut:0,subagents:0},seed:e.seed}}var $p=12e4,em=1e3,tm=6e4,nm=3e4,rm=new Map,im=2500,am=3e4,om=500,sm=`💬`,cm=36e5,lm=2500,um=[`armchair`,`beanbag`],dm=class{sim;character=null;ledger=new Eu;held=new Map;pending=[];slots=rm;attention=iu;plan=null;currentMode=`office`;nextCheckAt=0;recheck=!1;talkedAt=0;seenTalkAt=0;talkExpiresAt=0;away=`here`;awayDone=null;returnPending=!1;awaySpots=[];ownsSortY=!1;busyAt=0;nextFunAt=0;nextWalletAt=0;constructor(e){this.sim=e}get ch(){return this.character}setLook(e,t){this.character?.gathering&&this.sim.social.leave(this.character,t),this.sim.releasePlayerSeat(),this.character=e?this.sim.spawnPlayer(Qp(e,t)):null,this.plan=null,this.ownsSortY=!1,this.awaySpots.length=0,this.currentMode=`office`,this.busyAt=t,this.nextFunAt=0,this.character&&e&&this.sim.social.wallets.ensure({id:Zp,name:e.name,kind:`main`,tasks:[]},t),this.character||this.clearQueue()}get mode(){return this.currentMode}setAttention(e,t){this.attention=e,this.busyAt=t;let n=e.talk;n&&n.at!==this.seenTalkAt&&(this.seenTalkAt=n.at,this.talkExpiresAt=t+am),this.recheck=!0}setAway(e,t){e!==this.away&&(this.away=e,e===`here`&&(this.busyAt=t),this.awayDone=null,this.recheck=!0)}returned(e,t){this.character&&this.plan?.kind!==`return`&&(this.returnPending=!0,this.recheck=!0)}adoptAttention(e,t){this.talkedAt=this.seenTalkAt=e.talk?.at??0,this.setAttention(e,t)}queueSlots(){return this.slots}queueEntry(e){let t=this.held.get(e);return t?{agentId:e,since:0,kind:t.kind}:null}noteAttention(e,t){this.ledger.note(e,t),this.busyAt=t}ledgerSize(){return this.ledger.size}updateQueue(e){let t=this.sim;if(!this.character){this.clearQueue();return}this.ledger.prune(e);let n=[];for(let e of t.chars.values())!e.gone&&!e.leaving&&e.mode===`wait`&&n.push(e.info);let r=xu(n),i=new Set(r.map(e=>e.agentId));for(let[n,r]of[...this.held]){if(i.has(n)){r.phase===`queued`?r.lastWaitingAt=e:this.release(n);continue}let a=t.chars.get(n);if(!a||a.gone||a.leaving){this.ledger.take(n,e),this.release(n);continue}if(r.phase===`queued`){let t=this.ledger.take(n,e);if(t&&r.kind===`stamp`)r.phase=`stamp-wait`,r.color=t,r.deadline=e+nm,a.reactUntil=r.deadline;else if(r.kind===`terminal`||e-r.lastWaitingAt>=800){this.release(n);continue}}if(r.phase===`stamp-wait`)e>r.deadline?this.release(n):this.atQueueSpot(a,r.rank)&&(r.phase=`stamping`,this.pending.push(n));else if(r.phase===`stamping`){let i=t.stamps.get(n);(i&&e>=i.until||e>r.deadline)&&this.release(n)}}let a=new Set;for(let[e,t]of this.held)i.has(e)||a.add(t.rank);let o=t.spots.ofKind(`queue`).map(e=>e.rank??0).filter(e=>!a.has(e)).sort((e,t)=>e-t),{queued:s,overflow:c}=Su(r,o.length),l=new Map;for(let[e,t]of this.held)i.has(e)||l.set(e,t.rank);let u=new Set;s.forEach((t,n)=>{l.set(t.agentId,o[n]),u.add(t.agentId);let r=this.held.get(t.agentId);r?(r.rank=o[n],r.kind=t.kind):this.held.set(t.agentId,{rank:o[n],kind:t.kind,lastWaitingAt:e,phase:`queued`,color:null,deadline:0})});for(let e of[...this.held.keys()])i.has(e)&&!u.has(e)&&this.release(e);this.slots=l,t.queueOverflow=c}planQueue(e,t){let n=this.sim.spots.ofKind(`queue`).find(e=>e.rank===t);if(!n)return!1;let r=!e.atSpot&&e.tx===n.tx&&e.ty===n.ty,i=e.mode===`wait`;if(!i&&r)return!1;let a=[];return e.atSpot&&a.push({t:`exit`}),r||a.push({t:`go`,tx:n.tx,ty:n.ty,run:i,dir:n.dir}),i&&a.push({t:`until`,cond:()=>e.mode!==`wait`||this.slots.get(e.id)!==t,minMs:0,maxMs:6e4,pose:t===0?`wait`:`read`,held:`papers`,dir:n.dir}),e.queue.push(...a),!0}update(e,t){let n=this.character;n&&(n.animT+=e*1e3,n.icon&&t>=n.iconUntil&&(n.icon=null),this.interruptIfStale(n,t),t>=this.nextWalletAt&&(this.nextWalletAt=t+tm,this.sim.social.wallets.ensure({id:Zp,name:n.info.name,kind:`main`,tasks:[]},t)),!n.step&&!n.queue.length&&this.planNext(n,t),this.sim.stepActor(n,e,t),this.drawBehindAttended(n))}presentAgents(){let e=new Set;for(let t of this.sim.chars.values())!t.gone&&!t.leaving&&e.add(t.id);return e}spotTiles(){let e=this.sim.building.grid.w,t=new Set;for(let n of this.sim.chars.values())n.gone||(t.add((n.ty-1)*e+n.tx),this.slots.has(n.id)&&t.add(n.ty*e+n.tx+1));return t}tileStillGood(e,t,n,r){let i=this.sim.building.grid,a=Math.abs(e.x-t.tx),o=Math.abs(e.y-t.ty);if(a>1||o>1||a+o===0||!i.inside(e.x,e.y)||i.get(e.x,e.y)!==1)return!1;let s=e.y*i.w+e.x;return!n.has(s)&&!r.has(s)}desiredPlan(e){let t=this.presentAgents(),n=ou(this.attention,t),r=n?this.sim.chars.get(n):void 0;if(!n||!r)return this.restingPlan();let i=this.sim.busyTiles(Zp),a=this.spotTiles(),o=this.plan?.kind===`attend`&&this.plan.agentId===n?this.plan.tile:null,s=o&&this.tileStillGood(o,r,i,a)?o:null;if(!s){let e=Xp(this.sim.building.grid,{x:r.tx,y:r.ty},i,a);s=e?{x:e.x,y:e.y}:null}if(!s)return this.restingPlan();let c=this.attention.talk,l=!!c&&c.agentId===n&&c.at>this.talkedAt&&c.at===this.seenTalkAt&&e<this.talkExpiresAt;return{kind:`attend`,agentId:n,tile:s,talkAt:l?c.at:0}}restingPlan(){let e=this.held.size>0||this.pending.length>0;return this.away!==`here`&&this.awayDone!==this.away&&!e?{kind:`away`,agentId:``,stage:this.away,tile:null,talkAt:0}:{kind:`office`,agentId:``,tile:null,talkAt:0}}samePlan(e,t){return e.kind===`fun`?t.kind===`office`:e.kind===t.kind?e.kind===`office`||e.kind===`return`?!0:e.kind===`away`?e.stage===t.stage:e.agentId===t.agentId&&e.tile?.x===t.tile?.x&&e.tile?.y===t.tile?.y&&e.talkAt===t.talkAt:!1}interruptIfStale(e,t){if(this.currentMode===`stamp`&&(e.step||e.queue.length)||this.plan?.kind===`return`&&(e.step||e.queue.length))return;if(this.returnPending&&this.plan?.kind!==`return`){this.cancelPlan(e,!e.step||e.step.t===`go`||e.step.t===`until`||e.step.t===`act`,t);return}let n=!e.step||e.step.t===`go`||e.step.t===`until`||e.step.t===`act`;if(this.pending.length&&this.currentMode!==`stamp`){this.cancelPlan(e,n,t);return}if(!(!this.plan||!this.recheck&&t<this.nextCheckAt)){if(this.recheck=!1,this.nextCheckAt=t+om,this.standingOnBusyTile(e)){this.cancelPlan(e,n,t);return}this.samePlan(this.plan,this.desiredPlan(t))||this.cancelPlan(e,n,t)}}standingOnBusyTile(e){return e.atSpot||e.inside||this.plan?.kind===`return`||e.step?.t!==`gather`&&(e.step&&e.step.t!==`until`&&e.step.t!==`act`||e.queue.length)?!1:this.sim.busyTiles(Zp).has(e.ty*this.sim.building.grid.w+e.tx)}cancelPlan(e,t,n){e.queue.length=0,t&&(e.step=null),e.gathering&&this.sim.social.leave(e,n),this.plan=null}planNext(e,t){let n=this.sim.spots.ofKind(`player_door`)[0];for(;this.pending.length;){let t=this.pending.shift(),r=this.held.get(t);if(!r||r.phase!==`stamping`||!r.color)continue;if(!n){this.release(t);continue}let i=r.color,a=[];this.leaveSeat(e,a),(e.tx!==n.tx||e.ty!==n.ty||e.atSpot)&&a.push({t:`go`,tx:n.tx,ty:n.ty,dir:n.dir}),a.push({t:`do`,fn:()=>this.startStamp(t,i)},{t:`act`,pose:`use`,ms:900,dir:n.dir}),e.queue.push(...a),this.currentMode=`stamp`,this.plan=null;return}this.currentMode===`fun`&&(this.busyAt=t);let r=this.desiredPlan(t);if(this.returnPending){if(r.kind===`attend`||!this.planReturn(e,t))this.returnPending=!1,this.waveHello(t);else{this.plan={kind:`return`,agentId:``,tile:null,talkAt:0},this.currentMode=`away`;return}}if(r.kind===`office`&&this.wantsFun(e,t)&&this.sim.social.tryJoinPlayer(e,t)){this.plan={kind:`fun`,agentId:``,tile:null,talkAt:0},this.currentMode=`fun`,this.nextCheckAt=t+om,this.recheck=!1;return}this.plan=r,this.nextCheckAt=t+om,this.recheck=!1,r.kind===`attend`?(this.currentMode=`attend`,this.planAttend(e,r)):r.kind===`away`&&this.planAway(e,r.stage??`here`)?this.currentMode=`away`:(r.kind===`away`&&(this.plan=r={kind:`office`,agentId:``,tile:null,talkAt:0}),this.currentMode=r.kind===`away`?`away`:`office`,this.planOffice(e))}wantsFun(e,t){if(t<this.nextFunAt)return!1;this.nextFunAt=t+em;let n=this.sim.spots.ofKind(`player_desk`)[0];return!n||e.atSpot!==n.id||this.away!==`here`||this.returnPending||this.held.size||this.pending.length?!1:t-this.busyAt>=$p}planOffice(e){let t=this.sim.spots.ofKind(`player_desk`)[0];if(t&&e.atSpot!==t.id){let n=[];this.leaveSeat(e,n),n.push({t:`go`,tx:t.tx,ty:t.ty},{t:`enter`,spot:t.id}),e.queue.push(...n)}else this.releaseAwaySpots()}leaveSeat(e,t){e.atSpot&&t.push({t:`exit`}),this.releaseAwaySpots(),t.push({t:`do`,fn:()=>{e.held===`coffee`&&(e.held=`none`),e.icon===`zzz`&&e.setIcon(null,0,this.sim.now)}})}releaseAwaySpots(){for(let e of this.awaySpots)this.sim.spots.release(e,Zp);this.awaySpots.length=0}freeSpot(e,t,n,r=new Set){let i=this.sim.building.grid.w,a=this.sim.busyTiles(Zp),o=null,s=1/0;for(let e of t)for(let t of this.sim.spots.ofKind(e)){if(!this.sim.spots.isFree(t.id,`player:me`)||r.has(t.id)||a.has(t.ty*i+t.tx))continue;let e=Math.abs(t.tx-n.tx)+Math.abs(t.ty-n.ty);e<s&&(s=e,o=t)}return o}holdAway(e){return this.sim.spots.reserve(e.id,`player:me`)?(this.awaySpots.push(e.id),!0):!1}planAway(e,t){let n={tx:e.tx,ty:e.ty},r=[];if(t===`coffee`){let t=this.freeSpot(e,[`coffee`],n);if(!t)return!1;this.leaveSeat(e,r),this.holdAway(t),r.push({t:`go`,tx:t.tx,ty:t.ty,fx:t.x,fy:t.y,dir:t.dir},{t:`act`,pose:`use`,ms:1900,machine:t.furnitureId,icon:`coffee`},{t:`act`,pose:`drink`,held:`coffee`,ms:2600});let i=this.freeSpot(e,[`cafe_seat`],t);i&&this.holdAway(i)?r.push({t:`do`,fn:()=>this.sim.spots.release(t.id,Zp)},{t:`go`,tx:i.tx,ty:i.ty,held:`coffee`},{t:`enter`,spot:i.id},{t:`act`,pose:`sit`,held:`coffee`,ms:cm}):r.push({t:`do`,fn:()=>{this.sim.spots.release(t.id,Zp),this.awayDone=`coffee`}})}else if(t===`nap`){let t=this.freeSpot(e,[`sofa`],n)??this.freeSpot(e,um,n);if(!t||(this.leaveSeat(e,r),!this.holdAway(t)))return!1;r.push({t:`go`,tx:t.tx,ty:t.ty},{t:`enter`,spot:t.id},{t:`act`,pose:`sit`,ms:2500},{t:`act`,pose:`sleep`,ms:cm,icon:`zzz`})}else return!1;return e.queue.push(...r),!0}planReturn(e,t){let n=this.sim,r=null;for(let t of n.elevators){let i=n.spots.get(t.spotId);if(!i)continue;let a=Math.abs(i.tx-e.tx)+Math.abs(i.ty-e.ty);(!r||a<r.d)&&(r={index:t.index,tx:i.tx,ty:i.ty,d:a})}if(!r)return!1;this.returnPending=!1;let i=r,a=[];return this.leaveSeat(e,a),a.push({t:`go`,tx:i.tx,ty:i.ty},{t:`elevIn`,elev:i.index,phase:0},{t:`do`,fn:()=>this.reappear(e,i.index)},{t:`elevOut`,elev:i.index,phase:0},{t:`do`,fn:()=>this.waveHello(this.sim.now)}),e.queue.push(...a),!0}reappear(e,t){let n=this.sim.elevators[t],r=n&&this.sim.spots.get(n.spotId);n&&r&&(e.placeAtTile(r.tx,r.ty),e.x=r.x,e.y=r.y-6,e.dir=`down`,e.alpha=0,e.inside=!0,e.hiddenUntil=n.reserveAppear(this.sim.now))}waveHello(e){for(let t of this.sim.chars.values())t.gone||t.leaving||t.mode!==`idle`||t.gathering||!t.homeSpot||t.atSpot!==t.homeSpot||t.setIcon(`wave`,lm,e)}planAttend(e,t){let n=this.sim.chars.get(t.agentId),r=t.tile;if(!n||!r)return;let i=al(n.tx-r.x,n.ty-r.y,`down`),a=[];if(this.leaveSeat(e,a),a.push({t:`go`,tx:r.x,ty:r.y,dir:i}),t.talkAt){let n=t.talkAt;a.push({t:`do`,fn:()=>this.startTalk(e,n)},{t:`act`,pose:`talk`,ms:im,dir:i},{t:`do`,fn:()=>this.endTalk(e)})}a.push({t:`until`,cond:()=>!1,minMs:0,maxMs:6e5,pose:`stand`,dir:i}),e.queue.push(...a)}startTalk(e,t){this.talkedAt=t,e.chatEmoji=sm,e.chatUntil=this.sim.now+im,this.plan&&(this.plan.talkAt=0)}endTalk(e){e.chatEmoji=``,e.chatUntil=0}drawBehindAttended(e){let t=this.currentMode===`attend`&&this.plan?.kind===`attend`?this.sim.chars.get(this.plan.agentId):void 0;t&&!e.atSpot&&Math.abs(e.tx-t.tx)<=1&&Math.abs(e.ty-t.ty)<=1?(e.sortY=t.depth()-.5,this.ownsSortY=!0):this.ownsSortY&&=(e.atSpot||(e.sortY=null),!1)}startStamp(e,t){let n=this.held.get(e);if(!n)return;let r=this.sim.now+900;this.sim.stamps.set(e,{color:t,until:r}),n.deadline=r+1e3;let i=this.sim.chars.get(e);i&&(i.reactUntil=r)}atQueueSpot(e,t){let n=this.sim.spots.ofKind(`queue`).find(e=>e.rank===t);return!!n&&!e.atSpot&&e.tx===n.tx&&e.ty===n.ty&&!e.step&&!e.queue.length}release(e){this.held.delete(e),this.sim.stamps.delete(e);let t=this.pending.indexOf(e);t>=0&&this.pending.splice(t,1);let n=this.sim.chars.get(e);n&&(n.reactUntil=0,n.thinkAt=0)}clearQueue(){for(let e of[...this.held.keys()])this.release(e);this.pending.length=0,this.slots=rm,this.sim.queueOverflow=0}};function fm(e,t,n){let r=new Map;if(!t)return r;for(let i of e){if(!i.duplicateSession)continue;let e=r.get(i.roomId);(!e||i.duplicateSession.newest&&e.agentId!==i.id)&&r.set(i.roomId,{kind:`alarm`,text:n,at:t.at,until:t.until,agentId:i.id})}return r}function pm(e,t,n,r){let i=fm(t,n,r);return i.size?e.map(e=>e.effect||!i.has(e.id)?e:{...e,effect:i.get(e.id)}):e}var mm=`core:corredor`,hm=[`ficus`,`palm`,`monstera`,`bonsai`],gm=[`fern`,`succulent`,`flower`],_m=[`#8b9bb0`,`#8597ab`,`#909fb3`];function vm(e){let t=e*16,n=new Ac(mm,`corridor`,{x:0,y:12,w:t,h:5});n.floor(`concrete`,0,0,t,5,501);for(let e=0;e<5;e++)n.furn(`glass_partition`,0,e,e===0||e===4?`end`:`v`,{order:.1}),n.furn(`glass_partition`,t-1,e,e===0||e===4?`end`:`v`,{order:.1});n.walk(1,0,t-2,5);for(let t=0;t<e;t++){let r=t*16,i=t===e-1;if(t===0)n.furn(`plant_tall`,r+2,4,`palm`,{order:.5}),n.furn(`plant_small`,r+13,4,`flower`,{order:.5});else if(t===1){let e=n.furn(`bench`,r+2,0,void 0,{order:.5});for(let t=0;t<2;t++)n.seat(`bench`,`bench`,r+2+t,0,`down`,void 0,{noFurniture:!0,furnitureId:e});n.furn(`plant_tall`,r+13,0,`monstera`,{order:.5})}else{let e=t-2;if(e%2==0)n.furn(`water_cooler`,r+3,0,void 0,{order:.5}),n.spot(`water`,r+3,1,`up`,{dy:-3}),n.furn(`plant_small`,r+4,0,gm[e%gm.length],{order:.5});else{let t=n.furn(`bench`,r+11,0,void 0,{order:.5});for(let e=0;e<2;e++)n.seat(`bench`,`bench`,r+11+e,0,`down`,void 0,{noFurniture:!0,furnitureId:t});n.furn(`plant_tall`,r+13,0,hm[e%hm.length],{order:.5})}e%2==1&&n.furn(`plant_small`,r+12,4,gm[(e+1)%gm.length],{order:.5})}!i&&t%2==1&&n.furn(`plant_tall`,r+15,4,hm[(t+1)%hm.length],{order:.5}),n.rug(r+2,1.95,12,1.1,_m[t%_m.length],502+t),n.spot(`talk`,r+5,2,`right`,{group:`talk:corredor:${t}`,dx:-1}),n.spot(`talk`,r+6,2,`left`,{group:`talk:corredor:${t}`,dx:1})}return n.build()}var ym=null;function bm(){return ym??=[Qc(),$c(),el(),tl(),nl()]}function xm(e,t){for(let n of t.walkable)e.fill(n.x,n.y,n.w,n.h,1);for(let n of t.blocked??[])e.fill(n.x,n.y,n.w,n.h,0);for(let n of t.furniture){let t=on[n.kind];if(t.mount!==`floor`)continue;let{w:r,h:i}=t.footprint;if(jc(n.kind))e.fill(n.tx,n.ty,r,i,0);else if(Mc(n.kind))for(let t=n.ty;t<n.ty+i;t++)for(let i=n.tx;i<n.tx+r;i++)e.get(i,t)===1&&e.set(i,t,2)}}function Sm(e,t,n=0){let r=new qp(e*16,29,n);for(let e of t)xm(r,e);return r}function Cm(e,t,n=0){let r=bm(),i=vm(e),a=[...r,i,...t],o=Sm(e,a,n),s=[];for(let e of a)s.push(...e.spots);return{cols:e,rect:Vc(e),core:r,corridor:i,rooms:[...t],grid:o,spots:s}}var wm=[`palm`,`ficus`,`monstera`,`bonsai`],Tm=[`fern`,`succulent`,`flower`],Em=[`code`,`coffee`,`rocket`,`cat`,`bug`,`ship_it`],Dm=[`red`,`blue`,`yellow`,`green`];function Om(e,t){let n=/^#?([0-9a-f]{6})$/i.exec(e.trim());if(!n)return e;let r=parseInt(n[1],16),i=e=>Math.max(0,Math.min(255,Math.round(e+(t>0?(255-e)*t:e*t)))),a=i(r>>16&255),o=i(r>>8&255),s=i(r&255);return`#${(a<<16|o<<8|s).toString(16).padStart(6,`0`)}`}function km(e){let t=d((e^31249)>>>0),n=t()<.5,r=t(),i=r<.45?`table`:r<.78?`round`:`lounge`,a=[`rest`,`print`,`green`],o=[`standdesk`,`stands`,`green`],s=a[Math.floor(t()*a.length)%a.length],c=o[Math.floor(t()*o.length)%o.length];return c===s&&(c=`stands`),{mirror:n,meeting:i,left:s,right:c}}function Am(e,t){let n=Rc(e.slot),r=Fc(e.slot),i=d(e.seed^24301),a=e=>e[Math.floor(i()*e.length)%e.length],o=km(e.seed),s=new Ac(e.id,`room`,n),c=s.area;c.side=r;let l=t.wall,u=r===`north`,f={lx:7,w:2},p=o.mirror,m=(e,t=1)=>p?16-e-t:e,h=e=>p&&(e===`left`||e===`right`)?e===`left`?`right`:`left`:e,g=e=>e===void 0?void 0:p?-e:e,_=(e,t,n,r,i={})=>s.furn(e,m(t,on[e].footprint.w),n,r,{...i,dx:g(i.dx)}),v=(e,t,n,r,i={})=>s.spot(e,m(t),n,h(r),{...i,dx:g(i.dx)}),y=(e,t,n,r,i,a,o={},c=!1)=>s.seat(e,t,m(n),r,h(i),c?h(i):a,{...o,dx:g(o.dx)}),b=(e,t,n,r={})=>s.wall(e,p?16-t:t,n,r),x=(e,t,n,r,i,a)=>s.rug(m(e,n),t,n,r,i,a);s.floor(`marble`,0,0,16,12,e.seed),c.floorTint=t.carpet,x(1.5,3.25,7,5.5,t.carpet,e.seed),x(6.75,u?9.5:2,2.5,1.25,Om(t.carpet2,-.1),e.seed+1),u?(s.face(.5,15,l),s.south(.5,15,11,l,[f])):(s.face(.5,15,l,[f]),s.south(.5,15,11,{...l,exterior:!0}),s.wall(`door_frame`,8,void 0,{order:.05})),s.cap(0,0,.5,12,l),s.cap(15.5,0,.5,12,l),s.walk(1,2,14,9),c.door=u?{x:n.x+7,y:n.y+11,w:2,h:1}:{x:n.x+7,y:n.y,w:2,h:2},s.walk(c.door.x-n.x,c.door.y-n.y,c.door.w,c.door.h),c.signId=b(`sign`,u?8:10.5,void 0,{order:.95}),u?(b(`whiteboard`,4.5,void 0,{order:.6}),b(`clock`,10,void 0,{order:.7}),b(`poster`,11.1,a(Em),{order:.5}),b(`window`,12.75,void 0,{order:.4}),b(`light_switch`,6.5,`on`,{ly:12,on:`south`,order:.8}),v(`switch`,6,10,`down`,{dy:-1})):(b(`whiteboard`,2.5,void 0,{order:.6}),b(`light_switch`,6.5,`on`,{order:.8}),b(`clock`,12.3,void 0,{order:.7}),b(`poster`,13.35,a(Em),{order:.5}),v(`switch`,6,2,`up`,{dy:-3})),v(`whiteboard`,u?4:2,2,`up`,{dx:8,dy:2});let S=t.deskVariant,C=t.chairVariant,w=[2,0,4];for(let e=0;e<3;e++){let t=2+e*2,n=_(`desk_back`,t,5,S,{order:.35+e*.05,seat:`N${e}`}),r=_(`desk`,t,6,S,{order:.4+e*.05,seat:`S${e}`});y(`desk`,`office_chair_front`,t,4,`down`,C,{dx:8,deskId:n,rank:w[e]+1,side:`N`,order:.55+e*.03}),y(`desk`,`office_chair`,t,7,`up`,C,{dx:8,deskId:r,rank:w[e],side:`S`,order:.6+e*.03})}_(`trash_bin`,9,6,void 0,{order:.7}),o.meeting===`table`?(_(`meeting_table`,10,5,void 0,{order:.45}),y(`stool`,`stool`,10,4,`down`,void 0,{order:.65}),y(`stool`,`stool`,12,4,`down`,void 0,{order:.66}),y(`stool`,`stool`,10,7,`up`,void 0,{order:.67}),y(`stool`,`stool`,12,7,`up`,void 0,{order:.68})):o.meeting===`round`?(_(`cafe_table`,11,4,void 0,{order:.45}),y(`stool`,`stool`,10,4,`right`,void 0,{order:.65}),y(`stool`,`stool`,12,4,`left`,void 0,{order:.66}),_(`cafe_table`,11,7,void 0,{order:.46}),y(`stool`,`stool`,10,7,`right`,void 0,{order:.67}),y(`stool`,`stool`,12,7,`left`,void 0,{order:.68}),_(`plant_small`,12,5,a(Tm),{order:.47})):(x(9.6,3.7,4.8,4.6,Om(t.carpet2,.25),e.seed+2),_(`coffee_table`,10,5,void 0,{order:.45}),y(`nook`,`armchair`,9,5,`right`,void 0,{order:.65},!0),y(`nook`,`armchair`,12,5,`left`,void 0,{order:.66},!0),y(`nook`,`beanbag`,10,7,`up`,a(Dm),{order:.67}),y(`nook`,`beanbag`,11,7,`up`,a(Dm),{order:.68}),y(`nook`,`beanbag`,11,3,`down`,a(Dm),{order:.69}));let ee=a(wm),te=u?1:4;_(`bookshelf`,te,2,void 0,{order:.25}),v(`shelf`,te,3,`up`,{dx:8,dy:-2}),_(`plant_tall`,14,2,ee,{order:.2}),u?v(`window`,12,2,`up`,{dx:12,dy:1}):_(`plant_small`,1,2,a(Tm),{order:.22});let T=Math.floor(i()*3);T===0?(_(`binder_shelf`,14,4,void 0,{order:.3}),_(`printer`,14,6,void 0,{order:.32}),_(`floor_lamp`,14,8,void 0,{order:.34})):T===1?(_(`binder_shelf`,14,4,void 0,{order:.3}),_(`binder_shelf`,14,5,void 0,{order:.31}),_(`floor_lamp`,14,8,void 0,{order:.34})):(_(`floor_lamp`,14,4,void 0,{order:.3}),_(`filing_cabinet`,14,6,void 0,{order:.32}),_(`plant_tall`,14,8,a(wm),{order:.34})),E(o.left,`left`),E(o.right,`right`);function E(n,r){let i=r===`left`?1:10,o=.2+(r===`left`?0:.05);switch(n){case`rest`:x(i+.5,8.85,4,2,Om(t.carpet,.35),e.seed+3),y(`nook`,`beanbag`,i+1,10,`up`,a(Dm),{order:o+.4}),y(`nook`,`beanbag`,i+3,10,`up`,a(Dm),{order:o+.41}),_(`plant_small`,i+2,10,a(Tm),{order:o}),_(`plant_tall`,r===`left`?i:i+4,10,a(wm),{order:o+.01});return;case`print`:_(`printer`,i,10,void 0,{order:o}),_(`binder_shelf`,i+1,10,void 0,{order:o+.01}),_(`binder_shelf`,i+2,10,void 0,{order:o+.02}),_(`filing_cabinet`,i+3,10,void 0,{order:o+.03}),_(`trash_bin`,i+4,10,void 0,{order:o+.04});return;case`green`:_(`plant_tall`,i,10,a(wm),{order:o}),_(`floor_lamp`,i+1,10,void 0,{order:o+.01}),y(`nook`,`armchair`,i+2,10,`up`,void 0,{order:o+.4},!0),_(`plant_small`,i+3,10,a(Tm),{order:o+.02}),_(`plant_tall`,i+4,10,a(wm),{order:o+.03});return;case`standdesk`:_(`cafe_table`,i+2,10,void 0,{order:o}),v(`stand`,i+2,9,`down`,{dy:-1}),_(`plant_small`,i+4,10,a(Tm),{order:o+.01}),_(`trash_bin`,i,10,void 0,{order:o+.02});return;case`stands`:_(`filing_cabinet`,i+4,10,void 0,{order:o}),_(`plant_small`,i,10,a(Tm),{order:o+.01}),v(`stand`,i+1,9,`up`,{dy:-2}),v(`stand`,i+2,9,`up`,{dy:-2});return}}v(`stand`,9,3,`left`),v(`stand`,1,7,`right`),v(`stand`,13,9,`up`,{dy:-2});let D={x:n.x*16,y:n.y*16,w:n.w*16,h:n.h*16};return c.shade=u?{x:D.x,y:D.y,w:D.w,h:D.h-16}:{x:D.x,y:D.y,w:D.w,h:D.h},s.build()}var jm=6,Mm=.35,Nm=[1,-1,0,0],Pm=[0,0,1,-1],Fm=class{g;f;from;dirIn;stamp;closed;heap;heapKey;heapSize=0;gen=0;grid;constructor(e){this.setGrid(e)}setGrid(e){let t=e.w*e.h;(!this.g||this.g.length!==t)&&(this.g=new Float32Array(t),this.f=new Float32Array(t),this.from=new Int32Array(t),this.dirIn=new Int8Array(t),this.stamp=new Uint32Array(t),this.closed=new Uint32Array(t),this.heap=new Int32Array(t*4+8),this.heapKey=new Float32Array(t*4+8),this.gen=0),this.grid=e}find(e,t,n,r,i){i.length=0;let a=this.grid;if(!a.inside(e,t)||!a.walkable(n,r))return!1;if(e===n&&t===r)return!0;let o=a.w,s=a.cells;++this.gen>=4294967295&&(this.stamp.fill(0),this.closed.fill(0),this.gen=1);let c=this.gen,l=t*o+e,u=r*o+n;for(this.heapSize=0,this.stamp[l]=c,this.g[l]=0,this.f[l]=Math.abs(e-n)+Math.abs(t-r),this.from[l]=-1,this.dirIn[l]=-1,this.push(l);this.heapSize>0;){let e=this.pop();if(e===u)return this.reconstruct(u,l,o,i),!0;if(this.closed[e]===c)continue;this.closed[e]=c;let t=e%o,d=(e-t)/o,f=this.g[e],p=this.dirIn[e];for(let i=0;i<4;i++){let l=t+Nm[i],m=d+Pm[i];if(l<0||m<0||l>=o||m>=a.h)continue;let h=m*o+l,g=s[h];if(g===0||this.closed[h]===c)continue;let _=g===2&&h!==u?jm:1;p>=0&&p!==i&&(_+=Mm);let v=f+_;if(this.stamp[h]===c&&v>=this.g[h])continue;this.stamp[h]=c,this.g[h]=v;let y=Math.abs(l-n)+Math.abs(m-r);this.f[h]=v+y*1.001,this.from[h]=e,this.dirIn[h]=i,this.push(h)}}return!1}reconstruct(e,t,n,r){let i=0;for(let n=e;n!==t&&n>=0;n=this.from[n])i++;r.length=i*2;let a=i-1;for(let i=e;i!==t&&i>=0;i=this.from[i]){let e=i%n;r[a*2]=e,r[a*2+1]=(i-e)/n,a--}}push(e){if(this.heapSize>=this.heap.length){let e=new Int32Array(this.heap.length*2);e.set(this.heap),this.heap=e;let t=new Float32Array(this.heapKey.length*2);t.set(this.heapKey),this.heapKey=t}let t=this.heap,n=this.heapKey,r=this.f[e],i=this.heapSize++;for(;i>0;){let e=i-1>>1;if(n[e]<=r)break;t[i]=t[e],n[i]=n[e],i=e}t[i]=e,n[i]=r}pop(){let e=this.heap,t=this.heapKey,n=e[0],r=--this.heapSize,i=e[r],a=t[r],o=0;for(;;){let n=o*2+1;if(n>=r)break;let i=n+1,s=i<r&&t[i]<t[n]?i:n;if(t[s]>=a)break;e[o]=e[s],t[o]=t[s],o=s}return e[o]=i,t[o]=a,n}},Im=[a(`Bora!`),a(`Partiu!`),a(`Tá pago!`),a(`É hoje!`),a(`Simbora!`),a(`Bora codar!`),a(`Deu bom!`),a(`Que isso!`),a(`Show de bola!`),a(`Tamo junto!`),a(`Sem estresse.`),a(`Vai dar certo!`)];function Lm(e){let t=(e^1540483477)>>>0;return t=Math.imul(t^t>>>15,739982445),t=Math.imul(t^t>>>12,695872825),(t^t>>>15)>>>0}var Rm=new Map;function q(e){let t=Rm.get(e);if(t)return t;let n=d(Lm(e)),r=n()<.55?2:3,i=[];for(let e=0;i.length<r&&e<40;e++){let e=ge[Math.floor(n()*ge.length)%ge.length];i.includes(e)||i.some(t=>ee(t,e))||i.push(e)}let a=.45+n()*.3;i.includes(`timidez`)&&(a-=.3),i.includes(`fofoca`)&&(a+=.2),i.includes(`piadas`)&&(a+=.12);let o=.3+n()*.4;i.includes(`games`)&&(o+=.2),i.includes(`esporte`)&&(o+=.15),i.includes(`sonecas`)&&(o-=.1);let s=Im[Math.floor(n()*Im.length)%Im.length],c={traits:i,sociability:zm(a),skill:zm(o),catchphrase:s};return Rm.size>500&&Rm.clear(),Rm.set(e,c),c}function zm(e){return Math.max(.05,Math.min(.95,e))}function J(e,t){return e.traits.includes(t)}function Bm(e,t){if(e===t)return null;let n=Math.min(e>>>0,t>>>0),r=Math.max(e>>>0,t>>>0),i=d(Lm(n^Math.imul(r,2654435761)))(),a=q(e),o=q(t),s=.12+(J(a,`competicao`)&&J(o,`competicao`)?.18:0),c=.22+([a,o].some(e=>J(e,`fofoca`)||J(e,`piadas`))?.08:0);return i<s?`rivalidade`:i<s+c?`amizade`:null}var Vm={cafeina:{coffee:3},vaidade:{mirror:5,bathroom:1.3},leitura:{shelf:3,phone:1.6,window:1.2},sonecas:{lounge:2.5},esporte:{stretch:2.5,water:1.5},calma:{window:2.5,stretch:1.5},games:{arcade:3,phone:1.4},timidez:{window:1.5,shelf:1.5,phone:1.5},fofoca:{coffee:1.4,phone:1.4},series:{phone:1.5,lounge:1.3},economia:{snack:.4,water:1.6}};function Hm(e){let t={...yd};for(let n of e.traits)for(let[e,r]of Object.entries(Vm[n]??{}))t[e]*=r;return t}var Um={futebol:0,novela:1,desenho:2},Y={tv:{label:a(`Vendo TV`),emoji:`📺`,min:2,max:5},videogame:{label:a(`Jogando videogame`),emoji:`🎮`,min:2,max:5,match:!0},arcade:{label:a(`Duelo no fliperama`),emoji:`👾`,min:2,max:2,match:!0},pingpong:{label:a(`Jogando pingue-pongue`),emoji:`🏓`,min:2,max:4,match:!0},kitchen:{label:a(`Papo na copa`),emoji:`☕`,min:2,max:4},talk:{label:a(`Conversando`),emoji:`💬`,min:2,max:2},rps:{label:a(`Jokenpô`),emoji:`✊`,min:2,max:4,match:!0},mirror:{label:a(`Se arrumando no espelho`),emoji:`💄`,min:1,max:2,solo:!0}};function Wm(e){return`g:${e.id}`}function Gm(e){return e.members.filter(e=>e.role===`player`&&!e.left)}function Km(e){return e.members.filter(e=>!e.left)}var qm={tv:10,videogame:9,arcade:5,pingpong:9,kitchen:12,talk:8,rps:8,mirror:2},Jm={series:{tv:3},games:{videogame:3,arcade:2.5},esporte:{pingpong:3,tv:1.3},competicao:{pingpong:1.8,videogame:1.8,rps:1.8,arcade:1.5},apostas:{rps:3.5},fofoca:{kitchen:2.5,talk:1.8},cafeina:{kitchen:2.2},piadas:{kitchen:1.5,talk:1.5},vaidade:{mirror:5},timidez:{talk:.6,kitchen:.7,rps:.6,pingpong:.7,videogame:.8},sonecas:{tv:1.5,pingpong:.6},economia:{rps:.4},calma:{talk:1.3,kitchen:1.2,rps:.5,pingpong:.7},leitura:{tv:.8}};function Ym(e,t){let n=qm[e];for(let r of t.traits)n*=Jm[r]?.[e]??1;return n}function Xm(e,t,n){let r=Object.keys(qm).filter(e=>n[e]),i=0;for(let e of r)i+=Ym(e,t);if(i<=0)return null;let a=e()*i;for(let e of r)if(a-=Ym(e,t),a<0)return e;return r[r.length-1]??null}function Zm(e,t,n,r){let i=Ym(e,t)/qm[e]+t.sociability;return n===`amizade`&&(i+=1.2),n===`rivalidade`&&(i+=Y[e].match?1.6:-.8),i+r()*1.2}function Qm(e,t){if(J(t,`esporte`)&&e()<.7)return`futebol`;if(J(t,`series`)&&e()<.6)return`novela`;let n=e();return n<.4?`futebol`:n<.75?`novela`:`desenho`}function $m(e,t,n,r,i,a,o){let s=Math.min(r,i,50);if(s<1)return 0;let c;if(e===`rps`)c=10,(J(t,`apostas`)||J(n,`apostas`))&&(c=20),J(t,`competicao`)&&(c+=5);else if(Y[e].match){let e=a===`rivalidade`||J(t,`apostas`)||J(n,`apostas`);if(!e&&!(J(t,`competicao`)&&o()<.35)||e&&o()<.3)return 0;c=a===`rivalidade`?15:10}else return 0;return(J(t,`economia`)||J(n,`economia`))&&(c=5),Math.max(1,Math.min(s,c))}function eh(e,t){return e===t?0:{rock:`scissors`,scissors:`paper`,paper:`rock`}[e]===t?1:2}var th=[`rock`,`paper`,`scissors`];function nh(e,t){return J(t,`competicao`)&&e()<.2?`rock`:th[Math.floor(e()*3)%3]}function rh(e,t){return Math.max(.15,Math.min(.85,.5+(e-t)*.6))}var ih={pingpong:5,videogame:2,arcade:1},ah={rock:`hand_rock`,paper:`hand_paper`,scissors:`hand_scissors`},oh={tv:[a(`Bora ver TV? 📺`),a(`Sessão pipoca? 🍿`),a(`Vai começar o programa!`),a(`Bora ver um pouco de TV?`)],futebol:[a(`Vai começar o jogo! ⚽`),a(`Bora ver o futebol?`),a(`Tá passando o clássico! ⚽`)],novela:[a(`Tá passando a novela! 📺`),a(`Bora ver o capítulo de hoje?`)],desenho:[a(`Tá passando desenho! 😄`),a(`Bora ver desenho?`)],videogame:[a(`Bora uma partida no videogame? 🎮`),a(`Duvido você me ganhar 🎮`),a(`Videogame? Melhor de três!`)],arcade:[a(`Fliperama? 👾`),a(`Aposto que bato teu recorde 👾`),a(`Bora no fliperama?`)],pingpong:[a(`Pingue-pongue? 🏓`),a(`Bora uma partidinha? 🏓`),a(`Vem jogar ping-pong!`)],pingpongRival:[a(`Vem tomar uma surra no ping-pong 😏`),a(`Revanche no ping-pong? 🏓`)],kitchen:[a(`Bora tomar um café? ☕`),a(`Pausa pro café? ☕`),a(`Bora dar uma pausa na copa?`)],kitchenGossip:[a(`Tenho uma fofoca… 👀`),a(`Copa. Agora. Tenho novidade 👀`)],talk:[a(`E aí, tudo certo?`),a(`Ei, {nome}!`),a(`Bora trocar uma ideia?`),a(`Opa, {nome}! Beleza?`)],rps:[a(`Jokenpô valendo 🪙{v}?`),a(`Aposto 🪙{v} no jokenpô!`),a(`Pedra, papel e tesoura? 🪙{v}!`)],rpsHonor:[a(`Jokenpô? Só pela honra 😅`),a(`Jokenpô valendo nada?`)],mirror:[a(`Bora dar um tapa no visual? 💄`),a(`Espelho? Preciso me arrumar ✨`)]},sh=[a(`Bora!`),a(`Partiu!`),`Fechado! 🤝`,a(`Só se for agora!`),a(`Opa!`),a(`Já é!`),a(`Demorou!`)],ch=[`Fechado! 🤝`,a(`Prepara o bolso 💰`),a(`Vai perder!`),a(`Aceito!`)],lh=[a(`Tô liso 😅 Só pela honra!`),a(`Sem 🪙… valendo nada?`)],uh=[a(`Hã? Ah… bora 😴`),a(`Acordei! Bora.`),a(`Cinco minutinhos… tá, bora.`)],dh=[a(`Enquanto o build roda… bora! ⏳`),a(`Meu comando tá rodando, dá tempo ⏳`),a(`Tô esperando o terminal mesmo…`)],fh=[a(`Aposta? Só um pouquinho 💰`),a(`Valendo pouco, hein`)],ph={futebol:{goal:[`GOOOL! ⚽`,a(`É GOL!!`),a(`GOLAÇO! ⚽`),a(`Que golaço!`)],miss:[`Uuuuh! 😱`,a(`Na trave!`),a(`Quase!`),a(`Perdeu essa?!`)],against:[a(`Ah não! Gol deles 😩`),a(`Que fase…`),a(`Acorda, zaga!`),a(`Não acredito…`)],talk:[a(`Juiz ladrão! 😤`),a(`Que jogada!`),a(`Esse goleiro é bom demais`),a(`Bora, time!`),a(`Isso foi pênalti!`),a(`Tá jogando muito!`)]},novela:{twist:[a(`Não acredito! 😱`),a(`Eu sabia!`),a(`Que reviravolta!`),a(`Mentira!!`)],love:[a(`Esse casal! 😍`),`Finalmente! 😍`,a(`Que romance…`)],talk:[a(`Shhh, vai começar!`),a(`Chora não… 😭`),a(`Esse vilão não presta`),a(`Amanhã é o último capítulo!`)]},desenho:{funny:[`KKKKK 😂`,a(`Hahaha!`),a(`Muito bom 😂`),a(`Esse desenho é demais!`)],talk:[a(`Eu assistia isso criança!`),a(`Clássico!`),a(`Olha a cara dele 😂`)]},end:[a(`Bom demais!`),a(`Amanhã tem mais 📺`),a(`Que episódio!`),a(`Valeu a pausa!`)]},mh={trash:[a(`Vou te passar! 🏎️`),a(`Que lag é esse?!`),`Combo! 💥`,a(`Não vale!`),a(`Tá fácil 😎`),a(`Só aquecendo…`),a(`Ninguém me para!`),a(`Olha essa!`)],round:[a(`Ganhei essa! 🏆`),a(`Uma a zero!`),a(`Toma!`)],cheer:[a(`Vai, {nome}!`),a(`Uooou!`),a(`Que jogada!`),a(`Aperta o botão!`)]},hh={point:[a(`Ponto! 🏓`),a(`Toma!`),a(`Na quina!`),a(`Corta!`),a(`Defende essa!`)],cheer:[a(`Boa!`),a(`Vai, {nome}!`),a(`Uooou!`),a(`Que ralo!`)],final:[`{a} a {b}! 🏆`,a(`Ganhei de {a} a {b}! 🏆`)]},gh={count:[a(`Jo…`),a(`Ken…`),a(`Pô!`)],tie:[a(`Empate! De novo!`),a(`Pensamos igual 😂`),a(`De novo!`)],win:[a(`Ganhei! 💰`),a(`Hoje é meu dia!`),a(`Passa o 🪙!`),a(`Mole demais 😎`),a(`Sabia!`)],winHonor:[a(`Ganhei! 😎`),a(`Sabia!`),a(`Hoje é meu dia!`)],lose:[a(`Não valeu!`),a(`Sorte sua…`),a(`Meu dinheiro… 😭`),a(`Tá, tá…`),a(`Era pra ser pedra!`)],rematch:[a(`Revanche!`),a(`Melhor de três!`),a(`De novo, valendo!`)],stalemate:[a(`Deixa quieto 😅`),a(`Empatamos, então.`)],watch:[`KKKKK`,a(`Uou!`),a(`Eita!`),a(`Paga!`)]},_h={solo:[`Arrasei ✨`,a(`Hoje eu tô on 😎`),a(`Cabelo no lugar ✅`),a(`Look aprovado ✨`),a(`Esse cabelo não colabora…`),a(`Pronto pra próxima reunião ✨`)],lipstick:[a(`Batom perfeito 💄`),a(`Agora sim 💋`)],duo:[a(`Empresta o pente?`),a(`Ficou ótimo!`),a(`Que tal?`),a(`Tá arrasando!`)]},vh={fofoca:[a(`Viram o commit de {nome}? 👀`),a(`Dizem que {sala} vai pro ar hoje…`),a(`{nome} tá há horas no mesmo bug 🤫`),a(`Ouvi dizer que vai ter pizza 🍕`),a(`Sabia que {nome} aposta tudo no jokenpô?`)],work:[a(`Meu build passou de primeira 😎`),a(`Esse bug em {sala} tá osso`),a(`Deploy na sexta? 😈`),a(`Quem mexeu no package-lock?!`),a(`Os testes estão verdes ✅`),a(`Tô esperando o review…`),a(`Escrevi 300 linhas e apaguei 400`),a(`Refatorei {sala} inteiro hoje`)],cafeina:[a(`Esse café tá forte!`),a(`Já é o quinto café ☕`),a(`Sem café não compila ☕`)],piadas:[a(`Funciona na minha máquina! 😂`),a(`Por que o dev foi ao médico? Muitos bugs 🐛`),a(`Existem 10 tipos de pessoas… 😏`),a(`Commit: "ajustes finais (agora vai)"`),a(`Meu código não tem bug, tem feature surpresa`)],esporte:[a(`Viu o jogo ontem? ⚽`),a(`Bora correr no fim de semana?`)],series:[a(`Viram o último episódio? 📺`),a(`Sem spoiler, por favor!`)],games:[a(`Zerei aquele jogo ontem 🎮`),a(`Bora jogar online hoje?`)],leitura:[a(`Tô lendo um livro ótimo 📚`),a(`Terminei aquele livro!`)],calma:[a(`Respira… tudo vai compilar 🧘`),a(`Um passo de cada vez.`)],apostas:[a(`Quem topa um jokenpô depois? 🎲`),a(`Tô com sorte hoje 🍀`)],economia:[a(`Tô juntando 🪙 pra férias`),a(`Café de graça é o melhor café`)],generic:[a(`E o fim de semana?`),a(`Preciso de férias 🏖️`),a(`Que dia, hein`),a(`Tá tudo corrido hoje`)],react:[`KKKKK`,a(`Sério?!`),a(`Não acredito 😮`),a(`Verdade!`),a(`Hahaha`),a(`Nem me fala…`),`👀`,a(`Pois é`),a(`Mentira!`),a(`Que isso!`)],laugh:[`KKKKK`,a(`Hahaha!`),`😂😂😂`]},yh=[a(`Opa, me chamaram! 🏃`),a(`Fui! Trabalho chegou`),a(`Volto já!`),a(`Ih, tenho que ir!`)],bh=[a(`Meu comando terminou! 🏃`),a(`Terminou o build, fui!`)],xh={fofoca:`fofoca`,cafeina:`cafeina`,piadas:`piadas`,esporte:`esporte`,series:`series`,games:`games`,leitura:`leitura`,calma:`calma`,apostas:`apostas`,economia:`economia`};function Sh(e){let t=e.getDay(),n=e.getHours();return t===5&&n>=12?a(`Sextou! 🎉`):t===1&&n<12?a(`Segunda-feira, né…`):n>=6&&n<10?a(`Bom dia! ☀️`):n>=11&&n<14?a(`Que fome… almoço? 🍽️`):n>=20||n<5?a(`Ainda aqui a essa hora? 🌙`):null}function Ch(e,t){let n=!0,r=e.replace(/\{(nome|sala|v|a|b)\}/g,(e,r)=>{let i=t[r];return i===void 0||i===``?(n=!1,``):String(i)});return n?r:null}function X(e,t,n={},r){let i=e.length,a=Math.floor(t()*i),o=null;for(let t=0;t<i;t++){let s=Ch(e[(a+t)%i],n);if(s!==null){if(s!==r)return s;o??=s}}return o??e.find(e=>!/\{\w+\}/.test(e))??`…`}var wh=`ipe.jacaranda.jatoba.peroba.cedro.aroeira.araucaria.buriti.carnauba.figueira.oliveira.carvalho.salgueiro.sequoia.baoba.acacia.magnolia.cerejeira.pinheiro.palmeira.jade.ambar.ametista.quartzo.topazio.turmalina.agata.onix.opala.safira.rubi.esmeralda.granada.jaspe.malaquita.obsidiana.turquesa.citrino.peridoto.lapislazuli.aurora.orion.lyra.cygnus.draco.andromeda.cassiopeia.perseus.phoenix.hydra.aquila.carina.vela.centaurus.crux.pavo.columba.auriga.lupus.tucana`.split(`.`),Th={ipe:()=>a(`Projeto Ipê`),jacaranda:()=>a(`Projeto Jacarandá`),jatoba:()=>a(`Projeto Jatobá`),peroba:()=>a(`Projeto Peroba`),cedro:()=>a(`Projeto Cedro`),aroeira:()=>a(`Projeto Aroeira`),araucaria:()=>a(`Projeto Araucária`),buriti:()=>a(`Projeto Buriti`),carnauba:()=>a(`Projeto Carnaúba`),figueira:()=>a(`Projeto Figueira`),oliveira:()=>a(`Projeto Oliveira`),carvalho:()=>a(`Projeto Carvalho`),salgueiro:()=>a(`Projeto Salgueiro`),sequoia:()=>a(`Projeto Sequoia`),baoba:()=>a(`Projeto Baobá`),acacia:()=>a(`Projeto Acácia`),magnolia:()=>a(`Projeto Magnólia`),cerejeira:()=>a(`Projeto Cerejeira`),pinheiro:()=>a(`Projeto Pinheiro`),palmeira:()=>a(`Projeto Palmeira`),jade:()=>a(`Projeto Jade`),ambar:()=>a(`Projeto Âmbar`),ametista:()=>a(`Projeto Ametista`),quartzo:()=>a(`Projeto Quartzo`),topazio:()=>a(`Projeto Topázio`),turmalina:()=>a(`Projeto Turmalina`),agata:()=>a(`Projeto Ágata`),onix:()=>a(`Projeto Ônix`),opala:()=>a(`Projeto Opala`),safira:()=>a(`Projeto Safira`),rubi:()=>a(`Projeto Rubi`),esmeralda:()=>a(`Projeto Esmeralda`),granada:()=>a(`Projeto Granada`),jaspe:()=>a(`Projeto Jaspe`),malaquita:()=>a(`Projeto Malaquita`),obsidiana:()=>a(`Projeto Obsidiana`),turquesa:()=>a(`Projeto Turquesa`),citrino:()=>a(`Projeto Citrino`),peridoto:()=>a(`Projeto Peridoto`),lapislazuli:()=>a(`Projeto Lápis-lazúli`),aurora:()=>a(`Projeto Aurora`),orion:()=>a(`Projeto Órion`),lyra:()=>a(`Projeto Lira`),cygnus:()=>a(`Projeto Cisne`),draco:()=>a(`Projeto Dragão`),andromeda:()=>a(`Projeto Andrômeda`),cassiopeia:()=>a(`Projeto Cassiopeia`),perseus:()=>a(`Projeto Perseu`),phoenix:()=>a(`Projeto Fênix`),hydra:()=>a(`Projeto Hidra`),aquila:()=>a(`Projeto Águia`),carina:()=>a(`Projeto Quilha`),vela:()=>a(`Projeto Vela`),centaurus:()=>a(`Projeto Centauro`),crux:()=>a(`Projeto Cruzeiro do Sul`),pavo:()=>a(`Projeto Pavão`),columba:()=>a(`Projeto Pomba`),auriga:()=>a(`Projeto Cocheiro`),lupus:()=>a(`Projeto Lobo`),tucana:()=>a(`Projeto Tucano`)};function Eh(e){return typeof e==`string`&&wh.includes(e)}function Dh(e){return Eh(e)?Th[e]():a(`Projeto`)}var Oh=`world:`;function kh(e){return Oh+e}function Ah(e){return e.startsWith(Oh)}var jh={claude:{short:`C`,name:`Claude Code`,color:`#f08a3c`},codex:{short:`X`,name:`Codex`,color:`#a77bf3`},"gentle-shell":{short:`G`,name:`Gentle Shell`,color:`#5cc97b`}},Mh=[`claude`,`codex`],Nh=[`working`,`waiting`,`idle`,`shell`];function Ph(e){return!!e&&(e.discreet===!0||e.state===`away`)}function Fh(e,t){return t===e+1?`apply`:t<=e?`stale`:`resync`}function Ih(e,t,n){let{rooms:r,agents:i}=Rh(e.floors,Ph(e.building),t);return{rev:1,serverTime:t,rooms:r,agents:i,accounts:Vh(i),meta:{demo:!1,sources:[],startedAt:t,version:String(n.version),terminal:!1,messages:!1,world:{enabled:!0,configured:!0,state:`approved`}}}}function Lh(e,t,n,r){let i=Ph(t.building??r),a,o;if(t.floors){let r=Rh(t.floors,i,n),s=new Map(e.rooms.map(e=>[e.id,e])),c=e.rooms.reduce((e,t)=>Math.max(e,t.slot+1),0);a=r.rooms.map(e=>{let t=s.get(e.id);return t?{...e,slot:t.slot,createdAt:t.createdAt}:{...e,slot:c++}});let l=new Map(e.agents.map(e=>[e.id,e]));o=r.agents.map(e=>{let t=l.get(e.id);if(!t)return e;let r=t.status===e.status;return{...e,startedAt:t.startedAt,statusSince:r?t.statusSince:n,lastEventAt:r?t.lastEventAt:n}})}else if(i&&e.agents.length)a=e.rooms,o=[];else return{snapshot:e,rev:t.rev};let s=Vh(o);return Uh([a,o,s],[e.rooms,e.agents,e.accounts])?{snapshot:e,rev:t.rev}:{snapshot:{...e,rev:e.rev+1,serverTime:n,rooms:a,agents:o,accounts:s},rev:t.rev}}function Rh(e,t,n){let r=[],i=[],a=new Set,o=new Set;for(let s of Array.isArray(e)?e:[]){if(r.length>=ae.floors)break;if(!s||!Hh(s.id)||a.has(s.id)||(a.add(s.id),r.push({id:s.id,name:Dh(typeof s.label==`string`?s.label:``),path:``,slot:r.length,seed:c(s.id),createdAt:n}),t||!Array.isArray(s.agents)))continue;let e=0;for(let t of s.agents){if(e>=ae.agentsPerFloor||i.length>=ae.agentsTotal)break;t&&Hh(t.id)&&!o.has(t.id)&&(o.add(t.id),i.push({roomId:s.id,agent:t}),e++)}}return{rooms:r,agents:i.map(({roomId:e,agent:t})=>zh(t,e,n,o))}}function zh(e,t,n,r){let i=kh(e.id),o=e.kind===`sub`?`sub`:`main`,s=Mh.includes(e.provider)?e.provider:`claude`,l=Nh.includes(e.status)?e.status:`idle`,u={id:i,kind:o,provider:s,roomId:t,name:De(e.name)??a(`Agente`),look:e.look===`f`?`f`:`m`,role:a(o===`sub`?`Subagente`:`Agente principal`),sessionId:i,account:kh(s),status:l,recent:[],tasks:[],startedAt:n,lastEventAt:n,statusSince:n,stats:{toolCalls:0,tokensIn:0,tokensOut:0,subagents:0},seed:c(e.id)};o===`sub`&&Hh(e.parentId)&&e.parentId!==e.id&&r.has(e.parentId)&&(u.parentId=kh(e.parentId));let d=Bh(e.parts);return d&&(u.parts=d),u}function Bh(e){if(!e||typeof e!=`object`||Array.isArray(e))return;let t=e,n={};for(let e of ce){if(!Object.prototype.hasOwnProperty.call(t,e))continue;let r=ke({[e]:t[e]});r&&Object.assign(n,r)}return Object.keys(n).length?n:void 0}function Vh(e){return Mh.map(t=>({id:kh(t),provider:t,short:jh[t].short,name:jh[t].name,color:jh[t].color,configDir:``,sessions:e.filter(e=>e.kind===`main`&&e.provider===t).length,usageStatus:`disabled`}))}function Hh(e){return typeof e==`string`&&e.length>0&&e.length<=64}function Uh(e,t){return JSON.stringify(e)===JSON.stringify(t)}var Wh={main:100,sub:30},Gh=`habblaud.wallets.v1`,Kh=`habblaud:world-wallet`,qh=12,Jh=300,Yh=400,Xh=[`office`,`world`],Zh={office:Gh,world:Kh},Qh=e=>Ah(e)?`world`:`office`;function $h(e){if(e)try{e.removeItem?e.removeItem(Kh):e.setItem(Kh,``)}catch{}}function eg(){try{let e=globalThis.localStorage;return e?(e.getItem(Gh),e):null}catch{return null}}function tg(e){return`${e.id}|${e.title}`}var ng=class{storage;map=new Map;dirty={office:!1,world:!1};constructor(e){this.storage=e,this.load()}get(e){return this.map.get(e)}coins(e){return this.map.get(e)?.coins??0}ensure(e,t){let n=this.map.get(e.id);if(n)return n.name!==e.name&&(n.name=e.name),t-n.seenAt>6e4&&(n.seenAt=t,this.touch(e.id)),{entry:n,created:!1};let r=Wh[e.kind]??Wh.main;n={name:e.name,coins:r,earned:r,wins:0,losses:0,vs:{},paid:[],ledger:[],createdAt:t,seenAt:t},this.map.set(e.id,n),this.log(n,{at:t,delta:r,icon:`🏢`,text:a(`Chegou ao escritório`)});let i=e.tasks.filter(e=>e.status===`completed`);if(i.length){for(let e of i)n.paid.push(tg(e));let e=i.length*10;n.coins+=e,n.earned+=e,this.log(n,{at:t,delta:e,icon:`✅`,text:i.length===1?a(`1 tarefa já concluída`):a(`{0} tarefas já concluídas`,[i.length])})}return this.touch(e.id),{entry:n,created:!0}}payTasks(e,t){let n=this.map.get(e.id);if(!n)return 0;let r=0;for(let i of e.tasks){if(i.status!==`completed`)continue;let e=tg(i);n.paid.includes(e)||(n.paid.push(e),n.paid.length>Jh&&n.paid.splice(0,n.paid.length-Jh),n.coins+=10,n.earned+=10,r+=10,this.log(n,{at:t,delta:10,icon:`✅`,text:a(`Tarefa concluída: {0}`,[i.title])}))}return r&&this.touch(e.id),r}credit(e,t,n,r,i,a=!0){let o=this.map.get(e);return!o||t<=0?0:(o.coins+=t,a&&(o.earned+=t),this.log(o,{at:i,delta:t,icon:n,text:r}),this.touch(e),t)}debit(e,t,n,r,i){let a=this.map.get(e),o=a?Math.max(0,Math.min(Math.floor(t),a.coins)):0;return!a||!o?0:(a.coins-=o,this.log(a,{at:i,delta:-o,icon:n,text:r}),this.touch(e),o)}transfer(e,t,n,r,i,o){let s=this.map.get(e),c=this.map.get(t);if(!s||!c||e===t)return 0;let l=Math.max(0,Math.min(Math.floor(n),s.coins));return l?(s.coins-=l,c.coins+=l,this.log(s,{at:o,delta:-l,icon:r,text:a(`Perdeu {0} para {1}`,[i,c.name])}),this.log(c,{at:o,delta:l,icon:r,text:a(`Ganhou {0} de {1}`,[i,s.name])}),this.touch(e),this.touch(t),l):0}recordMatch(e,t){let n=this.map.get(e),r=this.map.get(t);n&&r&&(n.wins++,r.losses++,(n.vs[t]??=[0,0])[0]++,(r.vs[e]??=[0,0])[1]++,this.touch(e),this.touch(t))}save(e){for(let t of Xh){if(!this.dirty[t]||(this.dirty[t]=!1,this.prune(e,t),!this.storage))continue;let n=Object.fromEntries([...this.map].filter(([e])=>Qh(e)===t));try{this.storage.setItem(Zh[t],JSON.stringify({v:1,wallets:n}))}catch{}}}prune(e,t){for(let n of t?[t]:Xh){let t=[...this.map].filter(([e])=>Qh(e)===n);for(let[n,r]of t)e-r.seenAt>2592e5&&this.map.delete(n);let r=t.filter(([e])=>this.map.has(e));if(r.length<=Yh)continue;let i=r.sort((e,t)=>e[1].seenAt-t[1].seenAt);for(let[e]of i.slice(0,r.length-Yh))this.map.delete(e)}}touch(e){this.dirty[Qh(e)]=!0}log(e,t){e.ledger.unshift(t),e.ledger.length>qh&&(e.ledger.length=qh)}load(){for(let e of Xh)this.loadPart(e)}loadPart(e){if(this.storage)try{let t=this.storage.getItem(Zh[e]);if(!t)return;let n=JSON.parse(t);for(let[t,r]of Object.entries(n.wallets??{}))Qh(t)===e&&r&&typeof r.coins==`number`&&Number.isFinite(r.coins)&&this.map.set(t,{name:typeof r.name==`string`?r.name:t,coins:Math.max(0,Math.floor(r.coins)),earned:typeof r.earned==`number`?r.earned:r.coins,wins:typeof r.wins==`number`?r.wins:0,losses:typeof r.losses==`number`?r.losses:0,vs:r.vs&&typeof r.vs==`object`?r.vs:{},paid:Array.isArray(r.paid)?r.paid.filter(e=>typeof e==`string`):[],ledger:Array.isArray(r.ledger)?r.ledger.slice(0,qh):[],createdAt:typeof r.createdAt==`number`?r.createdAt:0,seenAt:typeof r.seenAt==`number`?r.seenAt:0})}catch{}}},rg=35e3,ig=2600,ag=1900,og=24,sg=40,cg=`#ffd34d`,lg=`#ff8a8a`,ug=Object.keys(Y),dg={[Kc]:a(`Lounge`),[Gc]:a(`Copa`),[Uc]:a(`Recepção`),[Wc]:a(`Banheiros`)},fg={rps:a(`no jokenpô`),pingpong:a(`no pingue-pongue`),videogame:a(`no videogame`),arcade:a(`no fliperama`)};function pg(e){return e.filter(e=>e.id!==Zp)}function mg(e,t,n){return t+e()*(n-t)}var hg=class{sim;gatherings=new Set;wallets;floaters=[];meRngs=new WeakMap;events=[];seq=1;eventSeq=0;nextSaveAt=0;constructor(e,t){this.sim=e,this.wallets=new ng(t)}canJoin(e,t){return!(e.gone||e.leaving||e.arriving||e.inside||e.gathering||e.mode!==`idle`&&e.mode!==`shell`||e.step||e.queue.length||!e.homeSpot||e.atSpot!==e.homeSpot||t<e.reactUntil||e.mode===`shell`&&(!e.shellSince||t-e.shellSince<4e4))}candidates(e,t){let n=[];for(let r of this.sim.chars.values())r!==e&&this.canJoin(r,t)&&n.push(r);return n}hasCompany(e,t){for(let n of this.sim.chars.values())if(n!==e&&this.canJoin(n,t))return!0;return[...this.gatherings].some(t=>this.openSpotFor(t,e)!==void 0)}tryInitiate(e,t,n){if(!this.canJoin(e,t))return!1;let r=q(e.info.seed),i=this.joinable(e,r);if(i&&e.rng()<.4)return this.join(i,e,t);let a=this.candidates(e,t),o={};for(let t of ug){let r=t===`mirror`?+!!n:Y[t].min-1;if(!(a.length<r)){if(t===`mirror`&&!n){o[t]=!!this.plan(t,1,e);continue}Y[t].solo&&r===0||(o[t]=!!this.plan(t,r+1,e))}}let s=Xm(e.rng,r,o);return s&&this.start(s,e,a,t,n)?!0:i?this.join(i,e,t):!1}startSolo(e,t,n){return this.canJoin(t,n)?this.start(e,t,[],n,!1,0):!1}force(e,t,n){let r=n?.length?n.map(e=>this.sim.chars.get(e)).filter(e=>!!e):[...this.sim.chars.values()];for(let e of r)e.gathering&&this.sim.clearPlan(e),(e.mode===`idle`||e.mode===`shell`)&&!e.leaving&&(e.step||e.queue.length)&&this.sim.clearPlan(e);let i=r.filter(e=>!e.leaving&&!e.gone&&(e.mode===`idle`||e.mode===`shell`)&&e.homeSpot&&e.atSpot===e.homeSpot&&!e.step&&!e.queue.length);if(!i.length)return null;let[a,...o]=i,s=e===`mirror`?Math.min(1,o.length):Math.min(o.length,Y[e].max-1);if(!this.start(e,a,o,t,!1,Math.max(Y[e].min-1,Math.min(s,e===`tv`||e===`kitchen`?3:1)),!0))return null;let c=a.gathering;return c?c.members.map(e=>this.sim.chars.get(e.id)?.info.name??e.id):null}start(e,t,n,r,i,a,o=!1){let s=Y[e],c=t.rng,l=q(t.info.seed),u;u=a===void 0?e===`tv`?1+Math.floor(c()*3):e===`kitchen`?1+Math.floor(c()*2.4):e===`mirror`?i||n.some(e=>J(q(e.info.seed),`vaidade`))&&c()<.5?1:0:s.min-1:a,a===void 0&&(e===`pingpong`||e===`videogame`||e===`rps`)&&c()<.3&&u++,u=Math.max(0,Math.min(u,n.length,s.max-1));let f=n.map(n=>{let i=q(n.info.seed),a=Zm(e,i,Bm(t.info.seed,n.info.seed),c);return this.sim.longIdle(n,r)&&(a-=1.5),e===`mirror`&&!J(i,`vaidade`)&&(a-=2),{c:n,s:a}}).sort((e,t)=>t.s-e.s).slice(0,u).map(e=>e.c);if(o||(f=f.filter((e,t)=>t<s.min-1||!this.sim.longIdle(e,r)||c()<.35)),f.length+1<(e===`mirror`?i?2:1:s.min))return!1;let p=this.plan(e,f.length+1,t);if(!p)return!1;let m=this.seq++,h={id:m,kind:e,host:t.id,members:[],phase:`gather`,createdAt:r,startAt:0,until:0,nextAt:0,step:0,seed:(t.info.seed^Math.imul(m,2654435761))>>>0,rng:d((t.info.seed^Math.imul(m,2246822507))>>>0),program:e===`tv`?Qm(c,l):null,bet:0,score:[0,0],gestures:null,ties:0,rematches:0,winner:null,loser:null,pool:[],lastLine:null,lastSpeaker:null,pending:[]},g=Wm(h);for(let e of p.pool)this.sim.spots.reserve(e.id,g)&&h.pool.push(e.id);let _=[t,...f],v=s.match?2:_.length;if(_.forEach((t,n)=>{let r=s.match?n<v?`player`:`watcher`:e===`kitchen`||e===`talk`?`talker`:`player`,i=p.seats[n]??null,a=this.member(t,r,i);!i&&r===`watcher`&&(a.tile=this.standNear(h,t)??void 0),h.members.push(a)}),s.match){let[t,n]=_;h.bet=$m(e,l,q(n.info.seed),this.wallets.coins(t.id),this.wallets.coins(n.id),Bm(t.info.seed,n.info.seed),h.rng)}this.gatherings.add(h);for(let e of h.members)this.dispatch(h,e,this.sim.person(e.id),r);return this.invite(h,t,f,r),!0}member(e,t,n){return{id:e.id,role:t,spot:n?.id??null,arrived:!1,left:!1,pose:`stand`,held:`none`,actPose:null,actHeld:`none`,actUntil:0,carry:`none`}}invite(e,t,n,r){let i=e.rng,a=q(t.info.seed),o=n[0],s={nome:o?.info.name,v:e.bet},c=sh,l=null;switch(e.kind){case`tv`:l=X(i()<.5?oh.tv:oh[e.program??`futebol`],i,s);break;case`pingpong`:l=X(o&&Bm(t.info.seed,o.info.seed)===`rivalidade`?oh.pingpongRival:oh.pingpong,i,s);break;case`kitchen`:l=X(J(a,`fofoca`)?oh.kitchenGossip:oh.kitchen,i,s);break;case`rps`:l=X(e.bet?oh.rps:oh.rpsHonor,i,s),c=e.bet?o&&J(q(o.info.seed),`economia`)?fh:ch:lh;break;case`mirror`:l=n.length?X(oh.mirror,i,s):null;break;default:l=X(oh[e.kind],i,s)}l&&this.say(t,l,r),n.forEach((t,n)=>{let a=this.sim.longIdle(t,r)?uh:t.mode===`shell`&&e.kind!==`rps`?dh:c;e.pending.push({id:t.id,at:r+900+n*650,text:X(a,i)})})}dispatch(e,t,n,r){let i=this.sim;n.gathering=e,n.nextSocialAt=0,n.icon===`zzz`&&n.setIcon(null,0,r);let a=[];n.atSpot&&a.push({t:`exit`});let o=`none`;if(e.kind===`kitchen`&&n.id!==`player:me`){let e=J(q(n.info.seed),`cafeina`)||n.rng()<.65?`coffee`:`water`,r=i.spots.findFree(e,{by:n.id,rng:n.rng})??i.spots.findFree(e===`coffee`?`water`:`coffee`,{by:n.id,rng:n.rng});if(r&&n.rng()<.8&&i.reserveTemp(n,r)){let e=r.kind===`coffee`;a.push({t:`go`,tx:r.tx,ty:r.ty,fx:r.x,fy:r.y,dir:r.dir},{t:`act`,pose:`use`,ms:e?1500:900,machine:e?r.furnitureId:void 0,icon:e?`coffee`:void 0},{t:`do`,fn:()=>i.spots.release(r.id,n.id)}),o=t.carry=e?`coffee`:`water`}}let s=t.spot?i.spots.get(t.spot):void 0;s?.seated?a.push({t:`go`,tx:s.tx,ty:s.ty,held:o},{t:`enter`,spot:s.id}):s?a.push({t:`go`,tx:s.tx,ty:s.ty,fx:s.x,fy:s.y,dir:s.dir,held:o}):t.tile&&a.push({t:`go`,tx:t.tile.x,ty:t.tile.y,dir:t.tile.dir,held:o}),a.push({t:`gather`,g:e},{t:`exit`},{t:`do`,fn:()=>n.gathering===e&&(n.gathering=null)}),n.queue.push(...a),n.id!==`player:me`&&i.pushHome(n,t.carry)}joinable(e,t,n=!1){let r=null,i=0;for(let a of this.gatherings){if(a.phase!==`run`&&(n||a.phase!==`gather`)||a.kind===`talk`||a.kind===`arcade`||a.kind===`mirror`||Km(a).length>=Y[a.kind].max||this.openSpotFor(a,e)===void 0)continue;let o=Y[a.kind].match?.8:1;o*=a.kind===`tv`?J(t,`series`)?3:1.4:a.kind===`kitchen`?J(t,`fofoca`)||J(t,`cafeina`)?2.5:1:J(t,`competicao`)||J(t,`esporte`)||J(t,`games`)?2:1,o+=this.friendBonus(a,e),o*=.6+e.rng()*.8,o>i&&(i=o,r=a)}return r}friendBonus(e,t){let n=0;for(let r of Km(e)){if(r.id===`player:me`&&t.id!==`player:me`)continue;let e=this.sim.person(r.id);e&&Bm(t.info.seed,e.info.seed)===`amizade`&&(n+=.8)}return n}openSpotFor(e,t){if(e.phase===`final`||e.phase===`ended`||e.kind===`talk`||e.kind===`arcade`||e.kind===`mirror`||Km(e).length>=Y[e.kind].max)return;let n=new Set(Km(e).map(e=>e.spot)),r=this.sim.player?.ch;r?.atSpot&&r!==t&&n.add(r.atSpot);for(let t of e.pool)if(!n.has(t))return this.sim.spots.get(t)??void 0;if(e.kind===`rps`)return this.standNear(e,t)?null:void 0}join(e,t,n){let r=this.openSpotFor(e,t);if(r===void 0)return!1;let i=e.kind===`kitchen`?`talker`:Y[e.kind].match?`watcher`:`player`,o=this.member(t,i,r);if(o.late=!0,!r){let n=this.standNear(e,t);if(!n)return!1;o.tile=n}e.phase===`run`&&this.basePose(e,o,n),e.members.push(o),t.id===`player:me`&&this.placeSideBet(e),this.dispatch(e,o,t,n);let s=e.kind===`tv`?a(`Posso ver junto? 📺`):e.kind===`kitchen`?a(`Tem lugar pra mais um? ☕`):a(`Quem tá ganhando?`);return this.say(t,s,n),!0}tryJoinPlayer(e,t){if(e.id!==`player:me`||e.gathering||e.gone||e.leaving||e.inside||e.step||e.queue.length)return!1;let n=this.joinable(e,q(e.info.seed),!0);return!!n&&this.join(n,e,t)}placeSideBet(e){if(!Y[e.kind].match||e.bet<=0||e.phase!==`run`)return;let t=Gm(e).filter(e=>!e.left),n=Math.min(e.bet,this.wallets.coins(Zp));t.length<2||n<=0||(e.sideBet={stake:n,backedId:t[Math.floor(this.meRng(e)()*t.length)%t.length].id})}settleSideBet(e,t,n){let r=e.sideBet;e.sideBet=null;let i=this.sim.person(Zp);if(!r||!i||!Km(e).some(e=>e.id===`player:me`))return;let o=Y[e.kind].emoji;if(r.backedId===t.id){let e=this.wallets.credit(Zp,r.stake,o,a(`Ganhou {0} da casa`,[a(`a aposta paralela`)]),n,!1);e&&this.float(i,`+🪙${e}`,cg,n)}else{let e=this.wallets.debit(Zp,r.stake,o,a(`Perdeu {0} para a casa`,[a(`a aposta paralela`)]),n);e&&this.float(i,`−🪙${e}`,lg,n)}}standNear(e,t){let n=e.members.filter(e=>e.role===`player`&&!e.left).map(e=>e.spot?this.sim.spots.get(e.spot):void 0).filter(e=>!!e);if(!n.length)return null;let r=n.reduce((e,t)=>e+t.tx,0)/n.length,i=n.reduce((e,t)=>e+t.ty,0)/n.length,a=this.sim.building.grid,o=this.sim.busyTiles(t.id),s=new Set(e.members.filter(e=>e.tile&&!e.left).map(e=>e.tile.y*a.w+e.tile.x)),c=null,l=1/0,u=e=>e===-1?0:e===-2?1.2:e===1?2.5:e===0?2:4;for(let e=-2;e<=2;e++)for(let t=-2;t<=3;t++){let d=Math.round(r)+t,f=Math.round(i)+e,p=f*a.w+d;if(a.get(d,f)!==1||o.has(p)||s.has(p)||n.some(e=>e.tx===d&&e.ty===f))continue;let m=n.some(e=>e.tx===d&&e.ty===f+1),h=Math.abs(d+.5-r)+u(e)+(m?3:0);h>=l||(l=h,c={x:d,y:f})}return c?{...c,dir:ol(c.x*16,c.y*16,r*16,i*16)}:null}plan(e,t,n){let r=this.sim.spots,i=this.sim.player?.ch,a=e=>r.isFree(e.id,n.id)&&!this.inPool(e.id)&&i?.atSpot!==e.id;switch(e){case`tv`:case`videogame`:{if(this.tvBusy())return null;let n=[...r.ofKind(`sofa`),...r.ofKind(`armchair`)].filter(e=>e.areaId===`core:lounge`&&a(e)),i=n.filter(e=>e.kind===`sofa`).sort((e,t)=>e.tx-t.tx),o=n.filter(e=>e.kind!==`sofa`);if(e===`videogame`){for(let e=0;e+1<i.length;e++){if(i[e+1].tx!==i[e].tx+1)continue;let n=[i[e],i[e+1]],r=[...i.filter(e=>!n.includes(e)),...o];return t>2+r.length?null:{seats:[...n,...r.slice(0,t-2)],pool:[...n,...r]}}return null}let s=[...i,...o];return s.length<t?null:{seats:s.slice(0,t),pool:s}}case`arcade`:{let e=r.ofKind(`arcade`).filter(a);return e.length>=2&&t<=2?{seats:e.slice(0,2),pool:e.slice(0,2)}:null}case`pingpong`:{let e=r.findFreeGroup(`pingpong`,{filter:e=>e.every(a)});if(!e)return null;let n=r.ofKind(`watch`).filter(a);return t>2+n.length?null:{seats:[...e,...n].slice(0,t),pool:[...e,...n]}}case`talk`:case`rps`:{let e=r.findFreeGroup(`talk`,{rng:n.rng,filter:e=>e.every(a)});return e?{seats:[...e],pool:[...e]}:null}case`kitchen`:return this.kitchenSeats(t,a,n.rng);case`mirror`:{let e=r.ofKind(`sink`).filter(e=>e.areaId===`core:banheiros`&&a(e)).sort((e,t)=>e.tx-t.tx);if(t===1)return e.length?{seats:[e[Math.floor(n.rng()*e.length)]],pool:[]}:null;for(let t=0;t+1<e.length;t++)if(e[t+1].tx===e[t].tx+1)return{seats:[e[t],e[t+1]],pool:[]};return null}}}kitchenSeats(e,t,n){let r=this.sim.spots.ofKind(`cafe_seat`).filter(e=>e.areaId===Gc),i=(e,t,n)=>r.find(r=>r.tx===e&&r.ty===t&&r.dir===n),a=[];for(let e of r)if(e.dir===`down`){let t=i(e.tx,e.ty+3,`up`);t&&a.push([e,t])}else if(e.dir===`right`){let t=i(e.tx+2,e.ty,`left`);t&&a.push([e,t])}let o=a.filter(e=>e.every(t));if(!o.length)return null;if(e<=2){let e=o[Math.floor(n()*o.length)];return{seats:e,pool:e}}let s=[];for(let e of o){if(e[0].dir!==`down`)continue;let t=o.find(t=>t[0].dir===`down`&&t[0].tx===e[0].tx+1);t&&s.push([e[0],t[0],e[1],t[1]])}if(!s.length)return null;let c=s[Math.floor(n()*s.length)],l=[c[0],c[2],c[1],c[3]];return{seats:l.slice(0,e),pool:l}}inPool(e){let t=this.sim.spots.ownerOf(e);return!!t&&t.startsWith(`g:`)}tvBusy(){for(let e of this.gatherings)if((e.kind===`tv`||e.kind===`videogame`)&&e.phase!==`ended`)return!0;return!1}tvScreen(){for(let e of this.gatherings)if(e.phase===`run`||e.phase===`final`){if(e.kind===`tv`)return{mode:`show`,seed:Um[e.program??`futebol`]};if(e.kind===`videogame`)return{mode:`game`,seed:e.seed}}return null}arcadeSeed(){for(let e of this.gatherings)if(e.kind===`arcade`&&(e.phase===`run`||e.phase===`final`))return e.seed;return null}stepGather(e,t,n){let r=t.members.find(t=>t.id===e.id);if(!r||r.left||t.phase===`ended`)return!0;r.arrived||=!0;let i=r.spot?this.sim.spots.get(r.spot):void 0;r.actPose&&n<r.actUntil?e.setPose(r.actPose,r.actHeld):t.phase===`gather`?e.setPose(e.seated?`sit`:`stand`,r.carry===`none`?`none`:r.carry):e.setPose(r.pose,r.held);let a=r.tile?.dir??i?.dir;return a&&(e.dir=a),!1}leave(e,t){let n=e.gathering;if(e.gathering=null,!n||n.phase===`ended`)return;let r=n.members.find(t=>t.id===e.id);if(!r||r.left)return;r.left=!0,n.pending=n.pending.filter(t=>t.id!==e.id);let i=Km(n);if(!i.length)return this.end(n,t);if(n.phase===`gather`){let e=Y[n.kind].match?2:n.kind===`mirror`?1:Y[n.kind].min;(Y[n.kind].match?Gm(n).length:i.length)<e&&this.end(n,t);return}if(n.phase===`run`){if(Y[n.kind].match&&r.role===`player`){let e=Gm(n)[0],r=e?this.sim.person(e.id):void 0;r&&(this.say(r,a(`Ganhei por W.O.! 😎`),t),this.act(e,`cheer`,`none`,1600,t)),n.phase=`final`,n.until=t+1800;return}(i.length<Math.max(1,Y[n.kind].min)||n.kind!==`tv`&&i.length<2&&n.kind!==`mirror`)&&(n.until=Math.min(n.until||t+4e3,t+4e3),n.kind!==`tv`&&(n.phase=`final`,n.until=t+1200))}}calledAway(e,t,n){e.gathering&&this.say(e,X(t===`shell`?bh:yh,e.rng),n)}end(e,t){if(e.phase===`ended`)return;e.phase=`ended`;let n=Wm(e);for(let t of e.pool)this.sim.spots.release(t,n);e.pool.length=0;for(let t of e.members){if(t.left||t.arrived)continue;let n=this.sim.person(t.id);n&&n.gathering===e&&this.sim.clearPlan(n)}}reset(e){for(let t of this.gatherings)this.end(t,e);this.gatherings.clear();for(let e of this.sim.chars.values())e.gathering=null;let t=this.sim.player?.ch;t&&(t.gathering=null),this.floaters.length=0}update(e){for(let t of this.gatherings)if(t.phase!==`ended`){if(t.pending.length&&this.flushPending(t,e),t.phase===`gather`){this.checkStart(t,e);continue}if(t.phase===`final`){e>=t.until&&this.end(t,e);continue}e>=t.nextAt&&this.beat(t,e)}if(this.floaters.length){let t=0;for(let n of this.floaters)e<n.until&&(this.floaters[t++]=n);this.floaters.length=t}}housekeeping(e){for(let e of this.gatherings)e.phase===`ended`&&this.gatherings.delete(e);e>=this.nextSaveAt&&(this.nextSaveAt=e+5e3,this.wallets.save(e))}flushPending(e,t){let n=0;for(let r of e.pending){if(t<r.at){e.pending[n++]=r;continue}let i=this.sim.person(r.id);i&&this.say(i,r.text,t)}e.pending.length=n}checkStart(e,t){let n=e.members.filter(e=>!e.left&&e.role!==`watcher`&&!e.late),r=n.filter(e=>e.arrived),i=e.kind===`mirror`?1:Y[e.kind].min;if(r.length===n.length&&r.length>=i)return this.begin(e,t);if(!(t-e.createdAt<rg)){if(!Y[e.kind].match&&r.length>=i){for(let t of n)t.arrived||this.dropMember(e,t);return this.begin(e,t)}this.end(e,t)}}dropMember(e,t){t.left=!0;let n=this.sim.person(t.id);n&&n.gathering===e&&this.sim.clearPlan(n)}begin(e,t){e.phase=`run`,e.startAt=t,e.nextAt=t+900;let n=e.rng;for(let n of Km(e))this.basePose(e,n,t);switch(e.kind){case`tv`:e.until=t+mg(n,3e4,65e3),e.nextAt=t+1500;break;case`kitchen`:e.until=t+mg(n,24e3,45e3),e.nextAt=t+500;break;case`talk`:e.until=t+mg(n,1e4,18e3),e.nextAt=t+400;break;case`mirror`:e.until=t+mg(n,6e3,11e3),e.nextAt=t+mg(n,2e3,3500);break;case`videogame`:case`arcade`:e.until=t+mg(n,7e3,1e4),e.nextAt=t+1200;break;case`pingpong`:e.nextAt=t+mg(n,1800,3e3);break;case`rps`:e.nextAt=t+600}}basePose(e,t,n){let r=t.id===`player:me`?this.meRng(e):e.rng,i=this.sim.person(t.id),a=i?q(i.info.seed):null;switch(e.kind){case`tv`:a&&(J(a,`series`)||J(a,`sonecas`)||r()<.3)?[t.pose,t.held]=[`wait`,`popcorn`]:[t.pose,t.held]=[`sit`,`none`];break;case`videogame`:[t.pose,t.held]=t.role===`player`?[`game`,`controller`]:[`sit`,`none`];break;case`arcade`:[t.pose,t.held]=[`use`,`none`];break;case`pingpong`:[t.pose,t.held]=t.role===`player`?[`play`,`paddle`]:[`stand`,`none`];break;case`kitchen`:[t.pose,t.held]=[`sit`,t.carry===`none`?`none`:t.carry];break;case`mirror`:[t.pose,t.held]=[`groom`,r()<.5?`lipstick`:`comb`];break;default:[t.pose,t.held]=[`stand`,`none`]}}beat(e,t){switch(e.kind){case`tv`:return this.beatTv(e,t);case`videogame`:case`arcade`:return this.beatGame(e,t);case`pingpong`:return this.beatPingPong(e,t);case`kitchen`:case`talk`:return this.beatChat(e,t);case`rps`:return this.beatRps(e,t);case`mirror`:return this.beatMirror(e,t)}}beatTv(e,t){let n=e.rng,r=Km(e);if(t>=e.until){let i=this.charOf(this.randomOf(pg(r),n));i&&this.say(i,X(ph.end,n),t),e.phase=`final`,e.until=t+1400;return}e.nextAt=t+mg(n,3500,6500);for(let n of r){let r=this.charOf(n);r&&n.pose!==`sleep`&&J(q(r.info.seed),`sonecas`)&&t-e.startAt>(e.until-e.startAt)*.5&&([n.pose,n.held]=[`sleep`,`none`],r.setIcon(`zzz`,Math.max(1e3,e.until-t),t))}let i=r.filter(e=>e.pose!==`sleep`),a=pg(i);if(!a.length)return;let o=this.charOf(this.randomOf(a,n)),s=n();switch(e.program){case`futebol`:{let r=this.sim.footballLance(t),a=r?r.progress>=r.goalAt&&e.step!==r.lance:s<.25;if(r){let n=(r.goalAt-r.progress+ +(r.progress>=r.goalAt))*r.period+150;e.nextAt=Math.min(e.nextAt,t+n)}if(a&&r&&!r.right){e.step=r.lance;for(let e of i)this.act(e,`sulk`,`none`,1600,t);o&&this.say(o,X(ph.futebol.against,n),t)}else if(a){r&&(e.step=r.lance);for(let e of i)this.act(e,`cheer`,`none`,1900,t);o&&this.say(o,X(ph.futebol.goal,n),t);for(let e of i){let n=this.charOf(e);n&&J(q(n.info.seed),`esporte`)&&n.setIcon(`star`,1600,t)}}else if(s<.3){o&&this.say(o,X(ph.futebol.miss,n),t);for(let e of i)this.charOf(e)!==o&&this.emote(e,`😱`,t)}else o&&s<.75&&this.say(o,X(ph.futebol.talk,n,{},e.lastLine),t);break}case`novela`:if(s<.3){o&&this.say(o,X(ph.novela.twist,n),t);for(let e of i)this.charOf(e)!==o&&this.emote(e,`😱`,t)}else if(s<.5){o&&this.say(o,X(ph.novela.love,n),t);for(let e of i)this.charOf(e)?.setIcon(`heart`,1600,t)}else o&&this.say(o,X(ph.novela.talk,n,{},e.lastLine),t);break;default:if(s<.45){for(let e of i)this.act(e,`laugh`,`none`,1600,t);o&&this.say(o,X(ph.desenho.funny,n),t)}else o&&this.say(o,X(ph.desenho.talk,n,{},e.lastLine),t)}}beatGame(e,t){let n=e.rng,r=Gm(e);if(r.length<2){e.phase=`final`,e.until=t+1e3;return}if(t<e.until){e.nextAt=t+mg(n,2e3,3400);let i=r[e.step++%2],a=this.charOf(i);a&&n()<.75&&this.say(a,X(mh.trash,n,{},e.lastLine),t);for(let i of Km(e).filter(e=>e.role===`watcher`)){let a=i.id===`player:me`?this.meRng(e):n;if(a()<.35){this.act(i,`cheer`,`none`,1300,t);let e=this.charOf(i),n=this.charOf(r[Math.floor(a()*2)]);e&&n&&a()<.6&&this.say(e,X(mh.cheer,a,{nome:n.info.name}),t)}}return}let[i,a]=r,o=this.charOf(i),s=this.charOf(a),c=o?q(o.info.seed):null,l=s?q(s.info.seed):null,u=n()<rh(c?.skill??.5,l?.skill??.5),[d,f]=u?[i,a]:[a,i];e.score[+!u]++;let p=ih[e.kind]??1;if(Math.max(...e.score)>=p)return this.finishMatch(e,d,f,t);this.act(d,`cheer`,e.kind===`videogame`?`controller`:`none`,1500,t),this.act(f,`sulk`,e.kind===`videogame`?`controller`:`none`,1500,t);let m=this.charOf(d);m&&this.say(m,X(mh.round,n),t),e.until=t+1500+mg(n,7e3,1e4),e.nextAt=t+1900}beatPingPong(e,t){let n=e.rng,r=Gm(e);if(r.length<2){e.phase=`final`,e.until=t+1e3;return}e.nextAt=t+mg(n,2200,3800);let[i,a]=r,o=this.charOf(i),s=this.charOf(a),c=n()<rh(o?q(o.info.seed).skill:.5,s?q(s.info.seed).skill:.5),l=+!c;e.score[l]++;let u=c?i:a,d=c?a:i;if(e.score[l]>=(ih.pingpong??5))return this.finishMatch(e,u,d,t);let f=this.charOf(u);if(f&&n()<.6){let r=e.score[l],i=e.score[1-l];this.say(f,n()<.5?`${r} × ${i} 🏓`:X(hh.point,n,{},e.lastLine),t)}for(let r of Km(e).filter(e=>e.role===`watcher`)){let i=r.id===`player:me`?this.meRng(e):n;if(i()<.4){this.act(r,`cheer`,`none`,1200,t);let e=this.charOf(r);e&&f&&i()<.4&&this.say(e,X(hh.cheer,i,{nome:f.info.name}),t)}}}finishMatch(e,t,n,r){let i=e.rng,a=this.charOf(t),o=this.charOf(n);e.winner=t.id,e.loser=n.id;let s=e.kind===`videogame`?`controller`:e.kind===`pingpong`?`paddle`:`none`;this.act(t,`cheer`,s,3e3,r),this.act(n,`sulk`,s===`paddle`?`none`:s,3e3,r),a?.setIcon(`trophy`,3e3,r);let[c,l]=e.score,u=Math.max(c,l),d=Math.min(c,l);a&&this.say(a,e.kind===`pingpong`?X(hh.final,i,{a:u,b:d}):X(mh.round,i),r),o&&e.pending.push({id:o.id,at:r+1e3,text:X(gh.lose,i)});for(let t of Km(e))t.role===`watcher`&&this.act(t,(t.id===`player:me`?this.meRng(e):i)()<.5?`cheer`:`laugh`,`none`,1800,r);this.settle(e,t,n,r),e.phase=`final`,e.until=r+3400}settle(e,t,n,r){let i=this.charOf(t),o=this.charOf(n);if(!i||!o)return;this.wallets.recordMatch(t.id,n.id);let s=fg[e.kind]??a(`na aposta`),c=Y[e.kind].emoji,l=e.bet?this.wallets.transfer(n.id,t.id,e.bet,c,s,r):0;l&&(this.float(i,`+🪙${l}`,cg,r),this.float(o,`−🪙${l}`,lg,r),this.sim.pushEffect({kind:`coins`,charId:o.id,toId:i.id,at:r})),this.settleSideBet(e,t,r);let u=e.kind===`pingpong`||e.kind===`videogame`?a(` ({0} a {1})`,[Math.max(...e.score),Math.min(...e.score)]):``;this.event(e,c,i.id,l?a(`ganhou 🪙{0} de {1} {2}{3}`,[l,o.info.name,s,u]):a(`venceu {0} {1}{2}`,[o.info.name,s,u]),r)}beatChat(e,t){let n=e.rng,r=Km(e),i=pg(r);if(i.length<2||t>=e.until){e.phase=`final`,e.until=t+900;return}e.nextAt=t+mg(n,2400,4200);let a=i.filter(t=>t.id!==e.lastSpeaker),o=a[0],s=-1;for(let e of a){let t=this.charOf(e),r=(t?q(t.info.seed).sociability:.5)+n();r>s&&(s=r,o=e)}let c=this.charOf(o);if(!c)return;let l=q(c.info.seed),{line:u,topic:d}=this.topicLine(e,c,l,t);e.lastSpeaker=o.id,this.act(o,`talk`,o.pose===`sit`?o.held:`none`,1700,t),this.say(c,u,t);let f=i.filter(e=>e!==o),p=r.filter(e=>e.id===Zp);if(d===`piadas`){for(let e of[...f,...p])this.act(e,`laugh`,`none`,1600,t);let r=this.charOf(this.randomOf(f,n));r&&e.pending.push({id:r.id,at:t+800,text:X(vh.laugh,n)})}else if(d===`fofoca`)for(let e of[...f,...p])this.emote(e,`👀`,t+300);else if(n()<.45){let r=this.charOf(this.randomOf(f,n));r&&e.pending.push({id:r.id,at:t+1100,text:X(vh.react,n)})}for(let e of i)e!==o&&(e.held===`coffee`||e.held===`water`)&&n()<.2&&this.act(e,`drink`,e.held,1400,t)}topicLine(e,t,n,r){let i=e.rng,a={nome:this.otherName(e,t,i),sala:this.roomName(t,i)},o=i();if(o<.12){let t=Sh(new Date(r));if(t&&t!==e.lastLine)return{line:t,topic:`time`}}if(o<.2)return{line:n.catchphrase,topic:`catch`};let s=n.traits.map(e=>xh[e]).filter(e=>!!e),c=s.length&&i()<.65?s[Math.floor(i()*s.length)]:i()<.6?`work`:`generic`;return(c===`react`||c===`laugh`)&&(c=`generic`),{line:X(vh[c],i,a,e.lastLine),topic:c}}beatRps(e,t){let n=e.rng,r=Gm(e);if(r.length<2){e.phase=`final`,e.until=t+1e3;return}let[i,a]=r,o=this.charOf(i),s=this.charOf(a);if(o&&s){if(e.step<=2){for(let e of r)this.act(e,`rps`,`none`,540,t);if(this.say(o,gh.count[e.step],t,700),e.step===0)for(let e of r)this.emote(e,`✊`,t);e.step++,e.nextAt=t+540;return}if(e.step===3){let r=nh(n,q(o.info.seed)),c=nh(n,q(s.info.seed));e.gestures=[r,c],this.act(i,`rps`,r,2200,t),this.act(a,`rps`,c,2200,t),o.setIcon(ah[r],2200,t),s.setIcon(ah[c],2200,t),e.step=4,e.nextAt=t+1500;return}if(e.step===4){let s=eh(e.gestures[0],e.gestures[1]);if(s===0){e.ties++;for(let e of r)this.act(e,`laugh`,`none`,1e3,t);if(e.ties>=3){this.say(o,X(gh.stalemate,n),t),e.phase=`final`,e.until=t+1600;return}this.say(this.charOf(r[e.ties%2])??o,X(gh.tie,n),t),e.step=0,e.nextAt=t+1400;return}let[c,l]=s===1?[i,a]:[a,i],u=this.charOf(c),d=this.charOf(l);this.act(c,`cheer`,`none`,2600,t),this.act(l,`sulk`,`none`,2600,t),u.setIcon(e.bet?`coin`:`trophy`,2600,t),this.say(u,X(e.bet?gh.win:gh.winHonor,n),t),e.pending.push({id:d.id,at:t+1e3,text:X(gh.lose,n)});for(let n of Km(e))n.role===`watcher`&&this.act(n,`laugh`,`none`,1600,t);let f=Km(e).find(e=>e.role===`watcher`&&e.id!==`player:me`),p=f?this.charOf(f):void 0;p&&e.pending.push({id:p.id,at:t+600,text:X(gh.watch,n)}),this.settle(e,c,l,t);let m=q(d.info.seed);if((J(m,`competicao`)||J(m,`apostas`))&&e.rematches<1&&n()<.6&&(!e.bet||this.wallets.coins(d.id)>=1)){e.rematches++,e.bet=e.bet?Math.min(e.bet,this.wallets.coins(d.id),this.wallets.coins(u.id)):0,e.pending.push({id:d.id,at:t+2200,text:X(gh.rematch,n)}),e.step=0,e.ties=0,e.nextAt=t+3400;return}e.phase=`final`,e.until=t+2900}}}beatMirror(e,t){let n=e.rng,r=Km(e);if(r.length){if(t>=e.until){for(let e of r){let r=this.charOf(e);r&&(r.setIcon(`sparkle`,1800,t),this.sim.pushEffect({kind:`sparkle`,charId:r.id,at:t}),this.say(r,X(e.held===`lipstick`&&n()<.6?_h.lipstick:_h.solo,n),t),this.act(e,`stand`,`none`,2e3,t))}e.phase=`final`,e.until=t+1600;return}if(e.nextAt=t+mg(n,2600,3600),r.length>1){let i=this.charOf(r[e.step++%r.length]);i&&this.say(i,X(_h.duo,n,{},e.lastLine),t)}else n()<.3&&this.charOf(r[0])&&this.emote(r[0],n()<.5?`💅`:`✨`,t)}}syncAgent(e,t,n,r){let{created:i}=this.wallets.ensure(t,n);if(i)return;let a=this.wallets.payTasks(t,n);a&&r&&this.earned(e,a,n)}turnDone(e,t){let n=this.wallets.credit(e.id,5,`💬`,a(`Pedido atendido`),t);n&&this.earned(e,n,t)}delivered(e,t){let n=this.wallets.credit(e.id,15,`📦`,a(`Entregou: {0}`,[e.info.title??a(`resultado`)]),t);n&&this.earned(e,n,t)}earned(e,t,n){this.float(e,`+🪙${t}`,cg,n),e.icon||e.setIcon(`coin`,1400,n)}doing(e){let t=this.sim.chars.get(e)?.gathering;if(!t||t.phase===`ended`)return null;let n=Km(t).filter(t=>t.id!==e).map(e=>this.sim.person(e.id)?.info.name).filter(e=>!!e),r=t.kind===`tv`&&t.program?a(`Vendo {0} na TV`,[t.program===`futebol`?a(`futebol`):t.program===`novela`?a(`novela`):a(`desenho`)]):Y[t.kind].label,i=t.phase===`gather`?a(` (a caminho)`):``,o=t.bet&&Y[t.kind].match?a(` · valendo 🪙{0}`,[t.bet]):``;return`${Y[t.kind].emoji} ${r}${n.length?` com ${gg(n)}`:``}${o}${i}`}info(e){let t=this.sim.chars.get(e);if(!t)return null;let n=q(t.info.seed),r=this.wallets.get(e),i=[];for(let e of this.sim.chars.values()){if(e===t||e.leaving||e.gone)continue;let n=Bm(t.info.seed,e.info.seed);n&&i.push({id:e.id,name:e.info.name,kind:n,record:r?.vs[e.id]?[r.vs[e.id][0],r.vs[e.id][1]]:null})}return i.sort((e,t)=>e.kind===t.kind?e.name.localeCompare(t.name):e.kind===`amizade`?-1:1),{traits:n.traits.map(e=>({emoji:it[e].emoji,label:it[e].label,desc:it[e].desc})),catchphrase:n.catchphrase,coins:r?.coins??0,earned:r?.earned??0,wins:r?.wins??0,losses:r?.losses??0,bonds:i,doing:this.doing(e),ledger:r?r.ledger.map(e=>({...e})):[]}}say(e,t,n,r=ig){e.sayText=t,e.sayAt=n,e.sayUntil=n+r;let i=e.gathering;i&&e.id!==`player:me`&&(i.lastLine=t)}act(e,t,n,r,i){e.actPose=t,e.actHeld=n,e.actUntil=i+r}emote(e,t,n){let r=this.charOf(e);!r||r.sayText&&n<r.sayUntil||(r.chatEmoji=t,r.chatUntil=n+1300)}float(e,t,n,r){this.floaters.length>=og&&this.floaters.shift(),this.floaters.push({charId:e.id,text:t,color:n,at:r,until:r+ag})}event(e,t,n,r,i){this.events.length>=sg&&this.events.shift();let o=e.members.find(e=>e.spot),s=o?.spot?this.sim.spots.get(o.spot)?.areaId:void 0,c=s&&(dg[s]??this.sim.rooms.get(s)?.info.name)||a(`Escritório`);this.events.push({id:`social:${e.id}:${++this.eventSeq}`,at:i,icon:t,agentId:n,text:r,place:c})}charOf(e){return e?this.sim.person(e.id):void 0}meRng(e){let t=this.meRngs.get(e);return t||(t=d((Math.imul(e.id,2654435761)^2812782503)>>>0),this.meRngs.set(e,t)),t}randomOf(e,t){return e.length?e[Math.floor(t()*e.length)%e.length]:void 0}otherName(e,t,n){let r=new Set(e.members.map(e=>e.id)),i=[...this.sim.chars.values()].filter(e=>e!==t&&!e.leaving),a=i.filter(e=>!r.has(e.id));return this.randomOf(a.length?a:i,n)?.info.name}roomName(e,t){let n=this.sim.rooms.get(e.roomId)?.info.name;if(n&&t()<.6)return n;let r=[...this.sim.rooms.values()].filter(e=>e.listed&&!e.annexOf);return this.randomOf(r,t)?.info.name??n}};function gg(e){return e.length<=1?e[0]??``:e.length===2?`${e[0]} e ${e[1]}`:`${e.slice(0,-1).join(`, `)} e ${e[e.length-1]}`}var _g=9,vg=650,yg=class{index;spotId;door=0;holdUntil=0;users=new Set;nextAppearAt=0;constructor(e,t){this.index=e,this.spotId=t}request(e){this.users.add(e)}release(e,t){this.users.delete(e)&&(this.holdUntil=Math.max(this.holdUntil,t+vg))}get load(){return this.users.size}get isOpen(){return this.door>=3.95}get state(){return Math.max(0,Math.min(4,Math.round(this.door)))}update(e,t){let n=this.users.size>0||t<this.holdUntil;this.door=Math.max(0,Math.min(4,this.door+(n?1:-1)*_g*e))}reserveAppear(e){let t=Math.max(e,this.nextAppearAt);return this.nextAppearAt=t+520,t}reset(){this.users.clear(),this.door=0,this.holdUntil=0,this.nextAppearAt=0}},bg=2600,xg=700,Sg=3e3,Cg=class{active=new Map;sync(e,t,n){let r=new Set;for(let i of e){let e=i.effect;if(!e||e.until<=t)continue;r.add(i.id);let a=n+(e.until-t),o=this.active.get(i.id);if(o&&o.key===e.at&&o.kind===e.kind){o.end=a,o.text=e.text,o.agentId=e.agentId;continue}let s=Math.max(0,Math.min(t-e.at,e.until-e.at));this.active.set(i.id,{roomId:i.id,kind:e.kind,text:e.text,agentId:e.agentId,key:e.at,start:n-s,end:a,cheered:new Set})}for(let[e,t]of[...this.active])!r.has(e)&&!t.sticky&&this.active.delete(e)}get(e,t){let n=this.active.get(e);return n&&t<n.end?n:void 0}alarmOwner(e,t){for(let n of this.active.values())if(n.kind===`alarm`&&n.agentId===e&&t<n.end)return n}update(e,t){for(let[n,r]of this.active){if(t>=r.end){this.active.delete(n);continue}r.kind===`party`&&r.end-t>=Sg&&Tg(e,r,t)}}};function wg(e){return c(e)%xg}function Tg(e,t,n){let r=e.rooms.get(t.roomId);if(r&&r.present)for(let i of e.chars.values()){if(t.cheered.has(i.id)||!Eg(i,t.roomId,r.layout.rect,n)||n-t.start<wg(i.id))continue;t.cheered.add(i.id);let a=i.id===t.agentId;a&&(i.setIcon(`star`,bg,n),e.pushEffect({kind:`confetti`,charId:i.id,at:n}));let o=e.spots.get(i.homeSpot);o&&i.atSpot===o.id&&!i.step&&!i.queue.length&&!i.gathering?(i.reactUntil=n+bg+360+200,o.seated&&i.queue.push({t:`exit`}),i.queue.push({t:`act`,pose:`cheer`,ms:bg}),o.seated&&i.queue.push({t:`enter`,spot:o.id})):a||(i.chatEmoji=`🎉`,i.chatUntil=n+2400)}}function Eg(e,t,n,r){return e.gone||e.leaving||e.inside||e.arriving||e.alpha<.5||r<e.hiddenUntil||e.mode===`wait`||e.mode===`leave`||e.mode===`deliver`?!1:e.roomId===t||Hc(n,e.tx,e.ty)}var Dg=class{info;seed;slot;theme;layout;phase;phaseAt;listed=!0;unlistedAt=0;lightOn;lightAt=-1e9;switchClaim=null;readyToDismantleAt=0;accounts=[];board=[];version=0;ghost=!1;annexOf=null;annexN=0;annexOverAt=0;annexUnderAt=0;constructor(e,t,n,r,i,a,o){this.info=e,this.seed=e.seed,this.slot=o,this.theme=t,this.layout=n,this.phase=r,this.phaseAt=i,this.lightOn=a,a&&(this.lightAt=i-1e4)}get id(){return this.info.id}progress(e){return this.phase===`building`?Math.min(1,(e-this.phaseAt)/Ec):this.phase===`dismantling`?Math.min(1,(e-this.phaseAt)/Dc):+(this.phase===`ready`)}get present(){return this.phase===`building`||this.phase===`ready`||this.phase===`dismantling`}setPhase(e,t){this.phase=e,this.phaseAt=t}rebuild(e){if(this.phase===`dismantling`){let t=this.progress(e);this.phase=`building`,this.phaseAt=e-(1-t)*Ec}else this.phase===`gone`&&this.setPhase(`building`,e)}setLight(e,t){this.lightOn!==e&&(this.lightOn=e,this.lightAt=t)}light(e){return Ad(this.lightOn,e-this.lightAt)}},Og=class{spots=new Map;owners=new Map;byKind=new Map;byGroup=new Map;setSpots(e){this.spots.clear(),this.byKind.clear(),this.byGroup.clear();for(let t of e){this.spots.set(t.id,t);let e=this.byKind.get(t.kind);if(e||this.byKind.set(t.kind,e=[]),e.push(t),t.group){let e=this.byGroup.get(t.group);e||this.byGroup.set(t.group,e=[]),e.push(t)}}let t=[];for(let[e,n]of this.owners)this.spots.has(e)||(t.push({spotId:e,owner:n}),this.owners.delete(e));return t}get(e){return e?this.spots.get(e):void 0}all(){return this.spots.values()}ofKind(e){return this.byKind.get(e)??[]}group(e){return this.byGroup.get(e)??[]}ownerOf(e){return this.owners.get(e)}isFree(e,t){let n=this.owners.get(e);return n===void 0||n===t}reserve(e,t){return!this.spots.has(e)||!this.isFree(e,t)?!1:(this.owners.set(e,t),!0)}release(e,t){e&&this.owners.get(e)===t&&this.owners.delete(e)}releaseAll(e){for(let[t,n]of this.owners)n===e&&this.owners.delete(t)}reservedBy(e){let t=[];for(let[n,r]of this.owners)r===e&&t.push(n);return t}findFree(e,t={}){let n=this.byKind.get(e);if(!n)return null;let r=[];for(let e of n){if(!this.isFree(e.id,t.by)||t.filter&&!t.filter(e))continue;let n=t.near?Math.abs(e.tx-t.near.tx)+Math.abs(e.ty-t.near.ty):0;r.push({s:e,d:n})}return r.length?(r.sort((e,t)=>e.d-t.d),t.rng?r[Math.floor(t.rng()*Math.min(3,r.length))].s:r[0].s):null}findFreeGroup(e,t={}){let n=[],r=new Set;for(let i of this.byKind.get(e)??[]){if(!i.group||r.has(i.group))continue;r.add(i.group);let e=this.group(i.group);e.length<2||!e.every(e=>this.isFree(e.id))||(!t.filter||t.filter(e))&&n.push(e)}return n.length?n[Math.floor((t.rng??Math.random)()*n.length)]:null}},kg=`visita:eu`,Ag=`#ff8a3d`,jg={dx:0,dy:0,run:!1};function Mg(e,t){return{id:kg,kind:`main`,provider:`claude`,roomId:Uc,name:e.name,look:e.look,...e.parts&&Object.keys(e.parts).length?{parts:e.parts}:{},role:a(`Visitante`),sessionId:kg,account:``,status:`idle`,recent:[],tasks:[],startedAt:t,lastEventAt:t,statusSince:t,stats:{toolCalls:0,tokensIn:0,tokensOut:0,subagents:0},seed:c(`${kg}:${e.name}`)}}function Ng(e,t){return{x:Math.floor(e/16),y:Math.floor(t/16)}}var Pg=4,Fg=2;function Ig(e,t,n){for(let[r,i]of[[-4,-4],[Pg,-4],[-4,Fg],[Pg,Fg]]){let a=Ng(t+r,n+i),o=e.get(a.x,a.y);if(o===0||o===2)return!1}return!0}function Lg(e,t,n,r){let{dx:i,dy:a}=n;if(i=Math.sign(i),a=Math.sign(a),!i&&!a)return{...t,moved:!1};let o=i&&a?Math.SQRT1_2:1,{x:s,y:c}=t,l=!1;if(i){let t=s+i*r*o;Ig(e,t,c)&&(s=t,l=!0)}if(a){let t=c+a*r*o;Ig(e,s,t)&&(c=t,l=!0)}return{x:s,y:c,dir:al(i,a,t.dir),moved:l}}var Rg=[`②`,`③`,`④`],zg=2200,Bg=4e3,Vg=32,Hg=`@mudança`,Ug={carpet:`#5b7fa6`,carpet2:`#4f7093`,wall:{base:`#e7e3db`,trim:`#9b9184`,pattern:`plain`},accent:`#3f7fd8`,deskVariant:`wood`,chairVariant:`black`},Wg=[`sofa`,`armchair`,`beanbag`],Gg=[`beanbag`,`sofa`,`armchair`,`cafe_seat`,`bench`],Kg=[`sofa`,`armchair`,`beanbag`,`cafe_seat`],qg=.15,Jg=9e4,Yg=5e3,Xg=180;function Zg(e,t,n){return t+e()*(n-t)}var Qg=(e,t)=>`${e.seed}|${e.look}|${k(e.parts)}|${t?k(t):``}`,$g=class{art;options;chars=new Map;rooms=new Map;spots=new Og;elevators=[];building;finder;layoutVersion=0;now=0;initialized=!1;machineUntil=new Map;stallBusy=new Set;social;forcedOffline=new Set;hiddenRooms=new Set;accounts=new Map;machines;defaultLook;injected={rooms:[],agents:[]};agentPatches=new Map;effects=[];roomFx=new Cg;intrusionEffect;lastSnapshot=null;gapSince=0;moveSeq=0;shrinkPending=!1;nextHousekeeping=0;panicking=new Set;motionReduced;visit;inbox=new fl(this);visitor=null;visitorIntent={...jg};visitLight=`live`;player=null;stamps=new Map;queueOverflow=0;constructor(e,t,n=eg(),r={}){this.art=e,this.options=t,this.visit=!!r.visit,this.motionReduced=r.reducedMotion??ac,this.social=new hg(this,n),this.building=Cm(Bc([]),[],0),this.finder=new Fm(this.building.grid),this.spots.setSpots(this.building.spots);for(let e of this.spots.ofKind(`elevator`))this.elevators.push(new yg(this.elevators.length,e.id))}applySnapshot(e,t){let n=this.injected.rooms.length||this.injected.agents.length?{...e,rooms:[...e.rooms,...this.injected.rooms],agents:[...e.agents,...this.injected.agents]}:e;if(this.agentPatches.size){let e=this.agentPatches;n={...n,agents:n.agents.map(t=>e.has(t.id)?{...t,...e.get(t.id)}:t)}}this.lastSnapshot=e,this.now=t;let r=!this.initialized;this.initialized=!0,this.machines=n.machines,this.defaultLook=n.defaultLook,this.accounts=new Map(n.accounts.map(e=>[e.id,{short:e.short,color:e.color,name:e.name,...e.provider===`codex`?{provider:e.provider}:{}}]));let i=!1,o=new Set;for(let e of[...n.rooms].sort((e,t)=>e.slot-t.slot)){if(this.hiddenRooms.has(e.id))continue;o.add(e.id);let n=this.rooms.get(e.id);if(!n){this.createRoom(e,r,t),i=!0;continue}(n.info.name!==e.name||n.info.seed!==e.seed)&&n.version++,n.info=e,this.syncAnnexInfo(n),n.listed||(n.listed=!0,n.readyToDismantleAt=0,n.phase===`dismantling`&&n.rebuild(t))}for(let e of this.rooms.values())!o.has(e.id)&&e.listed&&!e.annexOf&&(e.listed=!1,e.unlistedAt=t);i&&this.relayout(),this.roomFx.sync(pm(n.rooms,n.agents,n.meta.buildingEffect,a(`Intrusão!`)),e.serverTime,t);let s=new Set,c=[];for(let e of n.agents){s.add(e.id);let n=this.chars.get(e.id);if(n){this.updateAgent(n,e,t),this.social.syncAgent(n,e,t,!0);continue}if(e.status===`offline`||this.forcedOffline.has(e.id)||this.hiddenRooms.has(rl(e))||e.status===`done`)continue;if(e.kind===`sub`&&e.parentId){let t=this.chars.get(e.parentId);if(t&&(t.leaving||t.gone))continue}let i=this.spawn(e,r,t);i&&(c.push(i),this.social.syncAgent(i,e,t,!1))}for(let e of this.chars.values())!s.has(e.id)&&!e.leaving&&e.missingSince===null&&(e.missingSince=t);for(let e of c)e.mode=this.modeOf(e),this.refreshShell(e,t);if(r){let e=new Set,n=[...c].sort((e,t)=>Number(e.mode===`idle`)-Number(t.mode===`idle`));for(let r of n)this.placeInitial(r,t,e)}this.syncIntrusion(e.meta.buildingEffect,e.serverTime,t),this.updateIntrusion(t),this.refreshRoomInfo(),this.visit&&this.applyVisitLight(t,r)}reapply(e){this.lastSnapshot&&this.applySnapshot(this.lastSnapshot,e)}createRoom(e,t,n){let r=Ug;try{r=this.art.roomTheme(e.seed)??Ug}catch{r=Ug}let i=this.freeSlot(),a=Am({id:e.id,slot:i,seed:e.seed},r),o=new Dg(e,r,a,t?`ready`:`building`,n,t,i);return this.rooms.set(e.id,o),o}freeSlot(){let e=new Set;for(let t of this.rooms.values())t.phase!==`gone`&&e.add(t.slot);let t=0;for(;e.has(t);)t++;return t}updateAgent(e,t,n){let r=e.info.status,i=!!e.info.shells?.length,a=Ye(t,this.defaultLook)?this.defaultLook?.parts:void 0,o=Qg(t,a),s=e.lookSig||Qg(e.info);if(e.info=t,o!==s){e.lookSig=o;try{e.appearance=this.art.appearanceFromSeed(t.seed,{look:t.look,sub:t.kind===`sub`,parts:t.parts,defaultParts:a})}catch{}}e.missingSince=null;let c=rl(t);c!==e.roomId&&!e.leaving&&(e.homeSpot&&this.spots.release(e.homeSpot,e.id),e.homeSpot=null,e.roomId=c,this.interrupt(e));let l=t.activity;if(l&&l.id!==e.lastActivityId){let r=e.lastActivityId===null;e.lastActivityId=l.id,r||(e.activityChangedAt=n,l.kind===`done`&&e.setIcon(`check`,2600,n),l.kind===`error`&&e.setIcon(`sweat`,2200,n),l.kind===`delegate`&&e.info.kind===`main`&&t.status===`working`&&this.planDelegate(e,n),l.kind===`done`&&e.info.kind===`main`&&this.social.turnDone(e,n))}let u=Wl(t);u&&u.at>e.shellDoneAt&&(e.shellDoneAt=u.at,this.reactShellDone(e,!u.error,n)),(r!==t.status||i||t.shells?.length||e.mode===`shell`||this.forcedOffline.has(e.id))&&this.refreshMode(e),this.refreshShell(e,n)}refreshMode(e){if(e.leaving)return;let t=this.modeOf(e);if(t===e.mode)return;let n=e.mode;e.mode=t,n===`idle`&&t!==`idle`&&(e.nextOutingAt=0),e.icon===`zzz`&&e.setIcon(null,0,this.now),this.refreshShell(e,this.now),(!e.gathering||t!==`idle`&&t!==`shell`||n!==`idle`&&n!==`shell`)&&(e.gathering&&this.social.calledAway(e,n,this.now),!(this.now<e.reactUntil&&t!==`leave`&&t!==`deliver`)&&(e.reactUntil=0,this.interrupt(e)))}modeOf(e){let t=e.info;if(e.leaving)return`leave`;let n=t.parentId?this.chars.get(t.parentId):void 0,r=!!n&&(n.leaving||n.gone),i=e.missingSince!==null&&this.now-e.missingSince>=3e3,a=this.forcedOffline.has(e.id);if(t.kind===`sub`&&t.status===`done`&&!e.delivered&&!a&&!r)return`deliver`;let o=_d(a?`offline`:t.status,{kind:t.kind,missing:i,parentGone:r,shells:t.shells,now:this.now});return o===`deliver`&&e.delivered?`leave`:o}refreshShell(e,t){if(e.mode!==`shell`){e.shellSince=0,e.shellCount=0,e.shellStage=null,e.shellEnteredAt=0;return}let n=e.info;e.shellEnteredAt||=t,e.shellSince=Math.min(t,Hl(n)),e.shellCount=Math.max(1,Bl(n.shells,n.status!==`shell`));let r=Ul(n);r!==e.shellLabel&&(e.shellLabel=r,e.shellTextKey=-1),e.shellStage=this.visit?null:Fl(t-e.shellSince)}reactShellDone(e,t,n){if(e.leaving||e.mode===`leave`||e.mode===`deliver`)return;e.setIcon(t?`star`:`storm`,t?zg:Bg,n),t&&this.pushEffect({kind:`confetti`,charId:e.id,at:n});let r=this.spots.get(e.homeSpot);!r||e.atSpot!==r.id||e.step||e.queue.length||e.gathering||(t?(e.reactUntil=n+zg+360+200,r.seated&&e.queue.push({t:`exit`}),e.queue.push({t:`act`,pose:`stretch`,ms:zg*.55},{t:`act`,pose:`raise_hand`,ms:zg*.45}),r.seated&&e.queue.push({t:`enter`,spot:r.id})):(e.reactUntil=n+Bg,e.queue.push({t:`act`,pose:r.seated?`sleep`:`stand`,ms:Bg})))}footballLance(e){try{return this.art.footballLance?.(e,Um.futebol)??null}catch{return null}}pushEffect(e){this.effects.length>=Vg&&this.effects.shift(),this.effects.push(e)}syncIntrusion(e,t,n){if(!e||e.until<=t){this.intrusionEffect&&this.finishIntrusion();return}if(this.intrusionEffect?.key!==e.at){this.intrusionEffect&&this.returnPanickers();let r=Math.max(0,e.until-e.at),i=Math.max(0,Math.min(t-e.at,r)),a=Math.min(e.panicUntil??e.until,e.until);this.intrusionEffect={key:e.at,text:e.text,start:n-i,end:n+(e.until-t),panicEnd:n+(a-t)}}else this.intrusionEffect.end=n+(e.until-t),this.intrusionEffect.text=e.text}updateIntrusion(e){let t=this.intrusionEffect;if(t){if(e>=t.end){this.finishIntrusion();return}if(e>=t.panicEnd||this.motionReduced()||this.options().liveliness===`calm`){this.returnPanickers();return}for(let t of this.chars.values())this.panicking.has(t.id)||this.panicCharacter(t,e)}}finishIntrusion(){this.returnPanickers(),this.intrusionEffect=void 0}returnPanickers(){for(let e of this.panicking){let t=this.chars.get(e);if(!t||t.gone||t.leaving||(this.clearPlan(t),!t.homeSpot||t.atSpot===t.homeSpot))continue;t.atSpot&&t.queue.push({t:`exit`});let n=this.spots.get(t.homeSpot);n&&t.queue.push({t:`go`,tx:n.tx,ty:n.ty},{t:`enter`,spot:n.id})}this.panicking.clear()}panicCharacter(e,t){e.gone||e.leaving||e.inside||e.arriving||(this.clearPlan(e),this.panicking.add(e.id),this.queuePanicTarget(e,t))}queuePanicTarget(e,t){let n=this.building.grid;for(let r=0;r<30;r++){let r=Math.floor(e.rng()*n.w),i=Math.floor(e.rng()*n.h);if(!n.walkable(r,i)||r===e.tx&&i===e.ty)continue;let a=[];if(this.findPath(e.tx,e.ty,r,i,a)&&a.length){e.atSpot&&e.queue.push({t:`exit`}),e.queue.push({t:`go`,tx:r,ty:i,run:!0}),e.rng()<.45&&e.showBubble(e.rng()<.5?`!`:`?`,``,2400,t);return}}this.panicking.delete(e.id)}spawn(e,t,n){let r=Ye(e,this.defaultLook)?this.defaultLook?.parts:void 0,i;try{i=this.art.appearanceFromSeed(e.seed,{look:e.look,sub:e.kind===`sub`,parts:e.parts,defaultParts:r})}catch{return null}let a=new il(e,i);if(a.lookSig=Qg(e,r),a.lastActivityId=e.activity?.id??null,a.shellDoneAt=Wl(e)?.at??0,this.chars.set(e.id,a),t)return a;let o=this.pickElevator(a),s=this.spots.get(o.spotId);return a.placeAtTile(s.tx,s.ty),a.x=s.x,a.y=s.y-6,a.dir=`down`,a.alpha=0,a.inside=!0,a.arriving=!0,a.hiddenUntil=o.reserveAppear(n),e.kind===`sub`&&(a.hiddenUntil+=Math.floor(a.rng()*600)),a.queue.push({t:`elevOut`,elev:o.index,phase:0}),a}placeInitial(e,t,n){this.assignHome(e);let r=this.spots.get(e.homeSpot);if(e.nextOutingAt=t+Yg+Sd(e.rng,this.options().liveliness)*e.rng(),e.mode===`idle`&&r&&n.has(e.roomId)&&t-e.info.statusSince>=Jg&&!Cd(e.info.status,e.info.statusSince,t)&&e.rng()<qg){let t=this.randomFree(Kg,e);if(t&&this.spots.reserve(t.id,e.id)){e.tempSpots.push(t.id),this.snapTo(e,t);let n=t.kind===`cafe_seat`?`coffee`:`none`;e.queue.push({t:`act`,pose:`sit`,held:n,ms:Zg(e.rng,4e3,14e3)},{t:`exit`},{t:`do`,fn:()=>this.releaseTemp(e)});return}}r?(this.snapTo(e,r),n.add(e.roomId)):this.placeOverflow(e)}placeOverflow(e){let t=this.seatRoomOf(e),n=t&&t.present?this.overflowTile(e,t):null;e.standTile=n;let r=n??this.lobbyTile(e);e.placeAtTile(r.x,r.y)}snapTo(e,t){e.tx=t.tx,e.ty=t.ty,e.x=t.x,e.y=t.y,e.dir=t.dir,e.atSpot=t.id,e.seated=!!t.seated,e.sortY=t.sortY??null}assignHome(e){if(e.homeSpot&&this.spots.get(e.homeSpot)&&this.spots.ownerOf(e.homeSpot)===e.id)return;e.homeSpot=null,e.annexId=null;let t=this.rooms.get(e.roomId);if(!t||!t.present)return;let n=this.pickSeat(e);n&&this.spots.reserve(n.seat.id,e.id)&&(e.homeSpot=n.seat.id,e.annexId=n.room.annexOf?n.room.id:null)}pickSeat(e,t=!0){let n=this.seatRooms(e.roomId);for(let r of t?[!1,!0]:[!1])for(let t of n){let n=wd(t.layout.spots,t=>this.spots.isFree(t,e.id),e.info.kind,r);if(n)return{seat:n,room:t}}return null}seatRooms(e){let t=this.rooms.get(e);return!t||!t.present?[]:[t,...this.annexesOf(e).filter(e=>e.listed&&e.present)]}annexesOf(e){let t=[];for(let n of this.rooms.values())n.annexOf===e&&t.push(n);return t.sort((e,t)=>e.annexN-t.annexN)}seatRoomOf(e){return(e.annexId?this.rooms.get(e.annexId):void 0)??this.rooms.get(e.roomId)}countIn(e){let t=0;for(let n of this.chars.values())!n.leaving&&!n.gone&&(n.roomId===e||n.annexId===e)&&t++;return t}snapshotRoomIds(){return(this.lastSnapshot?.rooms??[]).map(e=>e.id)}roomIdAt(e,t){for(let n of this.rooms.values())if(n.present&&!n.ghost&&Hc(n.layout.rect,e,t))return n.annexOf??n.id;return null}pickElevator(e){let t=this.elevators[0];for(let n of this.elevators)(n.load<t.load||n.load===t.load&&e.rng()<.5)&&(t=n);return t}relayout(e=!1){let t=[...this.rooms.values()].filter(e=>e.present),n=Bc(t.map(e=>e.slot)),r=this.building.cols;if(n<r&&!e){let e=n*16*16;[...this.chars.values()].some(t=>!t.gone&&t.x>=e-16)?(n=r,this.shrinkPending=!0):this.shrinkPending=!1}else this.shrinkPending=!1;let i=Cm(n,t.map(e=>e.layout),this.layoutVersion+1);this.building=i,this.layoutVersion++,this.finder.setGrid(i.grid);let a=this.spots.setSpots(i.spots);for(let{owner:e}of a){let t=this.chars.get(e);t&&(t.homeSpot&&!this.spots.get(t.homeSpot)&&(t.homeSpot=null),t.tempSpots=t.tempSpots.filter(e=>this.spots.get(e)))}for(let e of this.chars.values()){e.atSpot&&!this.spots.get(e.atSpot)&&(e.atSpot=null,e.seated=!1,e.sortY=null);let t=!1;for(let n of e.step?[e.step,...e.queue]:e.queue)n.t===`go`&&(n.path=void 0,this.building.grid.nearestWalkable(n.tx,n.ty,4)||(t=!0));if(t&&this.interrupt(e),!this.building.grid.walkable(e.tx,e.ty)&&!e.atSpot&&!e.inside){let t=this.building.grid.nearestWalkable(e.tx,e.ty);t&&(e.tx=t.x,e.ty=t.y)}}}update(e,t){this.now=t,this.updateIntrusion(t);for(let n of this.elevators)n.update(e,t);this.player?.updateQueue(t),this.updateRooms(t),this.social.update(t),this.roomFx.active.size&&this.roomFx.update(this,t);for(let n of this.chars.values())n.missingSince!==null&&!n.leaving&&t-n.missingSince>=3e3&&this.refreshMode(n),this.runCharacter(n,e,t);this.visitor&&this.runVisitor(this.visitor,e,t),this.player?.update(e,t),this.inbox.update(e,t);for(let[e,t]of this.chars)t.gone&&(this.spots.releaseAll(e),this.chars.delete(e));t>=this.nextHousekeeping&&(this.nextHousekeeping=t+1e3,this.housekeeping(t))}housekeeping(e){for(let t of this.chars.values())(t.info.kind===`sub`&&!t.leaving||!t.leaving&&(t.mode===`shell`||t.info.status===`working`&&t.info.shells?.length))&&this.refreshMode(t),t.mode===`idle`&&this.longIdle(t,e)&&t.atSpot===t.homeSpot&&t.pose===`sleep`&&t.icon!==`zzz`&&t.setIcon(`zzz`,0xe8d4a51000,e);this.shrinkPending&&this.relayout(),this.social.housekeeping(e);for(let[t,n]of this.machineUntil)n<e&&this.machineUntil.delete(t);this.refreshRoomInfo(),this.visit&&this.applyVisitLight(e)}updateRooms(e){let t=this.updateAnnexes(e);for(let n of this.rooms.values())if(n.phase===`building`&&n.progress(e)>=1&&n.setPhase(`ready`,e),n.phase===`dismantling`&&n.progress(e)>=1&&(n.setPhase(`gone`,e),t=!0),!n.listed&&(n.phase===`ready`||n.phase===`building`)){let t=this.occupants(n);t===0&&n.lightOn&&!this.switchClaimValid(n)&&e-n.unlistedAt>2500&&n.setLight(!1,e),kd({listed:n.listed,occupants:t,lightOn:n.lightOn,dark:n.light(e)<=.01,unlistedForMs:e-n.unlistedAt},0)?n.readyToDismantleAt?e-n.readyToDismantleAt>=1500&&n.setPhase(`dismantling`,e):n.readyToDismantleAt=e:n.readyToDismantleAt=0}for(let[e,n]of this.rooms)n.phase===`gone`&&(this.rooms.delete(e),t=!0);t&&this.relayout(),this.compact(e)}annexName(e,t){return`${e.name} ${Rg[t-2]??t}`}syncAnnexInfo(e){for(let t of this.annexesOf(e.id)){let n={...e.info,id:t.id,name:this.annexName(e.info,t.annexN)};t.info.name!==n.name&&t.version++,t.info=n}}updateAnnexes(e){let t=!1;for(let t of this.rooms.values()){if(!t.annexOf||!t.listed)continue;let n=this.rooms.get(t.annexOf);(!n||!n.listed||n.phase===`gone`)&&this.closeAnnex(t,e)}let n=new Map;for(let e of this.chars.values())e.gone||e.leaving||(e.mode===`work`||e.mode===`wait`||e.mode===`shell`)&&n.set(e.roomId,(n.get(e.roomId)??0)+1);for(let r of[...this.rooms.values()]){if(r.annexOf||r.ghost)continue;if(!r.listed||r.phase!==`ready`||this.hiddenRooms.has(r.id)){r.annexOverAt=r.annexUnderAt=0;continue}let i=this.annexesOf(r.id),a=i.filter(e=>e.listed),o=Ed(r.layout.spots)+a.reduce((e,t)=>e+Ed(t.layout.spots),0),s=n.get(r.id)??0;if(s>o){if(r.annexUnderAt=0,a.length>=3){r.annexOverAt=0;continue}r.annexOverAt?e-r.annexOverAt>=8e3&&(r.annexOverAt=0,this.openAnnex(r,a.length+2,i,e)&&(t=!0)):r.annexOverAt=e;continue}r.annexOverAt=0;let c=a[a.length-1];c&&s<=o-Ed(c.layout.spots)-2?r.annexUnderAt?e-r.annexUnderAt>=6e4&&(r.annexUnderAt=0,this.closeAnnex(c,e)):r.annexUnderAt=e:r.annexUnderAt=0}return t}openAnnex(e,t,n,r){let i=`${e.id}#${t}`,a=n.find(e=>e.annexN===t);if(a)return a.phase!==`gone`&&(a.listed=!0,a.readyToDismantleAt=0,a.phase===`dismantling`&&a.rebuild(r),this.moveOverflowToAnnex(e),!1);let o=this.annexSlot(e,n,r);if(o===`wait`)return e.annexOverAt=r-Oc,!1;if(o===`moved`)return!0;let s=o,c={...e.info,id:i,name:this.annexName(e.info,t)},l=Am({id:i,slot:s,seed:e.seed},e.theme),u=new Dg(c,e.theme,l,`building`,r,!1,s);return u.annexOf=e.id,u.annexN=t,this.rooms.set(i,u),this.relayout(),this.moveOverflowToAnnex(e),!0}roomAtSlot(e){let t;for(let n of this.rooms.values())if(n.phase!==`gone`&&n.slot===e){if(!n.ghost)return n;t=n}return t}hasLiveAnnex(e){return this.annexesOf(e).some(e=>e.phase!==`gone`)}movable(e){return!e.ghost&&!e.annexOf&&e.listed&&e.phase===`ready`&&!this.hasLiveAnnex(e.id)}annexSlot(e,t,n){let r=new Set(t.filter(e=>e.phase!==`gone`).map(e=>e.slot)),i=t.find(t=>t.phase!==`gone`&&Fc(t.slot)===Fc(e.slot)),a=i&&i.slot<e.slot?[-1,1]:[1,-1];for(let t of a){let i=e.slot+2*t;for(;r.has(i);)i+=2*t;if(i<0)continue;let a=this.roomAtSlot(i);if(!a)return i;if(a.ghost)return`wait`;if(this.movable(a))return this.moveRoom(a,this.freeSlot(),n),`moved`}let o=zc(Pc(e.slot),Fc(e.slot)===`north`?`south`:`north`);return o>=0&&!this.roomAtSlot(o)?o:this.freeSlot()}moveOverflowToAnnex(e){for(let t of this.chars.values()){if(t.roomId!==e.id||t.leaving||t.gone||!t.homeSpot||this.spots.get(t.homeSpot)?.kind!==`stand`)continue;let n=this.pickSeat(t,!1);n&&this.spots.reserve(n.seat.id,t.id)&&(this.spots.release(t.homeSpot,t.id),t.homeSpot=n.seat.id,t.annexId=n.room.annexOf?n.room.id:null,t.standTile=null,this.interrupt(t))}}closeAnnex(e,t){e.listed=!1,e.unlistedAt=t,e.readyToDismantleAt=0;for(let t of this.chars.values())t.annexId!==e.id||t.leaving||t.gone||(t.homeSpot&&this.spots.release(t.homeSpot,t.id),t.homeSpot=null,t.annexId=null,this.interrupt(t))}compact(e){let t=this.freeSlot(),n=null;for(let e of this.rooms.values())e.slot>t&&!e.ghost&&!e.annexOf&&e.listed&&e.phase===`ready`&&(!n||e.slot>n.slot)&&!this.hasLiveAnnex(e.id)&&(n=e);if(!n){this.gapSince=0;return}this.gapSince||=e,!(e-this.gapSince<1200)&&(this.gapSince=0,this.moveRoom(n,t,e))}moveRoom(e,t,n){let r=e.layout,i=`${e.id}#mudança${++this.moveSeq}`,a=Am({id:i,slot:e.slot,seed:e.seed},e.theme),o=new Dg({...e.info,id:i,seed:e.seed},e.theme,a,`ready`,n,!1,e.slot);o.ghost=!0,o.listed=!1,o.unlistedAt=n,o.lightOn=e.lightOn,o.lightAt=e.lightAt,this.rooms.set(i,o);let s=new Map;r.spots.forEach((e,t)=>{let n=a.spots[t];n&&n.kind===e.kind&&s.set(e.id,n.id)}),e.slot=t,e.layout=Am({id:e.id,slot:t,seed:e.seed},e.theme),e.setPhase(`building`,n),e.lightOn=!1,e.lightAt=-1e9,e.switchClaim=null,e.readyToDismantleAt=0,e.version++,this.relayout();for(let e of a.spots)this.spots.reserve(e.id,Hg);for(let t of this.chars.values()){if(t.gone)continue;let n=!1;t.atSpot&&s.has(t.atSpot)&&(t.atSpot=s.get(t.atSpot),n=!0);for(let a of t.step?[t.step,...t.queue]:t.queue)a.t===`enter`&&s.has(a.spot)?(a.spot=s.get(a.spot),n=!0):a.t===`switch`&&a.room===e.id?(a.room=i,n=!0):a.t===`go`&&Hc(r.rect,a.tx,a.ty)&&(n=!0);t.tempSpots.some(e=>s.has(e))&&(n=!0),(n||Dd(t)===e.id&&t.standTile||Hc(r.rect,t.tx,t.ty))&&(t.standTile=null,this.interrupt(t))}}switchClaimValid(e){if(!e.switchClaim)return!1;let t=this.chars.get(e.switchClaim);return!t||t.gone?(e.switchClaim=null,!1):!0}occupants(e,t){let n=0;for(let r of this.chars.values())r.gone||r.id===t||(Dd(r)===e.id&&!r.leaving||Hc(e.layout.rect,r.tx,r.ty))&&n++;return n}physicallyInside(e,t){let n=0;for(let r of this.chars.values())!r.gone&&r.id!==t&&Hc(e.layout.rect,r.tx,r.ty)&&n++;return n}refreshRoomInfo(){for(let e of this.rooms.values()){let t=new Set,n=[];for(let r of this.chars.values())if(!((e.annexOf?r.annexId!==e.id:r.roomId!==e.id)||r.leaving)&&(t.add(r.info.account),!e.annexOf&&r.info.kind===`main`))for(let e of r.info.tasks)n.length<15&&n.push({status:e.status});e.accounts=[...t].sort(),e.board=n}}runCharacter(e,t,n){if(e.animT+=t*1e3,e.updateLane(t),e.icon&&n>=e.iconUntil&&(e.icon=null),e.icon===`zzz`&&e.pose!==`sleep`&&(e.icon=null),e.mode===`shell`&&e.shellSince&&!this.visit&&(e.shellStage=Fl(n-e.shellSince)),e.step||(e.replan&&(e.replan=!1,this.clearPlan(e)),e.step=e.queue.shift()??null,e.stepT=0,e.stepStarted=!1),e.step){let r=this.runStep(e,e.step,t,n);e.stepT+=t*1e3,r&&(e.step=null,e.replan&&(e.replan=!1,this.clearPlan(e)));return}if(this.panicking.has(e.id)){this.queuePanicTarget(e,n);return}n>=e.thinkAt&&(this.think(e,n)||(e.thinkAt=n+400)),!e.step&&!e.queue.length&&this.restPose(e,n)}runStep(e,t,n,r){let i=!e.stepStarted;switch(e.stepStarted=!0,t.t){case`go`:return this.stepGo(e,t,n);case`enter`:{let r=this.spots.get(t.spot);if(!r)return!0;i&&(e.enterFrom={x:e.x,y:e.y},r.seated&&(e.sortY=r.sortY??null));let a=Math.min(1,(e.stepT+n*1e3)/Xg),o=e.enterFrom??{x:e.x,y:e.y};return e.x=o.x+(r.x-o.x)*a,e.y=o.y+(r.y-o.y)*a,a>=1&&(this.snapTo(e,r),e.setPose(r.seated?`sit`:`stand`,e.held),!0)}case`exit`:{if(!e.atSpot)return!0;let t=this.spots.get(e.atSpot);if(!t)return e.atSpot=null,e.seated=!1,e.sortY=null,!0;let r=t.tx*16+Tc,a=t.ty*16+11;i&&(e.enterFrom={x:e.x,y:e.y});let o=Math.min(1,(e.stepT+n*1e3)/Xg),s=e.enterFrom??{x:e.x,y:e.y};return e.x=s.x+(r-s.x)*o,e.y=s.y+(a-s.y)*o,e.seated=!1,e.setPose(`stand`,e.held),o>=1&&(e.atSpot=null,e.sortY=null,e.tx=t.tx,e.ty=t.ty,!0)}case`act`:return i&&(t.dir&&(e.dir=t.dir),t.icon&&e.setIcon(t.icon,t.ms,r),t.machine&&this.machineUntil.set(t.machine,r+t.ms)),e.setPose(t.pose,t.held??`none`),e.stepT>=t.ms;case`until`:return i&&t.dir&&(e.dir=t.dir),e.setPose(t.pose??(e.seated?`sit`:`stand`),t.held??e.held),e.stepT>=t.maxMs||e.stepT>=t.minMs&&t.cond();case`elevOut`:return this.stepElevOut(e,t,n,r);case`elevIn`:return this.stepElevIn(e,t,n,r);case`stall`:return this.stepStall(e,t,n,r);case`switch`:return this.stepSwitch(e,t,r);case`gather`:return this.social.stepGather(e,t.g,r);case`do`:return t.fn(),!0;case`remove`:return e.gone=!0,!0}}findPath(e,t,n,r,i){let a=this.building.grid;if(!a.walkable(n,r)){let e=a.nearestWalkable(n,r,4);if(!e)return!1;n=e.x,r=e.y}if(this.finder.find(e,t,n,r,i))return!0;let o=a.nearestWalkable(e,t,6);return o&&(o.x!==e||o.y!==t)&&this.finder.find(o.x,o.y,n,r,i)?(i.unshift(o.x,o.y),!0):!1}stepGo(e,t,n){t.path||(t.path=[],t.i=0,this.findPath(e.tx,e.ty,t.tx,t.ty,t.path)||(e.placeAtTile(t.tx,t.ty),t.path.length=0));let r=t.path,i=(t.run?wc:Cc)*e.speedK*n,a=!1;for(;i>1e-4;){let n,o,s=t.i??0;if(s<r.length)e.tx=r[s],e.ty=r[s+1],n=e.tx*16+Tc,o=e.ty*16+11;else if(t.fx!==void 0&&t.fy!==void 0&&!t.fine)n=t.fx,o=t.fy;else break;let c=n-e.x,l=o-e.y,u=Math.hypot(c,l);u>.001&&(e.dir=al(c,l,e.dir)),u<=i?(e.x=n,e.y=o,i-=u,s<r.length?t.i=s+2:t.fine=!0):(e.x+=c/u*i,e.y+=l/u*i,i=0),a=!0}return(t.i??0)>=r.length&&(t.fx===void 0||t.fine)?(t.dir&&(e.dir=t.dir),e.setPose(`stand`,t.held??`none`),!0):(a&&e.setPose(t.run?`run`:`walk`,t.held??`none`),!1)}stepElevOut(e,t,n,r){let i=this.elevators[t.elev]??this.elevators[0],a=this.spots.get(i.spotId);if(e.dir=`down`,t.phase===0)return e.alpha=0,e.setPose(`stand`),r>=e.hiddenUntil&&(i.request(e.id),t.phase=1),!1;if(t.phase===1)return e.x=a.x,e.y=a.y-6,i.door>=2.5&&(e.inside=!1,e.alpha=Math.min(1,e.alpha+n*5),e.alpha>=1&&i.isOpen&&(t.phase=2)),!1;let o=a.tx*16+Tc,s=a.ty*16+11,c=o-e.x,l=s-e.y,u=Math.hypot(c,l),d=Cc*n;return e.alpha=1,u<=d?(e.x=o,e.y=s,e.tx=a.tx,e.ty=a.ty,i.release(e.id,r),e.setPose(`stand`),!0):(e.x+=c/u*d,e.y+=l/u*d,e.setPose(`walk`),!1)}stepElevIn(e,t,n,r){let i=this.elevators[t.elev]??this.elevators[0],a=this.spots.get(i.spotId);if(t.phase===0)return e.dir=`up`,e.setPose(`stand`),i.request(e.id),i.isOpen&&(t.phase=1),!1;if(t.phase===1){let r=a.x,i=a.y-6,o=r-e.x,s=i-e.y,c=Math.hypot(o,s),l=Cc*n;return e.dir=`up`,c<=l?(e.x=r,e.y=i,t.phase=2,e.dir=`down`,e.setPose(`stand`)):(e.x+=o/c*l,e.y+=s/c*l,e.setPose(`walk`)),!1}return e.alpha=Math.max(0,e.alpha-n*3.5),e.alpha<=0&&(e.inside=!0,i.release(e.id,r),!0)}stepStall(e,t,n,r){let i=this.spots.get(t.spot);if(!i)return!0;let a=i.furnitureId??i.id,o=i.tx*16+Tc,s=i.ty*16+11;if(t.phase===0){let o=i.x-e.x,s=i.y-e.y,c=Math.hypot(o,s),l=Cc*.8*n;return e.dir=`up`,e.setPose(`walk`),c>l?(e.x+=o/c*l,e.y+=s/c*l):(e.x=i.x,e.y=i.y),e.alpha=Math.max(0,e.alpha-n*4),c<=l&&e.alpha<=0&&(e.inside=!0,this.stallBusy.add(a),t.phase=1,e.stallUntil=r+t.ms),!1}if(t.phase===1)return r>=(e.stallUntil??0)&&(t.phase=2,this.stallBusy.delete(a),e.inside=!1,e.dir=`down`),!1;let c=o-e.x,l=s-e.y,u=Math.hypot(c,l),d=Cc*.8*n;return e.alpha=Math.min(1,e.alpha+n*4),e.dir=`down`,e.setPose(`walk`),u>d?(e.x+=c/u*d,e.y+=l/u*d,!1):(e.x=o,e.y=s,e.alpha=1,e.tx=i.tx,e.ty=i.ty,e.setPose(`stand`),!0)}stepSwitch(e,t,n){let r=this.rooms.get(t.room);if(!r)return!0;let i=r.layout.spots.find(e=>e.kind===`switch`);return i&&(e.dir=i.dir),t.phase===0?(e.setPose(`use`),e.stepT>=420&&(t.phase=1,(!t.onlyIfLast||Od(r.id,e.id,this.chars.values()))&&(!t.on||r.present)&&r.setLight(t.on,n)),!1):(e.setPose(`use`),e.stepT>=700&&(e.setPose(`stand`),!0))}interrupt(e){if(!(e.errand&&e.mode!==`leave`)){if(e.step&&!this.interruptible(e.step)){e.replan=!0,e.step.t===`stall`&&e.step.phase<=1&&(e.stallUntil=Math.min(e.stallUntil??0,this.now+2e3));return}this.clearPlan(e)}}interruptible(e){return e.t===`go`||e.t===`act`||e.t===`until`||e.t===`gather`||e.t===`do`}clearPlan(e){e.errand&&(e.errand=!1,this.inbox.errandAborted()),e.queue.length=0,e.step=null,e.thinkAt=0,this.releaseTemp(e);for(let t of this.rooms.values())t.switchClaim===e.id&&(t.switchClaim=null);e.gathering&&this.social.leave(e,this.now),e.chatUntil=0}releaseTemp(e){for(let t of e.tempSpots)t!==e.homeSpot&&this.spots.release(t,e.id);e.tempSpots.length=0}reserveTemp(e,t){return this.spots.reserve(t.id,e.id)?(e.tempSpots.push(t.id),!0):!1}think(e,t){if(e.gone)return!1;if(e.mode===`leave`)return this.planLeave(e,t);if(e.mode===`deliver`)return this.planDeliver(e,t);let n=this.player?.queueSlots().get(e.id);if(n!==void 0)return this.player.planQueue(e,n);let r=this.rooms.get(e.roomId);if(!r||!r.present)return this.planLobby(e,r);this.assignHome(e);let i=this.seatRoomOf(e);if(!e.homeSpot)return this.planOverflow(e,i);if(e.standTile=null,!i.lightOn&&i.phase!==`dismantling`&&!this.switchClaimValid(i)){i.switchClaim=e.id;let t=i.layout.spots.find(e=>e.kind===`switch`);if(t){let n=[];return this.pushLeave(e,n),n.push({t:`go`,tx:t.tx,ty:t.ty,fx:t.x,fy:t.y,dir:t.dir,run:e.mode===`wait`},{t:`until`,cond:()=>i.phase===`ready`,minMs:0,maxMs:6e3,dir:t.dir},{t:`switch`,room:i.id,on:!0,phase:0},{t:`do`,fn:()=>i.switchClaim===e.id&&(i.switchClaim=null)}),e.queue.push(...n),!0}}if(e.atSpot!==e.homeSpot)return this.planGoHome(e,t);if(e.arriving=!1,e.mode===`idle`&&!this.longIdle(e,t)&&(e.nextOutingAt||=t+Sd(e.rng,this.options().liveliness),t>=e.nextOutingAt)){if(this.planOuting(e,t))return!0;e.nextOutingAt=t+Sd(e.rng,this.options().liveliness)}if(e.mode===`shell`&&(e.nextSocialAt||=t+Sd(e.rng,this.options().liveliness)*1.3,t>=e.nextSocialAt)){e.nextSocialAt=t+Sd(e.rng,this.options().liveliness)*1.3;let n=q(e.info.seed);if(this.social.hasCompany(e,t)&&e.rng()<.5+n.sociability*.4&&this.social.tryInitiate(e,t,!0))return!0}return!1}pushLeave(e,t){e.atSpot&&t.push({t:`exit`})}planGoHome(e,t,n=`none`){let r=this.spots.get(e.homeSpot);if(!r)return!1;let i=[];this.pushLeave(e,i);let a=Td(Math.abs(r.tx-e.tx)+Math.abs(r.ty-e.ty),e.mode)&&(!e.arriving||e.mode===`wait`);return i.push({t:`go`,tx:r.tx,ty:r.ty,run:a,held:n},{t:`enter`,spot:r.id}),e.mode===`idle`&&i.push({t:`do`,fn:()=>e.nextOutingAt=this.now+Sd(e.rng,this.options().liveliness)}),e.queue.push(...i),!0}planLobby(e,t){let n=this.lobbyTile(e);return e.queue.push({t:`go`,tx:n.x,ty:n.y},{t:`until`,cond:()=>!!t&&t.present,minMs:800,maxMs:4e3,dir:`down`}),!0}planOverflow(e,t){let n=e.standTile&&!e.atSpot&&e.tx===e.standTile.x&&e.ty===e.standTile.y&&this.overflowFree(e.tx,e.ty,e)?e.standTile:this.overflowTile(e,t);if(!n)return this.planLobby(e,t);e.standTile=n,e.arriving=!1;let r=[];this.pushLeave(e,r);let i=t.layout.rect,a=ol(n.x*16,n.y*16,(i.x+5)*16,(i.y+6)*16);if(n.x!==e.tx||n.y!==e.ty||e.atSpot){let t=Math.abs(n.x-e.tx)+Math.abs(n.y-e.ty);r.push({t:`go`,tx:n.x,ty:n.y,dir:a,run:Td(t,e.mode)})}let o=e.mode===`wait`?`raise_hand`:e.mode===`work`?`read`:`stand`,s=e.mode===`work`?`laptop`:`none`;return r.push({t:`until`,cond:()=>this.hasFreeSeat(t,e),minMs:1500,maxMs:12e3,pose:o,held:s,dir:a}),e.queue.push(...r),!0}hasFreeSeat(e,t){return!!this.pickSeat(t)}overflowFree(e,t,n,r=this.busyTiles(n.id)){let i=this.building.grid;if(i.get(e,t)!==1||r.has(t*i.w+e))return!1;for(let n of this.spots.all())if(n.tx===e&&n.ty===t)return!1;return!0}overflowTile(e,t){let n=this.building.grid,r=t.layout.rect,i=t.layout.door,a=this.busyTiles(e.id),o=null,s=-1/0;for(let t=r.y+2;t<=r.y+10;t++)for(let c=r.x+1;c<=r.x+14;c++){if(!this.overflowFree(c,t,e,a)||i&&Math.abs(c-(i.x+i.w/2-.5))<=1.5&&Math.abs(t-(i.y+i.h/2-.5))<=2)continue;let r=(e,r)=>n.get(c+e,t+r)===0,l=0;for(let[e,r]of[[1,0],[-1,0],[0,1],[0,-1]])a.has((t+r)*n.w+c+e)&&l++;let u=(r(0,-1)||r(0,1)?2:r(1,0)||r(-1,0)?1:0)-(r(1,0)&&r(-1,0)||r(0,1)&&r(0,-1)?3:0)-l*3-(Math.abs(c-e.tx)+Math.abs(t-e.ty))*.05+e.rng()*.8;u>s&&(s=u,o={x:c,y:t})}return o}inPlayerZone(e,t){let n=Yc;return e>=n.x&&e<n.x+n.w&&t>=n.y&&t<n.y+n.h||this.spots.ofKind(`queue`).some(n=>n.tx===e&&n.ty===t)}lobbyTile(e){let t=this.building.core.find(e=>e.id===Uc).rect;for(let n=0;n<20;n++){let n=t.x+2+Math.floor(e.rng()*12),r=t.y+3+Math.floor(e.rng()*7);if(this.building.grid.get(n,r)===1&&!this.inPlayerZone(n,r))return{x:n,y:r}}return{x:t.x+6,y:t.y+9}}planDelegate(e,t){if(e.step||e.queue.length||e.atSpot!==e.homeSpot||!e.homeSpot)return;let n=this.seatRoomOf(e)?.layout.door,r=n?ol(e.x,e.y,(n.x+n.w/2)*16,(n.y+n.h/2)*16):`down`,i=e.homeSpot;e.queue.push({t:`exit`},{t:`until`,cond:()=>![...this.chars.values()].some(t=>t.info.parentId===e.id&&t.arriving),minMs:2600,maxMs:7500,pose:`talk`,held:`none`,dir:r},{t:`go`,tx:e.tx,ty:e.ty},{t:`enter`,spot:i}),e.setIcon(`chat`,2600,t)}planLeave(e,t){e.leaving=!0,e.arriving=!1,this.spots.releaseAll(e.id),e.homeSpot=null,e.tempSpots.length=0,e.gathering&&this.social.leave(e,t);let n=[];this.pushLeave(e,n);let r=this.seatRoomOf(e);if(r&&r.present&&r.lightOn&&!this.switchClaimValid(r)&&Od(r.id,e.id,this.chars.values())){let t=r.layout.spots.find(e=>e.kind===`switch`);t&&(r.switchClaim=e.id,n.push({t:`go`,tx:t.tx,ty:t.ty,fx:t.x,fy:t.y,dir:t.dir},{t:`until`,cond:()=>this.physicallyInside(r,e.id)===0,minMs:250,maxMs:9e3,dir:t.dir},{t:`switch`,room:r.id,on:!1,phase:0,onlyIfLast:!0},{t:`do`,fn:()=>r.switchClaim===e.id&&(r.switchClaim=null)}))}let i=this.pickElevator(e),a=this.spots.get(i.spotId);return n.push({t:`go`,tx:a.tx,ty:a.ty,fx:a.tx*16+Tc+(a.x-(a.tx*16+Tc))*.5,fy:a.ty*16+11-2,dir:`up`}),n.push({t:`elevIn`,elev:i.index,phase:0},{t:`remove`}),e.queue.push(...n),!0}planDeliver(e,t){let n=e.info.parentId?this.chars.get(e.info.parentId):void 0;if(!n||n.leaving||n.gone)return e.delivered=!0,e.mode=`leave`,this.planLeave(e,t);let r=this.besideTile(n,e),i=[];this.pushLeave(e,i);let o=e.rng()<.5?`papers`:`box`,s=e.info.title??a(`resultado`);return i.push({t:`go`,tx:r.x,ty:r.y,held:o},{t:`do`,fn:()=>{e.dir=ol(e.x,e.y,n.x,n.y),e.showBubble(`📦`,a(`Entregando: {0}`,[s]),3e3,this.now),e.setIcon(`box`,2800,this.now),n.setIcon(n.rng()<.5?`heart`:`check`,2800,this.now)}},{t:`act`,pose:`talk`,held:o,ms:2700},{t:`do`,fn:()=>{e.delivered=!0,e.mode=`leave`,this.social.delivered(e,this.now)}}),e.queue.push(...i),!0}besideTile(e,t){let n=this.building.grid,r=this.busyTiles(t.id,e.id),i=null,a=1/0;for(let[o,s]of[[-1,0],[1,0],[0,1],[0,-1],[-1,1],[1,1],[-1,-1],[1,-1]]){let c=e.tx+o,l=e.ty+s,u=n.get(c,l);if(u===0)continue;let d=Math.abs(c-t.tx)+Math.abs(l-t.ty)+(u===2?20:0)+(r.has(l*n.w+c)?40:0)+(o&&s?3:0);d<a&&(a=d,i={x:c,y:l})}return i??n.nearestWalkable(e.tx,e.ty)??{x:e.tx,y:e.ty}}busyTiles(e,t){let n=this.building.grid.w,r=new Set;for(let i of this.chars.values()){if(i.gone||i.id===e||i.id===t)continue;r.add(i.ty*n+i.tx);let a=i.step?.t===`go`?i.step:i.queue.find(e=>e.t===`go`);a&&r.add(a.ty*n+a.tx),i.standTile&&r.add(i.standTile.y*n+i.standTile.x)}return r}randomFree(e,t){let n=[];for(let r of e)for(let e of this.spots.ofKind(r))this.spots.isFree(e.id,t.id)&&n.push(e);return n.length?n[Math.floor(t.rng()*n.length)]:null}planOuting(e,t){let n={tx:e.tx,ty:e.ty},r=e.rng,i=q(e.info.seed);if(this.social.hasCompany(e,t)&&r()<.45+i.sociability*.4&&this.social.tryInitiate(e,t,!1))return!0;let a=bd(r,{coffee:!!this.spots.findFree(`coffee`,{by:e.id}),water:!!this.spots.findFree(`water`,{by:e.id}),bathroom:!!this.spots.findFree(`stall`,{by:e.id}),lounge:Wg.some(t=>!!this.spots.findFree(t,{by:e.id})),pingpong:!1,talk:!1,window:!!this.spots.findFree(`window`,{by:e.id}),shelf:!!this.spots.findFree(`shelf`,{by:e.id}),arcade:!!this.spots.findFree(`arcade`,{by:e.id}),snack:!!this.spots.findFree(`snack`,{by:e.id}),stretch:!0,mirror:!!this.social.plan(`mirror`,1,e),phone:!!this.randomFree(Gg,e)},Hm(i));if(!a)return!1;let o=[],s=(e,t=`none`)=>{o.push({t:`go`,tx:e.tx,ty:e.ty,fx:e.x,fy:e.y,dir:e.dir,held:t})},c=t=>o.push({t:`do`,fn:()=>this.spots.release(t.id,e.id)}),l=`none`;switch(a){case`coffee`:{let t=this.spots.findFree(`coffee`,{near:n,by:e.id,rng:r});if(!this.reserveTemp(e,t))return!1;if(this.pushLeave(e,o),s(t),o.push({t:`act`,pose:`use`,ms:1900,machine:t.furnitureId,icon:`coffee`},{t:`act`,pose:`drink`,held:`coffee`,ms:2600}),c(t),l=`coffee`,r()<.45){let n=this.spots.findFree(`cafe_seat`,{by:e.id,rng:r,near:{tx:t.tx,ty:t.ty}});n&&this.reserveTemp(e,n)&&(o.push({t:`go`,tx:n.tx,ty:n.ty,held:`coffee`},{t:`enter`,spot:n.id},{t:`act`,pose:`sit`,held:`coffee`,ms:Zg(r,6e3,15e3)},{t:`exit`}),c(n))}break}case`water`:{let t=this.spots.findFree(`water`,{near:n,by:e.id,rng:r});if(!this.reserveTemp(e,t))return!1;this.pushLeave(e,o),s(t),o.push({t:`act`,pose:`use`,ms:1e3},{t:`act`,pose:`drink`,held:`water`,ms:2500}),c(t),l=r()<.4?`water`:`none`;break}case`bathroom`:{let t=this.spots.findFree(`stall`,{by:e.id,rng:r});if(!this.reserveTemp(e,t))return!1;this.pushLeave(e,o),o.push({t:`go`,tx:t.tx,ty:t.ty},{t:`stall`,spot:t.id,ms:Zg(r,5e3,12e3),phase:0}),c(t);let n=this.spots.findFree(`sink`,{near:{tx:t.tx,ty:t.ty},by:e.id});n&&this.reserveTemp(e,n)&&(s(n),o.push({t:`act`,pose:`use`,ms:2200}),c(n));break}case`lounge`:{let t=this.randomFree(Wg,e);if(!t||!this.reserveTemp(e,t))return!1;this.pushLeave(e,o),o.push({t:`go`,tx:t.tx,ty:t.ty},{t:`enter`,spot:t.id}),r()<(J(i,`sonecas`)?.7:.25)?o.push({t:`act`,pose:`sit`,ms:Zg(r,3e3,6e3)},{t:`act`,pose:`sleep`,ms:Zg(r,8e3,16e3),icon:`zzz`}):o.push({t:`act`,pose:`sit`,ms:Zg(r,9e3,22e3),icon:r()<.3?`music`:void 0}),o.push({t:`exit`}),c(t);break}case`pingpong`:case`talk`:return this.social.tryInitiate(e,t,!1);case`mirror`:return this.social.startSolo(`mirror`,e,t);case`phone`:{let t=this.randomFree(Gg,e);if(!t||!this.reserveTemp(e,t))return!1;this.pushLeave(e,o),o.push({t:`go`,tx:t.tx,ty:t.ty},{t:`enter`,spot:t.id},{t:`act`,pose:`read`,held:`phone`,ms:Zg(r,8e3,18e3)},{t:`exit`}),c(t);break}case`window`:{let t=r()<.35?this.spots.findFree(`whiteboard`,{by:e.id,filter:t=>t.areaId===Dd(e)}):null,n=t??this.spots.findFree(`window`,{by:e.id,rng:r});if(!n||!this.reserveTemp(e,n))return!1;this.pushLeave(e,o),s(n),o.push({t:`act`,pose:t?`read`:`stand`,held:t?`papers`:`none`,ms:Zg(r,5e3,1e4),icon:r()<.3?`idea`:void 0}),c(n);break}case`shelf`:{let t=this.spots.findFree(`shelf`,{by:e.id,rng:r});if(!this.reserveTemp(e,t))return!1;this.pushLeave(e,o),s(t),o.push({t:`act`,pose:`read`,held:`book`,ms:Zg(r,5e3,9e3)}),c(t);break}case`arcade`:{let t=this.spots.findFree(`arcade`,{by:e.id,rng:r});if(!this.reserveTemp(e,t))return!1;this.pushLeave(e,o),s(t),o.push({t:`act`,pose:`use`,ms:Zg(r,6e3,12e3),icon:r()<.4?`star`:void 0}),c(t);break}case`snack`:{let t=this.spots.findFree(r()<.6?`snack`:`fridge`,{by:e.id,rng:r})??this.spots.findFree(`snack`,{by:e.id,rng:r});if(!t||!this.reserveTemp(e,t))return!1;this.pushLeave(e,o),s(t),o.push({t:`act`,pose:`use`,ms:1600},{t:`act`,pose:`stand`,ms:900}),c(t);break}case`stretch`:{let t=e.homeSpot;return t?(o.push({t:`exit`},{t:`act`,pose:`stretch`,ms:2600},{t:`enter`,spot:t}),o.push({t:`do`,fn:()=>e.nextOutingAt=this.now+Sd(e.rng,this.options().liveliness)}),e.queue.push(...o),!0):!1}}return e.queue.push(...o),this.pushHome(e,l),!0}pushHome(e,t){let n=this.spots.get(e.homeSpot);e.queue.push({t:`do`,fn:()=>this.releaseTemp(e)}),n&&(e.queue.push({t:`go`,tx:n.tx,ty:n.ty,held:t},{t:`enter`,spot:n.id}),e.queue.push({t:`do`,fn:()=>e.nextOutingAt=this.now+Sd(e.rng,this.options().liveliness)}))}restPose(e,t){let n=e.atSpot?this.spots.get(e.atSpot):void 0,r=!!n&&e.atSpot===e.homeSpot;if(!n){e.mode===`wait`?e.setPose(`raise_hand`):e.mode===`work`&&e.standTile?e.setPose(`read`,`laptop`):e.setPose(`stand`);return}if(n.kind===`stand`){e.dir=n.dir,e.mode===`work`?e.setPose(`read`,`laptop`):e.mode===`wait`?e.setPose(`raise_hand`):e.setPose(`stand`);return}if(!n.seated){e.setPose(`stand`);return}e.dir=n.dir;let i=n.kind===`stool`||n.kind===`nook`;r&&e.mode===`work`?e.setPose(`type`,i?`laptop`:`none`):r&&e.mode===`wait`?e.setPose(`raise_hand`):r&&e.mode===`shell`?this.shellPose(e,n,t):e.mode===`idle`&&this.longIdle(e,t)?e.setPose(`sleep`):e.setPose(`sit`)}shellPose(e,t,n){if(this.visit){e.setPose(`wait`);return}let r=n-e.shellSince;switch(e.shellStage??Fl(r)){case`popcorn`:e.setPose(`wait`,`popcorn`);return;case`restless`:e.dir=tu(Ql(r,e.info.seed),t.dir),e.setPose(`wait`);return;case`cobweb`:$l(r,e.info.seed)>=0?(n>e.chatUntil&&(e.chatEmoji=`🥱`,e.chatUntil=n+1300),e.setPose(`sleep`)):e.setPose(`wait`);return;case`nap`:e.setPose(`sleep`);return}}longIdle(e,t){return!this.visit&&Cd(e.info.status,e.info.statusSince,t)}*people(){let e=this.player?.ch;e&&!e.gone&&(yield e),yield*this.chars.values(),yield*this.inbox.couriers,this.visitor&&!this.visitor.gone&&(yield this.visitor)}person(e){return this.chars.get(e)??this.inbox.couriers.find(t=>t.id===e)??(this.visitor?.id===e?this.visitor:e===`player:me`?this.player?.ch??void 0:void 0)}queueSlots(){return this.player?.queueSlots()??new Map}stepActor(e,t,n){if(e.updateLane(t),e.step||(e.step=e.queue.shift()??null,e.stepT=0,e.stepStarted=!1),!e.step)return;let r=this.runStep(e,e.step,t,n);e.stepT+=t*1e3,r&&(e.step=null)}enablePlayer(){this.visit||this.player||(this.player=new dm(this))}spawnPlayer(e){let t=this.spots.ofKind(`player_desk`)[0];if(!t)return null;let n;try{n=this.art.appearanceFromSeed(e.seed,{look:e.look,sub:!1,parts:e.parts})}catch{return null}let r=new il(e,n);return this.snapTo(r,t),r.setPose(`sit`),this.spots.reserve(t.id,Zp),r}releasePlayerSeat(){this.spots.releaseAll(Zp)}setVisitor(e,t){let n=this.visitor;if(n)for(let e of this.elevators)e.release(n.id,t);if(this.visitor=null,this.visitorIntent={...jg},!e)return null;let r;try{r={...this.art.appearanceFromSeed(e.seed,{look:e.look,sub:!1,parts:e.parts}),lanyard:Ag}}catch{return null}let i=new il(e,r),a=this.elevators[0],o=a?this.spots.get(a.spotId):void 0;return!a||!o?null:(i.placeAtTile(o.tx,o.ty),i.x=o.x,i.y=o.y-6,i.dir=`down`,i.alpha=0,i.inside=!0,i.arriving=!0,i.hiddenUntil=a.reserveAppear(t),i.queue.push({t:`elevOut`,elev:a.index,phase:0}),this.visitor=i,i)}get visitorBusy(){let e=this.visitor;return!e||e.gone?!0:e.leaving||[e.step,...e.queue].some(e=>e?.t===`elevOut`||e?.t===`elevIn`)}visitorWalkTo(e,t,n=!1){let r=this.visitor;return!r||this.visitorBusy?!1:(r.queue.length=0,r.step=null,r.queue.push({t:`go`,tx:e,ty:t,run:n}),!0)}visitorElevator(){let e=this.visitor;if(!e||this.visitorBusy)return null;let t=Ng(e.x,e.y);for(let e of this.elevators){let n=this.spots.get(e.spotId);if(n&&Math.hypot(n.tx-t.x,n.ty-t.y)<=1.6)return e}return null}visitorExit(e){let t=this.visitor;if(!t||this.visitorBusy)return!1;let n=Ng(t.x,t.y),r=null;for(let e of this.elevators){let t=this.spots.get(e.spotId);if(!t)continue;let i=Math.hypot(t.tx-n.x,t.ty-n.y);(!r||i<r.d)&&(r={e,d:i,tx:t.tx,ty:t.ty})}return r?(t.queue.length=0,t.step=null,t.leaving=!0,this.visitorIntent={...jg},t.queue.push({t:`go`,tx:r.tx,ty:r.ty},{t:`elevIn`,elev:r.e.index,phase:0},{t:`do`,fn:e}),!0):!1}applyVisitLight(e,t=!1){if(!this.visit||this.visitLight===`live`)return;let n=t?e-1e4:e;for(let e of this.rooms.values())e.present&&!e.ghost&&(this.visitLight===`away`?e.lightOn&&this.occupants(e)===0&&!this.switchClaimValid(e)&&e.setLight(!1,n):!e.lightOn&&e.phase===`ready`&&e.setLight(!0,n))}runVisitor(e,t,n){e.animT+=t*1e3,e.icon&&n>=e.iconUntil&&(e.icon=null);let r=this.visitorIntent;if(!this.visitorBusy&&(r.dx||r.dy)){e.queue.length=0,e.step=null;let n=Lg(this.building.grid,{x:e.x,y:e.y,dir:e.dir},r,(r.run?wc:Cc)*t);e.x=n.x,e.y=n.y,e.dir=n.dir;let i=Ng(e.x,e.y);e.tx=i.x,e.ty=i.y,e.setPose(n.moved?r.run?`run`:`walk`:`stand`);return}if(e.step||(e.step=e.queue.shift()??null,e.stepT=0,e.stepStarted=!1),e.step){let r=this.runStep(e,e.step,t,n);e.stepT+=t*1e3,r&&(e.step=null),e.arriving&&!e.step&&!e.queue.length&&(e.arriving=!1);return}e.setPose(`stand`)}fastForward(e){this.now=e;for(let t of this.rooms.values())t.phase===`building`&&t.setPhase(`ready`,e-1e4),t.phase===`dismantling`&&t.setPhase(`gone`,e),t.lightAt=e-1e4;this.updateRooms(e);for(let e of this.elevators)e.reset();this.machineUntil.clear(),this.social.reset(e);for(let t of[...this.chars.values()]){for(let n=0;n<60&&!t.gone&&(t.step||=t.queue.shift()??null,t.step);n++)this.finishStep(t,t.step,e),t.step=null;if(t.gathering=null,t.leaving&&!t.gone&&(t.gone=!0),t.gone){this.spots.releaseAll(t.id),this.chars.delete(t.id);continue}if(t.alpha=1,t.inside=!1,t.arriving=!1,t.hiddenUntil=0,t.stepT=0,t.mode===`work`||t.mode===`wait`||t.mode===`idle`||t.mode===`shell`){t.reactUntil=0,this.assignHome(t);let n=this.spots.get(t.homeSpot);n?(this.snapTo(t,n),t.standTile=null):(t.atSpot=null,t.seated=!1,t.sortY=null,this.placeOverflow(t)),this.releaseTemp(t),t.nextOutingAt=e+Sd(t.rng,this.options().liveliness)}}for(let t of this.rooms.values())t.present&&this.occupants(t)>0&&t.setLight(!0,e-1e4),t.switchClaim=null;this.stallBusy.clear();let t=this.visitor;if(t){for(let n=0;n<10&&(t.step||=t.queue.shift()??null,t.step);n++){let n=t.step;t.step=null,n.t===`elevIn`?(t.inside=!0,t.alpha=0):this.finishStep(t,n,e)}t.leaving||(t.alpha=1,t.inside=!1,t.arriving=!1,t.hiddenUntil=0,t.setPose(`stand`))}this.visit&&this.applyVisitLight(e)}finishStep(e,t,n){switch(t.t){case`go`:e.placeAtTile(t.tx,t.ty),t.fx!==void 0&&t.fy!==void 0&&(e.x=t.fx,e.y=t.fy),t.dir&&(e.dir=t.dir);break;case`enter`:{let n=this.spots.get(t.spot);n&&this.snapTo(e,n);break}case`exit`:if(e.atSpot){let t=this.spots.get(e.atSpot);t&&e.placeAtTile(t.tx,t.ty)}e.atSpot=null,e.seated=!1,e.sortY=null;break;case`switch`:{let r=this.rooms.get(t.room);r&&(!t.onlyIfLast||Od(r.id,e.id,this.chars.values()))&&r.setLight(t.on,n-1e4);break}case`stall`:{let n=this.spots.get(t.spot);n&&e.placeAtTile(n.tx,n.ty);break}case`elevOut`:{let n=this.elevators[t.elev]??this.elevators[0],r=this.spots.get(n.spotId);r&&e.placeAtTile(r.tx,r.ty);break}case`do`:t.fn();break;case`remove`:case`elevIn`:e.gone=!0}}},e_=160,t_=1100,n_=class{sim;camera;rng;doors=[];keysAt=0;nextKeysAt=0;nextArcadeAt=0;rally=new Map;constructor(e,t,n=Math.random){this.sim=e,this.camera=t,this.rng=n}update(e,t){let n=this.camera.screenToWorld(0,0),r=this.camera.screenToWorld(this.camera.viewW,this.camera.viewH),i={x0:n.x,y0:n.y,x1:r.x,y1:r.y},a=Math.max(.45,Math.min(1,.25+this.camera.zoom*.25));this.elevators(i,t),this.keys(e,i,a,t),this.social(e,i,a,t)}pan(e,t){let n=Math.max(1,(t.x1-t.x0)/2);return Math.max(-.7,Math.min(.7,(e-(t.x0+t.x1)/2)/n*.7))}inView(e,t,n,r=16){return e>n.x0-r&&e<n.x1+r&&t>n.y0-r&&t<n.y1+r}elevators(e,t){this.sim.elevators.forEach((n,r)=>{let i=this.doors[r];if(this.doors[r]=n.door,i===void 0||i>.01||n.door<=.01)return;let a=this.sim.spots.get(n.spotId);a&&t({kind:`elevator`,gain:this.inView(a.x,a.y,e,24)?1:.5,pan:this.pan(a.x,e)})})}keys(e,t,n,r){if(e-this.keysAt<e_)return;this.keysAt=e;let i=0,a=0;for(let e of this.sim.chars.values())r_(e)&&this.inView(e.x,e.y,t)&&(i++,a+=e.x);!i||e<this.nextKeysAt||this.rng()>Math.min(.8,.3+.12*i)||(this.nextKeysAt=e+(700+this.rng()*1500)/Math.sqrt(Math.min(i,6)),r({kind:`keys`,gain:n*Math.min(1,.6+.1*i),pan:this.pan(a/i,t),count:2+Math.floor(this.rng()*5)}))}social(e,t,n,r){let i=new Set;for(let a of this.sim.social.gatherings){if(a.phase!==`run`||a.kind!==`pingpong`&&a.kind!==`arcade`)continue;let o=0,s=0,c=0;for(let e of a.members){if(e.role!==`player`||e.left)continue;let t=this.sim.chars.get(e.id);t&&(o+=t.x,s+=t.y,c++)}if(c&&(o/=c,s/=c,this.inView(o,s,t,24))){if(a.kind===`pingpong`){i.add(a.id);let s=Math.floor((e-a.startAt)%(t_*2)/(t_/2)),c=this.rally.get(a.id);this.rally.set(a.id,s),c!==void 0&&c!==s&&r({kind:s%2==0?`pingpong`:`table`,gain:n,pan:this.pan(o,t)})}else e>=this.nextArcadeAt&&(this.nextArcadeAt=e+500+this.rng()*900,r({kind:`arcade`,gain:n*.8,pan:this.pan(o,t)}))}}for(let e of this.rally.keys())i.has(e)||this.rally.delete(e)}};function r_(e){return e.mode===`work`&&e.seated&&e.pose===`type`&&!e.leaving&&!e.inside&&e.alpha>.5}function i_(e,t,n,r=1){if(n<=0||t<=0)return!0;let i=1e3/n;return e-t>=i-r}function a_(e,t){if(e.length===0)return 0;if(e.length===1)return e[0];let n=t/100*(e.length-1),r=Math.floor(n),i=Math.ceil(n),a=n-r;return Math.round((e[r]*(1-a)+e[i]*a)*10)/10}function o_(e,t){if(e.length===0)return{fps:0,p50:0,p95:0};let n=[...e].sort((e,t)=>e-t),r=a_(n,50),i=a_(n,95),a=0;if(t.length>=2){let e=(t[t.length-1]-t[0])/1e3;e>0&&(a=Math.round((t.length-1)/e))}else if(e.length>0){let t=e[e.length-1];a=t>0?Math.round(1e3/t):60}return{fps:a,p50:r,p95:i}}function s_(e){return e>50}function c_(e){return e>100}function l_(e){return e>0&&e<30}function u_(e,t=96,n=20,r=2){if(e.length===0)return``;if(e.length===1){let e=Math.round(n/2);return`0,${e} ${t},${e}`}let i=Math.min(...e),a=Math.max(...e)-i||1,o=n-r*2,s=(t-r*2)/(e.length-1);return e.map((e,t)=>{let n=r+t*s,c=r+o-(e-i)/a*o;return`${Math.round(n*10)/10},${Math.round(c*10)/10}`}).join(` `)}var d_=1500;function f_(e){if(e.lastDrawAt<=0)return`first`;if(e.dirty)return`dirty`;if(e.now<e.settleUntil)return`settling`;if(e.cameraMoving)return`camera`;if(e.timelapse)return`timelapse`;if(e.visit)return`visit`;if(e.actorsLive)return`actors`;if(e.socialLive)return`social`;if(e.fxLive)return`fx`;if(e.roomsLive)return`rooms`;if(e.propsLive)return`props`;if(e.particles)return`particles`;if(e.cars)return`cars`;if(e.night)return`night`;if(e.seasonal)return`seasonal`;if(e.highlight)return`highlight`;let t=e.now-e.lastDrawAt;return e.people?t>=100?`ambient`:null:t>=1e3?`heartbeat`:null}var p_=new Set([`stand`,`sit`,`sleep`]);function m_(e,t){return!!(e.mode!==`idle`||e.step||e.queue.length>0||!p_.has(e.pose)||e.alpha!==1||e.leaving||e.arriving||e.hiddenUntil>t||e.icon||e.bubbleText&&t<e.bubbleUntil||e.sayText&&t<e.sayUntil||e.chatEmoji&&t<e.chatUntil)}function h_(e,t){let n=!1,r=!1;for(let i of e.people)i.inside||(n=!0,!r&&m_(i,t)&&(r=!0));let i=!1;for(let n of e.rooms){let e=n.light(t);if(n.phase!==`ready`||e>0&&e<1){i=!0;break}}let a=e.stallsBusy.size>0;if(!a)for(let n of e.machinesUntil)n>t&&(a=!0);if(!a)for(let t of e.elevatorDoors)t>0&&(a=!0);return{actorsLive:r,socialLive:e.gatherings.size>0||e.floaters.length>0,fxLive:e.roomFxActive.size>0||e.intrusionEnd>t,roomsLive:i,propsLive:a,people:n}}var g_=Ho;function __(e,t,n={}){let r={...ue},i=!!n.visit,o=new yl,s=new $g(g_,()=>r,void 0,{visit:i}),c=null,l={name:a(`Você`),look:`m`,seed:1};t.mock&&!i&&(c=l);let u=cu,d=null,f=new Set,p=null,m=``,h=new du({setAttention:(e,t)=>s.player?.setAttention(e,t),noteAttention:(e,t)=>s.player?.noteAttention(e,t),setAway:(e,t)=>s.player?.setAway(e,t),returned:(e,t)=>{s.player?.returned(e,t),f.forEach(t=>t(e))}},{thresholds:()=>u,toLocal:e=>d?d.toLocalTime(e):e}),g=()=>{if(i||b)return;s.enablePlayer();let e=s.player;if(!e)return;let t=Date.now(),n=c?JSON.stringify(c):``;(e!==p||n!==m)&&e.setLook(c,t),e!==p&&(e.adoptAttention(h.attention,t),e.setAway(h.stage,t)),p=e,m=n},_=new Kp(e,g_,s,o),v=new dd(_.ctx,s,_,o),y=null,b=null,x=0,S=new Set,C=new Set,w=new Set,ee=new Set,te=new Set,T=new n_(s,o),E=null,D=null,ne=null,re=0,ie=0,ae=0,oe=!1,se=0,ce=!1,le=!1,de=-1,fe=new AbortController,pe=1,me=0,he=``,ge=``,_e=0,ve=0,be=0,xe=()=>void pe++,Se=()=>{let t=Math.max(1,Math.min(3,window.devicePixelRatio||1)),n=e.clientWidth||window.innerWidth,r=e.clientHeight||window.innerHeight,i=Math.floor(n*t),a=Math.floor(r*t);(e.width!==i||e.height!==a)&&(e.width=i,e.height=a),o.setView(n,r,t),we(),xe()},Ce=()=>({x:0,y:0,w:s.building.cols*16*16,h:464}),we=()=>{let e=Ce();o.bounds={x:e.x-112,y:e.y-96,w:e.w+224,h:e.h+288};let t=o.fitZoom(e,16);o.minZoom=Math.min(1,Math.max(.25,t)),o.clamp()},O=()=>{let e=_l(Ce(),o.viewW,o.viewH,o.insets),t=Math.max(o.minZoom,e.zoom),n=o.snapZoom(t,`down`),r=n>=t*.82?n:t,i=Math.min(r,4),a=o.centerFor(e.cx,e.cy,i);return{x:a.x,y:a.y-e.dy/i,zoom:i}},Te=(e=!0)=>{o.follow=null;let t=O();e?o.animateTo(t.x,t.y,t.zoom,Date.now(),420):(o.stop(),o.x=t.x,o.y=t.y,o.zoom=t.zoom,o.clamp())},Ee=()=>S.forEach(e=>e(E)),De=(e,t)=>e===t||!!e&&!!t&&e.type===t.type&&e.id===t.id,Oe=(e,t=!1)=>{let n=pu(e,Zp),i=De(n,E);E=n,r.followSelected&&(o.follow=n?.type===`agent`?n.id:null),t&&n&&(n.type===`agent`?ke(n.id,{follow:r.followSelected}):k(n.id)),i||Ee()},ke=(e,t={})=>{let n=e===`player:me`?void 0:s.person(e);if(!n)return;ce=!0;let r=Math.max(o.zoom,o.snapZoom(3)),i=o.centerFor(n.x,n.y-12,r);o.animateTo(i.x,i.y,r,Date.now(),420),o.follow=t.follow?e:null},k=e=>{let t=s.rooms.get(e);if(!t)return;ce=!0,o.follow=null;let n=t.layout.rect,r={x:n.x*16,y:n.y*16-8,w:n.w*16,h:n.h*16+16},i=o.fitZoom(r,40),a=Math.min(4,Math.max(o.minZoom,o.snapZoom(i,`down`))),c=o.centerFor(r.x+r.w/2,r.y+r.h/2,a);o.animateTo(c.x,c.y,a,Date.now(),420)},Ae=(e,t=o.viewW/2,n=o.viewH/2)=>{ce=!0,o.zoomAt(o.stepZoom(e),t,n,Date.now(),!0)};function*je(){for(let e of _.heads)e[0]!==`visita:eu`&&!e[0].startsWith(`@courier`)&&(yield e)}let Me=(e,t)=>{let n=o.screenToWorld(e,t),r=Math.max(1,3/o.zoom),i=Math.floor(n.x/16),a=Math.floor(n.y/16),c=fu(je(),n,r,{playerId:Zp,inOwnOffice:Hc(Yc,i,a)});if(c)return{type:`agent`,id:c};let l=s.roomIdAt(i,a);return l?{type:`room`,id:l}:null},Ne=t=>{t!==D&&(D=t,e.style.cursor=t?`pointer`:`grab`,C.forEach(e=>e(t)))},Pe=(e,t)=>{if(e?.type===`agent`)return Oe(e);Oe(null);let n=o.screenToWorld(t.x,t.y);s.visitorWalkTo(Math.floor(n.x/16),Math.floor(n.y/16))&&Fe()},Fe=()=>{s.visitor&&(ce=!0,o.follow=kg)},Ie=(e,t)=>{let n=_.inboxRect;if(!n||i||b)return!1;let r=o.screenToWorld(e,t),a=Math.max(1,3/o.zoom);return r.x>=n.x-a&&r.x<=n.x+n.w+a&&r.y>=n.y-a&&r.y<=n.y+n.h+a},Le=new Set,Re=!1,ze=_u(e,o,{pick:Me,click:(e,t)=>{let n=pu(e,Zp);return n?.type!==`agent`&&Ie(t.x,t.y)?Le.forEach(e=>e()):i?Pe(n,t):Oe(n)},doubleClick:e=>{let t=pu(e,Zp);t?.type===`agent`?(Oe(t),ke(t.id,{follow:!0})):t?.type===`room`&&k(t.id)},hover:(e,t,n)=>{ne=n?{x:e,y:t}:null,n||Ne(null)},interact:()=>{ce=!0,o.follow=null,o.stop()},overview:()=>Te(!0),zoomStep:Ae,active:()=>!oe,keys:()=>!i}),Be=()=>{let e=t.snapshot;if(e){xe();try{b?s.applySnapshot(yu(e,x-e.serverTime),x):s.applySnapshot(e,Date.now())}catch(e){console.error(`[mundo] snapshot inválido ignorado`,e)}}},Ve=t.on(`snapshot`,Be),He=t.on(`avatar`,e=>{c=e,g(),xe()}),Ue=i?()=>{}:t.on(`attention`,e=>h.onAttention(e,Date.now())),We=i?()=>{}:t.on(`presence`,e=>{d?.noteServerTime(e.now),h.onPresence(e,Date.now())}),Ge=e=>{let n=Cs(t.inboxItems).length;if(s.inbox.set(n),!e||i||b)return;let r={a:o.screenToWorld(0,0),b:o.screenToWorld(o.viewW,o.viewH)},a=Yc,c=Ds(e,{ownerRoomVisible:!document.hidden&&!oe&&!!s.player?.ch&&r.b.x>=a.x*16&&r.a.x<=(a.x+a.w)*16&&r.b.y>=a.y*16&&r.a.y<=(a.y+a.h)*16,reducedMotion:ac(),hasAgent:e=>s.chars.has(e)}),l=Date.now();c?.kind===`agent`&&s.inbox.agentErrand(c.agentId,l)||c&&s.inbox.courierErrand(l)},Ke=i?()=>{}:t.on(`inbox`,e=>(Ge(e),xe()));Ge(),g(),t.snapshot&&Be(),hl(fe.signal).then(e=>{e&&(y=e,_.setAssets(e),xe())}),document.fonts&&document.fonts.addEventListener?.(`loadingdone`,()=>{v.resetCaches(),xe()},{signal:fe.signal});let qe=0,Je=new Set,Ye=t=>{if(re=requestAnimationFrame(Ye),document.hidden&&r.pauseOnHidden!==!1||!i_(t,qe,r.fpsCap??60))return;qe=t;let n=performance.now(),a=!1,c=Date.now(),l=ie?Math.min(.1,Math.max(0,(t-ie)/1e3)):1/60;ie=t;let u=l*(b?Math.max(0,b.scale()):1);b&&(x+=u*1e3);let d=b?x:c;try{let n=Math.max(1,Math.min(3,window.devicePixelRatio||1));(e.clientWidth!==o.viewW||e.clientHeight!==o.viewH||n!==o.dpr)&&Se(),s.update(u,d),b||h.tick(c);let f=s.social.events;if(f.length){if(!b)for(let e of f)for(let t of w)t(e);f.length=0}let p=ye(r.theme,new Date);_.sync(p),s.building.cols!==de&&(de=s.building.cols,we(),!le&&s.initialized?(Te(!1),le=!0):ce||Te(!0)),i&&s.visitor&&(s.visitorIntent.dx||s.visitorIntent.dy)&&o.follow!==`visita:eu`&&Fe();let m=o.follow?s.person(o.follow):void 0;o.follow&&!m&&(o.follow=null),o.update(c,m?o.centerFor(m.x,m.y-12,o.zoom):null,l),be+=u;let g=`${o.x}|${o.y}|${o.zoom}|${o.viewW}|${o.viewH}|${o.dpr}`,y=`${E?.type}:${E?.id}|${D}|${p}|${r.showNames}|${r.bubbles}|${r.dayNight}|${r.daylight}|${r.liveliness}`,x=pe!==me||y!==he;x&&(ve=t+d_);let S=h_({people:s.people(),gatherings:s.social.gatherings,floaters:s.social.floaters,roomFxActive:s.roomFx.active,intrusionEnd:s.intrusionEffect?.end??0,rooms:s.rooms.values(),machinesUntil:s.machineUntil.values(),stallsBusy:s.stallBusy,elevatorDoors:s.elevators.map(e=>e.door)},d),C=f_({now:t,lastDrawAt:_e,dirty:x,settleUntil:ve,cameraMoving:g!==ge,timelapse:!!b,visit:i,...S,particles:_.particles.count>0,cars:_.cars.length>0,night:_.night>.01,seasonal:p!==`none`,highlight:E!==null||D!==null});if(ge=g,C){a=!0,_e=t,me=pe,he=y;let e=be;be=0,_.frame(d,e,r,{agent:E?.type===`agent`?E.id:null,room:E?.type===`room`?E.id:null,hover:D}),v.draw(d,r,{agent:E?.type===`agent`?E.id:null,room:E?.type===`room`?E.id:null,hover:D}),_.pruneHeads()}if(ee.size&&!b&&T.update(d,e=>ee.forEach(t=>t(e))),ne){let t=Me(ne.x,ne.y);Ne(t?.type===`agent`?t.id:null);let n=t?.type!==`agent`&&Ie(ne.x,ne.y);n!==Re&&(Re=n,e.style.cursor=n||D?`pointer`:`grab`)}E?.type===`agent`&&!s.chars.has(E.id)&&Oe(null),E?.type===`room`&&!s.rooms.has(E.id)&&Oe(null)}catch(e){console.error(`[mundo] erro no frame`,e)}finally{if(a&&Je.size>0){let e=performance.now()-n;for(let t of Je)t(e)}}},Xe=()=>{if(!oe){if(document.hidden){ae=Date.now();return}ie=0,qe=0,xe(),ae&&Date.now()-ae>5e3&&s.fastForward(b?x:Date.now()),ae=0}},Ze=t=>{if(!te.size)return;let n=e.getBoundingClientRect(),r=t.clientX-n.left,i=t.clientY-n.top,a=Me(r,i),c=o.screenToWorld(r,i),l=a?.type===`room`?a.id:a?.type===`agent`?s.chars.get(a.id)?.roomId??null:s.roomIdAt(Math.floor(c.x/16),Math.floor(c.y/16));l&&s.rooms.has(l)&&(t.preventDefault(),te.forEach(e=>e(l,{x:t.clientX,y:t.clientY})))};e.addEventListener(`contextmenu`,Ze),window.addEventListener(`resize`,Se),document.addEventListener(`visibilitychange`,Xe),Se(),re=requestAnimationFrame(Ye);let Qe=()=>{ce=!0,xe()},$e=ru(s,_,o,Qe),et=()=>{if(s.social.wallets.save(Date.now()),s=new $g(g_,()=>r,b?null:void 0,{visit:i}),g(),s.inbox.set(i||b?0:Cs(t.inboxItems).length),_=new Kp(e,g_,s,o),y&&_.setAssets(y),b){let e=b;_.clock=()=>e.clock()}v=new dd(_.ctx,s,_,o),$e=ru(s,_,o,Qe),T=new n_(s,o),de=-1,Ne(null),xe()};return{select:(e,t)=>Oe(e,!!t?.focus),getSelection:()=>E,onSelect:e=>(S.add(e),()=>void S.delete(e)),onHover:e=>(C.add(e),()=>void C.delete(e)),onInboxClick:e=>(Le.add(e),()=>void Le.delete(e)),focusAgent:ke,focusRoom:k,overview:()=>{ce=!1,Te(!0)},zoomBy:e=>{if(!Number.isFinite(e)||e<=0||e===1)return;let t=o.snapZoom(o.zoom*e,e>1?`up`:`down`);Math.abs(t-o.zoom)<.001?Ae(e>1?1:-1):(ce=!0,o.zoomAt(t,o.viewW/2,o.viewH/2,Date.now(),!0))},getOptions:()=>({...r}),setOptions:e=>{r={...r,...e},xe(),e.followSelected!==void 0&&(o.follow=e.followSelected&&E?.type===`agent`?E.id:null)},setViewInsets:e=>{let t=(e,t)=>typeof e==`number`&&Number.isFinite(e)?Math.max(0,e):t,n=o.insets;o.insets={top:t(e.top,n.top),right:t(e.right,n.right),bottom:t(e.bottom,n.bottom),left:t(e.left,n.left)},we(),xe(),!ce&&le&&Te(!0)},screenPositionOf:e=>{let t=_.heads.get(e);if(!t||!t.visible)return null;let n=o.worldToScreen(t.x,t.y-2);return n.x<0||n.y<0||n.x>o.viewW||n.y>o.viewH?null:n},social:e=>s.social.info(e),onRoomContextMenu:e=>(te.add(e),()=>void te.delete(e)),onSocialEvent:e=>(w.add(e),()=>void w.delete(e)),setPlayback:e=>{b=e,x=e?e.clock():0,et()},onSound:e=>(ee.add(e),()=>void ee.delete(e)),onFrameMetric:e=>(Je.add(e),()=>void Je.delete(e)),setSuspended:e=>{if(e!==oe){if(oe=e,e){cancelAnimationFrame(re),se=Date.now(),Ne(null),ne=null;return}ie=0,xe(),se&&Date.now()-se>5e3&&s.fastForward(b?x:Date.now()),se=0,ae=0,re=requestAnimationFrame(Ye)}},destroy:()=>{cancelAnimationFrame(re),fe.abort(),Ve(),He(),Ue(),Ke(),We(),f.clear(),ze(),window.removeEventListener(`resize`,Se),e.removeEventListener(`contextmenu`,Ze),document.removeEventListener(`visibilitychange`,Xe),S.clear(),C.clear(),w.clear(),ee.clear()},get debug(){return $e},avatar:{setLook:e=>{c=e,g()},bindAttention:e=>{d=e;let t=e.onLocal(e=>h.onAttention(e,Date.now()));return()=>{t(),d===e&&(d=null)}},setThresholds:e=>{u=e},onReturned:e=>(f.add(e),()=>void f.delete(e))},visit:{setVisitor:e=>{i&&s.setVisitor(e?Mg(e,Date.now()):null,Date.now())},setIntent:e=>{s.visitorIntent=i?{...e}:{...jg}},setLight:e=>{i&&s.visitLight!==e&&(s.visitLight=e,s.applyVisitLight(Date.now()))},atExit:()=>i&&!!s.visitorElevator(),exit:e=>!i||!s.visitorExit(e)?!1:(Fe(),!0),visitorScreen:()=>{let e=_.heads.get(kg);if(!e||!e.visible)return null;let t=o.worldToScreen(e.x,e.y-2);return t.x<0||t.y<0||t.x>o.viewW||t.y>o.viewH?null:t},boardScreen:()=>{let e=i?_.paintingRect(Uc):null;if(!e)return null;let t=o.worldToScreen(e.x,e.y),n=o.worldToScreen(e.x+e.w,e.y+e.h);return n.x<0||n.y<0||t.x>o.viewW||t.y>o.viewH?null:{x:t.x,y:t.y,w:n.x-t.x,h:n.y-t.y}}}}}function v_(e){return e.visible&&e.focused?0:Math.max(0,e.now-e.lastInputAt)}var y_={"Content-Type":`application/json`};function b_(){let e=globalThis.crypto;return e&&typeof e.randomUUID==`function`?e.randomUUID().replace(/-/g,``).slice(0,16):e&&typeof e.getRandomValues==`function`?Array.from(e.getRandomValues(new Uint8Array(8)),e=>e.toString(16).padStart(2,`0`)).join(``):Math.random().toString(16).slice(2,10)+Date.now().toString(16).slice(-8)}var x_=2e3,S_=class{screenId;fetchFn;now;mock;local=new Set;openAgent=null;offset=0;constructor(e={}){this.fetchFn=e.fetch??(typeof fetch==`function`?fetch.bind(globalThis):void 0),this.now=e.now??Date.now,this.mock=!!e.mock,this.screenId=e.screenId??b_()}onLocal(e){return this.local.add(e),()=>void this.local.delete(e)}get serverOffsetMs(){return this.offset}noteServerTime(e){Number.isFinite(e)&&(this.offset=e-this.now())}toLocalTime(e){return e-this.offset}report(e,t,n){e===`open`?this.openAgent=t:e===`close`&&this.openAgent===t&&(this.openAgent=null);let r={screenId:this.screenId,kind:e,agentId:t,...n?{verdict:n}:{}};if(this.mock){let e={...r,at:this.now()};this.local.forEach(t=>t(e));return}this.post(`/api/attention`,r)}startHeartbeat(e){if(this.mock)return()=>{};let t=e(),n=t.visible&&t.focused?this.now():0,r=-1/0,i=()=>{let t=e();t.visible&&t.focused&&(n=this.now());let r=v_({now:this.now(),lastInputAt:Math.max(t.lastInputAt,n),visible:t.visible,focused:t.focused});this.post(`/api/presence`,{screenId:this.screenId,idleMs:r})},a=()=>{let e=this.now();e-r<x_||(r=e,i())};i();let o=setInterval(i,su),s=()=>{this.openAgent&&this.post(`/api/attention`,{screenId:this.screenId,kind:`close`,agentId:this.openAgent},!0)},c=e=>{e.persisted&&(this.openAgent&&this.post(`/api/attention`,{screenId:this.screenId,kind:`open`,agentId:this.openAgent}),i())},l=()=>{n=this.now()},u=()=>{l(),e().visible&&a()},d=typeof addEventListener==`function`;return d&&(addEventListener(`pagehide`,s),addEventListener(`pageshow`,c),addEventListener(`blur`,l),addEventListener(`focus`,a),addEventListener(`visibilitychange`,u)),()=>{clearInterval(o),d&&typeof removeEventListener==`function`&&(removeEventListener(`pagehide`,s),removeEventListener(`pageshow`,c),removeEventListener(`blur`,l),removeEventListener(`focus`,a),removeEventListener(`visibilitychange`,u))}}post(e,t,n=!1){try{let r={method:`POST`,headers:y_,body:JSON.stringify(t)};n&&(r.keepalive=!0),this.fetchFn?.(e,r)?.catch(()=>{})}catch{}}};function C_(e,t){return t||(e?.type===`agent`?e.id:null)}var w_=class{ctx;sink;enabled;current=null;wasDisabled=!1;offs;constructor(e,t,n,r=()=>!0){this.ctx=e,this.sink=t,this.enabled=r,this.offs=[n.on(`sent`,({agentId:e})=>this.emit(`send`,e)),n.on(`decided`,({agentId:e,verdict:t})=>this.emit(`decide`,e,t))]}render(){if(!this.enabled()){this.wasDisabled=!0;return}let e=this.wasDisabled;this.wasDisabled=!1;let t=C_(this.ctx.selection(),this.ctx.terminals?.openAgentId??null);if(t===this.current&&!(e&&t))return;let n=this.current;this.current=t,t?this.emit(`open`,t):n&&this.emit(`close`,n)}dispose(){this.offs.forEach(e=>e())}emit(e,t,n){this.enabled()&&this.sink.report(e,t,n)}},T_=[`keydown`,`pointerdown`,`pointermove`,`wheel`,`touchstart`];function E_(e,t,n=Date.now){let r=n(),i=()=>{r=n()},a={capture:!0,passive:!0};for(let t of T_)e.addEventListener(t,i,a);return{read:()=>({lastInputAt:r,visible:t.visibilityState===`visible`,focused:t.hasFocus()}),dispose:()=>{for(let t of T_)e.removeEventListener(t,i,a)}}}var D_=`<svg class="ui-px-icon" width="20" height="20" viewBox="0 0 10 10" shape-rendering="crispEdges" aria-hidden="true" focusable="false"><path fill="currentColor" d="M0 9h10v1H0zM1 5h2v4H1zM4 2h2v7H4zM7 4h2v5H7z"/></svg>`,O_=class{ctx;mount;button;panel=null;loading=null;constructor(e,t){this.ctx=e,this.mount=t,this.button=j(D_,a(`Meu dia: para onde foi o tempo (M)`),()=>this.toggle()),this.button.setAttribute(`aria-haspopup`,`dialog`),e.store.mock&&this.load()}toggle(){this.panel?this.panel.toggle():this.load().then(e=>e.open()).catch(()=>this.ctx.announce(a(`Não foi possível abrir o painel Meu dia.`)))}render(){this.panel?.render()}load(){return this.loading??=o(()=>import(`./daystats-BaQmwDUl.js`).then(e=>{let t=new e.DayPanel(this.ctx,this.button);return this.mount(t.el),this.panel=t,t}),__vite__mapDeps([0,1,2,3,4,5])),this.loading.catch(()=>this.loading=null),this.loading}},k_=e=>String(e).padStart(2,`0`);function A_(e){let t=new Date(e);return`${t.getFullYear()}-${k_(t.getMonth()+1)}-${k_(t.getDate())}`}function j_(e){if(typeof e!=`string`)return!1;let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return!1;let[n,r,i]=[Number(t[1]),Number(t[2]),Number(t[3])];if(n<2e3||r<1||r>12||i<1)return!1;let a=new Date(Date.UTC(n,r-1,i));return a.getUTCFullYear()===n&&a.getUTCMonth()===r-1&&a.getUTCDate()===i}function M_(e){let[t,n,r]=e.split(`-`).map(Number);return new Date(t,n-1,r).getTime()}function N_(e,t){let[n,r,i]=e.split(`-`).map(Number);return A_(new Date(n,r-1,i+t,12).getTime())}var P_=e=>e.startsWith(`demo:`);function F_(e){return{rooms:new Map(e.rooms.map(e=>[e.id,e])),agents:new Map(e.agents.map(e=>[e.id,e])),accounts:new Map(e.accounts.map(e=>[e.id,e]))}}function I_(){return{rooms:new Map,agents:new Map,accounts:new Map}}var L_=e=>typeof e.id==`string`&&typeof e.roomId==`string`&&typeof e.name==`string`&&typeof e.status==`string`&&typeof e.seed==`number`;function R_(e,t){for(let[n,r]of t.rooms??[])r?e.rooms.set(n,r):e.rooms.delete(n);for(let[n,r]of t.accounts??[])r?e.accounts.set(n,r):e.accounts.delete(n);for(let[n,r]of t.agents??[]){if(!r){e.agents.delete(n);continue}let t=e.agents.get(n);if(!t){L_(r)&&e.agents.set(n,z_(r));continue}let i={...t};for(let[e,t]of Object.entries(r))t===null?delete i[e]:i[e]=t;e.agents.set(n,i)}}function z_(e){let t={};for(let[n,r]of Object.entries(e))r!==null&&(t[n]=r);return t}function B_(e){let t=[],n=-1/0;for(let r of e.split(`
3
- `)){if(!r.trim())continue;let e;try{e=JSON.parse(r)}catch{continue}V_(e)&&(e.at<n&&(e.at=n),n=e.at,t.push(e))}return t}function V_(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.at!=`number`||!Number.isFinite(t.at)?!1:t.t===`k`?Array.isArray(t.rooms)&&Array.isArray(t.agents)&&Array.isArray(t.accounts)&&typeof t.every==`number`:t.t===`d`?[`rooms`,`agents`,`accounts`].every(e=>t[e]===void 0||Array.isArray(t[e])):t.t===`end`}var H_={toolCalls:0,tokensIn:0,tokensOut:0,subagents:0};function U_(e,t){return`tl:${e}:${t.at}:${t.kind}`}function W_(e,t){let n={id:U_(e,t),kind:t.kind,icon:t.icon,text:t.text,at:t.at};return t.tool&&(n.tool=t.tool),t.error&&(n.error=!0),n}function G_(e,t=[]){let n=e.activity?W_(e.id,e.activity):void 0,r={id:e.id,kind:e.kind,roomId:e.roomId,name:e.name,look:e.look,role:e.role,sessionId:e.id,account:e.account,status:e.status,recent:t.length?t.slice():n?[n]:[],tasks:[],startedAt:e.startedAt,lastEventAt:Math.max(e.statusSince,n?.at??0),statusSince:e.statusSince,stats:{...H_},seed:e.seed};return e.provider&&(r.provider=e.provider),e.parentId&&(r.parentId=e.parentId),e.title&&(r.title=e.title),e.waitingFor&&(r.waitingFor=e.waitingFor),n&&(r.activity=n),e.shells?.length&&(r.shells=e.shells.map(e=>({...e}))),e.background&&(r.background=!0),e.parts&&(r.parts={...e.parts}),r}function K_(e){return{id:e.id,name:e.name,path:e.path,slot:e.slot,seed:e.seed,createdAt:e.createdAt}}function q_(e,t){let n={id:e.id,short:e.short,name:e.name,color:e.color,configDir:``,sessions:e.sessions,usageStatus:e.usageStatus};if(e.provider&&(n.provider=e.provider),e.plan&&(n.plan=e.plan),e.usage){let r={source:e.usage.source,fetchedAt:t};e.usage.fiveHour&&(r.fiveHour={...e.usage.fiveHour}),e.usage.sevenDay&&(r.sevenDay={...e.usage.sevenDay}),e.usage.noQuota&&(r.noQuota=!0),n.usage=r}return n}var J_=40;function Y_(e,t){return!pt(t)&&!!e.renameRoom&&!P_(t)&&!e.store.mock&&!e.store.replaying&&!!e.store.snapshot?.meta.terminal&&I().local}async function X_(e,t){let n;try{n=await fetch(`/api/rooms/rename`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({id:e,name:t})})}catch{throw Error(a(`o Habblaud não respondeu`))}if(!n.ok)throw Error((await n.json().catch(()=>({}))).error??a(`erro {0}`,[n.status]))}var Z_=class{ctx;el;input;hint;roomId=null;original=``;onDocDown=e=>{this.el.contains(e.target)||this.commit()};constructor(e){this.ctx=e,this.input=P(`input`,{class:`ui-rename__input`,type:`text`,attrs:{maxlength:J_,"aria-label":a(`Nome da sala`),spellcheck:`false`}}),this.hint=P(`p`,{class:`ui-rename__hint`}),this.el=P(`div`,{class:`ui-rename`,role:`dialog`,hidden:!0,attrs:{"aria-label":a(`Renomear sala`)}},P(`label`,{class:`ui-rename__label`,text:a(`Renomear sala`)}),this.input,this.hint),this.input.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),this.commit()):e.key===`Escape`&&(e.preventDefault(),this.close())}),this.input.addEventListener(`keyup`,e=>e.stopPropagation())}open(e,t){let n=this.ctx.store.room(e);if(!n)return;this.roomId=e,this.original=n.name,this.input.value=n.name,M(this.hint,a(`Enter salva · Esc cancela · vazio volta a “{0}”`,[n.path.split(/[\\/]/).filter(Boolean).pop()??n.path])),this.hint.classList.remove(`is-error`),this.el.hidden=!1;let r=this.el.offsetWidth||260,i=this.el.offsetHeight||80;this.el.style.left=`${Math.max(8,Math.min(t.x,innerWidth-r-8))}px`,this.el.style.top=`${Math.max(8,Math.min(t.y,innerHeight-i-8))}px`,this.input.focus(),this.input.select(),document.addEventListener(`pointerdown`,this.onDocDown,!0)}close(){this.el.hidden=!0,this.roomId=null,document.removeEventListener(`pointerdown`,this.onDocDown,!0)}async commit(){let e=this.roomId,t=this.input.value.trim();if(!e||t===this.original)return this.close();try{await X_(e,t),this.roomId===e&&this.close(),this.ctx.announce(t?a(`Sala renomeada para {0}.`,[t]):a(`A sala voltou ao nome da pasta.`))}catch(e){M(this.hint,a(`Não deu: {0}`,[e.message])),this.hint.classList.add(`is-error`)}}};function Q_(e,t){let n=``;for(let[r,i]of Object.entries(t)){let t=``;e.forEach((e,n)=>{let i=0;for(;i<e.length;){if(e[i]!==r){i++;continue}let a=1;for(;e[i+a]===r;)a++;t+=`M${i} ${n}h${a}v1h-${a}z`,i+=a}}),t&&(n+=`<path fill="${i}" d="${t}"/>`)}return n}function Z(e,t={"#":`currentColor`},n=`ui-px-icon`){let r=e.length,i=Math.max(...e.map(e=>e.length));return`<svg class="${n}" width="${i*2}" height="${r*2}" viewBox="0 0 ${i} ${r}" shape-rendering="crispEdges" aria-hidden="true" focusable="false">${Q_(e,t)}</svg>`}var Q={overview:Z([`###....###`,`#........#`,`#........#`,`...####...`,`...#..#...`,`...#..#...`,`...####...`,`#........#`,`#........#`,`###....###`]),zoomIn:Z([`..........`,`....##....`,`....##....`,`....##....`,`.########.`,`.########.`,`....##....`,`....##....`,`....##....`,`..........`]),zoomOut:Z([`..........`,`..........`,`..........`,`..........`,`.########.`,`.########.`,`..........`,`..........`,`..........`,`..........`]),sidebar:Z([`##########`,`#..#.....#`,`#..#.....#`,`#..#.....#`,`#..#.....#`,`#..#.....#`,`#..#.....#`,`#..#.....#`,`#..#.....#`,`##########`]),feed:Z([`##########`,`#........#`,`#........#`,`#........#`,`##########`,`#.##.###.#`,`#........#`,`#.##.##..#`,`#........#`,`##########`]),settings:Z([`....##....`,`.#.####.#.`,`..######..`,`.###..###.`,`####..####`,`####..####`,`.###..###.`,`..######..`,`.#.####.#.`,`....##....`]),help:Z([`..######..`,`.##....##.`,`.##....##.`,`......##..`,`.....##...`,`....##....`,`....##....`,`..........`,`....##....`,`....##....`]),perf:Z([`..######..`,`.#......#.`,`#...##...#`,`#..#..#..#`,`#.#....#.#`,`#......#.#`,`#...###..#`,`#........#`,`.#......#.`,`..######..`]),maximize:Z([`..........`,`.####.....`,`.##.......`,`.#.#......`,`.#........`,`........#.`,`......#.#.`,`.......##.`,`.....####.`,`..........`]),restore:Z([`..........`,`...#......`,`...#......`,`.###......`,`..........`,`..........`,`......###.`,`......#...`,`......#...`,`..........`]),pencil:Z([`.......##.`,`......#..#`,`.....#..#.`,`....#..#..`,`...#..#...`,`..#..#....`,`.#..#.....`,`.#.#......`,`.##.......`,`..........`]),close:Z([`..........`,`.##....##.`,`.###..###.`,`..######..`,`...####...`,`...####...`,`..######..`,`.###..###.`,`.##....##.`,`..........`]),starOutline:Z([`.....#.....`,`....#.#....`,`....#.#....`,`#####.#####`,`#.........#`,`.#.......#.`,`..#.....#..`,`.#..#.#..#.`,`.#.#...#.#.`,`.##.....##.`]),starFilled:Z([`.....o.....`,`....oho....`,`....ofo....`,`ooooofooooo`,`ohffffffffo`,`.offfffffo.`,`..offfffo..`,`.offo.offo.`,`.ofo...ofo.`,`.oo.....oo.`],{o:`#8a5a1c`,f:`#ffd166`,h:`#fff4c2`}),search:Z([`.####.....`,`#....#....`,`#....#....`,`#....#....`,`#....#....`,`.####.....`,`.....##...`,`......##..`,`.......##.`,`........#.`]),copy:Z([`...#######`,`...#.....#`,`...#.....#`,`#######..#`,`#.....#..#`,`#.....#..#`,`#.....####`,`#.....#...`,`#.....#...`,`#######...`]),check:Z([`..........`,`.........#`,`........##`,`.......##.`,`#.....##..`,`##...##...`,`.##.##....`,`..###.....`,`...#......`,`..........`]),follow:Z([`....##....`,`....##....`,`..######..`,`.#......#.`,`##..##..##`,`##..##..##`,`.#......#.`,`..######..`,`....##....`,`....##....`]),center:Z([`###....###`,`#........#`,`#........#`,`....##....`,`...####...`,`...####...`,`....##....`,`#........#`,`#........#`,`###....###`]),hand:Z([`...#.#....`,`..#.#.#...`,`..#.#.#.#.`,`..#.#.#.#.`,`..#######.`,`#.#######.`,`##.######.`,`.########.`,`..######..`,`...####...`]),warn:Z([`....##....`,`...####...`,`...#..#...`,`..##..##..`,`..##..##..`,`.###..###.`,`.########.`,`####..####`,`##########`,`..........`]),clock:Z([`..######..`,`.#......#.`,`#....#...#`,`#....#...#`,`#....###.#`,`#........#`,`#........#`,`.#......#.`,`..######..`,`..........`]),hourglass:Z([`#########`,`.#sssss#.`,`.#sssss#.`,`..#sss#..`,`...#s#...`,`...#s#...`,`..#.s.#..`,`.#..s..#.`,`.#.sss.#.`,`#########`],{"#":`currentColor`,s:`#f7c76b`}),terminal:Z([`##########`,`#........#`,`#.#......#`,`#..#.....#`,`#...#....#`,`#..#.....#`,`#.#..###.#`,`#........#`,`##########`]),newAgent:Z([`..##......`,`.####.....`,`.####...#.`,`..##...###`,`........#.`,`.####.....`,`######....`,`######....`]),delivery:Z([`...####...`,`..#....#..`,`.#......#.`,`##########`,`#....#...#`,`#...###..#`,`#....#...#`,`#........#`,`##########`]),chevronLeft:Z([`....##`,`...##.`,`..##..`,`.##...`,`..##..`,`...##.`,`....##`]),chevronRight:Z([`##....`,`.##...`,`..##..`,`...##.`,`..##..`,`.##...`,`##....`]),mic:Z([`...##...`,`..####..`,`..####..`,`..####..`,`#.####.#`,`#..##..#`,`.#....#.`,`..####..`,`...##...`,`..####..`]),stopRec:Z([`........`,`.######.`,`.######.`,`.######.`,`.######.`,`.######.`,`.######.`,`........`]),attach:Z([`...###..`,`..#...#.`,`..#.#.#.`,`..#.#.#.`,`..#.#.#.`,`..#.#.#.`,`..#...#.`,`...###..`]),lock:Z([`..####..`,`.##..##.`,`.#....#.`,`.#....#.`,`########`,`###..###`,`###..###`,`########`,`########`]),chevronDown:Z([`#......#`,`##....##`,`.##..##.`,`..####..`,`...##...`]),chevronUp:Z([`...##...`,`..####..`,`.##..##.`,`##....##`,`#......#`]),arrowDown:Z([`...##...`,`...##...`,`...##...`,`#######.`,`.#####..`,`..###...`,`...#....`].map(e=>e.padEnd(8,`.`))),city:Z([`......##..`,`..##..##..`,`..##.####.`,`####.#..#.`,`#..#.####.`,`####.#..#.`,`#..#.####.`,`####.#..#.`,`##########`]),office:Z([`..######..`,`..#.##.#..`,`..######..`,`..#.##.#..`,`..######..`,`..#.##.#..`,`..##..##..`,`..##..##..`,`##########`])},$_=Z([`.....######.....`,`.....#rrrr#.....`,`..############..`,`..#llllllllll#..`,`..#lwwlwwlbbl#..`,`..#lwwlwwlbbl#..`,`..#llllllllll#..`,`..#lbblwwlwwl#..`,`..#lbblwwlwwl#..`,`..#llllllllll#..`,`..#lwwlddlbbl#..`,`..#lwwlddlbbl#..`,`..#llllddllll#..`,`################`],{"#":`#2b3550`,l:`#dfe6f2`,r:`#ff8a5b`,w:`#ffd36b`,b:`#7cc8ff`,d:`#3a4566`},`ui-px-icon ui-mark`),ev=Z([`cccc....................t......t...t........`,`csssc...................t......s...t........`,`c...c.c...c..cccc.c...c.tttt..tt..ttt...tttt`,`ccccs.c...c.cssss.c...c.tssst.st..sts..tssss`,`csssc.c...c.sccc..c...c.t...t..t...t...sttt.`,`c...c.c...c..sssc.c...c.t...t..t...t....ssst`,`ccccs.scccc.ccccs.scccc.tttts.ttt..stt.tttts`,`ssss...ssss.ssss...sssc.ssss..sss...ss.ssss.`,`...................cccs.....................`,`...................sss......................`],{s:`rgba(6, 8, 14, 0.62)`,c:`#f4f1ea`,t:`#fac665`},`ui-wordmark`),tv=40;function nv(e){return!e.store.mock&&!e.store.replaying&&I().messages}async function rv(e,t,n){let r;try{r=await fetch(e,{method:t,...n||t===`DELETE`?{headers:{"Content-Type":`application/json`}}:{},...n?{body:JSON.stringify(n)}:{}})}catch{throw Error(a(`o Habblaud não respondeu`))}if(!r.ok){let e=await r.json().catch(()=>({}));throw Error(e.error??a(`erro {0}`,[r.status]))}return await r.json()}async function iv(e){await rv(`/api/rooms/custom/${encodeURIComponent(e)}`,`DELETE`)}var av=class{ctx;el;nameInput;status;list;preferredId=``;roomsKey=``;onCreated;constructor(e){this.ctx=e,this.nameInput=P(`input`,{class:`ui-custom-rooms__input`,type:`text`,attrs:{maxlength:tv,placeholder:a(`Digite o nome`),"aria-label":a(`Nome da sala`),autocomplete:`off`,spellcheck:`false`}});let t=P(`button`,{class:`ui-btn ui-btn--primary`,type:`button`,text:a(`Criar sala`),on:{click:()=>void this.create()}});this.status=P(`p`,{class:`ui-custom-rooms__status`,role:`status`}),this.list=P(`div`,{class:`ui-custom-rooms__list`});let n=j(Q.close,a(`Fechar`),()=>this.close(),`ui-icon-btn--sm`);this.el=P(`div`,{class:`ui-popover ui-custom-rooms`,role:`dialog`,tabIndex:-1,attrs:{"aria-label":a(`Salas personalizadas`),popover:`auto`}},P(`div`,{class:`ui-popover__head`},P(`h2`,{text:a(`Salas personalizadas`)}),n),P(`div`,{class:`ui-custom-rooms__create`},this.nameInput,t),this.status,this.list),this.nameInput.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault(),this.create())})}open(e,t,n){nv(this.ctx)&&(this.preferredId=e??``,this.onCreated=n,this.nameInput.value=``,M(this.status,``),this.render(),Ct(this.el,t??{x:Math.max(12,innerWidth-360),y:72}),(Array.from(this.list.querySelectorAll(`[data-room-id]`)).find(e=>e.dataset.roomId===this.preferredId)?.querySelector(`input`)??this.nameInput).focus())}close(){this.el.hidePopover()}render(){let e=(this.ctx.store.snapshot?.rooms??[]).filter(e=>e.custom),t=e.map(e=>`${e.id}\u0000${e.name}`).join(``);t!==this.roomsKey&&(this.roomsKey=t,this.list.replaceChildren(...e.map(e=>this.roomRow(e)))),M(this.status,e.length===0?a(`Não há salas customizadas.`):``)}roomRow(e){let t=P(`input`,{class:`ui-custom-rooms__input`,type:`text`,attrs:{maxlength:tv,"aria-label":a(`Nome da sala`)}});t.value=dt(e);let n=P(`span`,{class:`ui-custom-rooms__error`,role:`alert`}),r=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Salvar`),on:{click:()=>void this.rename(e,t,n)}}),i=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Excluir`)}),o=!1;return i.addEventListener(`click`,()=>{o?this.remove(e,n):(o=!0,M(i,a(`Confirmar exclusão`)))}),t.addEventListener(`keydown`,r=>{r.key===`Enter`&&(r.preventDefault(),this.rename(e,t,n))}),P(`div`,{class:`ui-custom-rooms__row`,attrs:{"data-room-id":e.id}},t,r,i,n)}async create(){let e=this.nameInput.value.trim();if(!e){M(this.status,a(`Digite o nome`)),this.nameInput.focus();return}try{let t=await rv(`/api/rooms/custom`,`POST`,{name:e});if(typeof t.id!=`string`)throw Error(a(`erro ao criar a sala`));this.nameInput.value=``,M(this.status,a(`Sala criada.`)),this.ctx.invalidate(),this.onCreated?.(t.id),this.onCreated=void 0}catch(e){M(this.status,e.message)}}async rename(e,t,n){let r=t.value.trim();if(!r){M(n,a(`Digite o nome`)),t.focus();return}try{await rv(`/api/rooms/custom/${encodeURIComponent(e.id)}/rename`,`POST`,{name:r}),M(n,``),M(this.status,a(`Sala renomeada.`)),this.ctx.invalidate()}catch(e){M(n,e.message)}}async remove(e,t){try{await iv(e.id),M(this.status,a(`Sala excluída.`)),this.ctx.invalidate()}catch(e){M(t,e.message)}}},ov=class{ctx;el;items;status;onSelect;constructor(e){this.ctx=e,this.items=P(`div`,{class:`ui-room-menu__items`}),this.status=P(`p`,{class:`ui-room-menu__status`,role:`alert`,hidden:!0}),this.el=P(`div`,{class:`ui-popover ui-room-menu`,role:`menu`,tabIndex:-1,attrs:{"aria-label":a(`Ações da sala`),popover:`auto`}},this.items,this.status)}openFavorites(e,t,n){nv(this.ctx)&&(this.onSelect=n,M(this.status,``),F(this.status,!0),this.items.replaceChildren(...e.filter(e=>e.custom).map(e=>this.item(dt(e),()=>{this.el.hidePopover(),this.onSelect?.(e.id)})),this.item(a(`Nova sala…`),()=>{this.el.hidePopover();let e=this.onSelect;this.ctx.manageCustomRooms?.(void 0,void 0,t=>e?.(t))})),Ct(this.el,t),this.items.querySelector(`button`)?.focus())}openCustomRoom(e,t){if(!nv(this.ctx))return;M(this.status,``),F(this.status,!0);let n=!1,r=this.item(a(`Renomear sala`),()=>{this.el.hidePopover(),this.ctx.manageCustomRooms?.(e.id,t)}),i;i=this.item(a(`Excluir`),()=>{n?this.remove(e.id,i):(n=!0,M(i,a(`Confirmar exclusão`)))}),this.items.replaceChildren(r,i),Ct(this.el,t),r.focus()}item(e,t){return P(`button`,{class:`ui-btn ui-room-menu__item`,type:`button`,role:`menuitem`,text:e,on:{click:t}})}async remove(e,t){try{t.disabled=!0;let n=await fetch(`/api/rooms/custom/${encodeURIComponent(e)}`,{method:`DELETE`,headers:{"Content-Type":`application/json`}});if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(e.error??a(`erro {0}`,[n.status]))}this.el.hidePopover(),this.ctx.invalidate()}catch(e){M(this.status,e instanceof Error?e.message:a(`erro ao excluir a sala`)),F(this.status,!1),t.disabled=!1}}};function sv(e){return e&&Ke(e)?e:void 0}function cv(e,t){return e.kind===`agent`?t(e.agentId)??a(`um agente`):e.name||a(`um script`)}function lv(e,t){let n=e.filter(e=>e.status===`open`).sort((e,t)=>t.updatedAt-e.updatedAt),r=t.showResolved?e.filter(e=>e.status===`resolved`).sort((e,t)=>(t.resolvedAt??t.updatedAt)-(e.resolvedAt??e.updatedAt)):[];return[...n,...r].map(e=>{let n=t.machineLabel(e.machine),r=sv(e.link);return{id:e.id,title:e.title,...e.body?{body:e.body}:{},...r?{link:r}:{},sender:cv(e.from,t.agentName),...n?{machine:n}:{},time:t.relativeTime(e.status===`resolved`?e.resolvedAt??e.updatedAt:e.createdAt,t.now),resolved:e.status===`resolved`}})}function uv(e){return e.length-Cs(e).length}function dv(e,t,n){let r=P(e,{class:t});return r.textContent=n,r}function fv(e,t){let n=[e.resolved?a(`resolvido {0}`,[e.time]):e.time,a(`de {0}`,[e.sender]),e.machine?a(`em {0}`,[e.machine]):null].filter(e=>!!e),r=P(`div`,{class:`ui-inbox__row-head`},dv(`strong`,`ui-inbox__title`,e.title));if(t.canResolve&&!e.resolved){let n=P(`button`,{class:`ui-btn ui-btn--sm ui-inbox__resolve`,type:`button`,text:a(`Resolver`),on:{click:()=>t.onResolve(e.id)}});t.busy?.has(e.id)&&(n.disabled=!0),r.append(n)}let i=P(`li`,{class:`ui-inbox__row${e.resolved?` is-resolved`:``}`,attrs:{"data-inbox-id":e.id}},r);if(e.body&&i.append(dv(`p`,`ui-inbox__body`,e.body)),e.link){let t=P(`a`,{class:`ui-inbox__link`,attrs:{href:e.link,target:`_blank`,rel:`noopener noreferrer`}});t.textContent=e.link,i.append(t)}return i.append(dv(`div`,`ui-inbox__meta`,n.join(` · `))),i}function pv(e,t){let n=[];t.error&&n.push(P(`p`,{class:`ui-inbox__error`,role:`alert`,text:t.error})),t.rows.length===0?n.push(P(`p`,{class:`ui-inbox__empty`,text:t.showResolved?a(`Nada por aqui.`):a(`Sua mesa está limpa: nada esperando.`)})):n.push(P(`ul`,{class:`ui-inbox__list`},...t.rows.map(e=>fv(e,t)))),(t.resolvedCount>0||t.showResolved)&&n.push(P(`button`,{class:`ui-link-btn ui-inbox__toggle${t.showResolved?` is-on`:``}`,type:`button`,text:t.showResolved?a(`Ocultar resolvidos`):a(`Mostrar resolvidos ({0})`,[t.resolvedCount]),attrs:{"aria-pressed":t.showResolved},on:{click:()=>t.onToggleResolved()}})),e.replaceChildren(...n)}var mv=class{ctx;el;button;count;body;showResolved=!1;error;busy=new Set;opener=null;lastKey=``;constructor(e){this.ctx=e,this.count=P(`span`,{class:`ui-counter__value`,text:`0`}),this.button=P(`button`,{class:`ui-counter ui-counter--inbox`,type:`button`,hidden:!0,title:a(`Itens deixados na sua mesa. Clique para abrir.`),attrs:{"aria-label":a(`Itens deixados na sua mesa. Clique para abrir.`)},on:{click:()=>this.open()}},P(`span`,{class:`ui-counter__icon`,attrs:{"aria-hidden":`true`},text:`📄`}),this.count,P(`span`,{class:`ui-counter__label`,text:a(`na mesa`)})),this.body=P(`div`,{class:`ui-inbox__content`});let t=j(Q.close,a(`Fechar (Esc)`),()=>this.close(),`ui-icon-btn--sm`);this.el=P(`dialog`,{class:`ui-dialog ui-inbox`,attrs:{"aria-labelledby":`ui-inbox-title`}},P(`div`,{class:`ui-dialog__head`},P(`h2`,{text:a(`Na sua mesa`),attrs:{id:`ui-inbox-title`}}),t),this.body),this.el.addEventListener(`click`,e=>{e.target===this.el&&this.close()}),this.el.addEventListener(`keydown`,e=>e.stopPropagation()),this.el.addEventListener(`close`,()=>{this.opener?.focus?.(),this.opener=null}),e.root.append(this.el),e.world.onInboxClick(()=>this.open()),Zt(()=>this.refresh(!0))}get isOpen(){return this.el.open}open(){this.el.open||(this.opener=document.activeElement instanceof HTMLElement?document.activeElement:null,this.error=void 0,this.el.showModal(),this.refresh(!0))}close(){this.el.open&&this.el.close()}render(){this.refresh(!1)}get canResolve(){return!this.ctx.store.mock&&I().messages}refresh(e){let t=this.ctx.store.inboxItems,n=Cs(t).length;if(F(this.button,n===0),M(this.count,Ts(n)),!this.el.open)return;let r=this.ctx.now(),i=lv(t,{showResolved:this.showResolved,now:r,relativeTime:Nt,agentName:e=>this.ctx.agent(e)?.name,machineLabel:e=>e?this.ctx.store.snapshot?.machines?.find(t=>t.id===e)?.label??e:void 0}),a=JSON.stringify([i,this.showResolved,this.canResolve,this.error,[...this.busy]]);(e||a!==this.lastKey)&&(this.lastKey=a,pv(this.body,{rows:i,resolvedCount:uv(t),showResolved:this.showResolved,canResolve:this.canResolve,error:this.error,busy:this.busy,onToggleResolved:()=>{this.showResolved=!this.showResolved,this.refresh(!0)},onResolve:e=>void this.resolve(e)}))}async resolve(e){this.busy.add(e),this.error=void 0,this.refresh(!0);let t=await this.ctx.store.resolveInbox(e);this.busy.delete(e),this.error=t,this.refresh(!0)}},hv=new Map,gv=null;function _v(e){gv=e}function vv(e,t){let n=oe(e,gv),r=`${e.seed}|${e.look}|${e.kind}|${t}|${k(n)}`,i=hv.get(r);if(!i){let a=cs(e.seed,{look:e.look,sub:e.kind===`sub`,scale:t,parts:n});i={url:a.toDataURL(`image/png`),w:a.width,h:a.height},hv.set(r,i)}return i}var yv={xs:1,sm:2,md:2,lg:4};function bv(e,t){let n=xv(t);return Sv(n,e,t),n}function xv(e){return P(`span`,{class:`ui-avatar ui-avatar--${e}`,attrs:{"aria-hidden":`true`}})}function Sv(e,t,n){let r=`${t.seed}|${t.look}|${t.kind}|${k(oe(t,gv))}`;if(e.dataset.sig===r)return;e.dataset.sig=r;let i=e.querySelector(`img`);i||(i=P(`img`,{attrs:{alt:``,draggable:`false`,decoding:`async`}}),e.append(i));try{let e=vv(t,yv[n]);i.width=e.w,i.height=e.h,i.src=e.url}catch(e){console.warn(`[ui] falha ao gerar avatar`,e)}}function Cv(e,t){return e.kind===`main`&&e.status!==`offline`&&t.live&&t.terminal&&t.local&&!t.replaying&&!t.mock&&!P_(e.id)}function wv(e,t){let n={};for(let r of D){let i=t[r];(r!==`face`||i!==`none`||e.face!==void 0)&&i!==void 0&&i!==e[r]&&(n[r]=i)}return n}var Tv=[{title:a(`Pele`),rows:[{key:`skin`,label:a(`Tom`),kind:`color`}]},{title:a(`Cabelo`),rows:[{key:`hairStyle`,label:a(`Estilo`),kind:`style`},{key:`hair`,label:a(`Cor`),kind:`color`}]},{title:a(`Barba`),rows:[{key:`facialHair`,label:a(`Estilo`),kind:`style`}]},{title:a(`Olhos`),rows:[{key:`eyes`,label:a(`Cor`),kind:`color`}]},{title:a(`Parte de cima`),rows:[{key:`topStyle`,label:a(`Estilo`),kind:`style`},{key:`top`,label:a(`Cor`),kind:`color`},{key:`topAccent`,label:a(`Detalhe`),kind:`color`}]},{title:a(`Parte de baixo`),rows:[{key:`bottomStyle`,label:a(`Estilo`),kind:`style`},{key:`bottom`,label:a(`Cor`),kind:`color`}]},{title:a(`Sapatos`),rows:[{key:`shoes`,label:a(`Cor`),kind:`color`}]},{title:a(`Acessório`),rows:[{key:`accessory`,label:a(`Tipo`),kind:`style`},{key:`accessoryColor`,label:a(`Cor`),kind:`color`}]},{title:a(`Máscara`),rows:[{key:`face`,label:a(`Tipo`),kind:`style`},{key:`faceColor`,label:a(`Cor`),kind:`color`}]}],Ev={hairStyle:{short:a(`Curto`),buzz:a(`Raspado`),spiky:a(`Espetado`),side_part:a(`Repartido`),curly:a(`Cacheado`),afro:a(`Black power`),bob:a(`Chanel`),long:a(`Longo`),ponytail:a(`Rabo de cavalo`),bun:a(`Coque`),pigtails:`Maria-chiquinha`,mohawk:a(`Moicano`),bald:a(`Careca`),wavy:a(`Ondulado`)},topStyle:{tshirt:a(`Camiseta`),hoodie:a(`Moletom`),shirt_tie:a(`Camisa e gravata`),sweater:a(`Suéter`),jacket:a(`Jaqueta`),blouse:a(`Blusa`),polo:`Polo`,hoodie_up:a(`Moletom com capuz`)},bottomStyle:{pants:a(`Calça`),shorts:a(`Bermuda`),skirt:a(`Saia`)},accessory:{none:a(`Nenhum`),glasses:a(`Óculos`),sunglasses:a(`Óculos escuros`),headphones:a(`Fone`),cap:a(`Boné`),beanie:a(`Gorro`),earrings:a(`Brincos`),bow:a(`Laço`),gamer_headphones:a(`Fone gamer`)},face:{none:a(`Nenhuma`),led_mask:a(`Máscara de LED`),bandana:a(`Bandana`),respirator:a(`Respirador`),visor:a(`Viseira neon`),ar_monocle:a(`Monóculo AR`),smile_mask:a(`Máscara sorridente`)},facialHair:{none:a(`Sem barba`),stubble:a(`Por fazer`),beard:a(`Barba`),mustache:a(`Bigode`),goatee:a(`Cavanhaque`)}};function Dv(e,t){return Ev[e]?.[t]??t}function Ov(e,t){return e.key===`faceColor`?!!t.face&&t.face!==`none`:e.key!==`accessoryColor`||t.accessory!==`none`}var kv=[`skin`,`hairStyle`,`hair`,`eyes`,`topStyle`,`top`,`topAccent`,`bottom`,`shoes`,`accessory`,`accessoryColor`,`face`,`faceColor`];function Av(e,t,n){if(!e.length||!n||!e.some(e=>!e.disabled))return-1;for(let r=1;r<=e.length;r++){let i=((t+Math.sign(n)*r)%e.length+e.length)%e.length;if(!e[i].disabled)return i}return-1}var jv=class{choices;current=``;active=-1;constructor(e,t){this.choices=e,this.options=e,t!==void 0&&(this.value=t)}get options(){return this.choices}set options(e){this.choices=e,e.some(e=>e.value===this.current)||(this.current=``);let t=e.findIndex(e=>e.value===this.current&&!e.disabled);this.active=t>=0?t:e.findIndex(e=>!e.disabled),!this.current&&this.active>=0&&(this.current=e[this.active].value)}get value(){return this.current}set value(e){let t=this.choices.findIndex(t=>t.value===e);this.current=t>=0?e:``,this.active=t>=0&&!this.choices[t].disabled?t:this.choices.findIndex(e=>!e.disabled)}get activeIndex(){return this.active}move(e){return this.active=Av(this.choices,this.active,e),this.active}moveFrom(e,t){return this.active=Av(this.choices,e,t),this.active}setActive(e){e>=0&&e<this.choices.length&&!this.choices[e].disabled&&(this.active=e)}selectActive(){if(this.active<0||this.choices[this.active].disabled)return;let e=this.choices[this.active];return this.current=e.value,e.value}},Mv=class{checked;constructor(e=!1){this.checked=e}get value(){return this.checked}set value(e){this.checked=e}toggle(){return this.checked=!this.checked,this.checked}},Nv=0,Pv=Z([`#...#`,`##.##`,`.###.`,`..#..`]),Fv=Z([`..####..`,`.#....#.`,`#......#`,`#......#`,`#......#`,`#......#`,`.#....#.`,`..####..`]),Iv=Z([`..####..`,`.#....#.`,`#..##..#`,`#.####.#`,`#.####.#`,`#..##..#`,`.#....#.`,`..####..`]),Lv=Z([`########`,`#......#`,`#.####.#`,`#.#..#.#`,`#.#..#.#`,`#.####.#`,`#......#`,`########`]),Rv=Z([`......##`,`.....##.`,`#...##..`,`##.##...`,`.###....`,`..#.....`]),zv=class{el;button;list;state;optionId=`ui-pixel-select-${++Nv}`;enabled=!1;onChange;options;constructor(e){this.options=e.options??[],this.state=new jv(this.options,e.value),this.onChange=e.onChange,this.el=P(`div`,{class:`ui-pixel-select ${e.className??``}`.trim()}),this.button=P(`button`,{class:`ui-btn ui-pixel-select__button`,type:`button`,role:`combobox`,attrs:{"aria-label":e.label,"aria-haspopup":`listbox`,"aria-expanded":`false`,"aria-controls":`${this.optionId}-list`},on:{click:()=>this.list.matches(`:popover-open`)?this.close():this.open(),keydown:e=>this.onKeydown(e)}}),this.list=P(`div`,{class:`ui-popover ui-pixel-select__list`,role:`listbox`,tabIndex:-1,attrs:{id:`${this.optionId}-list`,popover:`auto`,"aria-label":e.label}}),this.list.addEventListener(`toggle`,()=>this.button.setAttribute(`aria-expanded`,String(this.list.matches(`:popover-open`)))),this.el.append(this.button,this.list),this.enabled=!(e.disabled??!1),this.button.disabled=!this.enabled,this.render()}get value(){return this.state.value}set value(e){this.state.value=e,this.render()}get disabled(){return!this.enabled}set disabled(e){this.enabled=!e,this.button.disabled=e,e&&this.close(),this.render()}setOptions(e,t){this.options=e,this.state.options=e,t!==void 0&&(this.state.value=t),this.render()}setOnChange(e){this.onChange=e}render(){let e=this.options.find(e=>e.value===this.state.value);this.button.textContent=``;let t=P(`span`,{class:`ui-pixel-select__label`,text:e?.label??``}),n=P(`span`,{class:`ui-pixel-select__chevron`});n.innerHTML=Pv,this.button.append(t,n),this.list.textContent=``;let r,i=null,a;for(let[e,t]of this.options.entries()){let n=this.list;t.group?(a!==t.group&&(a=t.group,i=P(`div`,{class:`ui-pixel-select__group`,role:`group`,attrs:{"aria-label":t.group}}),i.append(P(`span`,{class:`ui-pixel-select__group-label`,role:`presentation`,text:t.group})),this.list.append(i)),n=i):(i=null,a=void 0);let o=`${this.optionId}-option-${e}`,s=P(`div`,{class:`ui-pixel-select__option`,role:`option`,tabIndex:-1,attrs:{id:o,"aria-selected":String(t.value===this.state.value),"aria-disabled":t.disabled?`true`:void 0},text:t.label});e===this.state.activeIndex&&!t.disabled&&s.classList.add(`is-active`),t.disabled&&s.classList.add(`is-disabled`),s.addEventListener(`pointermove`,()=>{if(!t.disabled){this.state.setActive(e);for(let[t,n]of[...this.list.querySelectorAll(`[role="option"]`)].entries())n.classList.toggle(`is-active`,t===e);this.button.setAttribute(`aria-activedescendant`,o)}}),s.addEventListener(`click`,()=>{t.disabled||this.select(t.value)}),e===this.state.activeIndex&&!t.disabled&&(r=o),n.append(s)}r?this.button.setAttribute(`aria-activedescendant`,r):this.button.removeAttribute(`aria-activedescendant`)}onKeydown(e){if(e.stopPropagation(),e.key===`Tab`){this.close();return}if(e.key===`Escape`){this.list.matches(`:popover-open`)&&(e.preventDefault(),this.close());return}if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),this.list.matches(`:popover-open`)?(this.state.move(e.key===`ArrowDown`?1:-1),this.render()):this.open();return}if(e.key===`Enter`||e.key===` `){if(e.preventDefault(),!this.list.matches(`:popover-open`))this.open();else{let e=this.options[this.state.activeIndex];e&&this.select(e.value)}}}open(){if(this.disabled)return;let e=this.button.getBoundingClientRect(),t=document.documentElement.clientWidth||innerWidth;this.list.style.width=`${Math.min(Math.max(e.width,180),t-16)}px`,Ct(this.list,{x:e.left,y:e.bottom+4}),this.button.setAttribute(`aria-expanded`,`true`)}close(){this.list.matches(`:popover-open`)&&this.list.hidePopover(),this.button.setAttribute(`aria-expanded`,`false`)}select(e){if(!this.options.find(t=>t.value===e&&!t.disabled))return;let t=this.state.value!==e;this.state.value=e,this.render(),this.close(),this.button.focus(),t&&this.onChange?.(e)}},Bv=class{el;buttons=[];state;enabled=!0;onChange;options;indicator;constructor(e){this.options=e.options,this.state=new jv(e.options,e.value),this.onChange=e.onChange,this.indicator=e.indicator??!0,this.el=P(`div`,{class:e.className??`ui-pixel-radio-group`,role:`radiogroup`,attrs:{"aria-label":e.label}}),this.disabled=e.disabled??!1,this.render()}get value(){return this.state.value}set value(e){this.state.value=e,this.sync()}get disabled(){return!this.enabled}set disabled(e){this.enabled=!e,this.sync()}setOptions(e,t){this.options=e,this.state.options=e,t!==void 0&&(this.state.value=t),this.render(!0)}render(e=!1){this.buttons.length=0;let t=this.options.map(e=>{let t=P(`button`,{class:`ui-pixel-radio ${e.className??``}`.trim(),type:`button`,role:`radio`,tabIndex:-1,title:e.title,style:e.style,attrs:{"aria-label":e.ariaLabel,"aria-checked":`false`,"aria-disabled":e.disabled?`true`:void 0},on:{click:()=>this.select(e.value),keydown:t=>this.onKeydown(t,e.value)}});if(e.content?t.append(e.content):t.textContent=e.label,this.indicator){let e=P(`span`,{class:`ui-pixel-radio__indicator`});e.innerHTML=`${Fv}<span class="ui-pixel-radio__on">${Iv}</span><span class="ui-pixel-radio__focus">${Lv}</span>`,t.append(e)}return this.buttons.push(t),t});e?this.el.replaceChildren(...t):this.el.append(...t),this.sync()}sync(){this.el.setAttribute(`aria-disabled`,String(!this.enabled));let e=this.options.findIndex(e=>e.value===this.state.value&&!e.disabled),t=e>=0?e:this.options.findIndex(e=>!e.disabled);this.buttons.forEach((e,n)=>{let r=this.options[n],i=r.value===this.state.value;e.disabled=!this.enabled||!!r.disabled,e.setAttribute(`aria-checked`,String(i)),e.setAttribute(`aria-disabled`,String(e.disabled)),e.tabIndex=n===t&&!e.disabled?0:-1})}onKeydown(e,t){let n=e.key===`ArrowRight`||e.key===`ArrowDown`?1:e.key===`ArrowLeft`||e.key===`ArrowUp`?-1:0;if(!n){(e.key===`Enter`||e.key===` `)&&e.stopPropagation();return}e.preventDefault(),e.stopPropagation();let r=this.options.findIndex(e=>e.value===t),i=this.state.moveFrom(r,n);i<0||(this.select(this.options[i].value),this.buttons[i].focus())}select(e){let t=this.options.find(t=>t.value===e&&!t.disabled);if(!this.enabled||!t)return;let n=this.state.value!==e;this.state.value=e,this.sync(),n&&this.onChange?.(e)}},Vv=class{el;state;enabled=!0;onChange;constructor(e){this.state=new Mv(e.value),this.onChange=e.onChange;let t={class:`ui-pixel-checkbox ${e.className??``}`.trim(),role:`checkbox`,attrs:{"aria-label":e.label,"aria-checked":`false`},on:{click:t=>{e.tag===`span`&&t.target instanceof Element&&t.target.closest(`a`)||this.toggle()},keydown:e=>e.key===` `?e.stopPropagation():void 0}};this.el=e.tag===`span`?P(`span`,{...t,tabIndex:0,on:{...t.on,keydown:e=>this.onKeydown(e)}}):P(`button`,{...t,type:`button`});let n=P(`span`,{class:`ui-pixel-checkbox__box`});n.innerHTML=Rv,this.el.append(n,e.content??P(`span`,{text:e.label})),this.disabled=e.disabled??!1,this.sync()}get value(){return this.state.value}set value(e){this.state.value=e,this.sync()}get disabled(){return!this.enabled}set disabled(e){this.enabled=!e,this.el instanceof HTMLButtonElement?this.el.disabled=e:this.el.tabIndex=e?-1:0,this.el.setAttribute(`aria-disabled`,String(e)),this.sync()}onKeydown(e){e.key===` `&&(e.preventDefault(),e.stopPropagation(),this.toggle())}toggle(){if(this.disabled)return;let e=this.state.toggle();this.sync(),this.onChange?.(e)}sync(){this.el.setAttribute(`aria-checked`,String(this.value)),this.el.classList.toggle(`is-checked`,this.value)}};function Hv(e,t,n){let r=`ui-sw-${e.replace(/\W+/g,`-`).toLowerCase()}`,i=P(`button`,{class:`ui-switch`,type:`button`,role:`switch`,attrs:{"aria-checked":`false`,"aria-labelledby":r}},P(`span`,{class:`ui-switch__knob`}));i.addEventListener(`click`,n);let a=P(`span`,{class:`ui-set__hint`,text:t});return{row:P(`div`,{class:`ui-set`},P(`div`,{class:`ui-set__text`},P(`span`,{class:`ui-set__label`,text:e,attrs:{id:r}}),a),i),btn:i,hint:a}}var Uv=4,Wv=class{onChange;opts;preview;groups;draft=null;constructor(e=()=>{},t={}){this.onChange=e,this.opts=t,this.preview=P(`canvas`,{class:`ui-char__preview`,role:`img`,attrs:{"aria-label":a(`Prévia do personagem`)}}),this.groups=P(`div`,{class:`ui-char__groups`})}get value(){return this.draft}set(e){this.draft=e,this.paint()}pick(e,t){this.draft&&(this.draft=re({...this.draft,[e]:t}),this.paint(e),this.onChange(this.draft))}paint(e){let t=this.draft;if(!t)return;this.drawPreview(t);let n=Te(t);this.groups.replaceChildren(...Tv.map(e=>({g:e,rows:e.rows.filter(e=>Ov(e,t)&&!this.hidden(e.key))})).filter(({rows:e})=>e.length>0).map(({g:e,rows:r})=>P(`fieldset`,{class:`ui-char__group`},P(`legend`,{text:e.title}),...r.map(r=>this.row(e.title,r,t,n[r.key].filter(e=>!this.opts.worldSafe||_e(e)===e)))))),e&&this.groups.querySelector(`[data-key="${e}"] [aria-checked="true"]`)?.focus()}hidden(e){return!!this.opts.worldSafe&&(e===`face`||e===`faceColor`)}row(e,t,n,r){let i=n[t.key]??``,a=t.kind===`color`,o=new Bv({label:`${e}: ${t.label}`,options:r.map(e=>{let r=b(n,t.key,e),i=a?e:Dv(t.key,e);return{value:e,label:i,className:a?`ui-char__swatch`:`ui-char__chip`,title:r??i,style:a?`--swatch: ${e}`:void 0,ariaLabel:a?e:void 0,content:a?P(`span`,{attrs:{"aria-hidden":`true`}}):void 0,disabled:!!r}}),value:i,indicator:!1,className:`ui-char__opts ui-char__opts--${t.kind}`,onChange:e=>this.pick(t.key,e)});return o.el.setAttribute(`data-key`,t.key),P(`div`,{class:`ui-char__row`},P(`span`,{class:`ui-char__row-label`,text:t.label}),o.el)}drawPreview(e){try{let t=ss({appearance:e,dir:`down`,pose:`stand`,frame:0}),n=this.preview;n.width=t.canvas.width*Uv,n.height=t.canvas.height*Uv;let r=n.getContext(`2d`);if(!r)return;r.imageSmoothingEnabled=!1,r.clearRect(0,0,n.width,n.height),r.drawImage(t.canvas,0,0,n.width,n.height)}catch(e){console.warn(`[ui] falha ao desenhar a prévia do personagem`,e)}}};function Gv(){return crypto.getRandomValues(new Uint32Array(1))[0]}var Kv=class{ctx;button;el;agentId=``;editId=0;editing=!1;busy=!1;confirmingReset=!1;seed=0;look=`f`;base=null;fields=new Wv;nameInput;error;saveBtn;resetBtn;constructor(e){this.ctx=e,this.button=j(Q.pencil,a(`Editar personagem`),()=>this.editing?this.cancel():this.start(),`ui-icon-btn--sm ui-char-edit`),N(this.button,`aria-expanded`,`false`),this.button.hidden=!0,this.nameInput=P(`input`,{class:`ui-char__name`,type:`text`,attrs:{maxlength:24,autocomplete:`off`,spellcheck:`false`}});let t=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Sortear`),title:a(`Sortear outra aparência (desfaz as peças escolhidas)`),on:{click:()=>this.roll()}});this.error=P(`p`,{class:`ui-char__error`,role:`alert`,hidden:!0}),this.saveBtn=P(`button`,{class:`ui-btn ui-btn--primary`,type:`button`,text:a(`Salvar`),on:{click:()=>void this.save()}});let n=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Cancelar`),on:{click:()=>this.cancel()}});this.resetBtn=P(`button`,{class:`ui-link-btn ui-char__reset`,type:`button`,text:a(`Voltar ao sorteio`),on:{click:()=>void this.reset()}}),this.el=P(`section`,{class:`ui-char`,hidden:!0,attrs:{"aria-label":a(`Editar personagem`)},on:{keydown:e=>this.onKey(e)}},P(`div`,{class:`ui-char__top`},this.fields.preview,P(`div`,{class:`ui-char__head`},P(`label`,{class:`ui-char__label`},P(`span`,{text:a(`Nome`)}),this.nameInput),t)),P(`p`,{class:`ui-muted ui-small`,text:a(`Vale para o projeto: a próxima sessão nesta sala chega com este personagem.`)}),this.fields.groups,this.error,P(`div`,{class:`ui-char__actions`},this.saveBtn,n,this.resetBtn))}open(e){e!==this.agentId&&this.close(),this.agentId=e}render(e,t){let n=this.ctx.store,r=Cv(e,{live:t,terminal:!!n.snapshot?.meta.terminal,local:I().local,replaying:n.replaying,mock:n.mock});F(this.button,!r),this.editing&&!r&&(this.close(),(!t||e.status===`offline`)&&this.ctx.announce(a(`O agente saiu do escritório.`))),this.editing&&!this.confirmingReset&&F(this.resetBtn,!e.custom)}start(){let e=this.ctx.agent(this.agentId);e&&(this.editId++,this.seed=e.seed,this.look=e.look,this.base=rs(e.seed,{look:e.look}),this.nameInput.value=e.name,this.confirmingReset=!1,M(this.resetBtn,a(`Voltar ao sorteio`)),F(this.resetBtn,!e.custom),this.showError(null),this.editing=!0,F(this.el,!1),N(this.button,`aria-expanded`,`true`),this.fields.set({...this.base,...e.parts}),this.nameInput.focus(),this.nameInput.select())}close(){this.editing&&(this.editing=!1,this.busy=!1,this.saveBtn.disabled=!1,F(this.el,!0),N(this.button,`aria-expanded`,`false`))}cancel(){this.close(),this.button.focus()}roll(){this.seed=Gv(),this.base=rs(this.seed,{look:this.look}),this.fields.set({...this.base})}async save(){let e=this.fields.value;if(this.busy||!this.base||!e)return;let t=this.nameInput.value.trim();if(!t)return this.showError(a(`Dê um nome ao personagem.`));let n=this.agentId,r=this.editId;this.busy=!0,this.saveBtn.disabled=!0;let i=await this.ctx.store.saveCharacter(n,{name:t,seed:this.seed,parts:wv(this.base,e)});if(this.editing&&this.agentId===n&&this.editId===r){if(this.busy=!1,this.saveBtn.disabled=!1,i)return this.showError(i);this.close(),this.button.focus(),this.ctx.announce(a(`Personagem salvo: {0}.`,[t]))}}async reset(){if(this.busy)return;if(!this.confirmingReset){this.confirmingReset=!0,M(this.resetBtn,a(`Confirmar: voltar ao sorteio`));return}let e=this.agentId,t=this.editId;this.busy=!0;let n=await this.ctx.store.resetCharacter(e);if(this.editing&&this.agentId===e&&this.editId===t){if(this.busy=!1,n)return this.showError(n);this.close(),this.button.focus(),this.ctx.announce(a(`O personagem voltou ao sorteio.`))}}showError(e){M(this.error,e??``),F(this.error,!e),e&&this.nameInput.focus()}onKey(e){e.key===`Escape`?(e.stopPropagation(),this.cancel()):e.key===`Enter`&&e.target===this.nameInput&&(e.preventDefault(),this.save())}},qv=a(`Para mandar mensagens daqui: npm run mod:install (plugin busybits-messages)`),Jv=a(`Para mandar mensagens ao Codex: com o Habblaud no Docker, deixe npm run codex:bridge rodando; no modo Node funciona sozinho`);function Yv(e,t){if(t.replaying)return{kind:`off`,text:a(`Sem mensagens no timelapse: o escritório mostrado é o de outro momento`)};if(e?.kind===`sub`)return{kind:`off`,text:a(`Subagentes não recebem mensagens: escreva para o agente principal`)};if(!e||e.status===`offline`||e.status===`done`)return{kind:`off`,text:a(`Sessão encerrada`)};if(e.provider===`agent-hub`)return{kind:`off`,text:a(`Somente leitura: o Agent Hub gerencia este job`)};let n=e.provider===`codex`;return t.enabled?t.local?e.duplicateSession&&!e.duplicateSession.newest?{kind:`hint`,text:a(`Esta conversa está aberta em outro terminal; as mensagens vão para o mais novo`)}:e.canMessage?{kind:`ready`}:{kind:`hint`,text:n?Jv:qv}:{kind:`off`,text:a(`Para mandar mensagens por aqui, abra o Habblaud por http://localhost (ou 127.0.0.1)`)}:{kind:`off`,text:a(n?`Para responder, use o Codex`:`Para responder, use o terminal do Claude Code`)}}function Xv(e=`claude`,t=!1){let n=Zv(e);return t?`${n} ${a(`Cole ou anexe imagens: o agente recebe o caminho dos arquivos.`)}`:n}function Zv(e){return a(e===`codex`?`Entra na fila da sessão e vira o próximo prompt quando o Codex terminar o que está fazendo. Enter manda; Shift+Enter quebra a linha.`:`Entra na sessão como se você tivesse digitado. Enter manda; Shift+Enter quebra a linha.`)}function Qv(e){return e.replace(/\s+$/,``)}function $v(e,t){let n=Qv(e);return t&&(t.ready>0||t.uploading>0||t.failed>0)?!(t.uploading>0||t.failed>0||n.length>2e4||n.trim()===`/`||h(n)):n.trim().length>0&&n.trim()!==`/`&&n.length<=2e4}function ey(e){return e.key===`Enter`&&!e.shiftKey&&!e.altKey&&!e.isComposing}function ty(e){return e===`delivered`||e===`failed`||e===`rejected`}function ny(e,t,n=`claude`){if(!e)return``;let r=n===`codex`;switch(e.phase){case`sending`:return a(`Enviando…`);case`queued`:return a(r?`Na fila: entregando ao Codex…`:`Na fila: esperando a sessão buscar a mensagem…`);case`sent`:return a(`Entregando à sessão…`);case`delivered`:return t-e.at>=12e3?``:a(r?`Entregue ✓ na fila da sessão: entra quando o Codex terminar o que está fazendo (até ~10 s)`:`Entregue ✓ (se o agente estiver ocupado, entra quando ele terminar)`);case`rejected`:return a(`Não foi possível mandar: {0}`,[e.error??a(`erro desconhecido`)]);case`failed`:return a(`Não foi entregue: {0}`,[e.error??a(`erro desconhecido`)])}}function ry(e){return e<1e4?700:e<4e4?1500:3e3}var iy=a(`o Habblaud não conhece mais esta mensagem (ele reiniciou?)`),ay=a(`sem notícia da entrega: confira no terminal do Claude Code`),oy=a(`sem notícia da entrega: confira no Codex`),sy=a(`não foi possível falar com o Habblaud`);function cy(e){return e instanceof TypeError?sy:e instanceof Error&&e.message?e.message:sy}var ly=a(`Comandos de barra não levam imagens.`);function uy(e=`claude`){return e===`codex`?oy:ay}var dy=[`user`,`plugin`,`mcp`,`builtin`],fy={user:()=>a(`Seus`),plugin:()=>a(`Plugins`),mcp:()=>a(`MCP`),builtin:()=>a(`Do Claude Code`)};function py(e){let t={user:[],plugin:[],mcp:[],builtin:[]};for(let n of e)t[n.source in t?n.source:`builtin`].push(n);let n=[];for(let e of dy){let r=t[e];r.length>0&&n.push({source:e,label:fy[e](),count:r.length,commands:r})}return n}function my(e,t){if(t<1)return;let n=hy(e,t),r=e.slice(n,t);if(!r.startsWith(`/`))return;let i=r.slice(1);return i.includes(`/`)?void 0:i}function hy(e,t){let n=t;for(;n>0&&!/\s/.test(e[n-1]);)n--;return n}function gy(e,t,n){let r=t.trim().toLowerCase();if(!r)return n===void 0?[...e]:e.slice(0,n);let i=[],a=[],o=[];for(let t of e){let e=t.name.toLowerCase(),n=(t.description??``).toLowerCase();e.startsWith(r)?i.push(t):e.includes(r)?a.push(t):n.includes(r)&&o.push(t)}let s=[...i,...a,...o];return n===void 0?s:s.slice(0,n)}function _y(e,t,n){let r=n===void 0?0:hy(e,n),i=e.slice(r+1),a=i.search(/\s/),o=a<0?``:i.slice(a).replace(/^[ \t]+/,``),s=`${e.slice(0,r)}/${t} `;return{value:s+o,caret:s.length}}function vy(e,t){return!!e&&e.commands.length>0&&t-e.at<3e4}function yy(e,t,n=8){if(!t.open)return{action:`none`};if(t.count<=0)return e===`Escape`?{action:`close`}:e===`Enter`||e===`Tab`?{action:`block`}:{action:`none`};switch(e){case`ArrowDown`:return{action:`move`,index:(t.index+1)%t.count};case`ArrowUp`:return{action:`move`,index:(t.index-1+t.count)%t.count};case`PageDown`:return t.focusedByKeyboard?{action:`move`,index:Math.min(t.count-1,t.index+n)}:{action:`none`};case`PageUp`:return t.focusedByKeyboard?{action:`move`,index:Math.max(0,t.index-n)}:{action:`none`};case`Home`:return t.focusedByKeyboard?{action:`move`,index:0}:{action:`none`};case`End`:return t.focusedByKeyboard?{action:`move`,index:t.count-1}:{action:`none`};case`Tab`:return{action:`accept`};case`Enter`:return t.exact?{action:`none`}:{action:`accept`};case`Escape`:return{action:`close`};default:return{action:`none`}}}var by=600,xy=15e4,Sy=[`audio/mp4`,`audio/webm;codecs=opus`,`audio/webm`,`audio/ogg;codecs=opus`];function Cy(e){return a(e===`pt`?`Ditado em português: confira o texto.`:e===`en`?`Ditado em inglês: confira o texto.`:e===`es`?`Ditado em espanhol: confira o texto.`:`Ditado pronto: confira o texto.`)}function wy(e,t,n,r){let i=r.trim();if(!i)return{value:e,caret:n};let a=e.slice(0,t),o=e.slice(n),s=a&&!/\s$/.test(a)?` `:``;return{value:`${a}${s}${i}${o&&!/^\s/.test(o)?` `:``}${o}`,caret:a.length+s.length+i.length}}function Ty(e){return Sy.find(t=>{try{return e(t)}catch{return!1}})}function Ey(){return typeof window<`u`&&window.isSecureContext&&!!navigator.mediaDevices?.getUserMedia&&typeof MediaRecorder<`u`}function Dy(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result).replace(/^data:[^,]*,/,``)),r.onerror=()=>n(Error(a(`não deu para ler a gravação`))),r.readAsDataURL(e)})}async function Oy(e,t){let n;try{n=await fetch(e,{credentials:`same-origin`,cache:`no-store`,...t})}catch{throw Error(a(`o Habblaud não respondeu`))}let r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??a(`erro {0}`,[n.status]));return r}var ky=3e4,Ay=null;function jy(e=Date.now()){if(!Ey())return Promise.resolve(!1);if(Ay&&e-Ay.at<ky)return Ay.value;let t=Oy(`/api/dictation`).then(e=>e.available===!0,()=>!1);return Ay={at:e,value:t},t}var My=class{onText;say;opts;el;label;state=`idle`;recorder=null;stream=null;chunks=[];timer=null;startedAt=0;cancelled=!1;constructor(e,t,n={}){this.onText=e,this.say=t,this.opts=n,this.label=P(`span`,{class:`ui-dictate__label`,text:n.compact?``:a(`Ditar`)}),this.el=P(`button`,{class:`ui-btn ui-dictate${n.compact?` ui-dictate--compact`:``}`,type:`button`,title:a(`Ditar (português ou inglês, o idioma é detectado sozinho)`),attrs:{"aria-pressed":`false`,"aria-label":a(`Ditar`)},on:{click:()=>void this.toggle()}});let r=P(`span`,{class:`ui-dictate__icon`,attrs:{"aria-hidden":`true`}});r.innerHTML=Q.mic,this.el.append(r,this.label)}get busy(){return this.state!==`idle`}cancel(){this.state===`recording`&&(this.cancelled=!0,this.stopRecorder())}async toggle(){if(this.state===`recording`)return this.stopRecorder();this.state!==`working`&&await this.start()}async start(){if(!Ey())return this.say(a(`Este navegador não deixa gravar áudio aqui (precisa de HTTPS).`),!0);try{this.stream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})}catch(e){let t=e?.name===`NotAllowedError`;return this.say(a(t?`Sem permissão para o microfone: libere nas configurações do navegador e tente de novo.`:`Não deu para abrir o microfone.`),!0)}let e=Ty(e=>MediaRecorder.isTypeSupported(e));try{this.recorder=new MediaRecorder(this.stream,e?{mimeType:e}:void 0)}catch{return this.release(),this.say(a(`Este navegador não grava áudio.`),!0)}this.chunks=[],this.cancelled=!1,this.recorder.addEventListener(`dataavailable`,e=>{e.data.size&&this.chunks.push(e.data)}),this.recorder.addEventListener(`stop`,()=>void this.finish(),{once:!0}),this.recorder.start(1e3),this.startedAt=Date.now(),this.opts.onStart?.(),this.set(`recording`),this.say(this.opts.compact?a(`Gravando… toque no microfone de novo para parar.`):a(`Gravando… fale em português ou inglês e toque em Parar.`)),this.timer=setInterval(()=>{let e=Date.now()-this.startedAt,t=Math.floor(e/1e3),n=`${Math.floor(t/60)}:${String(t%60).padStart(2,`0`)}`;M(this.label,this.opts.compact?n:a(`Parar {0}`,[n])),e>=18e4&&this.stopRecorder()},250)}stopRecorder(){this.timer&&clearInterval(this.timer),this.timer=null;try{this.recorder?.state!==`inactive`&&this.recorder?.stop()}catch{}}release(){this.stream?.getTracks().forEach(e=>e.stop()),this.stream=null}async finish(){let e=this.recorder?.mimeType||this.chunks[0]?.type||`audio/mp4`,t=new Blob(this.chunks,{type:e});if(this.chunks=[],this.recorder=null,this.release(),this.cancelled)return this.cancelled=!1,this.set(`idle`);if(t.size<512)return this.set(`idle`),this.say(a(`Não ouvi nada: tente de novo, mais perto do microfone.`),!0);this.set(`working`),this.say(a(`Transcrevendo no computador…`));try{let n=await Oy(`/api/dictation`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:e.split(`;`)[0],data:await Dy(t)})}),r=Date.now()+xy;for(;(n.status===`queued`||n.status===`sent`)&&Date.now()<r;)await new Promise(e=>setTimeout(e,by)),n=await Oy(`/api/dictation/${encodeURIComponent(n.id)}`);if(n.status!==`done`)throw Error(n.error||a(`o computador não respondeu a tempo`));n.text?.trim()?(this.onText({text:n.text,lang:n.lang}),this.say(Cy(n.lang))):this.say(a(`Não entendi nada na gravação: tente de novo.`),!0)}catch(e){this.say(a(`Ditado falhou: {0}`,[e.message]),!0)}finally{this.set(`idle`)}}set(e){this.state=e,this.el.classList.toggle(`is-recording`,e===`recording`),this.el.classList.toggle(`is-working`,e===`working`),this.el.setAttribute(`aria-pressed`,String(e===`recording`)),this.el.disabled=e===`working`;let t=this.el.querySelector(`.ui-dictate__icon`);t&&(t.innerHTML=e===`recording`?Q.stopRec:Q.mic),this.el.setAttribute(`aria-label`,a(e===`recording`?`Parar o ditado`:e===`working`?`Transcrevendo`:`Ditar`)),this.opts.compact?M(this.label,e===`recording`?`0:00`:e===`working`?`…`:``):M(this.label,e===`recording`?a(`Parar {0}`,[`0:00`]):a(e===`working`?`Transcrevendo…`:`Ditar`))}},Ny=s.join(`,`);function Py(e){let t=[],n=!1;for(let r=0;r<e.length;r++){let i=e[r];if(i.kind===`string`&&i.type.startsWith(`text/`))n=!0;else if(i.kind===`file`&&i.type.startsWith(`image/`)){let e=i.getAsFile();e&&t.push(e)}}return{files:t,hasText:n}}function Fy(e){let{files:t,hasText:n}=Py(e);return n?[]:t}function Iy(e,t){return t>=8?{ok:!1,error:a(`No máximo {0} imagens por mensagem.`,[8])}:e.type&&!s.includes(e.type.toLowerCase())?{ok:!1,error:a(`{0} não é uma imagem PNG, JPEG, GIF ou WebP.`,[e.name])}:e.size?e.size>15728640?{ok:!1,error:a(`{0} passa de {1} MB.`,[e.name,u/1024/1024])}:{ok:!0}:{ok:!1,error:a(`arquivo vazio`)}}var Ly=class{byAgent=new Map;list(e){return this.byAgent.get(e)??[]}add(e,t){this.byAgent.set(e,[...this.list(e),t])}patch(e,t,n){let r=this.byAgent.get(e);r&&this.byAgent.set(e,r.map(e=>e.key===t?{...e,...n}:e))}remove(e,t){let n=this.list(e),r=n.find(e=>e.key===t);if(r)return this.set(e,n.filter(e=>e!==r)),r}clear(e){let t=this.list(e);return this.byAgent.delete(e),t}counts(e){let t={ready:0,uploading:0,failed:0};for(let n of this.list(e))t[n.state]++;return t}set(e,t){t.length?this.byAgent.set(e,t):this.byAgent.delete(e)}};function Ry(e){return e.failed>0?e.failed===1?a(`{0} imagem não subiu: tente de novo ou tire-a`,[e.failed]):a(`{0} imagens não subiram: tente de novo ou tire-as`,[e.failed]):e.uploading>0?a(`Enviando imagens…`):``}function zy(e,t){return!e&&t===!0}function By(e,t,n){let r=[];for(let i of n){let n=e.remove(t,i);n&&r.push(n)}return r}function Vy(e,t,n,r,i){for(let a of n){let n=e.list(t).find(e=>e.key===a);(!i||n?.id&&i.includes(n.id))&&e.patch(t,a,{state:`failed`,error:r,id:void 0})}}function Hy(e){return e.imageError?{text:e.imageError,kind:`error`}:e.counts.failed>0?{text:Ry(e.counts),kind:`error`}:e.send?{text:e.send,kind:e.sendKind}:{text:Ry(e.counts),kind:``}}var Uy=class{box;opts;el;list;items=[];groups=[];index=0;dismissed=!1;focusedByKeyboard=!1;cache=new Map;constructor(e,t){this.box=e,this.opts=t,this.list=P(`div`,{class:`ui-slash__list`,role:`listbox`,attrs:{id:`ui-slash-${++Wy}`,"aria-label":a(`Comandos disponíveis`)}}),this.el=P(`div`,{class:`ui-slash`,hidden:!0},this.list),this.el.addEventListener(`mousedown`,e=>e.preventDefault()),this.box.setAttribute(`aria-controls`,this.list.id),this.box.setAttribute(`aria-autocomplete`,`list`),this.box.addEventListener(`blur`,()=>this.hide()),this.box.addEventListener(`keyup`,e=>{(e.key===`ArrowLeft`||e.key===`ArrowRight`||e.key===`Home`||e.key===`End`)&&this.update()}),this.box.addEventListener(`click`,()=>this.update())}get isOpen(){return!this.el.hidden}hide(){this.dismissed=!1,this.focusedByKeyboard=!1,this.close()}update(){let e=this.opts.enabled()?my(this.box.value,this.box.selectionStart??this.box.value.length):void 0;if(e===void 0)return this.dismissed=!1,this.focusedByKeyboard=!1,this.close();if(this.dismissed)return;let t=this.opts.agentId(),n=this.cache.get(t),r=vy(n,Date.now());if(r||this.fetch(t),!n?.commands.length&&!r){this.showLoading();return}this.show(e,n?.commands??[])}handleKey(e){if(e.isComposing||e.ctrlKey||e.metaKey||e.altKey||e.shiftKey)return!1;let t=this.items[this.index]?.name.toLowerCase()===(my(this.box.value,this.box.selectionStart??0)??``).toLowerCase(),n=yy(e.key,{open:this.isOpen,count:this.items.length,index:this.index,exact:t,focusedByKeyboard:this.focusedByKeyboard});switch(n.action){case`move`:this.focusedByKeyboard=!0,this.index=n.index,this.paintSelection();break;case`accept`:this.accept(this.index);break;case`block`:break;case`close`:this.dismissed=!0,this.focusedByKeyboard=!1,this.close();break;default:return!1}return e.preventDefault(),!0}async fetch(e){let t=this.cache.get(e);if(t?.pending)return;let n={at:Date.now(),commands:t?.commands??[],pending:void 0};this.cache.set(e,n),n.pending=this.opts.load(e).then(t=>{n.commands=t,n.at=Date.now(),n.pending=void 0,e===this.opts.agentId()&&this.repaint()},()=>{n.pending=void 0,e===this.opts.agentId()&&this.repaint()}),await n.pending}repaint(){let e=this.opts.enabled()?my(this.box.value,this.box.selectionStart??this.box.value.length):void 0;if(e===void 0)return this.close();this.dismissed||this.show(e,this.cache.get(this.opts.agentId())?.commands??[])}show(e,t){if(!t.length)return this.showEmptySession();let n=gy(t,e);if(!n.length)return this.showEmptyQuery(e);let r=n.length===this.items.length&&n.every((e,t)=>e.name===this.items[t]?.name);this.items=n,this.groups=py(n),r||(this.index=0),this.paint(e),F(this.el,!1),this.box.setAttribute(`aria-expanded`,`true`)}showLoading(){this.items=[],this.groups=[],this.index=0,this.list.replaceChildren(P(`div`,{class:`ui-slash__empty ui-slash__loading`,role:`presentation`,text:a(`Carregando comandos…`)})),this.box.removeAttribute(`aria-activedescendant`),F(this.el,!1),this.box.setAttribute(`aria-expanded`,`true`)}showEmptySession(){this.items=[],this.groups=[],this.index=0,this.list.replaceChildren(P(`div`,{class:`ui-slash__empty`,role:`presentation`,text:a(`Sem comandos desta sessão ainda — rode /reload-plugins no terminal dela`)})),this.box.removeAttribute(`aria-activedescendant`),F(this.el,!1),this.box.setAttribute(`aria-expanded`,`true`)}showEmptyQuery(e){this.items=[],this.groups=[],this.index=0,this.list.replaceChildren(P(`div`,{class:`ui-slash__empty`,role:`presentation`,text:a(`Nenhum comando com “{0}”`,[e])})),this.box.removeAttribute(`aria-activedescendant`),F(this.el,!1),this.box.setAttribute(`aria-expanded`,`true`)}close(){this.items=[],this.groups=[],this.index=0,this.el.hidden||F(this.el,!0),this.box.setAttribute(`aria-expanded`,`false`),this.box.removeAttribute(`aria-activedescendant`)}paint(e){let t=[],n=0;for(let r of this.groups){let i=P(`div`,{class:`ui-slash__group`,role:`group`,attrs:{"aria-label":`${r.label} (${r.count})`}}),a=P(`div`,{class:`ui-slash__group-header`,role:`presentation`},P(`span`,{class:`ui-slash__group-title`,text:r.label}),P(`span`,{class:`ui-slash__group-count`,text:String(r.count)}));i.append(a);for(let t of r.commands){let r=n++,a=`${this.list.id}-${r}`,o=r===this.index,s=this.renderRow(t,r,a,o,e);i.append(s)}t.push(i)}this.list.replaceChildren(...t),this.paintSelection()}renderRow(e,t,n,r,i){let a=this.renderName(e,i),o=P(`span`,{class:`ui-slash__desc`,attrs:{...e.description?{"data-tip":e.description}:{}},text:e.description||``}),s=P(`div`,{class:`ui-slash__item${r?` is-active`:``}`,role:`option`,attrs:{id:n,"aria-selected":r}},a,o);return s.addEventListener(`mouseenter`,()=>{this.focusedByKeyboard=!1,this.index=t,this.paintSelection()}),s.addEventListener(`click`,()=>this.accept(t)),s}renderName(e,t){let n=P(`span`,{class:`ui-slash__name`});n.append(P(`span`,{class:`ui-slash__slash`,text:`/`}));let r=e.source===`plugin`&&e.name.includes(`:`),i=r?e.name.indexOf(`:`)+1:0,a=t.toLowerCase(),o=a?e.name.toLowerCase().indexOf(a):-1;if(!r){if(o>=0){let t=e.name.slice(0,o),r=e.name.slice(o,o+a.length),i=e.name.slice(o+a.length);t&&n.append(t),n.append(P(`mark`,{class:`ui-slash__match`,text:r})),i&&n.append(i)}else n.append(e.name);return n}let s=P(`span`,{class:`ui-slash__ns`}),c=P(`span`,{class:`ui-slash__base`});if(o<0)return s.textContent=e.name.slice(0,i),c.textContent=e.name.slice(i),n.append(s,c),n;let l=o+a.length,u=e.name.slice(0,Math.min(i,Math.max(0,o))),d=e.name.slice(Math.max(0,Math.min(i,o)),Math.min(i,Math.max(0,l))),f=e.name.slice(Math.min(i,Math.max(0,l)),i);u&&s.append(u),d&&s.append(P(`mark`,{class:`ui-slash__match`,text:d})),f&&s.append(f);let p=e.name.slice(i,Math.min(e.name.length,Math.max(i,o))),m=e.name.slice(Math.max(i,Math.min(e.name.length,o)),Math.min(e.name.length,Math.max(i,l))),h=e.name.slice(Math.min(e.name.length,Math.max(i,l)));return p&&c.append(p),m&&c.append(P(`mark`,{class:`ui-slash__match`,text:m})),h&&c.append(h),n.append(s,c),n}paintSelection(){let e=this.list.querySelector(`.ui-slash__item.is-active`);e&&(e.classList.remove(`is-active`),e.setAttribute(`aria-selected`,`false`)),this.index>=this.items.length&&(this.index=Math.max(0,this.items.length-1));let t=this.list.querySelector(`#${this.list.id}-${this.index}`);t?(t.classList.add(`is-active`),t.setAttribute(`aria-selected`,`true`),this.box.setAttribute(`aria-activedescendant`,t.id),this.scrollToElement(t)):this.box.removeAttribute(`aria-activedescendant`)}scrollToElement(e){let t=typeof window<`u`&&!!window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches;e.scrollIntoView?.({block:`nearest`,behavior:t?`auto`:`smooth`})}accept(e){let t=this.items[e];if(!t)return;let n=_y(this.box.value,t.name,this.box.selectionStart??this.box.value.length);this.box.value=n.value,this.box.setSelectionRange(n.caret,n.caret),this.close(),this.opts.onChange()}},Wy=0,Gy=class{ctx;variant;opts;el;agentId=``;mode={kind:`off`,text:``};drafts=new Map;states=new Map;providers=new Map;provider=`claude`;shown=``;images=new Ly;imageErrors=new Map;imageSeq=0;imageAgents=new Set;thumbs;fileInput;attachBtn;row;box;sendBtn;hint;tip;status;dictate;slash;dictStatus;dictTimer=null;dictKey=``;canDictate=!1;constructor(e,t,n={}){this.ctx=e,this.variant=t,this.opts=n;let r=t===`terminal`;this.box=P(`textarea`,{class:`ui-msg__input${r?` ui-term__input`:``}`,attrs:{rows:1,maxlength:p,autocomplete:`off`,enterkeyhint:`send`}}),this.slash=new Uy(this.box,{load:e=>this.ctx.store.slashCommands(e),agentId:()=>this.agentId,enabled:()=>this.mode.kind===`ready`,onChange:()=>{this.drafts.set(this.agentId,this.box.value),this.resize(),this.syncButton()}}),this.box.addEventListener(`input`,()=>{this.imageErrors.delete(this.agentId),this.drafts.set(this.agentId,this.box.value),this.resize(),this.syncButton(),this.slash.update()}),this.box.addEventListener(`focus`,()=>this.resize()),this.box.addEventListener(`keydown`,e=>this.onKey(e)),this.box.addEventListener(`paste`,e=>this.onPaste(e)),this.sendBtn=P(`button`,{class:r?`ui-msg__send`:`ui-btn ui-msg__send`,type:`button`,title:a(`Mandar (Enter)`),attrs:{"aria-label":a(`Mandar a mensagem`)},on:{click:()=>void this.send()}},r?`↵`:a(`Enviar`)),this.dictStatus=P(`p`,{class:`ui-msg__status ui-msg__dictation`,role:`status`,hidden:!0,attrs:{"aria-live":`polite`}}),this.dictate=new My(e=>this.insertDictated(e.text),(e,t)=>this.sayDictation(e,t),{compact:!0,onStart:()=>this.dictKey=this.agentId}),this.dictate.el.classList.add(`ui-msg__mic`),F(this.dictate.el,!0),this.fileInput=P(`input`,{class:`ui-msg__file`,type:`file`,hidden:!0,attrs:{multiple:``,accept:Ny,"aria-hidden":`true`,tabindex:`-1`}}),this.fileInput.addEventListener(`change`,()=>{let e=Array.from(this.fileInput.files??[]);this.fileInput.value=``,this.addImages(e)}),this.attachBtn=j(Q.attach,a(`Anexar imagens`),()=>this.fileInput.click(),`ui-msg__attach`),F(this.attachBtn,!0),this.thumbs=P(`ul`,{class:`ui-msg__images`,hidden:!0,attrs:{"aria-label":a(`Anexar imagens`)}}),this.row=P(`div`,{class:`ui-msg__row${r?` ui-term__prompt ui-term__prompt--mic`:``}`}),r&&this.row.append(P(`span`,{class:`ui-term__caret`,text:`>`,attrs:{"aria-hidden":`true`}})),this.row.append(this.box,this.dictate.el,this.attachBtn,this.sendBtn),this.row.addEventListener(`mousedown`,e=>{e.target===this.row&&!this.box.disabled&&(e.preventDefault(),this.box.focus())}),this.hint=P(`p`,{class:`ui-msg__hint`,hidden:!0}),this.status=P(`p`,{class:`ui-msg__status`,role:`status`,hidden:!0,attrs:{"aria-live":`polite`}}),this.tip=r?null:P(`p`,{class:`ui-msg__tip`,text:Xv()}),this.el=P(`div`,{class:`ui-msg ui-msg--${t}`},this.hint,this.slash.el,this.thumbs,this.row,this.fileInput,this.dictStatus,this.status,this.tip)}render(e,t=e?.id??``){let n=this.ctx.store,r=Yv(e,{enabled:n.mock||!!n.snapshot?.meta.messages,local:n.mock||I().messages,replaying:n.replaying});this.mode=r;let i=r.kind===`ready`,o=this.variant===`terminal`;this.provider=e?.provider===`codex`?`codex`:`claude`,zy(n.mock,I().messageImages)||this.clearAllImages();let s=`${t}|${i}`;s!==this.shown&&(this.dictate.cancel(),this.slash.hide(),this.shown=s,this.agentId=t,this.box.value=i?this.drafts.get(t)??``:``,this.box.style.height=``,i&&requestAnimationFrame(()=>this.resize()),this.renderThumbs()),this.box.disabled=!i;let c=e?.name??a(`o agente`),l=i?a(o?`Mensagem para {0} (Enter manda, Shift+Enter quebra a linha)`:`Mensagem para {0}…`,[c]):r.text;return N(this.box,`placeholder`,l),N(this.box,`aria-label`,i?a(`Mensagem para {0}`,[c]):r.text),A(this.box,i?``:r.text),this.row.classList.toggle(`is-disabled`,!i),F(this.sendBtn,!i),F(this.attachBtn,!this.canImages()),jy().then(e=>{e!==this.canDictate&&(this.canDictate=e,this.ctx.invalidate())}),F(this.dictate.el,!this.canDictate||!i&&!this.dictate.busy),F(this.row,!o&&!i),this.tip&&(F(this.tip,!i),M(this.tip,Xv(this.provider,this.canImages()))),F(this.hint,o||r.kind!==`hint`),M(this.hint,r.kind===`hint`?r.text:``),this.syncButton(),r.kind}onKey(e){if(!e.ctrlKey&&!e.metaKey&&e.stopPropagation(),this.slash.handleKey(e)){e.stopPropagation();return}if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.opts.onEscape?this.opts.onEscape():this.box.blur();return}ey(e)&&(e.preventDefault(),this.send())}insertDictated(e){let t=this.dictKey;if(t===this.agentId&&!this.box.disabled){let n=this.box,{value:r,caret:i}=wy(n.value,n.selectionStart??n.value.length,n.selectionEnd??n.value.length,e);n.value=r.slice(0,p),this.drafts.set(t,n.value),this.resize(),this.syncButton(),n.focus({preventScroll:!0}),n.setSelectionRange(i,i)}else{let n=this.drafts.get(t)??``;this.drafts.set(t,wy(n,n.length,n.length,e).value.slice(0,p))}}sayDictation(e,t=!1){this.dictTimer&&clearTimeout(this.dictTimer),M(this.dictStatus,e),F(this.dictStatus,!e),this.dictStatus.classList.toggle(`is-error`,t),!t&&!/…$/.test(e)&&(this.dictTimer=setTimeout(()=>F(this.dictStatus,!0),6e3))}syncButton(){this.sendBtn.disabled=this.mode.kind!==`ready`||!$v(this.box.value,this.images.counts(this.agentId))||this.states.get(this.agentId)?.phase===`sending`,this.renderStatus()}renderStatus(){let e=this.agentId,t=this.states.get(e),n=this.images.counts(e),r=n.ready+n.uploading+n.failed>0&&h(Qv(this.box.value)),i=ny(t,Date.now(),this.providers.get(e)??this.provider),a=t?.phase===`failed`||t?.phase===`rejected`?`error`:t?.phase===`delivered`?`ok`:``,o=Hy({imageError:this.imageErrors.get(e)??(r?ly:void 0),send:i,sendKind:a,counts:n});M(this.status,o.text),F(this.status,!o.text),this.status.classList.toggle(`is-error`,o.kind===`error`),this.status.classList.toggle(`is-ok`,o.kind===`ok`)}canImages(){return zy(this.ctx.store.mock,I().messageImages)&&this.mode.kind===`ready`}onPaste(e){let t=Fy(e.clipboardData?.items??[]);t.length&&this.canImages()&&(e.preventDefault(),this.addImages(t))}addImages(e){if(!e.length||!this.canImages())return;let t=this.agentId;this.imageErrors.delete(t);for(let n of e){let e=Iy(n,this.images.list(t).length);if(!e.ok){this.imageErrors.set(t,e.error);continue}let r={key:`${Date.now()}-${++this.imageSeq}`,name:n.name,type:n.type,size:n.size,state:`uploading`,file:n,url:URL.createObjectURL(n)};this.images.add(t,r),this.imageAgents.add(t),this.upload(t,r)}this.refreshImages()}async upload(e,t){let n;try{n=await this.ctx.store.uploadMessageImage(t.file)}catch(e){n={error:cy(e)}}if(!this.images.list(e).some(e=>e.key===t.key)){`id`in n&&this.ctx.store.dropMessageImage(n.id);return}this.images.patch(e,t.key,`id`in n?{state:`ready`,id:n.id,error:void 0}:{state:`failed`,error:n.error}),e===this.agentId&&this.refreshImages()}retryImage(e){let t=this.agentId;this.imageErrors.delete(t),this.images.patch(t,e.key,{state:`uploading`,error:void 0}),this.refreshImages(),this.upload(t,e)}removeImage(e){this.imageErrors.delete(this.agentId);let t=this.images.remove(this.agentId,e.key);t&&this.release(t),this.refreshImages()}release(e){URL.revokeObjectURL(e.url),e.id&&this.ctx.store.dropMessageImage(e.id)}clearAllImages(){let e=this.images.list(this.agentId).length>0;for(let e of this.imageAgents)for(let t of this.images.clear(e))this.release(t);this.imageErrors.clear(),e&&this.refreshImages()}refreshImages(){this.renderThumbs(),this.syncButton()}renderThumbs(){let e=this.images.list(this.agentId);this.thumbs.replaceChildren(...e.map((e,t)=>{let n=P(`li`,{class:`ui-msg__image${e.state===`uploading`?` is-uploading`:e.state===`failed`?` is-failed`:``}`});e.error&&A(n,e.error);let r=P(`img`,{class:`ui-msg__image-img`,attrs:{src:e.url,alt:a(`Imagem {0} (anexo da mensagem)`,[t+1])}});return n.append(r,j(Q.close,a(`Tirar {0}`,[e.name]),()=>this.removeImage(e),`ui-icon-btn--sm ui-msg__image-x`)),e.state===`failed`&&n.append(P(`button`,{class:`ui-msg__image-retry`,type:`button`,title:a(`Tentar de novo`),text:`↻`,attrs:{"aria-label":a(`Tentar de novo`)},on:{click:()=>this.retryImage(e)}})),n})),F(this.thumbs,!e.length||this.mode.kind!==`ready`)}resize(){let e=this.box;e.isConnected&&e.offsetParent!==null&&(e.style.height=`auto`,e.style.height=`${e.scrollHeight+e.offsetHeight-e.clientHeight}px`)}setState(e,t){this.states.set(e,t),e===this.agentId&&this.syncButton(),this.ctx.invalidate()}async send(){let e=this.agentId,t=this.box.value;if(this.mode.kind!==`ready`||!$v(t,this.images.counts(e))||this.states.get(e)?.phase===`sending`)return;let n=this.images.list(e).filter(e=>e.state===`ready`),r=n.map(e=>e.key);this.imageErrors.delete(e),this.providers.set(e,this.provider),this.setState(e,{phase:`sending`,at:Date.now()});let i;try{i=await this.ctx.store.sendMessage(e,Qv(t),n.map(e=>e.id))}catch{i={error:sy}}if(`error`in i){`expired`in i&&i.expired&&(Vy(this.images,e,r,i.error,i.expired),this.imageErrors.set(e,i.error),e===this.agentId&&this.renderThumbs()),this.setState(e,{phase:`rejected`,error:i.error,at:Date.now()});return}for(let t of By(this.images,e,r))URL.revokeObjectURL(t.url);e===this.agentId&&this.renderThumbs(),(this.drafts.get(e)??``)===t&&(this.drafts.delete(e),this.agentId===e&&this.box.value===t&&(this.box.value=``,this.resize(),this.slash.hide()));let a=i.message;this.setState(e,{phase:a.status,id:a.id,error:a.error,at:Date.now()}),ty(a.status)||this.poll(e,a.id,Date.now())}poll(e,t,n){let r=async()=>{if(this.states.get(e)?.id!==t)return;let i;try{i=await this.ctx.store.messageStatus(t)}catch{}let a=this.states.get(e);if(a?.id!==t)return;let o=Date.now();if(i===null)return this.setState(e,{phase:`failed`,id:t,error:iy,at:o});if(i&&(i.status!==a.phase||i.error!==a.error)&&this.setState(e,{phase:i.status,id:t,error:i.error,at:o}),i&&ty(i.status))return;let s=o-n;if(s>=12e4)return this.setState(e,{phase:`failed`,id:t,error:uy(this.providers.get(e)),at:o});setTimeout(()=>void r(),ry(s))};setTimeout(()=>void r(),ry(0))}},Ky={working:a(`Trabalhando`),waiting:a(`Precisa de você`),"waiting-background":a(`Esperando em segundo plano`),shell:a(`Esperando o shell`),idle:a(`Ocioso`),done:a(`Concluído`),failed:a(`Falhou`),offline:a(`Saindo`)},qy={waiting:0,"waiting-background":1,shell:2,working:3,idle:4,done:5,failed:5,offline:6};function Jy(e){return Ky[e]}function Yy(e){return a(e===1?`Esperando {0} agente em segundo plano`:`Esperando {0} agentes em segundo plano`,[e])}function Xy(e,t=e.status){return t===`waiting-background`?Yy(e.backgroundAgents?.length??0):Jy(t)}function Zy(e){switch(e.status){case`working`:return a(`Trabalhando…`);case`waiting`:return e.waitingFor?a(`Precisa de você: {0}`,[e.waitingFor]):a(`Precisa de você`);case`waiting-background`:return Yy(e.backgroundAgents?.length??0);case`shell`:return a(`Esperando o shell terminar`);case`done`:return a(`Concluiu a tarefa`);case`failed`:return a(`O job falhou`);case`offline`:return a(`Saindo do escritório`);default:return a(`Aguardando instruções`)}}function Qy(e){return e.kind===`main`?e.role||a(`Agente principal`):e.role||a(`Subagente`)}function $y(e){return e.status!==`offline`}function eb(e,t){return t.filter(t=>e.custom===!0?t.favoriteRoomId===e.id:t.roomId===e.id)}function tb(e,t,n){let r=eb(e,n);if(e.custom)return r;let i=new Set(t.filter(e=>e.custom).map(e=>e.id));return r.filter(e=>e.kind!==`main`||!e.favoriteRoomId||!i.has(e.favoriteRoomId))}function nb(e,t,n){let r=new Map(t.filter(e=>e.custom).map(e=>[e.id,e])),i=new Map;for(let t of n)t.kind===`main`&&t.roomId===e&&t.favoriteRoomId&&r.has(t.favoriteRoomId)&&i.set(t.favoriteRoomId,(i.get(t.favoriteRoomId)??0)+1);return[...i].map(([e,t])=>({room:r.get(e),count:t}))}function rb(e,t,n){return e.custom?{newSession:!1,path:!1,copyPath:!1,rename:!0,delete:!0}:pt(e.id)?{newSession:!1,path:!1,copyPath:!1,rename:!1,delete:!1}:{newSession:t,path:!0,copyPath:!0,rename:n,delete:!1}}function ib(e,t=Date.now()){let n={rooms:0,agents:0,working:0,subagents:0,waiting:0,shells:0};if(!e)return n;n.rooms=e.rooms.length;for(let r of e.agents){if(!$y(r))continue;n.agents++;let i=lb(r,e.agents,t);i?n.shells+=Math.max(1,i.jobs.length):r.status===`working`&&n.working++,r.status===`waiting`&&n.waiting++,r.kind===`sub`&&r.status!==`done`&&r.status!==`failed`&&n.subagents++}return n}function ab(e){let t=new Map;for(let n of e){if(n.kind!==`main`||!n.duplicateSession||!$y(n))continue;let e=JSON.stringify([n.machine??``,n.provider??`claude`,n.sessionId]),r=t.get(e);r?r.push(n):t.set(e,[n])}return[...t].map(([e,t])=>({key:e,agents:t,newest:t.find(e=>e.duplicateSession?.newest)??t[t.length-1]}))}var ob=(e,t)=>e.startedAt-t.startedAt||e.id.localeCompare(t.id);function sb(e,t){let n=e.shells??[],r;if(e.status===`shell`)r=n.slice().sort(ob);else if(e.status===`working`)r=n.filter(e=>!e.background&&t-e.startedAt>=1e4).sort(ob);else return null;if(e.status===`working`&&r.length===0)return null;let i=r.find(e=>e.kind===`shell`)??r[0];return{jobs:r,main:i,since:Math.min(i?.startedAt??e.statusSince,t),foreground:e.status===`working`}}function cb(e,t){let n=[],r=new Set([e]),i=[e];for(;i.length;){let e=i.shift();for(let a of t)if(!(a.parentId!==e||r.has(a.id))){r.add(a.id),i.push(a.id);for(let e of a.shells??[])e.background&&n.push(e)}}return n}function lb(e,t,n){if(e.status===`shell`&&!e.shells?.length){let r=cb(e.id,t);if(r.length)return sb({status:e.status,statusSince:e.statusSince,shells:r},n)}return sb(e,n)}function ub(e,t){return(e.shells??[]).filter(e=>e.background||e.kind===`monitor`||t-e.startedAt>=2e3).sort(ob)}function db(e,t){return e.filter(e=>$y(e)).map(n=>({a:n,w:lb(n,e,t)})).filter(e=>!!e.w).sort((e,t)=>e.w.since-t.w.since||wb(e.a,t.a)).map(e=>e.a)}function fb(e){return!!e?.agents.some(e=>$y(e)&&(e.status===`shell`||(e.shells?.length??0)>0))}function pb(e){return e.kind===`monitor`?`monitor`:e.background?a(`segundo plano`):a(`primeiro plano`)}function mb(e,t){let n=e.main?.label?.trim()||(e.foreground?a(`Esperando o comando terminar`):a(`Esperando o shell terminar`)),r=Ht(t-e.since),i=e.jobs.length;return{label:n,time:r,count:i>1?`×${i}`:``,text:`⏳ ${n} · ${r}${i>1?` (${i} shells)`:``}`}}function hb(e){if(e.foreground)return a(`Está parado num comando no terminal, esperando ele terminar para continuar o turno.`);let t=e.jobs.length;return t>1?a(`Terminou o turno e está esperando {0} shells terminarem. A cada um que termina, o agente recebe o resultado.`,[t]):a(`Terminou o turno e está esperando o shell terminar. Quando ele terminar, o agente recebe o resultado.`)}var gb=6e4,_b=[{stage:`popcorn`,from:0,emoji:`🍿`,text:a(`Comendo pipoca e assistindo ao terminal`),help:a(`Até 3 min: recosta na cadeira com um balde de pipoca e assiste ao terminal como se fosse um filme.`)},{stage:`spin`,from:3*gb,emoji:`🪑`,text:a(`A pipoca acabou: girando na cadeira`),help:a(`De 3 a 10 min: a pipoca acaba; braços cruzados, dedos batendo e, de vez em quando, um giro completo na cadeira.`)},{stage:`cobweb`,from:10*gb,emoji:`🕸️`,text:a(`Já tem teia de aranha na cadeira`),help:a(`Depois de 10 min: aparece uma teia de aranha na cadeira (ela cresce depois de 20 min) e escapa um bocejo.`)},{stage:`nap`,from:25*gb,emoji:`😴`,text:a(`Cochilou esperando o shell`),help:a(`Depois de 25 min: cochila na mesa, coberto de teia.`)}];function vb(e){let t=Math.max(0,e),n=0;for(;n+1<_b.length&&t>=_b[n+1].from;)n++;let r=_b[n+1];return{..._b[n],nextIn:r?r.from-t:null}}function yb(e){return e?.tool===`ShellDone`?e.error?`fail`:`ok`:null}function bb(e){let t={completed:0,inProgress:0,total:e.length};for(let n of e)n.status===`completed`?t.completed++:n.status===`in_progress`&&t.inProgress++;return t}function xb(e){return bb(e.flatMap(e=>e.tasks))}function Sb(e){return e?[e.short,e.name,e.email??``,e.id,e.provider===`codex`?`Codex`:``].join(` `):``}function Cb(e,t,n,r){let i=Mt(r);if(!i)return!0;let a=Mt([e.name,Qy(e),e.title??``,e.project??``,t?.name??``,t?.path??``,Sb(n),e.activity?.text??``,e.status===`shell`?Ky.shell:``,...(e.shells??[]).map(e=>`shell ${e.label}`)].join(`  `));return i.split(/\s+/).every(e=>a.includes(e))}var wb=(e,t)=>e.startedAt-t.startedAt||e.id.localeCompare(t.id);function Tb(e,t){if(!e)return[];let n=new Map(e.accounts.map(e=>[e.id,e])),r=new Map(e.rooms.map(e=>[e.id,e])),i=new Set(e.rooms.filter(e=>e.custom).map(e=>e.id)),a=new Map(e.agents.filter(e=>e.kind===`main`&&e.favoriteRoomId&&i.has(e.favoriteRoomId)).map(e=>[e.id,e.favoriteRoomId])),o=new Set(a.keys()),s=new Map(e.accounts.map((e,t)=>[e.id,t])),c=t?.query.trim()??``,l=t?.hiddenAccounts??new Set,u=c.length>0||l.size>0,d=[];for(let t of[...e.rooms].sort((e,t)=>e.slot-t.slot)){let i=e.agents.filter(e=>t.custom?e.kind===`main`?e.favoriteRoomId===t.id:e.kind===`sub`&&!!e.parentId&&a.get(e.parentId)===t.id:e.roomId===t.id&&!o.has(e.id)&&!(e.kind===`sub`&&e.parentId&&o.has(e.parentId))).sort(wb),f=e=>!l.has(e.account)&&(Cb(e,t,n.get(e.account),c)||e.roomId!==t.id&&Cb(e,r.get(e.roomId),n.get(e.account),c)),p=new Set(i.map(e=>e.id)),m=new Map,h=[];for(let e of i)if(e.kind===`sub`&&e.parentId&&p.has(e.parentId)){let t=m.get(e.parentId);t||m.set(e.parentId,t=[]),t.push(e)}else h.push(e);let g=[],_=0;for(let e of h){let t=m.get(e.id)??[],n=f(e),i=n?t.filter(e=>!l.has(e.account)):t.filter(f);(n||i.length!==0)&&(_+=+!!n+i.length,g.push({agent:e,subs:i,subTotal:t.length,...o.has(e.id)&&r.get(e.roomId)?{projectRoom:r.get(e.roomId)}:{}}))}if(u&&g.length===0)continue;let v=[...new Set(i.map(e=>e.account))].sort((e,t)=>(s.get(e)??99)-(s.get(t)??99));d.push({room:t,accounts:v,nodes:g,agents:i,tasks:xb(i),matches:_})}return d}function Eb(e,t){let n=new Set(e.map(e=>e.account)),r=t.map(e=>e.id).filter(e=>n.has(e));for(let e of n)r.includes(e)||r.push(e);return r}function Db(e){return e.slice().sort((e,t)=>qy[e.status]-qy[t.status]||wb(e,t))}function Ob(e){let t=e.map(e=>e.short.toLowerCase()).filter(e=>/^[a-z0-9]{1,3}$/.test(e));return t.length===0?``:t.length===1?a(`atalho {0}`,[t[0]]):a(`atalhos {0} ou {1}`,[t.slice(0,-1).join(`, `),t[t.length-1]])}function kb(e,t,n=200,r){let i=new Map,a=e=>r===void 0||e.at<=r;for(let t of e)a(t)&&i.set(t.id,t);for(let e of t)a(e)&&i.set(e.id,e);return[...i.values()].sort((e,t)=>e.at-t.at).slice(-n)}var Ab=4,jb=80,Mb=300,Nb=160,Pb=[`n`,`s`,`e`,`w`,`ne`,`nw`,`se`,`sw`],Fb=class{el;opts;box=null;max=!1;sizing=null;drag=null;saveTimer=null;constructor(e,t,n){this.el=e,this.opts=n,t.classList.add(`ui-move-handle`),t.addEventListener(`pointerdown`,e=>this.onDown(e,t)),t.addEventListener(`pointermove`,e=>this.onMove(e)),t.addEventListener(`pointerup`,e=>this.onUp(e,t)),t.addEventListener(`pointercancel`,e=>this.onUp(e,t)),t.addEventListener(`dblclick`,e=>{Lb(e.target)||(this.max?this.toggleMaximize():this.dock())});for(let t of Pb)e.append(this.edgeHandle(t));let r=Rb(n.key);r&&this.allowed()&&this.float(r,!1),addEventListener(`resize`,()=>{if(!this.allowed())this.unfloat();else if(this.box)this.apply(this.box);else{let e=Rb(n.key);e&&this.float(e,!0)}}),typeof ResizeObserver==`function`&&new ResizeObserver(()=>{if(!this.box||this.max||this.drag?.moving||this.sizing||this.el.hidden)return;let e=this.el.offsetWidth,t=this.el.offsetHeight;e&&t&&(e!==this.box.w||t!==this.box.h)&&(this.box={...this.box,w:e,h:t},this.scheduleSave(),this.opts.onMove?.())}).observe(e)}get floating(){return this.box!==null}get maximized(){return this.max}toggleMaximize(e){let t=e??!this.max;t!==this.max&&(this.max=t,this.el.classList.toggle(`is-max`,t),this.opts.onMove?.())}restore(){let e=Rb(this.opts.key);if(e&&this.allowed())this.float(e,!1);else if(this.box){this.box=null,this.el.classList.remove(`is-floating`);for(let e of[`left`,`top`,`width`,`height`])this.el.style.removeProperty(e)}}dock(){this.box&&(zb(this.opts.key,null),this.unfloat())}unfloat(){if(this.box){this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=null,this.box=null,this.el.classList.remove(`is-floating`);for(let e of[`left`,`top`,`width`,`height`])this.el.style.removeProperty(e);this.opts.onChange?.(!1),this.opts.onMove?.()}}edgeHandle(e){let t=document.createElement(`div`);t.className=`ui-resize ui-resize--${e}`,t.setAttribute(`aria-hidden`,`true`),t.addEventListener(`pointerdown`,n=>{if(n.button!==0||this.max||!this.allowed())return;n.preventDefault(),n.stopPropagation();let r=this.el.getBoundingClientRect();this.box||this.float({x:r.left,y:r.top,w:r.width,h:r.height},!0),this.sizing={id:n.pointerId,edge:e,sx:n.clientX,sy:n.clientY,start:{...this.box}},this.el.classList.add(`is-resizing`),t.setPointerCapture(n.pointerId)}),t.addEventListener(`pointermove`,t=>{let n=this.sizing;if(!n||n.id!==t.pointerId)return;let r=t.clientX-n.sx,i=t.clientY-n.sy,a={...n.start};e.includes(`e`)&&(a.w=Math.max(Mb,n.start.w+r)),e.includes(`s`)&&(a.h=Math.max(Nb,n.start.h+i)),e.includes(`w`)&&(a.w=Math.max(Mb,n.start.w-r),a.x=n.start.x+n.start.w-a.w),e.includes(`n`)&&(a.h=Math.max(Nb,Math.min(n.start.h-i,n.start.y+n.start.h-this.minTop())),a.y=n.start.y+n.start.h-a.h),this.apply(a)});let n=e=>{let n=this.sizing;n&&n.id===e.pointerId&&(this.sizing=null,this.el.classList.remove(`is-resizing`),t.hasPointerCapture(e.pointerId)&&t.releasePointerCapture(e.pointerId),this.scheduleSave(),this.opts.onMove?.())};return t.addEventListener(`pointerup`,n),t.addEventListener(`pointercancel`,n),t}allowed(){return this.opts.enabled?.()??!0}onDown(e,t){if(e.button!==0||this.max||Lb(e.target)||!this.allowed())return;let n=this.el.getBoundingClientRect();this.drag={id:e.pointerId,dx:e.clientX-n.left,dy:e.clientY-n.top,sx:e.clientX,sy:e.clientY,moving:!1},t.setPointerCapture(e.pointerId)}onMove(e){let t=this.drag;if(t&&t.id===e.pointerId){if(!t.moving){if(Math.abs(e.clientX-t.sx)<Ab&&Math.abs(e.clientY-t.sy)<Ab)return;t.moving=!0;let n=this.el.getBoundingClientRect();this.float({x:n.left,y:n.top,w:n.width,h:n.height},!0),this.el.classList.add(`is-dragging`)}e.preventDefault(),this.box&&this.apply({...this.box,x:e.clientX-t.dx,y:e.clientY-t.dy})}}onUp(e,t){let n=this.drag;n&&n.id===e.pointerId&&(this.drag=null,t.hasPointerCapture(e.pointerId)&&t.releasePointerCapture(e.pointerId),n.moving&&(this.el.classList.remove(`is-dragging`),this.scheduleSave(),this.opts.onMove?.()))}float(e,t){let n=this.box!==null;this.el.classList.add(`is-floating`),this.apply(e),!n&&t?this.opts.onChange?.(!0):n||queueMicrotask(()=>this.opts.onChange?.(!0))}minTop(){let e=getComputedStyle(this.el);return(parseFloat(e.getPropertyValue(`--top-h`))||0)+(parseFloat(e.getPropertyValue(`--gap`))||0)}apply(e){let t=Math.max(Mb,Math.min(e.w,innerWidth)),n=Math.min(innerWidth-jb,Math.max(jb-t,e.x)),r=Math.max(this.minTop(),Math.min(innerHeight-Nb,e.y)),i=Math.max(Nb,Math.min(e.h,innerHeight-r-8));this.box={x:n,y:r,w:t,h:i};let a=this.el.style;a.left=`${Math.round(n)}px`,a.top=`${Math.round(r)}px`,a.width=`${Math.round(t)}px`,a.height=`${Math.round(i)}px`}scheduleSave(){this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=setTimeout(()=>zb(this.opts.key,this.box),250)}};function Ib(e,t){let n=document.createElement(`button`);n.type=`button`,n.className=`ui-icon-btn ui-icon-btn--sm ui-term__max`;let r=()=>{let t=!!e()?.maximized;n.innerHTML=t?Q.restore:Q.maximize;let r=a(t?`Restaurar o tamanho`:`Expandir na tela toda`);n.setAttribute(`data-tip`,r),n.setAttribute(`aria-label`,r),n.setAttribute(`aria-pressed`,String(t))};return n.addEventListener(`click`,()=>{e()?.toggleMaximize(),r(),t?.()}),r(),n}function Lb(e){return e instanceof Element&&!!e.closest(`button, a, input, select, textarea, [role="button"], kbd`)}function Rb(e){try{let t=JSON.parse(localStorage.getItem(e)??`null`);if(t&&[t.x,t.y,t.w,t.h].every(e=>typeof e==`number`&&Number.isFinite(e)))return t}catch{}return null}function zb(e,t){try{t?localStorage.setItem(e,JSON.stringify({x:Math.round(t.x),y:Math.round(t.y),w:Math.round(t.w),h:Math.round(t.h)})):localStorage.removeItem(e)}catch{}}var Bb={claude:`Claude Code`,codex:`Codex`,"gentle-shell":`Gentle Shell`,"agent-hub":`Agent Hub`};function Vb(e){return e?.provider??`claude`}function Hb(e){return e?.provider===`gentle-shell`}function Ub(e){return e?.provider===`codex`}function Wb(e){return/(?:^|[:/\\])\.?codex(?:[-_.~]|$)/i.test(e)}function Gb(e){return/(?:^|[:/\\])\.?gentle-shell(?:[-_.~]|$)/i.test(e)}function Kb(e,t=``,n){return e?Vb(e):n??(Wb(t)?`codex`:Gb(t)?`gentle-shell`:`claude`)}function qb(e,t=Kb(void 0,e)){let n=e.replace(/^.*:/,``).replace(/~\d+$/,``).replace(/^\.?(?:claude|codex|gentle-shell)(?=[-_.]|$)[-_.]?/i,``).replace(/^agent-hub[:_-]?/i,``),r=/[\p{L}\p{N}]/u.exec(n)?.[0];return r?r.toUpperCase():t===`codex`?`X`:t===`gentle-shell`?`G`:t===`agent-hub`?`A`:`?`}function Jb(e,t=``){return e!==`claude`&&!t.toLowerCase().includes(Bb[e].toLowerCase())}function Yb(e,t,n){if(!e)return t?`${t}${n===`claude`?``:` · ${Bb[n]}`}`:a(`Conta desconhecida`);if(n===`claude`)return`${e.name}${e.email?` (${e.email})`:``}`;let r=Jb(n,e.name)?` · ${Bb[n]}`:``;return`${e.name}${r}${e.plan?a(` · plano {0}`,[e.plan]):``}`}function Xb(e){let t=Ob(e.filter(e=>!Ub(e)));return e.some(Ub)?a(`Abra o Claude Code{0} ou o Codex em qualquer projeto e veja seu agente chegar.`,[t?` (${t})`:``]):a(`Abra o Claude Code em qualquer projeto{0} e veja seu agente chegar.`,[t?` (${t})`:``])}function Zb(e){return!!e?.agents.some(e=>e.permission&&Ub(e.permission)&&e.status!==`offline`&&e.status!==`done`)}var Qb=a("Para ver o Codex ao vivo e aprovar pelo escritório: `npm run codex:install` e aprove os hooks em `/hooks` no Codex."),$b={untrusted:a(`Pergunta antes de quase tudo`),"on-request":a(`Pergunta quando precisa`),"on-failure":a(`Pergunta quando um comando falha`),never:a(`Nunca pergunta`)};function ex(e){return e?$b[e]??e:`—`}function tx(e){return!!e&&e.kind===`main`&&!P_(e.id)}function nx(e){return tx(e)&&Vb(e)===`claude`}function rx(e){return tx(e)&&Vb(e)!==`agent-hub`&&!ut(e?.id??``)}async function ix(e){let t;try{t=await fetch(`/api/spawn/focus`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({agentId:e})})}catch{throw Error(a(`o Habblaud não respondeu`))}if(t.status===404)return;let n=await t.json().catch(()=>({}));if(!t.ok)throw Error(n.error??a(`erro {0}`,[t.status]));return typeof n.paneId==`string`?{paneId:n.paneId}:void 0}async function ax(e,t){let n;try{n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t??{})})}catch{throw Error(a(`o Habblaud não respondeu`))}if(n.status===204)return;let r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??a(`erro {0}`,[n.status]));return r}var ox={cols:120,rows:32};function sx(e,t){return ax(`/api/pty`,{cwd:e,account:t,...ox})}function cx(e){return ax(`/api/agents/${encodeURIComponent(e)}/takeover`,ox)}async function lx(e){await ax(`/api/agents/${encodeURIComponent(e)}/stop`,{})}async function ux(e){await ax(`/api/pty/${encodeURIComponent(e)}/close`,{})}var dx=4e3,fx=class{ctx;pty;withTakeover;onStop;el;agent=null;takeBtn;stopBtn;msg;confirm=null;confirmTimer=null;busy=!1;constructor(e,t,n,r){this.ctx=e,this.pty=t,this.withTakeover=n,this.onStop=r,this.takeBtn=P(`button`,{class:`ui-btn ui-btn--sm ui-btn--accent`,type:`button`,on:{click:()=>this.run(`takeover`)}}),A(this.takeBtn,a(`Encerra a sessão no terminal onde ela está e continua a mesma conversa aqui, podendo digitar`)),this.stopBtn=P(`button`,{class:`ui-btn ui-btn--sm ui-btn--danger`,type:`button`,on:{click:()=>this.run(`stop`)}}),A(this.stopBtn,a(`Encerra esta sessão do Claude Code (a conversa fica salva)`)),this.msg=P(`span`,{class:`ui-termact__msg`,role:`status`,hidden:!0}),this.el=P(`span`,{class:`ui-termact`,hidden:!0},this.msg,this.takeBtn,this.stopBtn)}render(e){e?.id!==this.agent?.id&&(this.resetConfirm(),this.showMsg(``)),this.agent=e;let t=nx(e)&&this.pty.enabled,n=!t&&this.withTakeover&&I().spawn&&rx(e),r=t||n;if(F(this.el,!r),!r)return;F(this.takeBtn,!this.withTakeover);let i=this.ctx.store.snapshot?.machines;F(this.stopBtn,n||!!e&&!bt(e.id,i)),A(this.takeBtn,a(n?`Mostra no herdr o painel onde esta sessão roda`:`Encerra a sessão no terminal onde ela está e continua a mesma conversa aqui, podendo digitar`)),M(this.takeBtn,this.confirm===`takeover`?a(`Confirmar?`):a(`Assumir daqui`)),M(this.stopBtn,this.confirm===`stop`?a(`Confirmar?`):a(`Encerrar`)),this.takeBtn.classList.toggle(`is-confirm`,this.confirm===`takeover`),this.stopBtn.classList.toggle(`is-confirm`,this.confirm===`stop`);let o=e?gt(e.id,i):{disabled:!1};o.tooltip&&A(this.takeBtn,o.tooltip),this.takeBtn.disabled=this.busy||o.disabled,this.stopBtn.disabled=this.busy}run(e){let t=this.agent;if(t&&!this.busy){if(this.confirm!==e){this.resetConfirm(),this.confirm=e,this.confirmTimer=setTimeout(()=>{this.resetConfirm(),this.ctx.invalidate()},dx),this.ctx.invalidate();return}this.resetConfirm(),this.busy=!0,this.showMsg(a(e===`stop`?`Encerrando…`:`Assumindo…`)),this.ctx.invalidate(),(e===`stop`?this.onStop?this.onStop(t):this.pty.stop(t.id):this.pty.takeover(t.id)).then(e=>this.showMsg(typeof e==`string`?e:``)).catch(e=>this.showMsg(a(`Não deu: {0}`,[e.message]),!0)).finally(()=>{this.busy=!1,this.ctx.invalidate()})}}showMsg(e,t=!1){M(this.msg,e),F(this.msg,!e),A(this.msg,e),this.msg.classList.toggle(`is-error`,t)}resetConfirm(){this.confirmTimer&&clearTimeout(this.confirmTimer),this.confirmTimer=null,this.confirm=null}},px=`habblaud.tabs.order`,mx=50;function hx(e,t,n){let r=_x()[e];if(!r?.length)return t.slice();let i=new Map(r.map((e,t)=>[e,t]));return t.map((e,t)=>({item:e,i:t,r:i.get(n(e))})).sort((e,t)=>(e.r??1/0)-(t.r??1/0)||e.i-t.i).map(e=>e.item)}function gx(e,t,n,r,i,a,o){let s=t.find(e=>n(e)===i),c=t.filter(e=>n(e)!==i),l=c.findIndex(e=>n(e)===a);return!s||l<0?!1:(c.splice(o?l+1:l,0,s),vx(e,c.map(r)),!0)}function _x(){try{let e=JSON.parse(localStorage.getItem(px)??`{}`);if(!e||typeof e!=`object`||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)&&(t[n]=r.filter(e=>typeof e==`string`));return t}catch{return{}}}function vx(e,t){try{let n=_x();delete n[e],n[e]=t;let r=Object.keys(n);for(let e of r.slice(0,Math.max(0,r.length-mx)))delete n[e];localStorage.setItem(px,JSON.stringify(n))}catch{}}function yx(e=`sm`){return P(`span`,{class:`ui-acc-chip ui-acc-chip--${e}`})}function bx(e,t,n=``,r){let i=Kb(t,n,r);M(e,t?.short??qb(n,i)),_t(e,`--acc`,t?.color??`#8b98b3`),N(e,`data-provider`,i===`codex`?`codex`:null);let a=Yb(t,n,i);A(e,a),N(e,`aria-label`,a)}function xx(e=``){return P(`span`,{class:`ui-prov${e?` ${e}`:``}`,text:`Codex`,hidden:!0,title:a(`Agente do Codex (OpenAI)`)})}function Sx(e,t,n=``){t===`gentle-shell`||t===`agent-hub`?(M(e,Bb[t]),t===`agent-hub`?A(e,a(`Job do Agent Hub`)):A(e,a(`Agente do Gentle Shell`))):(M(e,`Codex`),A(e,a(`Agente do Codex (OpenAI)`))),F(e,!Jb(t,n))}function Cx(){return P(`span`,{class:`ui-status-dot`,role:`img`})}function wx(e,t){vt(e,`is-`,t);let n=Jy(t);N(e,`aria-label`,n),A(e,n)}function Tx(){return P(`span`,{class:`ui-role`})}function Ex(e,t){M(e,t.kind===`main`?a(`Principal`):t.role||a(`Subagente`)),vt(e,`ui-role--`,t.kind),A(e,t.kind===`main`?a(`Agente principal`):a(`Subagente: {0}{1}`,[t.role,t.background?a(` (em segundo plano)`):``]))}function Dx(e){let t=P(`span`,{class:`ui-progress`,role:`progressbar`,attrs:{"aria-label":e,"aria-valuemin":0,"aria-valuemax":100}});return t.append(P(`span`,{class:`ui-progress__fill`})),t}function Ox(e,t,n,r=0){let i=n>0?Math.round(t/n*100):0,a=n>0?Math.round((t+r)/n*100):0;_t(e,`--p`,`${i}%`),_t(e,`--pp`,`${a}%`),N(e,`aria-valuenow`,String(i)),N(e,`aria-valuetext`,`${t} de ${n}`),e.classList.toggle(`is-complete`,n>0&&t===n)}function kx(){let e=P(`span`,{class:`ui-activity`});return e.append(P(`span`,{class:`ui-activity__icon`,attrs:{"aria-hidden":`true`}}),P(`span`,{class:`ui-activity__text`}),P(`span`,{class:`ui-activity__time`,hidden:!0}),P(`span`,{class:`ui-activity__count`,hidden:!0})),e}function Ax(e){return e.children}function jx(e,t,n=a(`Sem atividade ainda`)){let[r,i,o,s]=Ax(e);M(r,t?.icon??`·`),M(i,t?.text??n),F(o,!0),F(s,!0),e.classList.remove(`is-shell`),e.classList.toggle(`is-error`,!!t?.error);let c=yb(t);e.classList.toggle(`is-shell-ok`,c===`ok`),e.classList.toggle(`is-shell-fail`,c===`fail`),A(e,t?t.detail?`${t.text}\n${t.detail}`:t.text:n)}function Mx(e,t,n){let[r,i,a,o]=Ax(e),s=mb(t,n);M(r,`⏳`),M(i,s.label),M(a,s.time),F(a,!1),M(o,s.count),F(o,!s.count),e.classList.add(`is-shell`),e.classList.remove(`is-error`,`is-shell-ok`,`is-shell-fail`);let c=vb(n-t.since),l=t.main;A(e,[s.text,l?.command&&l.command!==l.label?l.command:``,`${c.emoji} ${c.text}`].filter(Boolean).join(`
4
- `))}function Nx(e=`ui-brand__name`){let t=P(`span`,{class:e});return t.innerHTML=ev,t.append(P(`span`,{class:`ui-sr`,text:`Busybits`})),t}var Px=3e3;function Fx(e){return e.status===`working`||e.status===`waiting`?e.activity?.text??Zy(e):e.title??``}var Ix=class{ctx;el;list;current=null;roomId=null;peers=[];confirming=null;confirmTimer=null;dragging=null;constructor(e){this.ctx=e,this.el=P(`div`,{class:`ui-ttabs`,role:`tablist`,hidden:!0,attrs:{"aria-label":a(`Agentes do projeto (arraste para reordenar)`)}}),this.list=new wt(this.el,{animate:!1,key:e=>e.id,create:t=>{let n=P(`button`,{class:`ui-ttab`,type:`button`,role:`tab`,attrs:{draggable:`true`}},Cx(),P(`span`,{class:`ui-ttab__name`}),P(`span`,{class:`ui-ttab__doing`}),P(`span`,{class:`ui-ttab__live`,text:`›_`,hidden:!0}),P(`span`,{class:`ui-ttab__close`,role:`button`,attrs:{"aria-label":a(`Encerrar esta sessão`)},text:`×`})),r=n.children[4];return r.addEventListener(`click`,e=>{e.stopPropagation(),this.closeTab(n.dataset.id)}),r.addEventListener(`pointerdown`,e=>e.stopPropagation()),n.addEventListener(`keydown`,e=>{e.key===`Delete`&&(e.preventDefault(),this.closeTab(n.dataset.id))}),n.dataset.id=t.id,n.addEventListener(`click`,()=>{let t=n.dataset.id;t!==this.current&&e.terminals?.open(t)}),this.wireDrag(n),n},update:(t,n)=>{t.dataset.id=n.id,wx(t.firstElementChild,n.status),M(t.children[1],xt(n,e.store.snapshot?.machines));let r=Fx(n);M(t.children[2],r),F(t.children[2],!r);let i=!!e.terminals?.interactive(n.id);F(t.children[3],!i);let o=t.children[4],s=this.confirming===n.id;F(o,!e.terminals?.interactiveEnabled||!nx(n)),o.classList.toggle(`is-confirm`,s),M(o,s?a(`encerrar?`):`×`),A(o,a(s?`Clique de novo para encerrar a sessão (a conversa fica salva)`:`Encerrar esta sessão`));let c=n.id===this.current;t.classList.toggle(`is-on`,c),N(t,`aria-selected`,String(c)),A(t,`${xt(n,e.store.snapshot?.machines)}${n.title?` · ${n.title}`:``}${r&&r!==n.title?`
5
- ${r}`:``}${i?a(` (interativo)`):``}`)}})}render(e){this.current=e;let t=e?this.ctx.agent(e):void 0;this.roomId=t?.roomId??null;let n=t?(this.ctx.store.snapshot?.agents??[]).filter(e=>e.kind===`main`&&e.roomId===t.roomId&&e.status!==`offline`&&!e.id.startsWith(`demo:`)).sort((e,t)=>e.startedAt-t.startedAt||e.id.localeCompare(t.id)):[];this.peers=t?hx(t.roomId,n,e=>e.sessionId):[],F(this.el,this.peers.length<2),this.list.sync(this.peers.length<2?[]:this.peers)}closeTab(e){if(!this.ctx.terminals?.interactiveEnabled||!nx(this.ctx.agent(e)))return;if(this.confirming!==e){this.resetConfirm(),this.confirming=e,this.confirmTimer=setTimeout(()=>{this.resetConfirm(),this.ctx.invalidate()},Px),this.ctx.invalidate();return}this.resetConfirm();let t=this.ctx.agent(e)?.name??a(`Sessão`);if(lx(e).then(()=>this.ctx.announce(a(`{0}: sessão encerrada.`,[t]))).catch(e=>this.ctx.announce(a(`Não deu para encerrar: {0}`,[e.message]))).finally(()=>this.ctx.invalidate()),e===this.current){let t=this.peers.findIndex(t=>t.id===e),n=this.peers[t+1]??this.peers[t-1];n&&this.ctx.terminals?.open(n.id)}}resetConfirm(){this.confirmTimer&&clearTimeout(this.confirmTimer),this.confirmTimer=null,this.confirming=null}wireDrag(e){e.addEventListener(`dragstart`,t=>{this.dragging=e.dataset.id??null,e.classList.add(`is-dragging`),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(`text/plain`,this.dragging??``))}),e.addEventListener(`dragend`,()=>{this.dragging=null,e.classList.remove(`is-dragging`),this.clearMarks()}),e.addEventListener(`dragover`,t=>{if(!this.dragging||this.dragging===e.dataset.id)return;t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect=`move`);let n=this.isAfter(e,t.clientX);this.clearMarks(),e.classList.add(n?`is-drop-after`:`is-drop-before`)}),e.addEventListener(`dragleave`,()=>e.classList.remove(`is-drop-before`,`is-drop-after`)),e.addEventListener(`drop`,t=>{t.preventDefault();let n=this.dragging,r=e.dataset.id;this.clearMarks(),n&&r&&n!==r&&this.move(n,r,this.isAfter(e,t.clientX))})}isAfter(e,t){let n=e.getBoundingClientRect();return t>n.left+n.width/2}clearMarks(){for(let e of this.el.querySelectorAll(`.is-drop-before, .is-drop-after`))e.classList.remove(`is-drop-before`,`is-drop-after`)}move(e,t,n){this.roomId&&gx(this.roomId,this.peers,e=>e.id,e=>e.sessionId,e,t,n)&&this.ctx.invalidate()}},Lx=2,Rx=8e3,zx=1e4;function Bx(e,t,n){let r=1e3*2**t;return e===429?Math.min(r,zx):e===404||e===200?n>=3e4?null:Math.min(r,Rx):null}function Vx(){return{createSource:e=>new EventSource(e),probe:async e=>{let t=new AbortController;try{let n=await fetch(e,{signal:t.signal,headers:{Accept:`text/event-stream`}}),r;if(!n.ok)try{let e=await n.json();typeof e.error==`string`&&e.error&&(r=e.error)}catch{}return{status:n.status,message:r}}catch{return{status:0}}finally{t.abort()}},setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e)}}var Hx=class{url;deps;handlers;es=null;timer=null;closed=!1;attempt=0;waited=0;gen=0;constructor(e,t,n){this.url=e,this.deps=t,this.handlers=n}start(){this.open(!1)}close(){this.closed=!0,this.gen++,this.timer!==null&&this.deps.clearTimer(this.timer),this.timer=null,this.es?.close(),this.es=null}open(e){let t=++this.gen;this.timer=null,this.handlers.onState(e?`waiting`:`connecting`,null);let n;try{n=this.deps.createSource(this.url)}catch{this.handlers.onState(`failed`,{status:0});return}this.es=n,n.addEventListener(`open`,()=>{this.es===n&&(this.attempt=0,this.waited=0,this.handlers.onState(`open`,null))});for(let e of[`init`,`append`])n.addEventListener(e,t=>{this.es===n&&this.handlers.onEvent(e,t.data)});n.addEventListener(`error`,()=>{if(this.es===n){if(n.readyState!==Lx)return this.handlers.onState(`reconnecting`,null);n.close(),this.es=null,this.diagnose(t)}})}async diagnose(e){this.handlers.onState(`waiting`,null);let t=await this.deps.probe(this.url);if(this.closed||e!==this.gen)return;let n=Bx(t.status,this.attempt,this.waited);if(n===null)return this.handlers.onState(`failed`,t);this.attempt++,this.waited+=n,this.timer=this.deps.setTimer(()=>this.open(!0),n)}},Ux=1500;function Wx(e){return e.type===`code`&&e.text!==``?e.text:null}var Gx=5,Kx=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/,qx=/^ {0,3}(#{1,6})(?:\s+(.*?))?\s*$/,Jx=/^ {0,3}([-*_])(?:\s*\1){2,}\s*$/,Yx=/^ {0,3}>\s?(.*)$/,Xx=/^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/,Zx=/^:?-{3,}:?$/;function Qx(e){let t=[],n=[],r=0,i=0;for(;i<e.length;){if(e[i]===`\\`&&i+1<e.length){i+=2;continue}if(e[i]==="`"){let t=1;for(;e[i+t]==="`";)t++;let n=i+t,r=-1;for(;n<e.length;){let i=e.indexOf("`",n);if(i===-1)break;let a=i+1;for(;e[a]==="`";)a++;if(a-i===t){r=a;break}n=a}if(r!==-1){i=r;continue}i+=t;continue}e[i]===`|`&&(t.push(e.slice(r,i).trim()),n.push(i),r=i+1),i++}return t.push(e.slice(r).trim()),n.length&&!e.slice(0,n[0]).trim()&&t.shift(),n.length&&!e.slice(n[n.length-1]+1).trim()&&t.pop(),t}function $x(e){let t=Qx(e);return!t.length||t.some(e=>!Zx.test(e))?null:t.map(e=>{let t=e.startsWith(`:`),n=e.endsWith(`:`);return t&&n?`center`:t?`left`:n?`right`:null})}function eS(e,t){let n=/^ {0,3}(`{3,}|~{3,})\s*$/.exec(e);return!!n&&n[1][0]===t[0]&&n[1].length>=t.length}function tS(e,t){if(t+1>=e.length)return!1;let n=$x(e[t+1]);return!!n&&Qx(e[t]).length===n.length}function nS(e,t){let n=e[t];if(Kx.test(n)||qx.test(n)||Yx.test(n)||Jx.test(n))return!0;let r=Xx.exec(n);return r&&(!/^\d/.test(r[2])||/^1[.)]$/.test(r[2]))?!0:tS(e,t)}var rS=e=>e.trim()===``;function iS(e){let t=e.replace(/\r\n?/g,`
6
- `).split(`
7
- `),n=[],r=0;for(;r<t.length;){let e=t[r];if(rS(e)){r++;continue}let i=Kx.exec(e);if(i){let a=e.length-e.trimStart().length,o=[];for(r++;r<t.length&&!eS(t[r],i[1]);)o.push(t[r].replace(RegExp(`^ {0,${a}}`),``)),r++;r++,n.push({type:`code`,lang:i[2]??``,text:o.join(`
8
- `)});continue}let a=qx.exec(e);if(a){n.push({type:`heading`,level:a[1].length,text:(a[2]??``).replace(/\s+#+$/,``)}),r++;continue}if(Jx.test(e)){n.push({type:`rule`}),r++;continue}if(tS(t,r)){let e=Qx(t[r]),i=$x(t[r+1]);r+=2;let a=[];for(;r<t.length&&!rS(t[r])&&!nS(t,r);){let n=Qx(t[r++]).slice(0,e.length);for(;n.length<e.length;)n.push(``);a.push(n.map(e=>hS(e)))}n.push({type:`table`,header:e.map(e=>hS(e)),alignments:i,rows:a});continue}if(Yx.test(e)){let e=[],i;for(;r<t.length&&(i=Yx.exec(t[r]));)e.push(i[1]),r++;n.push({type:`quote`,text:e.join(`
9
- `)});continue}if(Xx.test(e)){let e=[],i=[],a=e=>e[1].replace(/\t/g,` `).length,o=t=>!e.length||a(t)>i[0]||/^\d/.test(t[2])===e[0].ordered;for(;r<t.length;){let n=t[r],s=Xx.exec(n);if(s&&o(s)){let t=a(s);for(;i.length&&t<i[i.length-1];)i.pop();(!i.length||t>i[i.length-1])&&i.push(t);let n=/^\d/.test(s[2]);e.push({depth:Math.min(Gx,i.length-1),marker:s[2],ordered:n,text:s[3]}),r++;continue}if(rS(n)){let e=r;for(;e<t.length&&rS(t[e]);)e++;let n=e<t.length?Xx.exec(t[e]):null;if(n&&o(n)){r=e;continue}break}if(/^\s{2,}\S/.test(n)&&!Kx.test(n)){e[e.length-1].text+=`\n${n.trim()}`,r++;continue}break}n.push({type:`list`,ordered:e[0].ordered,items:e});continue}let o=[e];for(r++;r<t.length&&!rS(t[r])&&!nS(t,r);)o.push(t[r++]);n.push({type:`paragraph`,text:o.join(`
10
- `)})}return n}function aS(e){if(!/^https?:\/\/[^\s/?#]/i.test(e))return!1;try{let t=new URL(e);return(t.protocol===`http:`||t.protocol===`https:`)&&!!t.hostname}catch{return!1}}var oS=/[.,;:!?'"”’»)\]}]$/,sS=/[\s<>"`*\u2028\u2029]/;function cS(e,t){let n=0;for(let r of e)r===t&&n++;return n}function lS(e,t){if(!/^https?:\/\//i.test(e.slice(t,t+8))||t>0&&fS.test(e[t-1]))return null;let n=t;for(;n<e.length&&!sS.test(e[n]);)n++;let r=e.slice(t,n);for(;oS.test(r);){let e=r[r.length-1],t=e===`)`?`(`:e===`]`?`[`:e===`}`?`{`:``;if(t&&cS(r,t)>=cS(r,e))break;r=r.slice(0,-1)}return aS(r)?r:null}function uS(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r]===`h`||e[r]===`H`?lS(e,r):null;i?(n&&t.push({text:n}),n=``,t.push({text:i,href:i}),r+=i.length):n+=e[r++]}return n&&t.push({text:n}),t}var dS=/[!-/:-@[-`{-~]/,fS=/[\p{L}\p{N}]/u;function pS(e,t){if(!t)return;let n=e[e.length-1];n?.type===`text`?n.text+=t:e.push({type:`text`,text:t})}function mS(e,t,n){let r=t;for(;r<e.length;){if(e[r]===`\\`){r+=2;continue}if(e[r]==="`"){let t=e.indexOf("`",r+1);if(t===-1)return-1;r=t+1;continue}if(e[r]===n){if(e[r+1]===n){r+=2;continue}if(!/\s/.test(e[r-1]??` `)&&(n!==`_`||!fS.test(e[r+1]??``)))return r}r++}return-1}function hS(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r===`\\`&&n+1<e.length&&dS.test(e[n+1])){pS(t,e[n+1]),n+=2;continue}if(r==="`"){let r=1;for(;e[n+r]==="`";)r++;let i="`".repeat(r),a=e.indexOf(i,n+r);for(;a!==-1&&e[a+r]==="`";){let t=a;for(;e[t]==="`";)t++;a=e.indexOf(i,t)}if(a===-1){pS(t,i),n+=r;continue}let o=e.slice(n+r,a).replace(/\n/g,` `);o.length>2&&o.startsWith(` `)&&o.endsWith(` `)&&o.trim()&&(o=o.slice(1,-1)),t.push({type:`code`,text:o}),n=a+r;continue}if(r===`[`){let r=e.indexOf(`]`,n+1);if(r>n+1&&e[r+1]===`(`){let i=e.indexOf(`)`,r+2),a=i===-1?``:e.slice(r+2,i).trim();if(i!==-1&&a&&!/\s/.test(a.split(/\s+"/)[0])){t.push({type:`link`,text:e.slice(n+1,r),href:a.split(/\s+"/)[0]}),n=i+1;continue}}}if((r===`*`||r===`_`)&&e[n+1]===r){let i=e[n-1]??` `,a=!/\s/.test(e[n+2]??` `)&&(r===`*`||!fS.test(i))?e.indexOf(r+r,n+2):-1;if(a>n+2&&!/\s/.test(e[a-1])&&(r===`*`||!fS.test(e[a+2]??``))){t.push({type:`strong`,children:hS(e.slice(n+2,a))}),n=a+2;continue}pS(t,r+r),n+=2;continue}if(r===`*`||r===`_`){let i=e[n-1]??` `,a=!/\s/.test(e[n+1]??` `)&&(r===`*`||!fS.test(i))?mS(e,n+1,r):-1;if(a>n+1){t.push({type:`em`,children:hS(e.slice(n+1,a))}),n=a+1;continue}}if(r===`h`||r===`H`){let r=lS(e,n);if(r){t.push({type:`link`,text:r,href:r}),n+=r.length;continue}}pS(t,r),n++}return t}var gS=[`•`,`◦`,`▪`,`▫`];function _S(e,t){for(let n of t)switch(n.type){case`text`:e.append(document.createTextNode(n.text));break;case`code`:{let t=document.createElement(`code`);t.className=`ui-md__code`,t.textContent=n.text,e.append(t);break}case`strong`:case`em`:{let t=document.createElement(n.type);_S(t,n.children),e.append(t);break}case`link`:e.append(vS(n.text||n.href,n.href))}}function vS(e,t){if(aS(t)){let n=document.createElement(`a`);return n.className=`ui-md__link ui-md__link--live`,n.href=t,n.target=`_blank`,n.rel=`noopener noreferrer`,n.textContent=e,n.setAttribute(`data-tip`,t),n}let n=document.createElement(`span`);return n.className=`ui-md__link`,n.textContent=e,n.setAttribute(`data-tip`,t),n}function yS(e,t){e.replaceChildren(...uS(t).map(e=>e.href?vS(e.text,e.href):document.createTextNode(e.text)))}function bS(e,t){let n=document.createElement(e);return n.className=t,n}function xS(e){let t=a(`Copiar`),n=bS(`button`,`ui-md__copy`);n.type=`button`,n.setAttribute(`aria-label`,t);let r=(e,t,r)=>{n.innerHTML=e,n.classList.remove(`is-done`,`is-fail`),r&&n.classList.add(r),n.setAttribute(`aria-label`,t),A(n,t)};r(Q.copy,t,``);let i=null;return n.addEventListener(`click`,async n=>{n.stopPropagation();let o=await St(e);r(o?Q.check:Q.copy,a(o?`Copiado`:`Não foi possível copiar`),o?`is-done`:`is-fail`),i&&clearTimeout(i),i=setTimeout(()=>r(Q.copy,t,``),Ux)}),n}function SS(e){let t=document.createDocumentFragment();for(let n of iS(e))switch(n.type){case`paragraph`:{let e=bS(`p`,`ui-md__p`);_S(e,hS(n.text)),t.append(e);break}case`heading`:{let e=bS(`p`,`ui-md__h ui-md__h${Math.min(n.level,3)}`);_S(e,hS(n.text)),t.append(e);break}case`code`:{let e=bS(`div`,`ui-md__block`);if(n.lang){let t=bS(`span`,`ui-md__lang`);t.textContent=n.lang,e.append(t)}let r=bS(`pre`,`ui-md__pre`);r.textContent=n.text,e.append(r);let i=Wx(n);i!==null&&e.append(xS(i)),t.append(e);break}case`list`:{let e=bS(n.ordered?`ol`:`ul`,`ui-md__list`);for(let t of n.items){let n=bS(`li`,`ui-md__li`);n.style.setProperty(`--d`,String(t.depth));let r=bS(`span`,`ui-md__mark`);r.textContent=t.ordered?t.marker:gS[t.depth%gS.length],r.setAttribute(`aria-hidden`,`true`);let i=bS(`span`,`ui-md__item`);_S(i,hS(t.text)),n.append(r,i),e.append(n)}t.append(e);break}case`quote`:{let e=bS(`blockquote`,`ui-md__quote`);_S(e,hS(n.text)),t.append(e);break}case`table`:{let e=bS(`div`,`ui-md__table-wrap`),r=bS(`table`,`ui-md__table`),i=document.createElement(`thead`),a=document.createElement(`tr`);n.header.forEach((e,t)=>{let r=document.createElement(`th`);r.scope=`col`;let i=n.alignments[t];i&&(r.style.textAlign=i),_S(r,e),a.append(r)}),i.append(a),r.append(i);let o=document.createElement(`tbody`);for(let e of n.rows){let t=document.createElement(`tr`);e.forEach((e,r)=>{let i=document.createElement(`td`),a=n.alignments[r];a&&(i.style.textAlign=a),_S(i,e),t.append(i)}),o.append(t)}r.append(o),e.append(r),t.append(e);break}case`rule`:t.append(bS(`hr`,`ui-md__rule`))}return t}var CS=[[`all`,a(`Tudo`),a(`Toda a conversa`)],[`prompts`,a(`Só prompts`),a(`Só os seus prompts e as respostas finais do agente`)],[`noTools`,a(`Sem ferramentas`),a(`Esconde as ferramentas e os resultados`)]];function wS(e){let t=new Set,n=[];for(let r of e){if(r.type!==`entry`){n=[];continue}let e=r.entry.kind;if(e===`assistant`)n.push(r.key);else if(e===`user`){for(let e of n)t.add(e);n=[]}}for(let e of n)t.add(e);return t}function TS(e,t,n){return t===`all`?!0:e.type===`entry`?t===`noTools`||e.entry.kind===`user`||e.entry.kind===`assistant`&&n.has(e.key):!1}var ES=/^[\x00-\x7f]*$/,DS=/[̀-ͯ]/g;function OS(e){if(ES.test(e))return{text:e.toLowerCase()};let t=``,n=[],r=[],i=0;for(let a of e){let e=a.normalize(`NFD`).replace(DS,``).toLowerCase();!e&&r.length&&(r[r.length-1]=i+a.length);for(let t=0;t<e.length;t++)n.push(i),r.push(i+a.length);t+=e,i+=a.length}return{text:t,starts:n,ends:r}}function kS(e){return ES.test(e)?e.toLowerCase():e.normalize(`NFD`).replace(DS,``).toLowerCase()}function AS(e){return e.trim()?OS(e).text:``}function jS(e,t){if(!t||!e)return[];let n=OS(e),r=[];for(let e=n.text.indexOf(t);e!==-1;e=n.text.indexOf(t,e+t.length)){let i=e+t.length;r.push(n.starts?[n.starts[e],n.ends[i-1]]:[e,i])}return r}function MS(e,t,n){return t<=0?-1:e<0||e>=t?n===1?0:t-1:(e+n+t)%t}function NS(e,t){if(!t)return-1;let n=0;for(let[r,i]of e){if(r===t.key)return t.index<i?n+t.index:-1;n+=i}return-1}function PS(e,t){if(t<0)return null;let n=t;for(let[t,r]of e){if(n<r)return{key:t,index:n};n-=r}return null}function FS(e,t){return`${e>=0&&e<t?e+1:0}/${t}`}function IS(e){switch(e.kind){case`tool`:return e.input?.trim()?e.input.replace(/\s+$/,``):e.title;case`thinking`:return e.text??``;case`system`:return e.detail?.trim()?`${e.text}\n${e.detail.replace(/\s+$/,``)}`:e.text;default:return e.text.replace(/\s+$/,``)}}var LS=`ui-term__hit`;function RS(e){return e.tagName===`BUTTON`||e.getAttribute(`aria-hidden`)===`true`||e.hasAttribute(`data-chrome`)||e.classList.contains(`ui-md__lang`)}function zS(e){let t=new Set;for(let n of e){let e=n.parentNode;e&&(e.replaceChild(document.createTextNode(n.textContent??``),n),t.add(e))}for(let e of t)e.normalize()}function BS(e,t){if(!t||!kS(e.textContent??``).includes(t))return[];let n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,{acceptNode:e=>e.nodeType===Node.TEXT_NODE?NodeFilter.FILTER_ACCEPT:RS(e)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_SKIP}),r=[];for(;n.nextNode();)r.push(n.currentNode);let i=[];for(let e of r){let n=e.data,r=jS(n,t);if(!r.length)continue;let a=document.createDocumentFragment(),o=0;for(let[e,t]of r){e>o&&a.append(n.slice(o,e));let r=document.createElement(`span`);r.className=LS,r.textContent=n.slice(e,t),a.append(r),i.push(r),o=t}o<n.length&&a.append(n.slice(o)),e.replaceWith(a)}return i}var VS=1500;function HS(e,t){return!e||e.status===403?t?GS:WS:e.message?e.message:e.status===0?a(`Não foi possível abrir o terminal: sem resposta do servidor.`):a(`Não foi possível abrir o terminal (erro {0}).`,[e.status])}var US=a(`O terminal só fica disponível quando o Habblaud roda com acesso local (bind 127.0.0.1)`),WS=a(`Não foi possível abrir o terminal. O recurso só funciona no acesso local, com o agente ainda aberto.`),GS=a(`Não foi possível abrir a sessão. O histórico só funciona no acesso local, com o transcript ainda no disco.`),KS=120,qS=1500,JS=new Intl.DateTimeFormat(e(),{day:`2-digit`,month:`short`}),YS=32,XS=[`·`,`✢`,`✳`,`✶`,`✻`,`✽`,`✻`,`✶`,`✳`,`✢`],ZS=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`],QS=120,$S=`⏺︎`;function eC(e){return`${e.kind}:${e.id}`}function tC(e){return`tool:${e}`}function nC(e){return`/api/agents/${encodeURIComponent(e)}/terminal`}function rC(e,t){return`/api/sessions/${encodeURIComponent(e)}/${encodeURIComponent(t)}/terminal`}function iC(e,t){return`session:${e}:${t}`}function aC(e){let t=e.project?.replace(/[\\/]+$/,``);return t?t.slice(Math.max(t.lastIndexOf(`/`),t.lastIndexOf(`\\`))+1)||t:e.projectDir}function oC(e,t){if(!Number.isFinite(e)||e<=0)return a(`Sessão encerrada`);let n=Ft(e,!1),r=Vt(e,t);return r===0?a(`Sessão encerrada às {0}`,[n]):r===-1?a(`Sessão encerrada ontem às {0}`,[n]):a(`Sessão encerrada em {0} às {1}`,[JS.format(e),n])}var sC=class{items=new Map;seen=new Set;get size(){return this.items.size}values(){return this.items.values()}get(e){return this.items.get(e)}reset(){this.items.clear(),this.seen.clear()}push(e){let t=[],n=[],r=new Set;for(let i of e){let e=eC(i);if(!this.seen.has(e)){if(this.seen.add(e),i.kind===`tool`){let n={type:`tool`,key:e,tool:i};this.items.set(e,n),t.push(n),r.add(e)}else if(i.kind===`result`){let a=tC(i.toolUseId),o=this.items.get(a);if(o?.type===`tool`&&!o.result)o.result=i,r.has(a)||n.push({toolKey:a,result:i});else{let n={type:`orphan`,key:e,result:i};this.items.set(e,n),t.push(n)}}else{let n={type:`entry`,key:e,entry:i};this.items.set(e,n),t.push(n)}}}return{added:t,attached:n}}trim(e){let t=[];for(let[n,r]of this.items){if(this.items.size<=e)break;this.items.delete(n),this.seen.delete(n),r.type===`tool`&&r.result&&this.seen.delete(eC(r.result)),t.push(n)}return t}},cC=new Set([`user`,`assistant`,`thinking`,`tool`,`result`,`system`]);function lC(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.id!=`string`||!cC.has(t.kind))return!1;switch(t.kind){case`thinking`:return t.text===void 0||typeof t.text==`string`;case`tool`:return typeof t.title==`string`;case`result`:return typeof t.toolUseId==`string`&&typeof t.text==`string`;default:return typeof t.text==`string`}}function uC(e,t,n){let r=Wt(e.at,t,n),i=e.doneLabel;return typeof i==`string`&&i.includes(`{0}`)?i.replace(`{0}`,()=>r):a(`pronto {0}`,[r])}function dC(e){return Array.isArray(e)?e.filter(lC):[]}function fC(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return}}function pC(e){let t=fC(e);if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;return{agentId:typeof n.agentId==`string`?n.agentId:``,entries:dC(n.entries),truncated:n.truncated===!0}}function mC(e){return dC(fC(e))}function hC(e,t,n=t*200){let r=e.replace(/\s+$/,``),i=r===``?[]:r.split(`
11
- `),a=i.length;if(a<=t+2&&r.length<=n)return{text:r,headEnd:r.length,ellipsis:!1,collapsed:!1,hiddenLines:0,total:a};let o=Math.min(a,t),s=i.slice(0,o).join(`
12
- `).length,c=!1;return s>n&&(s=r.slice(0,n).replace(/\s+$/,``).length,c=!0,o=r.slice(0,s).split(`
13
- `).length),{text:r,headEnd:s,ellipsis:c,collapsed:!0,hiddenLines:Math.max(0,a-o),total:a}}function gC(e,t,n=t*200){let r=hC(e,t,n),i=r.collapsed?`${r.text.slice(0,r.headEnd)}${r.ellipsis?`…`:``}`:r.text;return{text:r.text,head:i,collapsed:r.collapsed,hiddenLines:r.hiddenLines,total:r.total}}function _C(e){return e<=0?a(`… mostrar tudo`):`… +${e} ${a(e===1?`linha`:`linhas`)}`}function vC(e){let t=e.indexOf(`(`);return t>0&&e.endsWith(`)`)&&!/\s/.test(e.slice(0,t))?{name:e.slice(0,t),args:e.slice(t)}:{name:e,args:``}}function yC(e){let t=e.input?.trim();return!(!t||(e.inputKind??`text`)===`command`&&!t.includes(`
14
- `)&&e.title.includes(t))}function bC(e){return e.startsWith(`+`)?`add`:e.startsWith(`-`)?`del`:e.startsWith(`@@`)?`hunk`:`ctx`}function xC(e,t){return!Number.isFinite(e)||e<=0?``:Vt(e,t)===0?Ft(e):kt(e)}function SC(e){return e===`codex`?ZS:XS}function CC(e,t){return e===`working`?t===`codex`?`•`:`✻`:{waiting:`✋`,shell:`⏳`,idle:`○`,ended:`■`}[e]}function wC(e){return e.contextTokens??0}function TC(e,t,n){if(!e||e.status===`offline`)return{kind:`ended`,text:a(`Sessão encerrada`)};if(e.status===`done`)return{kind:`ended`,text:a(`Subagente concluído · sessão encerrada`)};if(e.status===`waiting-background`)return{kind:`idle`,text:Yy(e.backgroundAgents?.length??0)};let r=lb(e,t,n);if(r){let e=r.main?.label?.trim(),t=r.jobs.length>1?` (+${r.jobs.length-1})`:``;return{kind:`shell`,text:e?a(`Esperando o shell: {0}{1}`,[e,t]):a(`Esperando o shell terminar`),since:r.since}}switch(e.status){case`working`:return{kind:`working`,text:`${e.activity?.text?.trim().replace(/(?:…|\.{1,3})$/,``)||a(`Trabalhando`)}…`,since:e.statusSince};case`waiting`:{let t=e.waitingFor?a(`Esperando você: {0}`,[e.waitingFor]):a(`Esperando você`);return e.permission?{kind:`waiting`,text:t,since:e.statusSince}:{kind:`waiting`,text:e.provider===`codex`?a(`{0} · responda no Codex: este pedido não chegou ao Habblaud ou passou do tempo de espera`,[t]):a(`{0} · responda no Claude Code: este pedido não chegou ao Habblaud ou passou do tempo de espera`,[t]),since:e.statusSince}}default:return{kind:`idle`,text:a(`Aguardando o próximo prompt`)}}}var EC=(e,t)=>{e.textContent=t},DC=yS,OC=(e,t)=>{let n=document.createDocumentFragment();for(let e of t.split(`
15
- `))n.append(P(`span`,{class:`ui-term__dl is-${bC(e)}`,text:e||` `}));e.append(n)},kC=new WeakMap;function AC(e,t){let n=!1;for(let r=e;r&&r!==t;r=r.parentElement){r.hidden&&(n=!0);let e=kC.get(r);e&&n&&(e(),n=!1)}}function jC(e,t,n,r=EC){let i=hC(e,t),o=P(`div`,{class:`ui-term__pre`}),s=P(`div`,{class:n},o);if(!i.collapsed)return r(o,i.text),s;let c=r===OC,l=P(c?`div`:`span`,{});r(l,i.text.slice(0,i.headEnd));let u=P(c?`div`:`span`,{hidden:!0});r(u,c?i.text.slice(i.headEnd).replace(/^\n/,``):i.text.slice(i.headEnd));let d=i.ellipsis?P(`span`,{class:`ui-term__dots`,text:`…`,attrs:{"aria-hidden":`true`}}):null;o.append(l,...d?[d]:[],u);let f=!1,p=P(`button`,{class:`ui-term__more`,type:`button`,attrs:{"aria-expanded":`false`}}),m=e=>{f=e,u.hidden=!f,d&&(d.hidden=f),M(p,f?a(`recolher`):_C(i.hiddenLines)),N(p,`aria-expanded`,String(f)),A(p,f?a(`Recolher`):a(`Mostrar tudo ({0} {1})`,[i.total,i.total===1?a(`linha`):a(`linhas`)]))};return m(!1),p.addEventListener(`click`,()=>m(!f)),kC.set(s,()=>{f||m(!0)}),s.append(p),s}function MC(e,t,n,r){let i=P(`div`,{class:r,text:n,hidden:!0}),a=P(`button`,{class:t,type:`button`,text:e,attrs:{"aria-expanded":`false`}}),o=!1,s=e=>{o=e,i.hidden=!o,N(a,`aria-expanded`,String(o))};a.addEventListener(`click`,()=>s(!o));let c=P(`div`,{class:`ui-term__exp`},a,i);return kC.set(c,()=>s(!0)),c}function NC(e,t=``){return P(`span`,{class:`ui-term__mark ${t}`.trim(),text:e,attrs:{"aria-hidden":`true`}})}function PC(e,t,n,...r){return P(`div`,{class:`ui-term__row ui-term__row--${e}`,title:xC(t,n)},...r)}function FC(e,t){let n=P(`div`,{class:`ui-term__out`}),r=e.text.replace(/\s+$/,``);r?n.append(jC(r,6,`ui-term__res-text`)):n.append(P(`span`,{class:`ui-term__empty`,text:e.error?a(`(erro sem mensagem)`):a(`(sem saída)`),attrs:{"data-chrome":``}})),e.truncated&&n.append(P(`span`,{class:`ui-term__cut`,text:a(`(resultado cortado)`),attrs:{"data-chrome":``}}));let i=P(`div`,{class:`ui-term__result${e.error?` is-error`:``}`},P(`span`,{class:`ui-term__elbow`,text:`⎿`,attrs:{"aria-hidden":`true`}}),n);return r&&i.append(t(IS(e),a(`resultado`))),i}function IC(e){if(!yC(e))return null;let t=e.inputKind??`text`,n=e.input.replace(/\s+$/,``);if(t===`diff`)return jC(n,10,`ui-term__in ui-term__in--diff`,OC);if(t===`command`){let e=jC(n,10,`ui-term__in ui-term__in--command`);return e.prepend(P(`span`,{class:`ui-term__dollar`,text:`$`,attrs:{"aria-hidden":`true`}})),e}return jC(n,10,`ui-term__in ui-term__in--${t===`json`?`json`:`text`}`)}function LC(e,t,n){let{name:r,args:i}=vC(e.title),o=P(`div`,{class:`ui-term__title`},P(`strong`,{text:r}),i?document.createTextNode(i):null),s=IC(e),c=e.inputKind===`command`||e.tool===`Bash`?a(`comando`):a(s?`entrada da ferramenta`:`ferramenta`),l=P(`div`,{class:`ui-term__call`},o,s,n(IS(e),c)),u=P(`div`,{class:`ui-term__slot`}),d=PC(`tool`,e.at,t,NC($S,`ui-term__dot`),P(`div`,{class:`ui-term__col`},l,u));return d.classList.add(`is-pending`),{row:d,slot:u}}function RC(e,t,n){e.row.classList.remove(`is-pending`),e.row.classList.toggle(`is-error`,!!t.error),e.row.classList.toggle(`is-ok`,!t.error),e.slot.replaceChildren(FC(t,n))}function zC(e,t,n){switch(e.kind){case`user`:{let r=PC(`user`,e.at,t,NC(`>`),P(`div`,{class:`ui-term__col`},jC(e.text,24,`ui-term__user-text`,DC)));return r.append(n(IS(e),`prompt`)),r}case`assistant`:{let r=P(`div`,{class:`ui-term__col ui-md`});r.append(SS(e.text));let i=PC(`assistant`,e.at,t,NC($S,`ui-term__dot`),r);return i.append(n(IS(e),a(`resposta`))),i}case`thinking`:{let n=e.text?.trim(),r=n?MC(a(`Pensando…`),`ui-term__think`,n,`ui-term__think-text`):P(`span`,{class:`ui-term__think`,text:a(`Pensando…`),attrs:{"data-chrome":``}});return PC(`thinking`,e.at,t,NC(`✻`),P(`div`,{class:`ui-term__col`},r))}case`system`:{let n=P(`span`,{class:`ui-term__sys-text`,text:e.turnDone?`${e.text} · ${uC(e,t)}`:e.text}),r=P(`div`,{class:`ui-term__col`},n);e.detail?.trim()&&r.append(MC(a(`detalhes`),`ui-term__sys-more`,e.detail.trim(),`ui-term__sys-detail`));let i=PC(`system`,e.at,t,NC(`※`),r);return(e.level===`warn`||e.level===`error`)&&i.classList.add(`is-${e.level}`),i}}}var BC=new Set;function VC(e){return e.filteredOut?a(`Nada para mostrar com este filtro.`):e.empty?e.conn===`waiting`?Vb(e.agent)===`agent-hub`&&e.agent?.status===`waiting`?a(`Na fila do Agent Hub`):a(`Esperando o agente começar…`):e.loaded?e.isSession?a(`Nenhuma mensagem nesta sessão.`):a(`Nenhuma mensagem nesta sessão ainda.`):a(`Abrindo o terminal…`):``}var HC=class{ctx;el;id=null;session=null;last=null;stream=null;failure=null;opener=null;conn=`connecting`;loaded=!1;truncated=!1;log=new sC;rows=new Map;tools=new Map;follow=!0;unread=0;spinTimer=null;spinFrame=0;lastEntryAt=0;filter=`all`;filterGroup;visibleRows=0;searchOpen=!1;folded=``;hits=new Map;current=null;currentEl=null;searchTimer=null;kindEl;accEl;nameEl;provEl;frames=XS;roleEl;roomEl;reconnEl;findBtn;alertEl;alertText;searchBox;searchInput;countEl;scroll;list;note;placeholder;newBtn;status;glyph;statusText;statusTime;backgroundList;backgroundTimer=null;actions;tabs;movable;composer;readOnlyLine;constructor(e,t){this.ctx=e,this.actions=t?new fx(e,t,!0):null,this.tabs=new Ix(e);let n=typeof navigator<`u`&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent||``)?`⌘F`:`Ctrl+F`,r=P(`span`,{class:`ui-term__icon`,attrs:{"aria-hidden":`true`}});r.innerHTML=Q.terminal,this.kindEl=P(`span`,{class:`ui-term__kind`,text:`terminal`}),this.accEl=yx(`sm`),this.accEl.hidden=!0,this.nameEl=P(`strong`,{class:`ui-term__name`}),this.provEl=xx(`ui-prov--xs`),this.roleEl=P(`span`,{class:`ui-role`}),this.roomEl=P(`span`,{class:`ui-term__room`}),this.reconnEl=P(`span`,{class:`ui-term__reconn`,text:a(`reconectando…`),hidden:!0,role:`status`}),this.findBtn=j(Q.search,a(`Buscar na conversa ({0})`,[n]),()=>this.toggleSearch(),`ui-icon-btn--sm ui-term__find`),N(this.findBtn,`aria-expanded`,`false`);let i=j(Q.close,a(`Fechar terminal (Esc)`),()=>this.close(),`ui-icon-btn--sm ui-term__close`),o=P(`div`,{class:`ui-term__bar`},r,this.kindEl,P(`div`,{class:`ui-term__who`},this.accEl,this.nameEl,this.provEl,this.roleEl,this.roomEl),this.reconnEl,this.findBtn,...this.actions?[this.actions.el]:[],Ib(()=>this.movable),i);this.filterGroup=new Bv({label:a(`Filtrar a conversa`),options:CS.map(([e,t,n])=>({value:e,label:t,title:n,className:`ui-seg__opt`})),value:this.filter,className:`ui-seg ui-term__filter`,indicator:!1,onChange:e=>this.setFilter(e)});let s=this.filterGroup.el,c=P(`span`,{class:`ui-term__search-icon`,attrs:{"aria-hidden":`true`}});c.innerHTML=Q.search,this.searchInput=P(`input`,{class:`ui-term__search-input`,type:`text`,attrs:{placeholder:a(`Buscar na conversa`),"aria-label":a(`Buscar na conversa`),autocomplete:`off`,spellcheck:`false`,enterkeyhint:`search`}}),this.searchInput.addEventListener(`input`,()=>this.scheduleSearch()),this.searchInput.addEventListener(`keydown`,e=>{e.key===`Enter`?(e.preventDefault(),this.go(e.shiftKey?-1:1)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.closeSearch(!0))}),this.countEl=P(`span`,{class:`ui-term__count`,attrs:{"aria-live":`polite`}}),this.searchBox=P(`div`,{class:`ui-term__search`,role:`search`,hidden:!0},c,this.searchInput,this.countEl,j(Q.chevronUp,a(`Resultado anterior (Shift+Enter)`),()=>this.go(-1),`ui-icon-btn--sm ui-term__step`),j(Q.chevronDown,a(`Próximo resultado (Enter)`),()=>this.go(1),`ui-icon-btn--sm ui-term__step`),j(Q.close,a(`Fechar a busca (Esc)`),()=>this.closeSearch(!0),`ui-icon-btn--sm ui-term__step`));let l=P(`div`,{class:`ui-term__tools`},s,this.searchBox),u=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Tentar de novo`),on:{click:()=>this.connect()}});this.alertText=P(`span`,{class:`ui-term__alert-text`,text:WS}),this.alertEl=P(`div`,{class:`ui-term__alert`,role:`alert`,hidden:!0},this.alertText,u),this.note=P(`p`,{class:`ui-term__note`,text:a(`Conversa anterior não carregada`),hidden:!0}),this.list=P(`div`,{class:`ui-term__list`}),this.placeholder=P(`p`,{class:`ui-term__placeholder`}),this.scroll=P(`div`,{class:`ui-term__scroll`,tabIndex:0,attrs:{"aria-label":a(`Conversa da sessão`)}},this.note,this.list,this.placeholder),this.scroll.addEventListener(`scroll`,()=>this.onScroll(),{passive:!0}),this.newBtn=P(`button`,{class:`ui-term__new`,type:`button`,hidden:!0,on:{click:()=>this.jumpToEnd()}}),this.glyph=P(`span`,{class:`ui-term__glyph`,attrs:{"aria-hidden":`true`}}),this.statusText=P(`span`,{class:`ui-term__status-text`}),this.statusTime=P(`span`,{class:`ui-term__status-time`}),this.status=P(`p`,{class:`ui-term__status`},this.glyph,this.statusText,this.statusTime),this.backgroundList=P(`div`,{class:`ui-term__background-agents`,hidden:!0}),this.composer=new Gy(e,`terminal`,{onEscape:()=>this.focusLog()}),this.readOnlyLine=P(`p`,{class:`ui-term__readonly ui-muted`,hidden:!0}),this.el=P(`section`,{class:`ui-term`,role:`dialog`,hidden:!0,tabIndex:-1,attrs:{"aria-label":a(`Terminal`)}},o,this.tabs.el,l,P(`div`,{class:`ui-term__body`},this.alertEl,this.scroll,this.newBtn),P(`div`,{class:`ui-term__foot`},this.status,this.backgroundList,this.readOnlyLine,this.composer.el)),this.el.addEventListener(`keydown`,e=>this.onKey(e)),this.movable=new Fb(this.el,o,{key:`habblaud.move.term`,enabled:()=>!e.isNarrow()}),this.renderFilter(),typeof ResizeObserver==`function`&&new ResizeObserver(()=>this.follow&&this.scrollToEnd()).observe(this.scroll)}get agentId(){return this.session?null:this.id}get isOpen(){return this.id!==null}open(e,t=UC()){this.start(e,null,t)}openSession(e,t=UC()){if(e.open&&e.agentId&&this.ctx.agent(e.agentId))return this.open(e.agentId,t);this.start(iC(e.account,e.sessionId),e,t)}close(){if(this.id===null)return;this.disconnect(),this.stopSpinner(),this.stopBackgroundTimer(),this.closeSearch(!1);let e=this.el.contains(document.activeElement)||document.activeElement===document.body;this.id=null,this.session=null,this.last=null,this.el.hidden=!0,this.clear();let t=this.opener;this.opener=null,e&&t?.isConnected&&t.focus({preventScroll:!0}),this.ctx.invalidate()}toggle(e,t=UC()){this.agentId===e?this.close():this.open(e,t)}escape(){return this.id!==null&&(this.searchOpen?this.closeSearch(this.el.contains(document.activeElement)):this.close(),!0)}render(){if(this.id===null)return;this.session?this.renderSessionHead(this.session):this.renderAgentHead();let e=this.session?null:this.ctx.agent(this.id)??null;this.actions?.render(e),this.tabs.render(e?e.id:null),this.renderFooter(),this.renderState();let t=Vb(this.session?null:this.ctx.agent(this.id)??this.last)===`agent-hub`;F(this.composer.el,t),F(this.readOnlyLine,!t),t?M(this.readOnlyLine,a(`Somente leitura: o Agent Hub gerencia este job`)):this.composer.render(this.session?void 0:this.ctx.agent(this.id),this.id)}start(e,t,n){if(n&&!this.el.contains(n)&&(this.opener=n),this.id===e){this.focusLog();return}this.disconnect(),this.clear(),this.id=e,this.session=t,this.last=t?null:this.ctx.agent(e)??null,this.loaded=!1,this.truncated=!1,this.follow=!0,this.unread=0,this.lastEntryAt=0,this.el.hidden&&this.movable.restore(),this.el.hidden=!1,this.el.classList.toggle(`is-session`,!!t),this.connect(),this.render(),this.focusLog(),this.ctx.invalidate()}renderAgentHead(){let e=this.ctx.agent(this.id);e&&(this.last=e);let t=this.last,n=t?xt(t,this.ctx.store.snapshot?.machines):a(`Agente`);M(this.kindEl,`terminal`),F(this.accEl,!0),M(this.nameEl,n),A(this.nameEl,``),Sx(this.provEl,Vb(t)),M(this.roleEl,t?Qy(t):``),F(this.roleEl,!t),t&&vt(this.roleEl,`ui-role--`,t.kind);let r=t?this.ctx.store.room(t.roomId):void 0;M(this.roomEl,r?a(`sala {0}`,[r.name]):``),A(this.roomEl,r?.path??``),F(this.roomEl,!r),N(this.el,`aria-label`,a(`Terminal de {0}`,[n])),this.el.classList.toggle(`is-gone`,!e)}renderSessionHead(e){let t=e.title?.trim()||a(`Sessão sem título`);M(this.kindEl,a(`histórico`)),bx(this.accEl,this.ctx.account(e.account),e.account,e.provider),F(this.accEl,!1),M(this.nameEl,t),A(this.nameEl,t),Sx(this.provEl,Vb(e)),F(this.roleEl,!0),M(this.roomEl,`${aC(e)} · ${kt(e.firstAt??e.lastAt)}`),A(this.roomEl,e.project??e.projectDir),F(this.roomEl,!1),N(this.el,`aria-label`,a(`Terminal da sessão {0}`,[t])),this.el.classList.remove(`is-gone`)}onKey(e){if(e.defaultPrevented)return;let t=(e.ctrlKey||e.metaKey)&&!e.altKey,n=e.key.toLowerCase();if(t&&!e.shiftKey&&n===`f`){e.preventDefault(),e.stopPropagation(),this.openSearch();return}if(t&&n===`g`&&this.searchOpen){e.preventDefault(),this.go(e.shiftKey?-1:1);return}e.key!==`Escape`||e.ctrlKey||e.metaKey||e.altKey||(e.preventDefault(),e.stopPropagation(),this.escape())}connect(){this.disconnect();let e=this.id;if(e===null)return;this.conn=`connecting`,this.failure=null;let t=new Hx(this.session?rC(this.session.account,this.session.sessionId):nC(e),Vx(),{onState:(e,n)=>{this.stream===t&&(this.conn=e,this.failure=n,this.renderState())},onEvent:(e,n)=>{if(this.stream===t){if(e===`init`){let e=pC(n);e&&this.onInit(e)}else{let e=mC(n);e.length&&this.ingest(e,!1)}}}});this.stream=t,t.start(),this.renderState()}disconnect(){this.stream?.close(),this.stream=null}onInit(e){let t=this.follow?null:this.captureAnchor();this.clear(),this.conn=`open`,this.loaded=!0,this.truncated=e.truncated,this.unread=0,this.ingest(e.entries,!0),this.folded&&this.runSearch(!1);let n=t?this.rows.get(t.key):void 0;t&&n?this.scroll.scrollTop=n.offsetTop-t.offset:(this.follow=!0,this.scrollToEnd()),this.renderState()}ingest(e,t){for(let t of e)t.at>this.lastEntryAt&&(this.lastEntryAt=t.at);let n=this.log.push(e),r=this.log.trim(VS);if(r.length){let e=this.follow?0:this.scroll.scrollHeight;for(let e of r)this.rows.get(e)?.remove(),this.rows.delete(e),this.tools.delete(e),this.hits.delete(e),this.current?.key===e&&(this.current=null);this.follow||(this.scroll.scrollTop-=e-this.scroll.scrollHeight)}let i=[];for(let{toolKey:e,result:t}of n.attached){let n=this.tools.get(e);n&&(RC(n,t,this.copier),i.push(e))}let a=new Set(r),o=this.ctx.now(),s=document.createDocumentFragment(),c=0;for(let e of n.added){if(a.has(e.key))continue;let t=this.buildRow(e,o);t.dataset.key=e.key,this.rows.set(e.key,t),s.append(t),i.push(e.key),c++}this.list.append(s),this.applyFilter(),!t&&this.folded&&this.refreshHits(i),t||(this.follow?this.scrollToEnd():this.unread+=c+n.attached.length,this.renderState())}buildRow(e,t){if(e.type===`entry`)return zC(e.entry,t,this.copier);if(e.type===`orphan`){let n=PC(`orphan`,e.result.at,t,NC(``),P(`div`,{class:`ui-term__col`},FC(e.result,this.copier)));return n.getAttribute(`data-tip`)||A(n,a(`Resultado de uma ferramenta anterior`)),n}let n=LC(e.tool,t,this.copier);return this.tools.set(e.key,n),e.result&&RC(n,e.result,this.copier),n.row}clear(){this.log.reset(),this.rows.clear(),this.tools.clear(),this.hits.clear(),this.current=null,this.currentEl=null,this.visibleRows=0,this.list.replaceChildren()}copier=(e,t)=>{let n=a(`Copiar {0}`,[t]),r=P(`span`,{class:`ui-term__copy-icon`,attrs:{"aria-hidden":`true`}});r.innerHTML=Q.copy;let i=P(`span`,{class:`ui-term__copy-done`,text:a(`Copiado`)}),o=P(`button`,{class:`ui-term__copy`,type:`button`,title:n,attrs:{"aria-label":n}},r,i),s=null;return o.addEventListener(`click`,async t=>{t.stopPropagation();let c=await St(e);o.classList.toggle(`is-done`,c),o.classList.toggle(`is-fail`,!c),r.innerHTML=c?Q.check:Q.copy,M(i,a(c?`Copiado`:`Não foi possível copiar`)),A(o,a(c?`Copiado`:`Não foi possível copiar`)),this.ctx.announce(a(c?`Copiado.`:`Não foi possível copiar.`)),s&&clearTimeout(s),s=setTimeout(()=>{o.classList.remove(`is-done`,`is-fail`),r.innerHTML=Q.copy,M(i,a(`Copiado`)),A(o,n)},qS)}),o};setFilter(e){e!==this.filter&&(this.filter=e,this.renderFilter(),this.applyFilter(),this.folded&&(this.markCurrent(!1),this.renderSearch()),this.follow&&this.scrollToEnd(),this.renderState())}renderFilter(){this.filterGroup.value=this.filter}applyFilter(){let e=this.filter===`prompts`?wS(this.log.values()):BC,t=0;for(let n of this.log.values()){let r=this.rows.get(n.key);if(!r)continue;let i=TS(n,this.filter,e);r.classList.toggle(`is-filtered`,!i),i&&t++}this.visibleRows=t}toggleSearch(){this.searchOpen?this.closeSearch(!0):this.openSearch()}openSearch(){if(this.id===null)return;let e=this.searchOpen;this.searchOpen=!0,F(this.searchBox,!1),N(this.findBtn,`aria-expanded`,`true`),this.findBtn.classList.add(`is-on`),this.searchInput.focus(),this.searchInput.select(),!e&&this.searchInput.value.trim()?this.runSearch(!0):this.renderSearch()}closeSearch(e){this.searchTimer&&clearTimeout(this.searchTimer),this.searchTimer=null,this.searchOpen&&(this.searchOpen=!1,F(this.searchBox,!0),N(this.findBtn,`aria-expanded`,`false`),this.findBtn.classList.remove(`is-on`),this.runSearch(!1),e&&this.focusLog())}scheduleSearch(){this.searchTimer&&clearTimeout(this.searchTimer),this.searchTimer=setTimeout(()=>this.runSearch(!0),KS)}flushSearch(){this.searchTimer&&(clearTimeout(this.searchTimer),this.runSearch(!0))}runSearch(e){this.searchTimer=null;let t=this.searchOpen?AS(this.searchInput.value):``;for(let e of this.hits.values())zS(e);this.hits.clear(),this.currentEl=null;let n=this.current;if(this.current=null,this.folded=t,t){for(let[e,n]of this.rows){let r=BS(n,t);r.length&&this.hits.set(e,r)}this.current=e?this.firstHitInView():n,this.markCurrent(e)}this.renderSearch()}refreshHits(e){for(let t of e){let e=this.hits.get(t);e&&zS(e),this.hits.delete(t);let n=this.rows.get(t),r=n?BS(n,this.folded):[];r.length&&this.hits.set(t,r)}this.markCurrent(!1),this.renderSearch()}visibleCounts(){let e=[];for(let[t,n]of this.rows){let r=this.hits.get(t);r&&!n.classList.contains(`is-filtered`)&&e.push([t,r.length])}return e}firstHitInView(){let e=this.scroll.getBoundingClientRect().top,t=null;for(let[n]of this.visibleCounts()){if(t??={key:n,index:0},this.rows.get(n).getBoundingClientRect().bottom<e)continue;let r=this.hits.get(n).findIndex(t=>t.getBoundingClientRect().bottom>=e);if(r>=0)return{key:n,index:r}}return t}go(e){if(!this.searchOpen)return this.openSearch();this.flushSearch();let t=this.visibleCounts(),n=t.reduce((e,[,t])=>e+t,0);n&&(this.current=PS(t,MS(NS(t,this.current),n,e)),this.markCurrent(!0),this.renderSearch(t))}markCurrent(e){this.currentEl?.classList.remove(`is-current`),this.currentEl=null;let t=this.current;if(!t)return;let n=this.rows.get(t.key),r=this.hits.get(t.key);if(!n||!r?.length||n.classList.contains(`is-filtered`)){this.current=null;return}let i=Math.min(t.index,r.length-1),a=r[i];this.current={key:t.key,index:i},AC(a,n),a.classList.add(`is-current`),this.currentEl=a,e&&this.scrollToHit(a)}scrollToHit(e){let t=e.getBoundingClientRect(),n=this.scroll.getBoundingClientRect();(t.top<n.top+8||t.bottom>n.bottom-8)&&(this.scroll.scrollTop+=t.top-n.top-(n.height-t.height)/2),this.follow=this.distanceToEnd()<=YS,this.renderNewButton()}renderSearch(e=this.visibleCounts()){let t=e.reduce((e,[,t])=>e+t,0),n=this.searchOpen&&!!this.folded;M(this.countEl,n?FS(NS(e,this.current),t):``),A(this.countEl,n?t?`${t} ${a(t===1?`resultado`:`resultados`)}`:a(`Nenhum resultado`):``),this.searchBox.classList.toggle(`is-miss`,n&&t===0)}distanceToEnd(){let e=this.scroll;return e.scrollHeight-e.scrollTop-e.clientHeight}onScroll(){let e=this.distanceToEnd()<=YS;e!==this.follow&&(this.follow=e,e&&(this.unread=0),this.renderNewButton())}scrollToEnd(){this.scroll.scrollTop=this.scroll.scrollHeight}jumpToEnd(){this.follow=!0,this.unread=0,this.scrollToEnd(),this.renderNewButton()}captureAnchor(){let e=this.scroll.scrollTop;for(let[t,n]of this.rows)if(!n.classList.contains(`is-filtered`)&&n.offsetTop+n.offsetHeight>e)return{key:t,offset:n.offsetTop-e};return null}focusLog(){this.scroll.focus({preventScroll:!0})}renderState(){F(this.reconnEl,this.conn!==`reconnecting`),F(this.alertEl,this.conn!==`failed`),M(this.alertText,HS(this.failure,!!this.session)),F(this.note,!(this.loaded&&this.truncated));let e=this.rows.size===0,t=!e&&this.visibleRows===0;F(this.placeholder,!(e||t)||this.conn===`failed`);let n=this.session?null:this.ctx.agent(this.id)??this.last;M(this.placeholder,VC({empty:e,filteredOut:t,conn:this.conn,loaded:this.loaded,isSession:!!this.session,agent:n})),this.renderNewButton()}renderNewButton(){F(this.newBtn,this.follow||this.visibleRows===0),M(this.newBtn,this.unread>0?a(`↓ Novas mensagens`):a(`↓ Ir para o fim`))}renderFooter(){if(this.id===null)return;let e=this.ctx.now();if(this.session){let t=Math.max(this.session.lastAt,this.lastEntryAt),n=oC(t,e);this.stopSpinner(),vt(this.status,`is-`,`ended`),M(this.statusText,n),A(this.status,`${n} (${kt(t)})`),M(this.statusTime,``),F(this.statusTime,!0),M(this.glyph,`■`),this.renderBackgroundAgents([],e);return}let t=this.ctx.agent(this.id),n=Vb(t??this.last);this.frames=SC(n);let r=TC(t,this.ctx.store.snapshot?.agents??[],e);this.renderBackgroundAgents(t?.backgroundAgents,e),vt(this.status,`is-`,r.kind),M(this.statusText,r.text),A(this.status,r.text);let i=``;if(r.since!==void 0){let t=Math.max(0,e-r.since);r.kind===`working`?i=`(${zt(t)})`:r.kind===`shell`?i=Ht(t):r.kind===`waiting`&&(i=Nt(r.since,e))}M(this.statusTime,i),F(this.statusTime,!i),r.kind===`working`&&!ht()?this.startSpinner():(this.stopSpinner(),M(this.glyph,CC(r.kind,n)))}renderBackgroundAgents(e,t){let n=e??[];F(this.backgroundList,n.length===0),this.backgroundList.replaceChildren(...n.map(e=>{let n=wC(e),r=Ht(t-e.startedAt);return P(`div`,{class:`ui-term__background-agent`,attrs:{"aria-label":a(`{0} · {1} · rodando há {2}`,[e.type,e.description??``,r])}},P(`span`,{class:`ui-term__background-glyph`,attrs:{"aria-hidden":`true`},text:`○`}),P(`span`,{class:`ui-term__background-type`,text:e.type}),P(`span`,{class:`ui-term__background-description`,text:e.description??``}),P(`span`,{class:`ui-term__background-time`,text:r}),...n>0?[P(`span`,{class:`ui-term__background-tokens`,text:a(`{0} tokens`,[At(n)])})]:[])})),n.length>0?this.backgroundTimer||=setInterval(()=>this.renderFooter(),1e3):this.stopBackgroundTimer()}stopBackgroundTimer(){this.backgroundTimer&&=(clearInterval(this.backgroundTimer),null)}startSpinner(){this.spinTimer||=(M(this.glyph,this.frames[this.spinFrame%this.frames.length]),setInterval(()=>{this.spinFrame=(this.spinFrame+1)%(this.frames.length*8),M(this.glyph,this.frames[this.spinFrame%this.frames.length]),this.spinFrame%8==0&&this.renderFooter()},QS))}stopSpinner(){this.spinTimer&&clearInterval(this.spinTimer),this.spinTimer=null}};function UC(){return typeof document<`u`&&document.activeElement instanceof HTMLElement?document.activeElement:null}var WC=`habblaud:permission-focus`,GC=12,KC=1e3,qC={session:a(`só nesta sessão`),localSettings:a(`neste projeto, só para você`),projectSettings:a(`neste projeto, para todos (versionado)`),userSettings:a(`em todos os projetos`)};function JC(e){return qC[e]??e}function YC(e,t,n=!1){let r=e-t;return r<=0?a(`voltando ao terminal…`):r<6e4?n?a(`volta ao terminal em {0} s`,[Math.ceil(r/1e3)]):a(`volta ao terminal em menos de 1 min`):a(`volta ao terminal em {0}`,[zt(r)])}var XC=a(`No Codex, a aprovação só aparece no terminal depois que você responder aqui ou o prazo acabar.`);function ZC(e,t){if(e.provider===`codex`)return{always:!1,interrupt:!1,reasonRequired:!0,seconds:!0,note:XC};let n=t.kind===`sub`&&!!t.background;return{always:!!e.suggestions?.length,interrupt:!0,reasonRequired:!1,seconds:!1,note:n?a(`Este subagente roda em segundo plano: o terminal só mostra o pedido depois que você responder aqui ou escolher “Responder no terminal”.`):``}}function QC(e){return e.filter(e=>e.permission&&e.status!==`offline`&&e.status!==`done`).sort((e,t)=>e.permission.createdAt-t.permission.createdAt)}function $C(e,t){let n=QC(e);if(n.length)return n[((t?n.findIndex(e=>e.id===t):-1)+1)%n.length]}function ew(e,t){e.select({type:`agent`,id:t},{focus:!0}),e.root.dispatchEvent(new CustomEvent(WC,{detail:t}))}function tw(e){return!!e&&e.provider!==`codex`&&e.tool===`AskUserQuestion`&&!!e.questions?.length}function nw(e,t,n,r){let i=new Set(e.options.map(e=>e.index));return{options:t.map(Number).filter(e=>Number.isInteger(e)&&i.has(e)),otherOn:n,otherText:r}}function rw(e,t){if(!t)return;let n=t.otherOn?t.otherText.trim().slice(0,l):``;if(t.otherOn&&!n)return;let r=e.multiSelect||!n?t.options.filter(t=>e.options.some(e=>e.index===t)):[];if(r.length||n)return{question:e.index,...r.length?{options:[...r]}:{},...n?{other:n}:{}}}function iw(e,t){let n=[];for(let r of e){let e=rw(r,t.get(r.index));if(!e)return;n.push(e)}return m(e,n)}function aw(e){return!!e&&e.inputKind===`command`&&!!e.input?.trim()}function ow(e){if(!aw(e)&&!yC(e))return null;let t=e.inputKind??`text`,n=e.input.replace(/\s+$/,``),r=(e,n)=>{if(e.replaceChildren(),t!==`diff`)return void(e.textContent=n);for(let t of n.split(`
16
- `))e.append(P(`span`,{class:`ui-term__dl is-${bC(t)}`,text:t||` `}))},i=gC(n,GC),o=P(`div`,{class:`ui-term__pre`});r(o,i.head);let s=P(`div`,{class:`ui-term__in ui-term__in--${t}`},o);if(t===`command`&&s.prepend(P(`span`,{class:`ui-term__dollar`,text:`$`,attrs:{"aria-hidden":`true`}})),i.collapsed){let e=!1,t=P(`button`,{class:`ui-term__more`,type:`button`,text:_C(i.hiddenLines),attrs:{"aria-expanded":`false`}});t.addEventListener(`click`,()=>{e=!e,r(o,e?i.text:i.head),M(t,e?a(`recolher`):_C(i.hiddenLines)),N(t,`aria-expanded`,String(e))}),s.append(t)}return s}var sw={allow:a(`Aprovado`),deny:a(`Recusado`),answer:a(`Respondido`),terminal:a(`Devolvido ao terminal`)},cw=class{ctx;el;id=``;agentId=``;phase=`idle`;detailReq=0;detail=null;pendingFocus=null;icon;title;what;timer;tool;preview;note;queue;approveBtn;denyBtn;terminalBtn;always;suggestions;denyForm;reason;interrupt;interruptRow;denySubmit;opts={always:!1,interrupt:!0,reasonRequired:!1,seconds:!1,note:``};status;remote;askForm;askId=``;askRefs=[];answerBtn;constructor(e){this.ctx=e,this.icon=P(`span`,{class:`ui-perm__icon`,attrs:{"aria-hidden":`true`}}),this.title=P(`strong`,{class:`ui-perm__title`}),this.what=P(`p`,{class:`ui-perm__what`}),this.timer=P(`span`,{class:`ui-perm__timer`}),this.tool=P(`div`,{class:`ui-perm__tool`}),this.preview=P(`div`,{class:`ui-perm__preview`}),this.note=P(`p`,{class:`ui-perm__note`,hidden:!0}),this.queue=P(`p`,{class:`ui-perm__queue`,hidden:!0}),this.remote=P(`p`,{class:`ui-perm__note`,hidden:!0,text:a(`Para responder por aqui, abra o Habblaud por http://localhost (ou 127.0.0.1). Por enquanto, responda no terminal.`)}),this.approveBtn=P(`button`,{class:`ui-btn ui-perm__btn ui-perm__btn--allow`,type:`button`,on:{click:()=>this.send({behavior:`allow`})}},a(`✓ Aprovar`)),this.answerBtn=P(`button`,{class:`ui-btn ui-perm__btn ui-perm__btn--allow`,type:`button`,hidden:!0,on:{click:()=>this.sendAnswer()}},a(`✓ Responder`)),this.askForm=P(`form`,{class:`ui-perm-ask`,hidden:!0,attrs:{"aria-label":a(`Perguntas do agente`)}}),this.askForm.addEventListener(`submit`,e=>{e.preventDefault(),this.sendAnswer()}),this.askForm.addEventListener(`change`,()=>this.syncAnswer()),this.denyBtn=P(`button`,{class:`ui-btn ui-perm__btn ui-perm__btn--deny`,type:`button`,attrs:{"aria-expanded":`false`},on:{click:()=>this.toggleDeny()}},a(`✕ Recusar…`)),this.terminalBtn=P(`button`,{class:`ui-btn ui-perm__btn`,type:`button`,title:a(`O Habblaud deixa este pedido de lado: vale o que você responder no terminal`),on:{click:()=>this.send({behavior:`terminal`})}},a(`Responder no terminal`));let t=P(`div`,{class:`ui-perm__rules`});this.suggestions=new wt(t,{animate:!1,key:e=>String(e.index),create:e=>P(`button`,{class:`ui-btn ui-perm__rule`,type:`button`,on:{click:()=>this.send({behavior:`allow`,suggestion:e.index})}}),update:(e,t)=>{let n=t.rules.join(`, `);M(e,`${n} · ${JC(t.destination)}`),A(e,a(`Aprovar agora e não perguntar de novo: {0} ({1})`,[n,JC(t.destination)]))}}),this.always=P(`div`,{class:`ui-perm__always`,hidden:!0},P(`span`,{class:`ui-perm__always-label`,text:a(`Aprovar e não perguntar de novo:`)}),t),this.reason=P(`textarea`,{class:`ui-perm__reason`,attrs:{rows:2,maxlength:KC,placeholder:a(`Motivo (opcional, vai para o agente). Ex.: use pnpm em vez de npm`),"aria-label":a(`Motivo da recusa (opcional)`)}}),this.interrupt=new Vv({label:a(`Interromper o agente (ele para e espera você)`),className:`ui-perm__check`}),this.interruptRow=P(`div`,{class:`ui-perm__check-row`},this.interrupt.el),this.denySubmit=P(`button`,{class:`ui-btn ui-perm__btn ui-perm__btn--deny`,type:`submit`},a(`Recusar`)),this.denyForm=P(`form`,{class:`ui-perm__deny`,hidden:!0},this.reason,this.interruptRow,P(`div`,{class:`ui-perm__actions`},this.denySubmit,P(`button`,{class:`ui-btn ui-perm__btn`,type:`button`,on:{click:()=>this.toggleDeny(!1)}},a(`Cancelar`)))),this.reason.addEventListener(`input`,()=>this.syncDeny()),this.denyForm.addEventListener(`submit`,e=>{e.preventDefault();let t=this.reason.value.trim().slice(0,KC);if(this.opts.reasonRequired&&!t)return this.reason.focus();this.send({behavior:`deny`,...t?{message:t}:{},...this.opts.interrupt&&this.interrupt.value?{interrupt:!0}:{}})}),this.denyForm.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),this.toggleDeny(!1))}),this.status=P(`p`,{class:`ui-perm__status`,role:`status`,attrs:{"aria-live":`polite`}}),this.el=P(`section`,{class:`ui-perm`,hidden:!0,tabIndex:-1},P(`div`,{class:`ui-perm__head`},this.icon,P(`div`,{class:`ui-perm__head-text`},this.title,this.what),this.timer),this.tool,this.preview,this.askForm,this.note,this.queue,this.remote,P(`div`,{class:`ui-perm__actions`},this.approveBtn,this.answerBtn,this.denyBtn,this.terminalBtn),this.always,this.denyForm,this.status),e.root.addEventListener(WC,t=>{this.pendingFocus=t.detail,e.invalidate()})}get visible(){return!this.el.hidden}render(e){let t=e?.permission;if(!e||!t){F(this.el,!0),this.reset(``,e?.id??``);return}(t.id!==this.id||e.id!==this.agentId)&&this.reset(t.id,e.id),F(this.el,!1);let n=this.ctx.now(),r=this.opts=ZC(t,e),i=t.provider===`codex`;this.el.classList.toggle(`is-codex`,i);let o=tw(t),s=o?`ask`:`perm`;this.el.dataset.kind!==s&&(this.el.dataset.kind=s,this.icon.innerHTML=o?Q.help:Q.lock,N(this.el,`aria-label`,a(o?`Pergunta do agente`:`Pedido de permissão`))),M(this.title,o?t.questions.length>1?a(`Perguntas para você`):a(`Pergunta para você`):a(`Pede permissão`));let c=t.subagent?a(` · subagente {0}`,[t.subagent]):``;if(M(this.what,o?a(`Aqui ou no terminal: vale a primeira resposta{0}`,[c]):`${t.icon} ${t.text}${c}`),M(this.timer,YC(t.expiresAt,n,r.seconds)),A(this.timer,a(i?`Pedido feito às {0}. Sem resposta aqui até {1}, o Codex segue sem a decisão do escritório e pede a aprovação no terminal.`:`Pedido feito às {0}. Sem resposta aqui até {1}, o Habblaud devolve o pedido ao terminal.`,[Ft(t.createdAt),Ft(t.expiresAt)])),F(this.tool,o),F(this.preview,o),F(this.askForm,!o),o&&this.askId!==t.id&&this.buildAsk(t),!o){let e=this.detail?.id===t.id?this.detail:t.input===void 0?null:t,{name:n,args:r}=vC(t.title),i=aw(e)?``:r;this.tool.dataset.title!==`${t.title}|${i}`&&(this.tool.dataset.title=`${t.title}|${i}`,this.tool.replaceChildren(P(`strong`,{text:n}),i?document.createTextNode(i):``)),A(this.tool,t.title),this.preview.dataset.id!==`${t.id}:${e?`full`:`short`}`&&(this.preview.dataset.id=`${t.id}:${e?`full`:`short`}`,this.preview.replaceChildren(e?ow(e)??``:P(`span`,{class:`ui-muted ui-small`,text:a(`Carregando os detalhes…`)})))}F(this.note,!r.note),M(this.note,r.note),F(this.queue,!t.queued),M(this.queue,t.queued?a(`+{0} {1} deste agente na fila`,[t.queued,t.queued===1?a(`pedido`):a(`pedidos`)]):``),F(this.remote,this.isLocal());let l=this.isBusy();F(this.approveBtn,o),F(this.answerBtn,!o);for(let e of[this.approveBtn,this.denyBtn,this.terminalBtn])e.disabled=l;for(let e of this.askForm.querySelectorAll(`input`))e.disabled=l;o&&this.syncAnswer(),A(this.denyBtn,o?a(`Não responder: o agente segue sem a resposta (com o motivo, se você escrever um)`):i?a(`Recusar com um motivo (o Codex pede um)`):``),A(this.terminalBtn,a(i?`O Habblaud solta o pedido agora: o Codex mostra a aprovação no terminal`:`O Habblaud deixa este pedido de lado: vale o que você responder no terminal`)),this.suggestions.sync(r.always?t.suggestions??[]:[]);for(let e of this.suggestions.container.querySelectorAll(`button`))e.disabled=l;F(this.always,o||!r.always||this.phase===`deny`),F(this.denyForm,this.phase!==`deny`),F(this.interruptRow,!r.interrupt),N(this.reason,`placeholder`,r.reasonRequired?a(`Motivo (obrigatório no Codex, vai para o agente). Ex.: use pnpm em vez de npm`):a(`Motivo (opcional, vai para o agente). Ex.: {0}`,[a(o?`decida você, com o que for mais seguro`:`use pnpm em vez de npm`)])),N(this.reason,`aria-label`,r.reasonRequired?a(`Motivo da recusa (obrigatório)`):a(`Motivo da recusa (opcional)`));for(let e of this.denyForm.querySelectorAll(`button, textarea, input`))e.disabled=l;this.syncDeny(),N(this.denyBtn,`aria-expanded`,String(this.phase===`deny`)),this.denyBtn.classList.toggle(`is-on`,this.phase===`deny`),this.pendingFocus===e.id&&(this.pendingFocus=null,requestAnimationFrame(()=>{this.el.scrollIntoView({block:`nearest`,behavior:`smooth`}),this.el.focus({preventScroll:!0})}))}reset(e,t){if(e===this.id&&t===this.agentId||(this.id=e,this.agentId=t,this.phase=`idle`,this.detail=null,this.reason.value=``,this.interrupt.value=!1,M(this.status,``),this.status.classList.remove(`is-error`),delete this.preview.dataset.id,this.askId=``,this.askRefs=[],this.askForm.replaceChildren(),!e))return;let n=++this.detailReq;this.ctx.store.permissionDetail(t,e).then(e=>{n===this.detailReq&&e&&(this.detail=e,this.ctx.invalidate())}).catch(()=>{})}syncDeny(){let e=this.opts.reasonRequired&&!this.reason.value.trim();this.denySubmit.disabled=this.isBusy()||e,A(this.denySubmit,e?a(`Escreva o motivo: o Codex recusa só com um motivo`):``)}toggleDeny(e=this.phase!==`deny`){this.phase!==`sending`&&this.phase!==`sent`&&(this.phase=e?`deny`:`idle`,this.ctx.invalidate(),e?requestAnimationFrame(()=>this.reason.focus()):this.denyBtn.focus())}async send(e){let t=this.id;if(!t||this.phase===`sending`||this.phase===`sent`)return;this.phase=`sending`,this.status.classList.remove(`is-error`),M(this.status,a(`Enviando a resposta…`)),this.ctx.invalidate();let n;try{n=await this.ctx.store.decidePermission(t,e)}catch{n=a(`Não foi possível falar com o Habblaud. Responda no terminal.`)}if(this.id===t){if(n)this.phase=`idle`,this.status.classList.add(`is-error`),M(this.status,n);else{this.phase=`sent`;let t=sw[e.behavior];M(this.status,`${t}.`),this.ctx.announce(`${t}: ${yt(this.ctx,this.agentId,a(`agente`))}.`)}this.ctx.invalidate()}}isLocal(){return this.ctx.store.mock||I().permissions}isBusy(){return this.phase===`sending`||this.phase===`sent`||!this.isLocal()}buildAsk(e){this.askId=e.id,this.askRefs=(e.questions??[]).map(e=>this.askQuestion(e)),this.askForm.replaceChildren(...this.askRefs.map(e=>e.el))}askQuestion(e){let t=(e,t)=>P(`span`,{class:`ui-perm-ask__opt-text`},P(`strong`,{text:e}),t?P(`span`,{class:`ui-ask__desc`,text:t}):null),n=[],r,i;e.multiSelect?(n=e.options.map(e=>({value:String(e.index),control:new Vv({label:e.label,className:`ui-perm-ask__opt ui-perm-ask__input`,content:t(e.label,e.description),onChange:()=>this.syncAnswer()})})),r=new Vv({label:a(`Outro`),className:`ui-perm-ask__opt ui-perm-ask__input`,content:t(a(`Outro`)),onChange:()=>this.syncAnswer()})):i=new Bv({label:e.header||e.question,value:``,options:[...e.options.map(e=>({value:String(e.index),label:e.label,className:`ui-perm-ask__opt`,content:t(e.label,e.description)})),{value:`other`,label:a(`Outro`),className:`ui-perm-ask__opt`,content:t(a(`Outro`))}],className:`ui-perm-ask__options`,onChange:()=>this.syncAnswer()});let o=P(`input`,{class:`ui-perm-ask__text`,type:`text`,attrs:{maxlength:l,placeholder:a(`Escreva a sua resposta`),autocomplete:`off`,"aria-label":a(`Outra resposta para: {0}`,[e.question])}});return o.addEventListener(`input`,()=>{o.value.trim()&&(e.multiSelect&&r?r.value=!0:i&&(i.value=`other`)),this.syncAnswer()}),o.addEventListener(`keydown`,e=>{e.key===`Enter`?(e.preventDefault(),this.sendAnswer()):e.key===`Escape`&&(e.preventDefault(),o.blur())}),{q:e,el:P(`fieldset`,{class:`ui-perm-ask__q`},P(`legend`,{class:`ui-perm-ask__legend`},e.header?P(`span`,{class:`ui-ask__tag`,text:e.header}):null,P(`span`,{class:`ui-ask__question`,text:e.question})),P(`p`,{class:`ui-ask__hint`,text:e.multiSelect?a(`Pode escolher mais de uma`):a(`Escolha uma`)}),e.multiSelect?P(`div`,{class:`ui-perm-ask__options`,role:`group`,attrs:{"aria-label":e.header||e.question}},...n.map(e=>e.control.el)):i.el,P(`div`,{class:`ui-perm-ask__other`},...r?[r.el]:[],o)),options:n,other:r,radio:i,text:o}}choices(){return new Map(this.askRefs.map(e=>{let t=e.radio?.value,n=e.q.multiSelect?e.options.filter(e=>e.control.value).map(e=>e.value):t&&t!==`other`?[t]:[],r=e.q.multiSelect?!!e.other?.value:t===`other`;return[e.q.index,nw(e.q,n,r,e.text.value)]}))}answers(){return iw(this.askRefs.map(e=>e.q),this.choices())}syncAnswer(){let e=!!this.answers();this.answerBtn.disabled=this.isBusy()||!e,A(this.answerBtn,a(e?`Mandar as respostas ao agente`:`Responda todas as perguntas (no “Outro”, escreva a resposta)`))}sendAnswer(){let e=this.answers();e&&!this.isBusy()&&this.send({behavior:`answer`,answers:e})}},lw=new WeakMap;function uw(e,t,n=`md`){let r=bv(e,n),i=P(`span`,{class:`ui-agent__name`}),a=yx(`sm`),o=Tx(),s=P(`span`,{class:`ui-duplicate-badge`,hidden:!0}),c=Cx(),l=kx(),u=P(`span`,{class:`ui-agent__task`,hidden:!0}),d=P(`span`,{class:`ui-agent__since`,hidden:!0}),f=P(`button`,{class:`ui-agent`,type:`button`},r,P(`span`,{class:`ui-agent__main`},P(`span`,{class:`ui-agent__top`},i,a,d,o,s),u,l),c);return f.dataset.id=e.id,f.addEventListener(`click`,()=>t(f.dataset.id)),lw.set(f,{avatar:r,name:i,chip:a,role:o,duplicate:s,dot:c,activity:l,task:u,since:d,size:n}),f}function dw(e,t,n,r,i,o=[],s){let c=lw.get(e);if(!c)return;e.dataset.id=t.id,Sv(c.avatar,t,c.size),_t(e,`--acc`,n?.color??`#8b98b3`);let l=xt(t,s);M(c.name,l),N(c.name,`data-tip`,l),bx(c.chip,n,t.account,t.provider),Ex(c.role,t),F(c.duplicate,!t.duplicateSession),M(c.duplicate,t.duplicateSession?a(`duplicada`):``),A(c.duplicate,t.duplicateSession?a(`Conversa aberta em {0} terminais`,[t.duplicateSession.count]):``);let u=t.title?.trim()??``;M(c.task,u),A(c.task,u),F(c.task,!u);let d=t.kind===`main`&&t.status===`idle`&&t.statusSince?i-t.statusSince:0,f=d>=6e4;M(c.since,f?a(`ocioso {0}`,[zt(d)]):``),A(c.since,f?a(`Ocioso há {0}`,[zt(d)]):``),F(c.since,!f),F(c.role,f);let p=lb(t,o,i),m=p?`shell`:t.status;wx(c.dot,m),p?Mx(c.activity,p,i):jx(c.activity,t.activity,Zy(t)),vt(e,`is-`,m),e.classList.toggle(`is-selected`,r),N(e,`aria-current`,r?`true`:null);let h=p?a(`{0}, há {1}`,[mb(p,i).label,zt(i-p.since)]):t.activity?.text;N(e,`aria-label`,`${l}, ${t.kind===`main`?a(`agente principal`):a(`subagente {0}`,[t.role])}, ${n?.name??t.account}${t.provider===`codex`?` (Codex)`:``}, ${Jy(m)}${h?`: ${h}`:``}`)}function fw(e){return`${e>=0?`+`:`−`}🪙${Math.abs(e)}`}function pw(e,t){return!e&&!t?a(`Sem partidas ainda`):`${Lt(e,a(`vitória`),a(`vitórias`))} · ${Lt(t,a(`derrota`),a(`derrotas`))}`}var mw=6,hw=class{ctx;el;extra;doing;coins;earned;record;traits;phrase;friends;rivals;friendsRow;rivalsRow;ledger;ledgerBox;keys={traits:``,bonds:``,ledger:``};constructor(e){this.ctx=e;let t=P(`h3`,{class:`ui-sec__title`,text:a(`Vida social`)});this.extra=P(`span`,{class:`ui-sec__extra ui-social__balance`}),this.doing=P(`p`,{class:`ui-social__doing`}),this.coins=P(`strong`,{class:`ui-social__coins`}),this.earned=P(`span`,{class:`ui-social__earned`}),this.record=P(`span`,{class:`ui-social__record`}),this.traits=P(`div`,{class:`ui-social__traits`}),this.phrase=P(`p`,{class:`ui-social__phrase`}),this.friends=P(`span`,{class:`ui-social__names`}),this.rivals=P(`span`,{class:`ui-social__names`}),this.friendsRow=P(`p`,{class:`ui-social__bond`},P(`span`,{class:`ui-social__bond-label`,text:a(`💛 Amizades`)}),this.friends),this.rivalsRow=P(`p`,{class:`ui-social__bond`},P(`span`,{class:`ui-social__bond-label`,text:a(`⚔️ Rivalidades`)}),this.rivals),this.ledger=P(`ol`,{class:`ui-social__ledger`}),this.ledgerBox=P(`details`,{class:`ui-social__extract`},P(`summary`,{text:a(`Extrato`)}),this.ledger);let n=P(`div`,{class:`ui-social__wallet`},P(`span`,{class:`ui-social__purse`,attrs:{"aria-hidden":`true`},text:`🪙`}),P(`div`,{class:`ui-social__wallet-body`},P(`div`,{class:`ui-social__wallet-line`},this.coins,this.record),this.earned));A(n,a(`Moedinhas fictícias: entra no escritório com um saldo, ganha 🪙10 por tarefa concluída e 🪙5 por pedido atendido, e aposta com os colegas. Ficam salvas neste navegador.`)),this.el=P(`section`,{class:`ui-sec ui-social`},P(`div`,{class:`ui-sec__head`},t,this.extra),this.doing,n,this.traits,this.phrase,this.friendsRow,this.rivalsRow,this.ledgerBox)}render(e,t){let n=this.ctx.world.social?.(e)??null;if(F(this.el,!n),!n)return;M(this.extra,`🪙 ${n.coins}`),M(this.doing,n.doing??``),F(this.doing,!n.doing),M(this.coins,a(`{0} moedinhas`,[n.coins])),M(this.record,pw(n.wins,n.losses)),M(this.earned,a(`{0} ganhos trabalhando`,[fw(n.earned)])),M(this.phrase,a(`Bordão: “{0}”`,[n.catchphrase]));let r=n.traits.map(e=>e.label).join(`|`);r!==this.keys.traits&&(this.keys.traits=r,this.traits.replaceChildren(...n.traits.map(e=>P(`span`,{class:`ui-trait`,title:e.desc,text:`${e.emoji} ${e.label}`}))));let i=n.bonds.map(e=>`${e.id}:${e.kind}:${e.name}:${e.record?.join(`-`)??``}`).join(`|`);if(i!==this.keys.bonds){this.keys.bonds=i;let e=e=>{let t=e.record?`${e.name} (${e.record[0]}×${e.record[1]})`:e.name;return P(`button`,{class:`ui-social__name`,type:`button`,text:t,title:e.record?a(`Retrospecto contra {0}: {1}`,[e.name,pw(e.record[0],e.record[1])]):a(`Ver {0}`,[e.name]),on:{click:()=>this.ctx.select({type:`agent`,id:e.id},{focus:!0})}})},t=n.bonds.filter(e=>e.kind===`amizade`),r=n.bonds.filter(e=>e.kind===`rivalidade`);this.friends.replaceChildren(...t.map(e)),this.rivals.replaceChildren(...r.map(e)),F(this.friendsRow,!t.length),F(this.rivalsRow,!r.length)}let o=n.ledger.slice(0,mw),s=o.map(e=>`${e.at}:${e.delta}:${e.text}`).join(`|`)+`@${Math.floor(t/3e4)}`;s!==this.keys.ledger&&(this.keys.ledger=s,this.ledger.replaceChildren(...o.map(e=>P(`li`,{class:`ui-social__entry ${e.delta>=0?`is-plus`:`is-minus`}`},P(`span`,{class:`ui-social__delta`,text:fw(e.delta)}),P(`span`,{class:`ui-social__what`,text:`${e.icon} ${e.text}`}),P(`time`,{class:`ui-social__when`,text:Nt(e.at,t)}))))),F(this.ledgerBox,!o.length)}};function gw(e){if(e===null)return`normal`;let t=Gt(e);return t===`crit`?`critical`:t===`warn`?`warning`:`normal`}function _w(e){let t=e.filter(e=>e!==null);return t.length?Math.max(...t):null}function vw(e){return e.map((e,t)=>({item:e,index:t})).sort((e,t)=>{let n=e.item.pct,r=t.item.pct;return n===null&&r===null?e.index-t.index:n===null?1:r===null?-1:r-n||e.index-t.index}).map(e=>e.item)}function yw(e,t,n){if(t===`noquota`)return a(`{0}: sem cota`,[e]);if(n===null||t===`empty`)return a(`{0}: sem dados de uso`,[e]);let r=Math.max(0,Math.min(100,100-n));return a(t===`stale`?`{0}: {1}% restante (números antigos)`:`{0}: {1}% restante`,[e,String(r)])}function bw(e){let t=Math.max(0,Math.min(e.panelWidth,e.viewportWidth-2*e.margin)),n=e.anchorRight-t;n<e.margin&&(n=e.anchorLeft);let r=e.viewportWidth-e.margin-t;return n=Math.max(e.margin,Math.min(n,r)),{left:n,width:t}}var xw={mode:`rest`},Sw={mode:`rest`},Cw={mode:`fanned`};function ww(e,t){switch(t.type){case`stack-enter`:return e.mode===`rest`?Cw:e;case`stack-leave`:case`blur`:case`escape`:case`tap-outside`:return e.mode===`rest`?e:Sw;case`card-enter`:case`focus`:return e.mode===`expanded`&&e.id===t.id?e:{mode:`expanded`,id:t.id};case`card-leave`:return e.mode===`expanded`&&e.id===t.id?Cw:e;case`tap-stack`:return e.mode===`rest`?Cw:e;case`tap-card`:return e.mode===`rest`||e.mode===`expanded`&&e.id===t.id?Cw:{mode:`expanded`,id:t.id}}}var Tw={cache:a(`cache do /usage do Claude Code`),statusline:a(`ao vivo (statusline do Claude Code)`),codex:a(`arquivos do Codex`)};function Ew(e){return e.source===`statusline`&&e.via===`mod`?a(`ao vivo (mod do Habblaud)`):Tw[e.source]??e.source}var Dw=[[`npm run mod:install`,a("Recomendado: instala o mod do Habblaud no Claude Code (2.1.287 ou mais novo), que passa o uso de 5 h e da semana ao vivo. Rode na pasta do Habblaud, no computador onde o Claude Code roda; nas sessões já abertas, `/reload-plugins`.")],[`npm run usage:install`,a(`No Claude Code anterior ao 2.1.287: liga um tap na linha de status, que passa os mesmos números ao vivo.`)],[`/usage`,a("Sem instalar nada: rode `/usage` no Claude Code desta conta para atualizar o cache (os números envelhecem até a próxima vez).")]];function Ow(e){return e.split("`").map((e,t)=>t%2?P(`code`,{class:`ui-usage-setup__inline`,text:e}):document.createTextNode(e))}var kw=0;function Aw(e,t,n){let r=P(`span`,{class:`ui-meter__bar`},P(`span`,{class:`ui-meter__fill`})),i=P(`span`,{class:`ui-meter__pct`}),a=P(`span`,{class:`ui-meter__reset-long`}),o=P(`span`,{class:`ui-meter__reset-short`}),s=P(`span`,{class:`ui-meter__reset`},a,o),c=P(`span`,{class:`ui-meter__label`},P(`span`,{class:`ui-meter__label-long`,text:e}),P(`span`,{class:`ui-meter__label-short`,text:t,attrs:{"aria-hidden":`true`}}));return{el:P(`div`,{class:`ui-meter`,role:`img`,attrs:{"aria-label":n}},c,r,i,s),bar:r,pct:i,reset:s,resetLong:a,resetShort:o}}function jw(e,t,n){if(!t||t.pct===null){vt(e.el,`is-`,`none`),e.el.classList.remove(`is-zero`),e.el.classList.toggle(`is-renewed`,!!t?.renewed),_t(e.bar,`--pct`,`0`),M(e.pct,`—`),M(e.resetLong,t?.renewed?a(`↻ renovada`):``),M(e.resetShort,``);let r=t?`${n}: ${t.summary}`:a(`{0}: sem dados`,[n]);N(e.el,`aria-label`,r),A(e.el,t?.renewed?a(`{0}: a janela já renovou depois da última leitura; o uso atual é desconhecido.`,[n]):r);return}let r=t.pct;e.el.classList.remove(`is-renewed`),vt(e.el,`is-`,Gt(r)),e.el.classList.toggle(`is-zero`,r===0),_t(e.bar,`--pct`,String(r)),M(e.pct,`${r}%`),M(e.resetLong,t.reset?`↻ ${t.reset}`:``),M(e.resetShort,t.resetShort?`↻${t.resetShort}`:``),N(e.el,`aria-label`,`${n}: ${t.summary}`),A(e.el,`${n}: ${t.summary}`)}function Mw(e,t){for(;e.children.length>t.length*2;)e.lastElementChild.remove();t.forEach(([t,n],r)=>{let i=e.children[r*2],a=e.children[r*2+1];(!i||!a)&&(i=P(`dt`),a=P(`dd`),e.append(i,a)),M(i,t),M(a,n)})}function Nw(){return P(`ol`,{class:`ui-usage-setup`},...Dw.map(([e,t])=>P(`li`,{},P(`code`,{class:`ui-usage-setup__cmd`,text:e}),P(`span`,{},...Ow(t)))))}function Pw(e){return!!e.usage&&!!(e.usage.fiveHour||e.usage.sevenDay)}function Fw(e){return e.usage?.noQuota?`noquota`:Pw(e)?e.usageStatus===`ok`?`ok`:`stale`:`empty`}function Iw(e){if(!e.usage)return!1;let t=Fw(e);return t===`stale`||Ub(e)&&t!==`empty`}function Lw(e){return e.email?e.email:Ub(e)?e.plan?a(`plano {0}`,[e.plan]):`Codex`:e.configDir}function Rw(e){return Fw(e)===`noquota`?[a(`sem cota`),a(`sem cota`)]:Ub(e)?[a(`sem dados ainda`),a(`sem dados`)]:[a(`sem dados de uso`),a(`sem dados`)]}function zw(e,t){if(!Ub(e))return``;let n=e.usage,r=Fw(e);if(r===`empty`)return a(`Não precisa instalar nada: os números chegam com a próxima sessão do Codex.`);let i=n?Nt(n.fetchedAt,t):``;return a(r===`noquota`?`Na última leitura ({0}), a conta estava sem cota nem créditos para usar (ex.: os créditos do workspace acabaram). Não é 0%: o Codex não informou as janelas. Os números voltam com a próxima sessão.`:`O Codex só grava o uso enquanto alguma sessão roda: estes números são da última leitura ({0}).`,[i])}function Bw(e,t){let n=e.usage;return!n||!Pw(e)||Fw(e)===`noquota`?null:_w([Kt(n.fiveHour,n.fetchedAt,t,18e6)?.pct??null,Kt(n.sevenDay,n.fetchedAt,t,6048e5)?.pct??null])}var Vw=310,Hw=8,Uw=class{ctx;el;list;refs=new WeakMap;state=xw;ids=[];roving=``;touching=!1;quietFocus=!1;constructor(e){this.ctx=e,this.el=P(`div`,{class:`ui-usage`,role:`group`,attrs:{"aria-label":a(`Uso por conta`)}}),this.list=new wt(this.el,{key:e=>e.id,create:()=>this.createCard(),update:(e,t)=>this.updateCard(e,t)}),this.el.addEventListener(`pointerenter`,e=>{e.pointerType!==`touch`&&this.dispatch({type:`stack-enter`})}),this.el.addEventListener(`pointerleave`,e=>{e.pointerType!==`touch`&&(this.el.querySelector(`:focus-visible`)||this.dispatch({type:`stack-leave`}))}),this.el.addEventListener(`pointerdown`,e=>{this.touching=e.pointerType===`touch`}),this.el.addEventListener(`click`,e=>this.onClick(e)),this.el.addEventListener(`focusin`,e=>this.onFocusIn(e)),this.el.addEventListener(`focusout`,e=>{let t=e.relatedTarget;t instanceof Node&&this.el.contains(t)||this.touching||this.dispatch({type:`blur`})}),this.el.addEventListener(`keydown`,e=>this.onKeyDown(e)),document.addEventListener(`pointerdown`,e=>{this.state.mode!==`rest`&&!this.el.contains(e.target)&&this.dispatch({type:`tap-outside`})}),typeof ResizeObserver==`function`&&new ResizeObserver(()=>this.placeOpen()).observe(e.root)}render(){let e=this.ctx.now(),t=this.ctx.store.snapshot?.accounts??[],n=vw(t.map(t=>({a:t,pct:Bw(t,e)}))),r=n.map(e=>e.a.id),i=r.join(`|`)!==this.ids.join(`|`);this.ids=r,this.list.sync(n.map(e=>e.a)),this.el.classList.toggle(`is-empty`,t.length===0),_t(this.el,`--count`,String(t.length)),n.forEach((e,t)=>{let n=this.list.get(e.a.id);n&&(_t(n,`--i`,String(t)),n.classList.toggle(`is-hot`,t===0&&gw(e.pct)!==`normal`))}),this.state.mode===`expanded`&&!r.includes(this.state.id)&&(this.state=xw),r.includes(this.roving)||(this.roving=r[0]??``),this.apply(i)}dispatch(e){let t=ww(this.state,e);t!==this.state&&(this.state=t,this.apply(!0))}apply(e){let t=this.state.mode===`expanded`?this.state.id:``;this.el.classList.toggle(`is-fanned`,this.state.mode!==`rest`);for(let e of this.ids){let n=this.list.get(e),r=n&&this.refs.get(n);if(!n||!r)continue;let i=e===t;n.classList.toggle(`is-open`,i),N(r.mini,`aria-expanded`,i?`true`:`false`),N(r.mini,`tabindex`,e===this.roving?`0`:`-1`),F(r.full,!i)}e&&this.placeOpen()}placeOpen(){if(this.state.mode!==`expanded`)return;let e=this.state.id,t=this.ids.indexOf(e),n=this.list.get(e),r=n&&this.refs.get(n);if(t<0||!r)return;let i=getComputedStyle(this.el),a=(e,t)=>Number.parseFloat(i.getPropertyValue(e))||t,o=a(`--slot-w`,38),s=this.el.getBoundingClientRect().right-t*a(`--fan`,38),c=s-o,l=bw({anchorLeft:c,anchorRight:s,panelWidth:Vw,viewportWidth:document.documentElement.clientWidth,margin:Hw});_t(r.full,`--panel-dx`,`${l.left-c}px`),_t(r.full,`--panel-w`,`${l.width}px`)}idOf(e){return e?.closest?.(`.ui-usage-card`)?.dataset.key??``}onClick(e){if(!this.touching||e.target.closest(`.ui-usage-card__full`))return;let t=this.idOf(e.target);this.dispatch(t?{type:`tap-card`,id:t}:{type:`tap-stack`})}onFocusIn(e){if(this.touching||this.quietFocus)return;let t=this.idOf(e.target);t&&(this.roving=t,this.dispatch({type:`focus`,id:t}),this.apply(!1))}focusMini(e){let t=this.list.get(e),n=t&&this.refs.get(t);if(n){this.quietFocus=!0;try{n.mini.focus()}finally{this.quietFocus=!1}}}onKeyDown(e){if(this.touching=!1,e.key===`Escape`){if(this.state.mode===`rest`)return;let t=this.idOf(e.target);this.dispatch({type:`escape`}),t&&e.target.closest(`.ui-usage-card__full`)&&this.focusMini(t),e.stopPropagation();return}if(!e.target.classList.contains(`ui-usage-card__mini`))return;let t=this.ids.indexOf(this.idOf(e.target));if(t<0)return;let n=e.key===`ArrowLeft`||e.key===`ArrowDown`?1:e.key===`ArrowRight`||e.key===`ArrowUp`?-1:0,r=-1;if(n?r=Math.max(0,Math.min(this.ids.length-1,t+n)):e.key===`Home`?r=0:e.key===`End`&&(r=this.ids.length-1),r<0)return;e.preventDefault();let i=this.ids[r];this.roving=i,this.apply(!1),this.focusMini(i),this.dispatch({type:`focus`,id:i})}createCard(){let e=`ui-usage-tip-${++kw}`,t=`ui-usage-full-${kw}`,n=yx(`lg`),r=yx(`md`),i=P(`span`,{class:`ui-usage-card__mini-fill`}),o=P(`div`,{class:`ui-usage-card__mini`,role:`button`,tabIndex:-1,attrs:{"aria-expanded":`false`,"aria-controls":t}},r,P(`span`,{class:`ui-usage-card__mini-bar`,attrs:{"aria-hidden":`true`}},i)),s=P(`span`,{class:`ui-usage-card__name`}),c=xx(`ui-prov--xs`),l=P(`span`,{class:`ui-usage-card__email`}),u=P(`span`,{class:`ui-usage-card__state-icon`,attrs:{"aria-hidden":`true`}});u.innerHTML=Q.clock;let d=P(`span`),f=P(`span`,{class:`ui-usage-card__state`},u,d),p=Aw(`5h`,`5h`,a(`Sessão de 5 horas`)),m=Aw(a(`Semana`),a(`Sem.`),a(`Limite semanal`)),h=P(`div`,{class:`ui-usage-card__meters`},p.el,m.el),g=P(`span`,{class:`ui-usage-card__msg-long`,text:a(`sem dados de uso`)}),_=P(`span`,{class:`ui-usage-card__msg-short`,text:a(`sem dados`),attrs:{"aria-hidden":`true`}}),v=P(`span`,{class:`ui-usage-card__how-long`,text:a(`Como ativar`)}),y=P(`span`,{class:`ui-usage-card__how-short`,text:a(`Ativar`),attrs:{"aria-hidden":`true`}}),b=P(`button`,{class:`ui-usage-card__how`,type:`button`,title:a(`Como mostrar o uso desta conta (abre a ajuda em “Contas e uso”)`),on:{click:()=>this.ctx.openHelp(b.dataset.help===`codex`?`codex`:`usage`)}},v,y),x=P(`div`,{class:`ui-usage-card__msg`},P(`span`,{class:`ui-usage-card__msg-text`},g,_),b),S=P(`div`,{class:`ui-usage-tip__title`}),C=P(`dl`,{class:`ui-kv`}),w=P(`p`,{class:`ui-usage-tip__note`}),ee=P(`div`,{class:`ui-usage-tip__setup`},P(`p`,{class:`ui-usage-tip__setup-title`,text:a(`Como ter o uso ao vivo`)}),Nw()),te=P(`div`,{class:`ui-usage-tip`,role:`tooltip`,attrs:{id:e}},S,C,w,ee),T=P(`div`,{class:`ui-usage-card__full`,role:`group`,tabIndex:-1,hidden:!0,attrs:{id:t,"aria-describedby":e}},n,P(`div`,{class:`ui-usage-card__body`},P(`div`,{class:`ui-usage-card__head`},s,c,l,f),h,x),te),E=P(`div`,{class:`ui-usage-card`},o,T);return E.addEventListener(`pointerenter`,e=>{e.pointerType!==`touch`&&this.dispatch({type:`card-enter`,id:E.dataset.key??``})}),E.addEventListener(`pointerleave`,e=>{e.pointerType!==`touch`&&this.dispatch({type:`card-leave`,id:E.dataset.key??``})}),this.refs.set(E,{mini:o,miniChip:r,miniFill:i,full:T,chip:n,name:s,prov:c,email:l,state:f,stateText:d,meters:h,five:p,week:m,msg:x,msgLong:g,msgShort:_,how:b,howLong:v,howShort:y,tip:te,tipTitle:S,tipRows:C,tipNote:w,tipSetup:ee}),E}updateCard(e,t){let n=this.refs.get(e),r=this.ctx.now(),i=Ub(t);bx(n.chip,t),bx(n.miniChip,t),_t(e,`--acc`,t.color),M(n.name,t.name),Sx(n.prov,Vb(t),t.name),M(n.email,Lw(t)),N(n.full,`aria-label`,a(`{0}{1}: uso do plano`,[t.name,i?` (Codex)`:``]));let o=t.usage,s=Fw(t);vt(e,`is-`,s);let c=Bw(t,r);vt(e,`sev-`,gw(c)),_t(n.miniFill,`--pct`,String(c??0)),N(n.mini,`aria-label`,yw(t.name,s,c));let l=o?Kt(o.fiveHour,o.fetchedAt,r,Ut):null,u=o?Kt(o.sevenDay,o.fetchedAt,r,Rt):null,d=Pw(t);F(n.meters,!d),o&&d&&(jw(n.five,l,a(`Sessão de 5 horas`)),jw(n.week,u,a(`Semana`))),n.meters.classList.toggle(`is-dim`,s!==`ok`);let f=Iw(t);if(F(n.state,!f),n.state.classList.toggle(`is-fresh`,f&&t.usageStatus===`ok`),f&&o){let e=Nt(o.fetchedAt,r);M(n.stateText,e),A(n.state,a(i?`Atualizado {0}: o Codex só grava o uso enquanto alguma sessão roda.`:`Números de {0}: podem não refletir o uso atual.`,[e]))}let[p,m]=Rw(t);M(n.msgLong,p),M(n.msgShort,m),F(n.msg,s!==`empty`&&s!==`noquota`),F(n.how,s===`noquota`),n.msg.classList.toggle(`is-noquota`,s===`noquota`),A(n.msg,s===`noquota`?zw(t,r):``),M(n.howLong,a(i?`Como funciona`:`Como ativar`)),M(n.howShort,a(i?`Saber`:`Ativar`)),n.how.dataset.help=i?`codex`:`usage`,F(n.how,Hb(t)),A(n.how,a(i?`Como o uso do Codex chega ao Habblaud (abre a ajuda em “Codex”)`:`Como mostrar o uso desta conta (abre a ajuda em “Contas e uso”)`)),this.updateTip(n,t,s,l,u,r)}updateTip(e,t,n,r,i,o){let s=Ub(t);M(e.tipTitle,`${t.name}${s&&!/codex/i.test(t.name)?` · Codex`:``}${t.plan?a(` · plano {0}`,[t.plan]):``}`);let c=[];s&&c.push([a(`Ferramenta`),`Codex`]),t.email&&c.push([`E-mail`,t.email]),t.organization&&c.push([a(`Organização`),t.organization]),t.plan&&c.push([a(`Plano`),t.plan]),c.push([a(`Pasta`),t.configDir]),c.push([a(`Sessões abertas`),String(t.sessions)]);let l=t.usage;if(l&&(l.fiveHour||l.sevenDay)){c.push([a(`Sessão de 5 h`),r?.summary??`—`]),c.push([a(`Semana`),i?.summary??`—`]);let e=s?null:Kt(l.sevenDayOpus,l.fetchedAt,o,Rt),t=s?null:Kt(l.sevenDaySonnet,l.fetchedAt,o,Rt);e&&c.push([a(`Opus (semana)`),e.summary]),t&&c.push([a(`Sonnet (semana)`),t.summary])}if(l&&n===`noquota`&&c.push([a(`Cota`),a(`sem cota nem créditos agora`)]),l&&(n!==`empty`||s)&&(c.push([a(`Origem`),Ew(l)]),c.push([a(`Atualizado`),Nt(l.fetchedAt,o)])),Mw(e.tipRows,c),s){let n=zw(t,o);M(e.tipNote,n),F(e.tipNote,!n),F(e.tipSetup,!0);return}let u=``;n===`empty`?u=l?a(`A última leitura ({0}, {1}) não trouxe números de 5 h nem da semana.`,[Ew(l),Nt(l.fetchedAt,o)]):a(`Ainda não há números de uso para esta conta.`):n===`stale`?u=a(`Números antigos: refletem a última leitura, não o uso de agora.`):l?.source===`cache`?u=a(`Cache do /usage: atualiza quando alguém roda /usage nesta conta.`):(r?.renewed||i?.renewed)&&(u=a(`Uma das janelas já reiniciou depois da última leitura.`)),M(e.tipNote,u),F(e.tipNote,!u);let d=l?.source===`statusline`&&n===`ok`;F(e.tipSetup,d)}};function Ww(e){return a(e?`Remover dos favoritos`:`Adicionar à sala favorita`)}function Gw(e,t){if(!e.favoriteRoomId)return;let n=t.find(t=>t.id===e.favoriteRoomId&&t.custom);return n?dt(n):void 0}function Kw(e,t){if(e.kind!==`main`)return{kind:`hidden`};if(e.favoriteRoomId)return{kind:`remove`,roomId:e.favoriteRoomId};let n=t.filter(e=>e.custom);return n.length===0?{kind:`create`,name:`Favoritos`}:n.length===1?{kind:`move`,roomId:n[0].id}:{kind:`menu`,rooms:n}}var qw=15;function Jw(e,...t){let n=P(`h3`,{class:`ui-sec__title`,text:e}),r=P(`span`,{class:`ui-sec__extra`});return{el:P(`section`,{class:`ui-sec`},P(`div`,{class:`ui-sec__head`},n,r),...t.filter(e=>!!e)),title:n,extra:r}}function Yw(e,t){let n=j(Q.copy,t,async()=>{let r=await St(e());n.classList.toggle(`is-done`,r),n.innerHTML=r?Q.check:Q.copy,A(n,a(r?`Copiado!`:`Não foi possível copiar`)),setTimeout(()=>{n.classList.remove(`is-done`),n.innerHTML=Q.copy,A(n,t)},1400)},`ui-icon-btn--sm`);return n}var Xw={completed:`✓`,in_progress:`◐`,pending:`○`},Zw={completed:a(`concluída`),in_progress:a(`em andamento`),pending:`pendente`};function Qw(){return P(`li`,{class:`ui-task`},P(`span`,{class:`ui-task__mark`,attrs:{"aria-hidden":`true`}}),P(`span`,{class:`ui-task__text`}),P(`span`,{class:`ui-task__owner`}))}function $w(e,t,n){let[r,i,a]=e.children;M(r,Xw[t.status]),M(i,t.status===`in_progress`&&t.activeForm?t.activeForm:t.title),M(a,n??``),F(a,!n),vt(e,`is-`,t.status),N(e,`aria-label`,`${t.title}: ${Zw[t.status]}`)}function eT(){return P(`li`,{class:`ui-tl`},P(`span`,{class:`ui-tl__icon`,attrs:{"aria-hidden":`true`}}),P(`span`,{class:`ui-tl__text`}),P(`time`,{class:`ui-tl__time`}))}function tT(e,t,n,r){let[i,a,o]=e.children;M(i,t.icon),M(a,r?`${r}: ${t.text}`:t.text),M(o,Nt(t.at,n)),N(o,`datetime`,new Date(t.at).toISOString()),A(e,`${Ft(t.at)} · ${t.text}${t.detail?`\n${t.detail}`:``}`),e.classList.toggle(`is-error`,!!t.error);let s=yb(t);e.classList.toggle(`is-shell-ok`,s===`ok`),e.classList.toggle(`is-shell-fail`,s===`fail`)}var nT=new WeakMap,rT=e=>e.kind===`monitor`?`monitor`:e.background?`bg`:`fg`;function iT(){let e=P(`span`,{class:`ui-shell__icon`,attrs:{"aria-hidden":`true`}}),t=P(`span`,{class:`ui-shell__label`}),n=P(`time`,{class:`ui-shell__time`}),r=P(`span`,{class:`ui-shell__badge`}),i=P(`span`,{class:`ui-shell__since`}),o=P(`pre`,{class:`ui-mono`}),s=P(`details`,{class:`ui-shell__cmd`},P(`summary`,{text:a(`Comando`)}),P(`div`,{class:`ui-shell__cmd-body`},o,Yw(()=>o.textContent??``,a(`Copiar comando`)))),c=P(`li`,{class:`ui-shell`},P(`div`,{class:`ui-shell__head`},e,t,n),P(`div`,{class:`ui-shell__meta`},r,i),s);return nT.set(c,{icon:e,label:t,time:n,badge:r,since:i,details:s,command:o}),c}function aT(e,t,n){let r=nT.get(e);M(r.icon,t.kind===`monitor`?`📡`:`💻`),M(r.label,t.label),A(r.label,t.label);let i=Math.max(0,n-t.startedAt);M(r.time,Ht(i)),N(r.time,`datetime`,new Date(t.startedAt).toISOString()),A(r.time,a(`Rodando há {0} (desde {1})`,[zt(i),Ft(t.startedAt)])),M(r.badge,pb(t)),vt(r.badge,`ui-shell__badge--`,rT(t)),M(r.since,a(`desde {0}`,[Ft(t.startedAt,!1)])),A(r.since,a(`Iniciado em {0} · id {1}`,[kt(t.startedAt),t.id])),F(r.details,!t.command),M(r.command,t.command??``),N(e,`aria-label`,a(`{0}, {1}, rodando há {2}`,[t.label,pb(t),zt(i)]))}var oT=class{ctx;terminal;pty;el;id=``;last=null;history=[];historyReq=0;historyGen=0;historyReplay=!1;historyAt=0;historyBound=!1;avatar;name;role;title;accChip;accName;accProv;accEmail;codexHint;roomBtn;roomName;projectLine;projectLabel;favoriteButton;favoriteRoomLine;favoriteRoomLabel;favoriteError;duplicateBadge;duplicateNotice;favoriteBusy=!1;gone;dot;statusText;statusSince;followBtn;termBtn;termLabel;termWhy;termWhyTimer=null;alert;alertText;alertQuestions;alertQuestionsKey=``;alertAnswerHint;perm;shellBox;shellText;shellMood;shellNext;shellsSec;shells;actIcon;actText;actTime;actDetails;actDetail;composer;msgSec;tasksSec;tasksBar;tasks;teamSec;team;teamEmpty;timeline;timelineSec;timelineMore;timelineLess;timelineShown=qw;stats;social;character;sessionValue;linesPlus;linesMinus;termRo;constructor(e,t,n){this.ctx=e,this.terminal=t,this.pty=n,this.avatar=xv(`lg`),this.name=P(`h2`,{class:`ui-hero__name`}),this.role=P(`span`,{class:`ui-role`}),this.title=P(`p`,{class:`ui-hero__title`}),this.accChip=yx(`md`),this.accName=P(`span`,{class:`ui-hero__acc-name`}),this.accProv=xx(`ui-prov--xs`),this.accEmail=P(`span`,{class:`ui-hero__acc-email`}),this.roomName=P(`span`),this.roomBtn=P(`button`,{class:`ui-room-link`,type:`button`,on:{click:()=>this.last&&e.select({type:`room`,id:this.last.roomId},{focus:!0})}},this.roomName),this.projectLabel=P(`span`),this.projectLine=P(`div`,{class:`ui-hero__where ui-hero__project`,hidden:!0},P(`span`,{class:`ui-muted`,text:a(`Projeto`)}),this.projectLabel),this.favoriteButton=P(`button`,{class:`ui-icon-btn ui-favorite__button`,type:`button`,hidden:!0,attrs:{"aria-pressed":`false`},on:{click:()=>void this.toggleFavorite()}});let r=P(`span`,{class:`ui-favorite-room__icon`});r.innerHTML=Q.starFilled,this.favoriteRoomLabel=P(`span`),this.favoriteRoomLine=P(`div`,{class:`ui-hero__where ui-favorite-room`,hidden:!0},r,this.favoriteRoomLabel),this.favoriteError=P(`span`,{class:`ui-favorite__error`,role:`alert`,hidden:!0}),this.duplicateBadge=P(`span`,{class:`ui-duplicate-badge`,hidden:!0}),this.duplicateNotice=P(`p`,{class:`ui-duplicate-notice`,role:`status`,hidden:!0}),this.character=new Kv(e);let i=P(`div`,{class:`ui-hero__text`},P(`div`,{class:`ui-hero__line`},this.name,this.character.button,this.favoriteButton,this.role,this.duplicateBadge,this.favoriteError),P(`div`,{class:`ui-hero__acc`},this.accChip,this.accName,this.accProv,this.accEmail),P(`div`,{class:`ui-hero__where`},P(`span`,{class:`ui-muted`,text:a(`Sala`)}),this.roomBtn),this.projectLine,this.favoriteRoomLine);this.gone=P(`p`,{class:`ui-gone`,text:a(`Este agente já saiu do escritório.`),hidden:!0}),this.dot=Cx(),this.statusText=P(`span`,{class:`ui-status__text`}),this.statusSince=P(`span`,{class:`ui-status__since`}),this.followBtn=P(`button`,{class:`ui-btn`,type:`button`,attrs:{"aria-pressed":`false`},title:a(`Câmera acompanha o agente (F)`),on:{click:()=>this.toggleFollow()}}),this.followBtn.innerHTML=Q.follow,this.followBtn.append(P(`span`,{text:a(`Seguir`)}));let o=P(`button`,{class:`ui-btn`,type:`button`,title:a(`Levar a câmera até o agente`),on:{click:()=>e.focusSelection()}});o.innerHTML=Q.center,o.append(P(`span`,{text:a(`Centralizar`)}));let s=P(`div`,{class:`ui-status`},P(`span`,{class:`ui-status__label`},this.dot,this.statusText,this.statusSince),P(`span`,{class:`ui-status__actions`},this.followBtn,o));this.termLabel=P(`span`,{class:`ui-term-cta__label`,text:a(`Abrir terminal`)});let c=P(`span`,{class:`ui-term-cta__icon`,attrs:{"aria-hidden":`true`}});c.innerHTML=Q.terminal,this.termBtn=P(`button`,{class:`ui-btn ui-term-cta`,type:`button`,attrs:{"aria-pressed":`false`},on:{click:()=>this.toggleTerminal()}},c,this.termLabel,this.termRo=P(`span`,{class:`ui-term-cta__ro`,text:a(`ao vivo`)}),P(`kbd`,{class:`ui-kbd`,text:`T`,attrs:{"aria-hidden":`true`}})),this.termWhy=P(`p`,{class:`ui-term-cta__why`,hidden:!0,attrs:{role:`status`}}),this.alertText=P(`p`,{class:`ui-alert__text`}),this.alertQuestions=P(`div`,{class:`ui-ask`,hidden:!0}),this.alertAnswerHint=P(`p`,{class:`ui-ask__answer-hint`,hidden:!0,text:a(`Com o plugin busybits-permissions (npm run mod:install), dá para responder as perguntas por aqui.`)});let l=P(`span`,{class:`ui-alert__icon`,attrs:{"aria-hidden":`true`}});l.innerHTML=Q.hand,this.alert=P(`div`,{class:`ui-alert`,role:`alert`,hidden:!0},l,P(`div`,{},P(`strong`,{class:`ui-alert__title`,text:a(`Precisa de você`)}),this.alertText,this.alertQuestions,this.alertAnswerHint)),this.shellText=P(`p`,{class:`ui-alert__text`}),this.shellMood=P(`span`,{class:`ui-shell-mood__text`}),this.shellNext=P(`span`,{class:`ui-shell-mood__next`});let u=P(`span`,{class:`ui-alert__icon ui-hourglass`,attrs:{"aria-hidden":`true`}});u.innerHTML=Q.hourglass,this.shellBox=P(`div`,{class:`ui-alert ui-alert--shell`,hidden:!0},u,P(`div`,{},P(`strong`,{class:`ui-alert__title`,text:a(`Esperando o shell`)}),this.shellText,P(`p`,{class:`ui-shell-mood`},this.shellMood,this.shellNext)));let d=P(`ul`,{class:`ui-shells`});this.shellsSec=Jw(a(`Shells rodando`),d),this.shells=new wt(d,{key:e=>e.id,create:iT,update:(t,n)=>aT(t,n,e.now())}),this.actIcon=P(`span`,{class:`ui-now__icon`,attrs:{"aria-hidden":`true`}}),this.actText=P(`span`,{class:`ui-now__text`}),this.actTime=P(`span`,{class:`ui-now__time`}),this.actDetail=P(`pre`,{class:`ui-mono`}),this.actDetails=P(`details`,{class:`ui-now__details`},P(`summary`,{text:a(`Detalhes`)}),this.actDetail);let f=Jw(a(`Agora`),P(`div`,{class:`ui-now`},this.actIcon,P(`div`,{class:`ui-now__body`},this.actText,this.actTime)),this.actDetails);this.composer=new Gy(e,`drawer`),this.msgSec=Jw(a(`Mandar mensagem`),this.composer.el),this.msgSec.el.classList.add(`ui-sec--msg`),this.social=new hw(e),this.perm=new cw(e),this.tasksBar=Dx(a(`Progresso das tarefas`));let p=P(`ul`,{class:`ui-tasks`});this.tasksSec=Jw(a(`Tarefas`),this.tasksBar,p),this.tasks=new wt(p,{key:e=>e.id,create:Qw,update:(e,t)=>$w(e,t)});let m=P(`div`,{class:`ui-team`});this.teamEmpty=P(`p`,{class:`ui-muted ui-small`,text:a(`Nenhum subagente no momento.`)}),this.teamSec=Jw(a(`Subagentes`),m,this.teamEmpty),this.team=new wt(m,{key:e=>e.id,create:t=>uw(t,t=>e.select({type:`agent`,id:t},{focus:!0}),`sm`),update:(t,n)=>dw(t,n,e.account(n.account),!1,e.now(),e.store.snapshot?.agents,e.store.snapshot?.machines)});let h=P(`ol`,{class:`ui-timeline`});this.timelineMore=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,on:{click:()=>this.showTimeline(this.timelineShown+qw)}}),this.timelineLess=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Mostrar menos`),on:{click:()=>this.showTimeline(qw)}}),this.timelineSec=Jw(a(`Linha do tempo`),h,P(`div`,{class:`ui-timeline__more`},this.timelineMore,this.timelineLess)),this.timeline=new wt(h,{key:e=>e.id,create:eT,update:(t,n)=>tT(t,n,e.now())}),this.sessionValue=P(`span`,{class:`ui-mono-inline`}),this.linesPlus=P(`span`,{class:`ui-plus`}),this.linesMinus=P(`span`,{class:`ui-minus`}),this.stats=new sT([[`tools`,a(`Chamadas de ferramenta`)],[`tokensIn`,a(`Tokens de entrada`)],[`tokensOut`,a(`Tokens de saída`)],[`cost`,a(`Custo estimado`)],[`lines`,a(`Linhas`),P(`span`,{class:`ui-lines`},this.linesPlus,this.linesMinus)],[`subs`,a(`Subagentes disparados`)],[`model`,a(`Modelo`)],[`branch`,`Branch`],[`perm`,a(`Permissões`)],[`session`,a(`Sessão`),P(`span`,{class:`ui-copy-row`},this.sessionValue,Yw(()=>this.last?.sessionId??``,a(`Copiar id da sessão`)))],[`start`,a(`Início`)],[`duration`,a(`Duração`)],[`bg`,a(`Execução`)]]);let g=Jw(a(`Estatísticas`),this.stats.el);this.codexHint=P(`p`,{class:`ui-codex-hint`,hidden:!0},...Ow(Qb)),this.el=P(`div`,{class:`ui-drawer__view ui-agent-view`},P(`div`,{class:`ui-hero`},this.avatar,i),this.character.el,this.title,this.duplicateNotice,this.gone,s,this.termBtn,this.termWhy,this.alert,this.perm.el,this.shellBox,this.shellsSec.el,f.el,this.msgSec.el,this.social.el,this.tasksSec.el,this.teamSec.el,this.timelineSec.el,g.el,this.codexHint)}get agentId(){return this.id}open(e){this.id!==e&&(this.character.open(e),this.id=e,this.last=null,M(this.favoriteError,``),F(this.favoriteError,!0),this.history=[],this.timelineShown=qw,this.timeline.clear(),this.tasks.clear(),this.team.clear(),this.shells.clear(),this.actDetails.open=!1,this.loadHistory())}loadHistory(){let e=this.id;if(!e)return;let t=++this.historyReq,n=this.historyGen;this.ctx.store.agentHistory(e).then(e=>{t===this.historyReq&&n===this.historyGen&&(this.history=kb(e,this.history,200,this.ctx.store.replaying?this.ctx.store.snapshot?.serverTime:void 0),this.ctx.invalidate())}).catch(()=>{})}historyUntil(){let e=this.ctx.store.replaying,t=this.ctx.store.snapshot?.serverTime??0;if(this.historyBound){let n=e!==this.historyReplay,r=e&&t<this.historyAt;(n||r)&&(this.historyGen++,n&&(this.history=[],e||this.loadHistory()))}return this.historyBound=!0,this.historyReplay=e,this.historyAt=t,e?t:void 0}toggleTerminal(){if(this.id){if(this.termBtn.getAttribute(`aria-disabled`)===`true`){let e=this.termBtn.getAttribute(`data-tip`)??this.termBtn.title??``;M(this.termWhy,e),F(this.termWhy,!1),this.ctx.announce(e),this.termWhyTimer&&clearTimeout(this.termWhyTimer),this.termWhyTimer=setTimeout(()=>F(this.termWhy,!0),8e3);return}F(this.termWhy,!0),this.ctx.terminals?this.ctx.terminals.toggle(this.id,this.termBtn):this.terminal.toggle(this.id,this.termBtn)}}showTimeline(e){this.timelineShown=Math.max(qw,e),this.ctx.invalidate()}updateFavorite(e,t){let n=t&&e.kind===`main`&&!this.ctx.store.mock&&!this.ctx.store.replaying&&I().messages;if(F(this.favoriteButton,!n),F(this.favoriteError,!n||!this.favoriteError.textContent),!n)return;let r=Kw(e,this.ctx.store.snapshot?.rooms??[]).kind===`remove`,i=Ww(r);this.favoriteButton.innerHTML=r?Q.starFilled:Q.starOutline,N(this.favoriteButton,`data-tip`,i),N(this.favoriteButton,`aria-label`,i),N(this.favoriteButton,`aria-pressed`,r?`true`:`false`),this.favoriteButton.disabled=this.favoriteBusy}async toggleFavorite(){let e=this.last;if(!e||!I().messages||this.favoriteBusy)return;let t=Kw(e,this.ctx.store.snapshot?.rooms??[]);if(t.kind!==`hidden`){if(t.kind===`menu`){let t=this.favoriteButton.getBoundingClientRect();this.ctx.favoriteRoomsMenu?.(e.id,{x:t.left,y:t.bottom+4},t=>void this.changeFavorite(e.id,t));return}this.favoriteBusy=!0,this.favoriteButton.disabled=!0,M(this.favoriteError,``),F(this.favoriteError,!0);try{if(t.kind===`create`){let t=await this.favoriteFetch(`/api/rooms/custom`,`POST`,{name:a(`Favoritos`)});if(typeof t.id!=`string`)throw Error(a(`erro ao criar a sala`));await this.favoriteFetch(`/api/agents/${encodeURIComponent(e.id)}/favorite`,`POST`,{roomId:t.id})}else await this.favoriteFetch(`/api/agents/${encodeURIComponent(e.id)}/favorite`,t.kind===`remove`?`DELETE`:`POST`,t.kind===`remove`?void 0:{roomId:t.roomId});this.ctx.invalidate()}catch(e){M(this.favoriteError,e.message),F(this.favoriteError,!1)}finally{this.favoriteBusy=!1,this.ctx.invalidate()}}}async changeFavorite(e,t){let n=this.ctx.agent(e);if(n&&n.kind===`main`&&I().messages&&!this.favoriteBusy){this.favoriteBusy=!0,this.favoriteButton.disabled=!0,M(this.favoriteError,``),F(this.favoriteError,!0);try{await this.favoriteFetch(`/api/agents/${encodeURIComponent(n.id)}/favorite`,`POST`,{roomId:t}),this.ctx.invalidate()}catch(e){M(this.favoriteError,e.message),F(this.favoriteError,!1)}finally{this.favoriteBusy=!1,this.ctx.invalidate()}}}async favoriteFetch(e,t,n){let r;try{r=await fetch(e,{method:t,...t===`DELETE`?{headers:{"Content-Type":`application/json`}}:{},...n?{headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}:{}})}catch{throw Error(a(`o Habblaud não respondeu`))}let i=await r.json().catch(()=>({}));if(!r.ok)throw Error(i.error??a(`erro {0}`,[r.status]));return i}toggleFollow(){let e=!this.ctx.world.getOptions().followSelected;this.ctx.world.setOptions({followSelected:e}),this.id&&this.ctx.focusSelection(),this.ctx.invalidate()}render(){let e=this.ctx.agent(this.id);e&&(this.last=e);let t=this.last;if(!t)return;let n=this.ctx.now(),r=this.ctx.account(t.account),i=this.ctx.store.room(t.roomId),o=Vb(t),s=o===`codex`;Sv(this.avatar,t,`lg`),_t(this.avatar,`--acc`,r?.color??`#8b98b3`);let c=this.ctx.store.snapshot?.machines;M(this.name,xt(t,c)),this.character.render(t,!!e),M(this.role,Qy(t)),vt(this.role,`ui-role--`,t.kind),M(this.title,t.title??``),F(this.title,!t.title),A(this.title,t.title??``),F(this.duplicateBadge,!t.duplicateSession),M(this.duplicateBadge,t.duplicateSession?a(`duplicada`):``),A(this.duplicateBadge,t.duplicateSession?a(`Conversa aberta em {0} terminais`,[t.duplicateSession.count]):``),F(this.duplicateNotice,!t.duplicateSession),M(this.duplicateNotice,t.duplicateSession?t.duplicateSession.newest?a(`Esta é a conversa mais nova; feche o outro terminal.`):a(`Esta é a conversa mais antiga; feche este terminal e mantenha o mais novo aberto.`):``),bx(this.accChip,r,t.account,t.provider),M(this.accName,r?.name??t.account),Sx(this.accProv,o,r?.name??``);let l=r?.email??(s&&r?.plan?a(`plano {0}`,[r.plan]):``);M(this.accEmail,l),F(this.accEmail,!l),M(this.roomName,i?Dt(i,c).text:t.roomId),A(this.roomBtn,i?a(`{0}
17
- Clique para ver a sala`,[i.path]):``);let u=t.project;M(this.projectLabel,u??``),N(this.projectLabel,`data-tip`,u?a(`Projeto: {0}`,[u]):``),F(this.projectLine,!u);let d=Gw(t,this.ctx.store.snapshot?.rooms??[]);M(this.favoriteRoomLabel,d??``),F(this.favoriteRoomLine,!d),this.updateFavorite(t,!!e),F(this.gone,!!e),this.el.classList.toggle(`is-gone`,!e);let f=e?lb(t,this.ctx.store.snapshot?.agents??[],n):null,p=f?`shell`:t.status;wx(this.dot,p),M(this.statusText,Xy(t,p));let m=f?.foreground?f.since:t.statusSince;M(this.statusSince,Nt(m,n)),A(this.statusSince,a(`Desde {0}`,[Ft(m)]));let h=this.ctx.world.getOptions().followSelected;N(this.followBtn,`aria-pressed`,String(h)),this.followBtn.classList.toggle(`is-on`,h),this.renderTerminalButton(!!e);let g=t.status===`waiting`&&!!e;if(this.perm.render(e),F(this.alert,!g||this.perm.visible),g){let e=r?.name??t.account,n=s?a(`ao Codex{0}`,[/codex/i.test(e)?``:` (${e})`]):a(`ao terminal da {0}`,[e]);M(this.alertText,a(`Vá {0} em {1} para responder{2}`,[n,i?.name??a(`seu projeto`),t.waitingFor?`: ${t.waitingFor}`:`.`]))}let _=g&&!s&&t.activity?.kind===`ask`?t.activity:void 0;this.renderQuestions(_);let v=!s&&!!_?.questions?.length&&!this.perm.visible&&!this.ctx.store.mock&&!!this.ctx.store.snapshot?.meta.terminal&&I().permissions;if(F(this.alertAnswerHint,!v),F(this.shellBox,!f),f){M(this.shellText,hb(f));let e=vb(n-f.since);M(this.shellMood,`${e.emoji} ${e.text}`),M(this.shellNext,e.nextIn===null?``:a(`Próxima fase em {0}`,[zt(Math.max(1e3,e.nextIn))])),F(this.shellNext,e.nextIn===null),A(this.shellNext,a(`Quanto falta para o personagem mudar o que faz enquanto espera (veja a Ajuda)`))}let y=e?ub(t,n):[],b=y.length||!f?y:f.jobs;F(this.shellsSec.el,b.length===0),M(this.shellsSec.extra,b.length>1?String(b.length):``),this.shells.sync(b);let x=t.activity,S=t.status===`waiting-background`&&!!e;M(this.actIcon,S?`○`:x?.icon??`·`),M(this.actText,S?Zy(t):x?.text??Zy(t));let C=!!x?.durationMs&&x.kind!==`done`&&!/\d\s?(?:ms|s|min|h)\b/.test(x.text);M(this.actTime,S?Nt(t.statusSince,n):x?`${Nt(x.at,n)}${C?` · levou ${zt(x.durationMs)}`:``}`:``),this.actText.classList.toggle(`is-error`,!S&&!!x?.error);let w=S?``:x?.detail??``;F(this.actDetails,!w),M(this.actDetail,w),F(this.msgSec.el,this.composer.render(e,this.id)===`off`),e?this.social.render(t.id,n):F(this.social.el,!0);let ee=bb(t.tasks);if(F(this.tasksSec.el,t.tasks.length===0),Ox(this.tasksBar,ee.completed,ee.total,ee.inProgress),M(this.tasksSec.extra,`${ee.completed}/${ee.total}`),this.tasks.sync(t.tasks),t.kind===`main`){let e=Db((this.ctx.store.snapshot?.agents??[]).filter(e=>e.parentId===t.id));M(this.teamSec.title,a(`Subagentes`)),M(this.teamSec.extra,e.length?String(e.length):``),M(this.teamEmpty,t.stats.subagents?a(`Nenhum ativo agora ({0} nesta sessão).`,[Lt(t.stats.subagents,a(`disparado`),a(`disparados`))]):a(`Nenhum subagente disparado ainda.`)),F(this.teamEmpty,e.length>0),this.team.sync(e)}else{let e=t.parentId?this.ctx.agent(t.parentId):void 0;M(this.teamSec.title,a(`Responsável`)),M(this.teamSec.extra,``),M(this.teamEmpty,a(`O agente principal já não está no escritório.`)),F(this.teamEmpty,!!e),this.team.sync(e?[e]:[])}let te=this.historyUntil();this.history=kb(this.history,t.recent,200,te);let T=this.history.slice(-this.timelineShown).reverse(),E=Math.max(0,this.history.length-this.timelineShown);F(this.timelineMore,E===0),M(this.timelineMore,a(`Mostrar mais {0}`,[Math.min(qw,E)])),F(this.timelineLess,this.timelineShown<=qw||this.history.length<=qw),this.timeline.sync(T),M(this.timelineSec.extra,this.history.length?String(this.history.length):``),this.renderStats(t,n),F(this.codexHint,!s||t.kind!==`main`||!e||this.ctx.store.replaying)}renderQuestions(e){let t=e?.questions??[];F(this.alertQuestions,t.length===0);let n=t.length?`${e.id}|${t.length}`:``;n!==this.alertQuestionsKey&&(this.alertQuestionsKey=n,this.alertQuestions.replaceChildren(...t.map(e=>P(`div`,{class:`ui-ask__q`},e.header?P(`span`,{class:`ui-ask__tag`,text:e.header}):null,P(`p`,{class:`ui-ask__question`,text:e.question}),e.multiSelect?P(`p`,{class:`ui-ask__hint`,text:a(`Pode escolher mais de uma`)}):null,P(`ol`,{class:`ui-ask__opts`},...e.options.map(e=>P(`li`,{},P(`strong`,{text:e.label}),e.description?P(`span`,{class:`ui-ask__desc`,text:e.description}):null)))))))}renderTerminalButton(e,t=Vb(this.last)){let n=this.ctx.terminals,r=(n?n.available:!!this.ctx.store.snapshot?.meta.terminal)&&I().terminal,i=(n?n.openAgentId:this.terminal.agentId)===this.id,o=!!this.ctx.store.snapshot?.meta.terminal,s=this.id?n?.interactive(this.id)?`interativo`:!o&&this.pty.enabled&&nx(this.last)?`em outro terminal`:`ao vivo`:``;M(this.termRo,s===`interativo`?a(`interativo`):s===`ao vivo`?a(`ao vivo`):s?a(`em outro terminal`):``);let c=i||r&&e;c&&F(this.termWhy,!0),N(this.termBtn,`aria-disabled`,c?null:`true`),this.termBtn.classList.toggle(`is-disabled`,!c),N(this.termBtn,`aria-pressed`,String(i)),this.termBtn.classList.toggle(`is-on`,i),M(this.termLabel,a(i?`Fechar terminal`:`Abrir terminal`)),A(this.termBtn,i?a(`Fechar o terminal (T)`):r?e?s===`ao vivo`?a(`Ver a conversa desta sessão como no {0}, ao vivo{1} (T)`,[t===`codex`?`Codex`:t===`agent-hub`?`Agent Hub`:a(`terminal do Claude Code`),this.pty.enabled&&nx(this.last)?a(`; "Assumir daqui" continua nela aqui`):``]):a(s===`interativo`?`Abrir o terminal desta sessão, que roda aqui no Habblaud (T)`:`Abrir o terminal: a sessão roda em outro terminal; dá para assumir daqui (T)`):a(`O agente já saiu do escritório.`):this.ctx.store.replaying?a(`Sem terminal no timelapse: a conversa é a de agora, não a do momento reproduzido.`):this.ctx.store.snapshot?.meta.terminal&&I().remote?a(`O terminal não está liberado no acesso remoto (HABBLAUD_REMOTE_ALLOW).`):US)}renderStats(e,t){let n=e.stats,r=this.stats;r.set(`tools`,At(n.toolCalls)),r.set(`tokensIn`,It(n.tokensIn)),r.set(`tokensOut`,It(n.tokensOut)),r.set(`cost`,n.costUSD===void 0?null:jt(n.costUSD));let i=Vb(e)===`codex`,o=n.linesAdded!==void 0||n.linesRemoved!==void 0;r.show(`lines`,o),M(this.linesPlus,`+${At(n.linesAdded??0)}`),M(this.linesMinus,`−${At(n.linesRemoved??0)}`),r.set(`subs`,e.kind===`main`?At(n.subagents):null),r.set(`model`,Pt(e.model)),r.set(`branch`,e.gitBranch??null),r.label(`perm`,a(i?`Aprovações`:`Permissões`)),r.set(`perm`,e.kind===`main`?i?e.permissionMode?ex(e.permissionMode):null:Bt(e.permissionMode):null),M(this.sessionValue,e.sessionId),A(this.sessionValue,e.sessionId),r.set(`start`,kt(e.startedAt)),r.set(`duration`,zt(t-e.startedAt)),r.set(`bg`,e.background?a(`Em segundo plano`):null)}},sT=class{el;rows=new Map;constructor(e){this.el=P(`dl`,{class:`ui-kv ui-stats`});for(let[t,n,r]of e){let e=P(`dt`,{text:n}),i=P(`dd`);r&&i.append(r),this.rows.set(t,{dt:e,dd:i}),this.el.append(e,i)}}label(e,t){M(this.rows.get(e).dt,t)}set(e,t){let n=this.rows.get(e);this.show(e,t!==null),t!==null&&M(n.dd,t)}show(e,t){let n=this.rows.get(e);F(n.dt,!t),F(n.dd,!t)}},cT=class{ctx;pty;el;id=``;last=null;swatch;name;renameBtn;path;pathRow;deleteBtn;deleteConfirming=!1;gone;accs;agents;agentsSec;agentsEmpty;favoriteSummary;tasksSec;tasksBar;tasks;feed;feedSec;newBtn;newMsg;constructor(e,t){this.ctx=e,this.pty=t,this.newBtn=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Nova sessão`),title:a(`Abre um Claude Code novo nesta pasta, num terminal interativo`),on:{click:()=>this.newSession()}}),this.newMsg=P(`p`,{class:`ui-actions__msg is-error`,role:`status`,hidden:!0}),this.swatch=P(`span`,{class:`ui-room-hero__swatch`,attrs:{"aria-hidden":`true`}}),this.name=P(`h2`,{class:`ui-hero__name`}),this.renameBtn=P(`button`,{class:`ui-btn ui-btn--sm ui-room-hero__rename`,type:`button`,text:a(`Renomear sala`),on:{click:()=>{let t=this.name.getBoundingClientRect();this.last?.custom?e.manageCustomRooms?.(this.id,{x:t.left,y:t.bottom+6}):e.renameRoom?.(this.id,{x:t.left,y:t.bottom+6})}}}),this.deleteBtn=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Excluir`),on:{click:()=>void this.removeCustomRoom()}}),this.path=P(`span`,{class:`ui-room-hero__path`}),this.pathRow=P(`span`,{class:`ui-copy-row`},this.path,Yw(()=>this.last?.path??``,a(`Copiar caminho`)));let n=P(`button`,{class:`ui-btn`,type:`button`,title:a(`Levar a câmera até a sala`),on:{click:()=>e.focusSelection()}});n.innerHTML=Q.center,n.append(P(`span`,{text:a(`Centralizar`)})),this.gone=P(`p`,{class:`ui-gone`,text:a(`Esta sala foi fechada: todos os agentes saíram.`),hidden:!0});let r=P(`div`,{class:`ui-acc-list`});this.accs=new wt(r,{animate:!1,key:e=>e,create:()=>P(`span`,{class:`ui-acc-item`},yx(`sm`),P(`span`)),update:(t,n)=>{let r=e.account(n);bx(t.firstElementChild,r,n),M(t.lastElementChild,Yb(r,n,Kb(r,n)).replace(/ \((.+)\)$/,` · $1`))}});let i=P(`div`,{class:`ui-team`});this.agentsEmpty=P(`p`,{class:`ui-muted ui-small`,text:a(`Ninguém na sala agora.`)}),this.favoriteSummary=P(`p`,{class:`ui-muted ui-small`,hidden:!0}),this.agentsSec=Jw(a(`Agentes`),i,this.agentsEmpty,this.favoriteSummary),this.agents=new wt(i,{key:e=>e.id,create:t=>{let n=uw(t,t=>e.select({type:`agent`,id:t},{focus:!0}),`sm`);return n.querySelector(`.ui-agent__main`)?.append(P(`span`,{class:`ui-agent__room-label`})),n},update:(t,n)=>{let r=e.store.snapshot;dw(t,n,e.account(n.account),!1,e.now(),r?.agents,r?.machines);let i=t.querySelector(`.ui-agent__room-label`);if(i){let e=r?.rooms.find(e=>e.id===n.roomId),t=n.project??(e?Dt(e,r?.machines).text:void 0),o=!!t&&(!!n.project||!!this.last?.custom),s=t?a(`Projeto: {0}`,[t]):``;M(i,s),A(i,n.project??e?.path??n.roomId),N(i,`data-tip`,s),F(i,!o)}}}),this.tasksBar=Dx(a(`Progresso das tarefas da sala`));let o=P(`ul`,{class:`ui-tasks`});this.tasksSec=Jw(a(`Tarefas`),this.tasksBar,o),this.tasks=new wt(o,{key:e=>e.key,create:Qw,update:(e,t)=>$w(e,t.task,t.owner)});let s=P(`ol`,{class:`ui-timeline`});this.feedSec=Jw(a(`Atividade recente`),s),this.feed=new wt(s,{key:e=>e.id,create:eT,update:(t,n)=>tT(t,n.activity,e.now(),n.agentName)}),this.el=P(`div`,{class:`ui-drawer__view ui-room-view`},P(`div`,{class:`ui-room-hero`},this.swatch,P(`div`,{class:`ui-hero__text`},P(`div`,{class:`ui-room-hero__title`},this.name,this.renameBtn,this.deleteBtn),this.pathRow)),this.gone,P(`div`,{class:`ui-status`},r,P(`span`,{class:`ui-status__actions`},this.newBtn,n)),this.newMsg,this.agentsSec.el,this.tasksSec.el,this.feedSec.el)}get roomId(){return this.id}newSession(){let e=this.last;if(!e)return;let t=(this.ctx.store.snapshot?.agents??[]).find(t=>t.roomId===e.id&&nx(t))?.account;F(this.newMsg,!0),this.pty.newSession(e.path,t).catch(e=>{M(this.newMsg,a(`Não deu: {0}`,[e.message])),F(this.newMsg,!1)})}open(e){this.id!==e&&(this.id=e,this.last=null,this.resetDeleteConfirmation(),this.agents.clear(),this.tasks.clear(),this.feed.clear())}render(){let e=this.ctx.store.room(this.id);e&&(this.last=e);let t=this.last;if(!t)return;let n=Dt(t,this.ctx.store.snapshot?.machines);M(this.name,n.tag?`${n.text} (${n.tag})`:n.text),M(this.path,Ot(t.path)),A(this.path,t.path);try{_t(this.swatch,`--room`,fs(t.seed).accent)}catch{}F(this.gone,!!e);let r=rb(t,this.pty.enabled,Y_(this.ctx,t.id));F(this.renameBtn,!e||!r.rename||t.custom===!0&&!nv(this.ctx)),F(this.deleteBtn,!e||!r.delete||!nv(this.ctx)),F(this.pathRow,!r.path),F(this.newBtn,!r.newSession);let i=this.ctx.store.snapshot,o=i?.rooms??[],s=i?.agents??[],c=tb(t,o,s),l=t.custom?[]:nb(t.id,o,s);M(this.favoriteSummary,l.map(({room:e,count:t})=>a(`{0} em {1}`,[t,dt(e)])).join(` · `)),F(this.favoriteSummary,l.length===0),this.accs.sync(Eb(c,i?.accounts??[]));let u=Db(c);M(this.agentsSec.extra,c.length?String(c.length):``),F(this.agentsEmpty,c.length>0),this.agents.sync(u);let d=xb(c);F(this.tasksSec.el,d.total===0),Ox(this.tasksBar,d.completed,d.total,d.inProgress),M(this.tasksSec.extra,`${d.completed}/${d.total}`),this.tasks.sync(c.flatMap(e=>e.tasks.map(t=>({task:t,owner:xt(e,this.ctx.store.snapshot?.machines),key:`${e.id}#${t.id}`}))));let f=this.ctx.store.feed.filter(e=>e.roomId===t.id).slice(-15).reverse();F(this.feedSec.el,f.length===0),this.feed.sync(f)}async removeCustomRoom(){if(!this.deleteConfirming){this.deleteConfirming=!0,M(this.deleteBtn,a(`Confirmar exclusão`));return}let e=this.id;this.deleteBtn.disabled=!0,F(this.newMsg,!0);try{await iv(e),this.ctx.invalidate();let t=this.ctx.selection();t?.type===`room`&&t.id===e&&this.ctx.select(null)}catch(t){if(this.id!==e)return;M(this.newMsg,t instanceof Error?t.message:a(`erro ao excluir a sala`)),F(this.newMsg,!1),this.resetDeleteConfirmation()}}close(){this.deleteBtn.disabled||this.resetDeleteConfirmation()}resetDeleteConfirmation(){this.deleteConfirming=!1,M(this.deleteBtn,a(`Excluir`)),this.deleteBtn.disabled=!1}},lT=class{ctx;el;body;agentView;roomView;mode=null;heading;movable;onLayoutChange=null;constructor(e,t,n){this.ctx=e,this.agentView=new oT(e,t,n),this.roomView=new cT(e,n),this.heading=P(`span`,{class:`ui-drawer__kind`});let r=j(Q.close,a(`Fechar detalhes (Esc)`),()=>e.select(null));this.body=P(`div`,{class:`ui-drawer__body`});let i=P(`div`,{class:`ui-drawer__bar`},this.heading,r);this.el=P(`aside`,{class:`ui-panel ui-drawer`,attrs:{"aria-label":a(`Detalhes`),id:`ui-drawer`,"aria-hidden":`true`}},i,this.body),this.movable=new Fb(this.el,i,{key:`habblaud.move.drawer`,enabled:()=>!e.isNarrow(),onChange:()=>this.onLayoutChange?.()}),this.el.inert=!0}get isOpen(){return this.mode!==null}get floating(){return this.movable.floating}toggleFollow(){this.mode===`agent`&&this.agentView.toggleFollow()}render(){let e=this.ctx.selection(),t=e?.type??null;t!==this.mode&&(this.mode===`agent`&&this.agentView.character.close(),this.mode===`room`&&this.roomView.close(),this.mode=t,this.body.replaceChildren(...t===`agent`?[this.agentView.el]:t===`room`?[this.roomView.el]:[]),this.body.scrollTop=0,this.el.classList.toggle(`is-open`,t!==null),N(this.el,`aria-hidden`,t?`false`:`true`),this.el.inert=t===null),e?.type===`agent`?(this.agentView.agentId!==e.id&&(this.body.scrollTop=0),this.agentView.open(e.id),M(this.heading,this.ctx.agent(e.id)?.kind===`sub`?a(`Subagente`):a(`Agente`)),this.agentView.render()):e?.type===`room`&&(this.roomView.roomId!==e.id&&(this.body.scrollTop=0),this.roomView.open(e.id),M(this.heading,a(`Sala`)),this.roomView.render())}},uT=8e3;function dT(e){let t=P(`span`,{class:`ui-brand__mark`}),n=P(`img`,{attrs:{src:`/assets/brand/logo-mark@4x.png`,alt:``,width:e,height:e,draggable:`false`}});return n.addEventListener(`error`,()=>{t.innerHTML=$_}),t.append(n),t}var fT=class{ctx;el;text;done=!1;startedAt=performance.now();tick=null;constructor(e){this.ctx=e,this.text=P(`p`,{class:`ui-splash__text`,text:a(`Conectando ao escritório…`)}),this.el=P(`div`,{class:`ui-splash`,role:`status`,attrs:{"aria-live":`polite`}},P(`div`,{class:`ui-splash__inner`},dT(64),Nx(`ui-splash__name`),this.text,P(`span`,{class:`ui-splash__bar`})))}render(){if(this.done)return;let{store:e}=this.ctx;if(e.snapshot){this.done=!0,this.el.classList.add(`is-hidden`);let e=()=>this.el.remove();ht()?e():setTimeout(e,600);return}let t=performance.now()-this.startedAt,n=a(`Conectando ao escritório…`);t>uT?n=a(`O servidor do Habblaud não responde. Confira se ele está rodando (npm run dev ou npm start); seguimos tentando.`):e.connection===`closed`&&(n=a(`Não foi possível conectar ao servidor do Habblaud. Tentando de novo…`)),M(this.text,n),this.tick??=setTimeout(()=>{this.tick=null,this.ctx.invalidate()},1e3)}};function pT(e){let{store:t}=e,n=t.snapshot;return(t.connection===`open`||t.connection===`mock`)&&!t.replaying&&!!n&&n.agents.length===0&&n.rooms.length===0}var mT=class{ctx;el;hint;demoBtn;busy=!1;constructor(e){this.ctx=e;let t=P(`div`,{class:`ui-empty__art`,attrs:{"aria-hidden":`true`}}),n=P(`img`,{attrs:{src:`/assets/illustrations/empty-office.png`,alt:``,draggable:`false`}});n.addEventListener(`error`,()=>{n.remove(),t.classList.add(`is-css`),t.append(P(`span`,{class:`ui-empty__lamp`}),P(`span`,{class:`ui-empty__monitor`}),P(`span`,{class:`ui-empty__desk`}),P(`span`,{class:`ui-empty__chair`}),P(`span`,{class:`ui-empty__plant`}))}),t.append(n),this.hint=P(`p`,{class:`ui-empty__text`}),this.demoBtn=P(`button`,{class:`ui-btn ui-btn--primary`,type:`button`,text:a(`Ver demonstração`),on:{click:()=>void this.startDemo()}}),this.el=P(`section`,{class:`ui-empty`,hidden:!0,attrs:{"aria-labelledby":`ui-empty-title`}},t,P(`h2`,{class:`ui-empty__title`,text:a(`O escritório está vazio`),attrs:{id:`ui-empty-title`}}),this.hint,this.demoBtn)}render(){let{store:e}=this.ctx,t=e.snapshot,n=pT(this.ctx);F(this.el,!n),n&&t&&(M(this.hint,Xb(t.accounts)),this.demoBtn.disabled=this.busy,F(this.demoBtn,e.mock))}async startDemo(){this.busy=!0,this.ctx.invalidate();try{await this.ctx.store.setDemo(!0)||this.ctx.announce(a(`Não foi possível ligar a demonstração.`))}catch{this.ctx.announce(a(`Não foi possível falar com o servidor.`))}finally{this.busy=!1,this.ctx.invalidate()}}},hT=class{ctx;el;since=null;timer=null;text;retry;constructor(e){this.ctx=e,this.text=P(`span`),this.retry=P(`span`,{class:`ui-banner__retry`});let t=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Tentar agora`),on:{click:()=>e.store.reconnectNow()}});this.el=P(`div`,{class:`ui-banner`,role:`alert`,hidden:!0},P(`span`,{class:`ui-banner__dot`,attrs:{"aria-hidden":`true`}}),P(`span`,{class:`ui-banner__text`},this.text,this.retry),t)}render(){let{store:e}=this.ctx,t=e.connection;if(t!==`connecting`&&t!==`closed`){this.since=null,this.timer&&clearTimeout(this.timer),this.timer=null,F(this.el,!0);return}this.since??=Date.now();let n=Date.now()-this.since;if(n<uT){this.timer??=setTimeout(()=>{this.timer=null,this.ctx.invalidate()},uT-n+50);return}M(this.text,e.snapshot?a(`Sem conexão com o servidor do Habblaud há algum tempo. O escritório mostra o último estado conhecido.`):a(`O servidor do Habblaud não responde. Confira se ele está rodando (npm run dev ou npm start).`));let r=e.nextRetryAt,i=r===null?0:Math.max(1,Math.ceil((r-Date.now())/1e3));M(this.retry,r===null?a(` Tentando reconectar…`):a(` Nova tentativa em {0} s.`,[i])),F(this.el,!1),this.timer??=setTimeout(()=>{this.timer=null,this.ctx.invalidate()},1e3)}},gT=class{ctx;el;list;rows;items=[];pending=[];pendingCounts=new Map;hovering=!1;scrolledUp=!1;newPill;ticker;toggleBtn;empty;filterNote;meta=new Map;constructor(e){this.ctx=e,this.list=P(`ol`,{class:`ui-feed__list`,role:`log`,attrs:{"aria-label":a(`Eventos recentes`),"aria-live":`off`}}),this.rows=new wt(this.list,{key:e=>e.id,create:e=>this.createRow(e),update:(e,t)=>this.updateRow(e,t)}),this.empty=P(`p`,{class:`ui-feed__empty`,text:a(`Os eventos dos agentes aparecem aqui assim que acontecem.`)}),this.newPill=P(`button`,{class:`ui-feed__new`,type:`button`,hidden:!0,on:{click:()=>this.resume()}}),this.ticker=P(`span`,{class:`ui-feed__ticker`,attrs:{"aria-hidden":`true`}}),this.filterNote=P(`span`,{class:`ui-feed__filter`,hidden:!0}),this.toggleBtn=P(`button`,{class:`ui-icon-btn ui-icon-btn--sm`,type:`button`,on:{click:()=>e.togglePanel(`feed`)}});let t=P(`div`,{class:`ui-feed__scroll`},this.list,this.empty);t.addEventListener(`scroll`,()=>{this.scrolledUp=t.scrollHeight-t.scrollTop-t.clientHeight>24,!this.scrolledUp&&!this.hovering&&this.flushSoon()}),this.el=P(`section`,{class:`ui-panel ui-feed`,attrs:{"aria-label":a(`Feed de atividade`),id:`ui-feed`}},P(`div`,{class:`ui-feed__head`},P(`button`,{class:`ui-feed__title`,type:`button`,on:{click:()=>e.togglePanel(`feed`)}},P(`h2`,{text:a(`Atividade`)}),this.filterNote,this.ticker),this.newPill,this.toggleBtn),t),t.addEventListener(`mouseenter`,()=>this.hovering=!0),t.addEventListener(`mouseleave`,()=>{this.hovering=!1,this.flushSoon()}),e.store.on(`feed`,t=>{this.appendPending(t),e.invalidate()}),this.appendPending(e.store.feed.slice(-50)),e.world.onSocialEvent?.(t=>{let n=e.agent(t.agentId);n&&(this.appendPending([{id:t.id,agentId:n.id,roomId:n.roomId,agentName:n.name,roomName:t.place,account:n.account,activity:{id:t.id,kind:`other`,icon:t.icon,text:t.text,at:t.at}}]),e.invalidate())})}render(){for(let e of this.ctx.store.snapshot?.agents??[]){let t=this.meta.get(e.id);(!t||t.seed!==e.seed||t.account!==e.account||k(t.parts)!==k(e.parts))&&this.meta.set(e.id,{seed:e.seed,look:e.look,kind:e.kind,account:e.account,parts:e.parts})}let e=this.ctx.isPanelOpen(`feed`),t=this.hovering||this.scrolledUp;this.pending.length&&(!t||!e)&&this.flush(),this.pruneMeta();let n=this.ctx.prefs.hiddenAccounts,r=n.length>0,i=r?this.items.filter(e=>this.visible(e)):this.items,o=r?this.pending.filter(e=>this.visible(e)):this.pending,s=0;for(let[e,t]of this.pendingCounts)(!e||!n.includes(e))&&(s+=t);if(F(this.newPill,!(t&&s>0&&e)),s&&M(this.newPill,s===1?a(`1 nova`):a(`{0} novas`,[Math.min(s,99)])),F(this.empty,i.length>0||pT(this.ctx)),M(this.empty,r&&this.items.length>0?a(`Nenhum evento das contas selecionadas.`):a(`Os eventos dos agentes aparecem aqui assim que acontecem.`)),F(this.filterNote,!r),r){let e=n.map(e=>this.ctx.account(e)?.name??e);M(this.filterNote,`filtrado`),A(this.filterNote,a(`Sem {0} (filtro da barra lateral)`,[e.join(`, `)]))}let c=o[o.length-1]??i[i.length-1];M(this.ticker,c?`${yt(this.ctx,c.agentId,c.agentName)}: ${c.activity.icon} ${c.activity.text}`:``),this.toggleBtn.innerHTML=e?Q.chevronDown:Q.chevronUp;let l=a(e?`Recolher feed ( ] )`:`Abrir feed ( ] )`);N(this.toggleBtn,`aria-label`,l),A(this.toggleBtn,l),N(this.toggleBtn,`aria-expanded`,String(e)),e&&this.rows.sync(i)}accountOf(e){return e.account??this.meta.get(e.agentId)?.account??this.ctx.agent(e.agentId)?.account}visible(e){let t=this.accountOf(e);return!t||!this.ctx.prefs.hiddenAccounts.includes(t)}appendPending(e){for(let t of e){let e=this.accountOf(t);this.pendingCounts.set(e,(this.pendingCounts.get(e)??0)+1)}this.pending.push(...e.slice(-50)),this.pending=this.pending.slice(-50),this.pruneMeta()}pruneMeta(){let e=new Set([...this.items,...this.pending].map(e=>e.agentId));for(let t of this.ctx.store.snapshot?.agents??[])e.add(t.id);for(let t of this.meta.keys())e.has(t)||this.meta.delete(t)}flush(){let e=new Set(this.items.map(e=>e.id));for(let t of this.pending)e.has(t.id)||this.items.push(t);this.pending=[],this.pendingCounts.clear(),this.items=this.items.slice(-50),this.pruneMeta(),this.rows.sync(this.ctx.prefs.hiddenAccounts.length?this.items.filter(e=>this.visible(e)):this.items);let t=this.list.parentElement;requestAnimationFrame(()=>{t.scrollTop=t.scrollHeight})}flushSoon(){this.scrolledUp=!1,this.ctx.invalidate()}resume(){this.hovering=!1,this.scrolledUp=!1,this.flush(),this.ctx.invalidate()}createRow(e){let t=this.meta.get(e.agentId)??this.metaFromStore(e.agentId),n=t?bv(t,`xs`):xv(`xs`),r=P(`button`,{class:`ui-feed__row`,type:`button`},P(`time`,{class:`ui-feed__time`}),n,P(`span`,{class:`ui-feed__who`}),yx(`sm`),P(`span`,{class:`ui-feed__room`}),P(`span`,{class:`ui-feed__icon`,attrs:{"aria-hidden":`true`}}),P(`span`,{class:`ui-feed__text`}));return r.addEventListener(`click`,()=>{this.ctx.agent(e.agentId)?this.ctx.select({type:`agent`,id:e.agentId},{focus:!0}):this.ctx.store.room(e.roomId)&&this.ctx.select({type:`room`,id:e.roomId},{focus:!0})}),P(`li`,{class:`ui-feed__item`},r)}updateRow(e,t){let n=e.firstElementChild,[r,i,a,o,s,c,l]=n.children,u=this.meta.get(t.agentId);M(r,Ft(t.activity.at)),N(r,`datetime`,new Date(t.activity.at).toISOString()),u&&Sv(i,u,`xs`),M(a,yt(this.ctx,t.agentId,t.agentName));let d=this.accountOf(t);bx(o,d?this.ctx.account(d):void 0,d??``),F(o,!d),M(s,t.roomName),M(c,t.activity.icon),M(l,t.activity.text),e.classList.toggle(`is-error`,!!t.activity.error),e.classList.toggle(`is-social`,t.id.startsWith(`social:`));let f=yb(t.activity);e.classList.toggle(`is-shell-ok`,f===`ok`),e.classList.toggle(`is-shell-fail`,f===`fail`);let p=!!this.ctx.agent(t.agentId);e.classList.toggle(`is-gone`,!p),A(n,`${Ft(t.activity.at)} · ${yt(this.ctx,t.agentId,t.agentName)} em ${t.roomName}\n${t.activity.text}${t.activity.detail?`\n${t.activity.detail}`:``}`)}metaFromStore(e){let t=this.ctx.agent(e);if(!t)return;let n={seed:t.seed,look:t.look,kind:t.kind,account:t.account,parts:t.parts};return this.meta.set(e,n),n}},_T=[[`working`,a(`Na mesa, digitando: está processando um pedido.`)],[`waiting`,a(`Mão levantada: espera uma resposta sua no terminal (permissão, pergunta ou escolha).`)],[`waiting-background`,a(`Terminou o turno e espera os subagentes em segundo plano; pode retomar depois.`)],[`shell`,a(`Ampulheta sobre a cabeça: terminou o turno e fica na mesa esperando um shell terminar.`)],[`idle`,a(`Terminou o turno e circula pelo escritório até a próxima instrução.`)],[`done`,a(`Subagente que concluiu: entrega o resultado e vai embora.`)],[`failed`,a(`O job falhou e vai sair do escritório.`)],[`offline`,a(`A sessão foi fechada: o personagem vai até o elevador e sai.`)]],vT=[[`📨`,a(`Recebeu um pedido`)],[`💭`,a(`Pensando`)],[`📖`,a(`Lendo arquivo`)],[`🔎`,a(`Buscando no código`)],[`✏️`,a(`Editando`)],[`📝`,a(`Escrevendo arquivo`)],[`💻`,a(`Comando no terminal`)],[`⏳`,a(`Esperando um shell`)],[`🧪`,a(`Rodando testes`)],[`🌐`,a(`Pesquisando na web`)],[`🗒️`,a(`Organizando tarefas`)],[`👥`,a(`Chamando subagentes`)],[`✋`,a(`Precisa de você`)],[`✅`,a(`Concluiu`)],[`❌`,a(`Shell falhou`)],[`🛑`,a(`Shell interrompido`)],[`⚠️`,a(`Algo deu errado`)]],yT=[[`📺`,a(`TV no lounge: futebol (comemoram o gol junto com a tela), novela ou desenho, com pipoca.`)],[`🎮`,a(`Videogame no sofá (melhor de 3) ou duelo nos fliperamas, com torcida.`)],[`🏓`,a(`Pingue-pongue até 5 pontos, com placar e torcida atrás da mesa.`)],[`☕`,a(`Papo na copa: pegam café e sentam para fofocar, contar piada e falar de trabalho.`)],[`✊`,a(`Jokenpô valendo moedinhas: jo-ken-pô, revelação, quem ganha leva o 🪙 (e quem perde pede revanche).`)],[`💄`,a(`Espelho do banheiro: se arrumam (batom, pente) e aparecem refletidos no vidro.`)],[`🪙`,a(`Carteira: entram com 🪙100 (subagentes 🪙30), ganham 🪙10 por tarefa concluída, 🪙5 por pedido atendido e 🪙15 por entrega de subagente.`)]],bT=[[`🎉`,a(`Festa: PR aberto ou mergeado, release publicada (ou CI verde depois de um alarme). Confete cai na sala, todos comemoram e uma faixa diz o motivo (~12 s).`)],[`🚨`,a(`Alarme: o CI ficou vermelho. Giroflex nos cantos da sala, chão avermelhado e um balão “!” sobre quem viu a falha, até um CI verde na sala (ou 10 min).`)],[`🚀`,a(`Push: só o aviso e o feed, sem mexer na sala.`)]],xT=[a(`Cada projeto aberto no Codex (no terminal ou no app) vira uma sala: a mesma do Claude Code naquela pasta, e os dois dividem a sala.`),a(`Os agentes do Codex têm o chip da conta vazado (só a borda na cor da conta) e o selo CODEX na etiqueta e nos detalhes.`),a(`{0} Sem os hooks, o escritório lê os arquivos de sessão do Codex: cada passo aparece quando termina.`,[Qb]),a(`Aprovar pelo escritório: no Codex, a aprovação só aparece no terminal depois que você responder aqui ou o prazo acabar (alguns segundos). Não há “não perguntar de novo” nem “interromper”, e recusar pede um motivo.`),a("Mensagens: entram na fila da sessão e viram o próximo prompt quando o Codex terminar o que está fazendo (até ~10\xA0s). Com o Habblaud no Docker, deixe `npm run codex:bridge` rodando; no modo Node funciona sozinho."),a(`Perguntas do Codex são respondidas no próprio Codex.`),a(`Uso: vem dos arquivos de sessão do Codex, sem instalar nada, e só se renova enquanto alguma sessão roda (por isso o cartão mostra a idade, ex.: “há 12 min”). “sem cota” quer dizer sem cota nem créditos para usar agora.`),a(`Meu dia: o Codex conta tokens, mas não grava custo.`)],ST=[[`🎉`,a(`Terminou bem: levanta, comemora com confete e uma estrela.`)],[`🌧️`,a(`Falhou ou foi interrompido: nuvenzinha de chuva sobre a cabeça e ombros caídos.`)]],CT=a(`Cada projeto aberto no Claude Code ou no Codex vira uma sala (os dois no mesmo projeto dividem a sala), e cada sessão aberta é um personagem com nome próprio. `)+a(`Subagentes chegam como colegas novos, trabalham na mesma sala e vão embora quando terminam. `)+a(`Quando a última sessão de uma sala é fechada, quem sai apaga a luz e a sala é desmontada.`),wT=[[[`/`],a(`Buscar agente, projeto ou conta`)],[[`/ …`],a(`Na caixa de mensagem: /comando roda um comando da sessão; as setas, Enter e Tab escolhem na lista`)],[[`F`],a(`Seguir o agente selecionado`)],[[`T`],a(`Abrir ou fechar o terminal do agente selecionado`)],[[`Ctrl+F`],a(`Com o terminal em foco: buscar na conversa (⌘F no Mac); Enter e Shift+Enter navegam`)],[[`L`],a(`Abrir ou fechar o timelapse do dia`)],[[`P`],a(`Ir até o próximo pedido de permissão ou pergunta para responder pelo escritório`)],[[`M`],a(`Meu dia: para onde foi o tempo (trabalhando, esperando você...)`)],[[`O`,`0`],a(`Visão geral do prédio`)],[[`Esc`],a(`Fechar a busca do terminal, depois o terminal; depois, a gaveta e a seleção`)],[[`[`],a(`Mostrar ou ocultar o painel lateral`)],[[`]`],a(`Mostrar ou ocultar o feed de atividade`)],[[`?`],a(`Abrir esta ajuda`)],[[`←`,`↑`,`→`,`↓`],a(`Mover a câmera (também W A S D)`)],[[`+`,`−`],a(`Aproximar e afastar`)]];function TT(e){return P(`span`,{class:`ui-keys`},...e.map(e=>P(`kbd`,{class:`ui-kbd`,text:e})))}var ET=class{el;sections=new Map;constructor(){let e=j(Q.close,a(`Fechar ajuda`),()=>this.el.close(),`ui-icon-btn--sm`),t=P(`ul`,{class:`ui-legend`},..._T.map(([e,t])=>P(`li`,{},P(`span`,{class:`ui-status-dot is-${e}`,attrs:{"aria-hidden":`true`}}),P(`strong`,{text:Ky[e]}),P(`span`,{text:t})))),n=P(`ul`,{class:`ui-icon-legend`},...vT.map(([e,t])=>P(`li`,{},P(`span`,{class:`ui-icon-legend__icon`,text:e,attrs:{"aria-hidden":`true`}}),P(`span`,{text:t})))),r=P(`dl`,{class:`ui-shortcuts`},...wT.flatMap(([e,t])=>[P(`dt`,{},TT(e)),P(`dd`,{text:t})]));this.el=P(`dialog`,{class:`ui-dialog ui-help`,attrs:{"aria-labelledby":`ui-help-title`}},P(`div`,{class:`ui-dialog__head`},P(`h2`,{text:a(`Como ler o escritório`),attrs:{id:`ui-help-title`}}),e),P(`div`,{class:`ui-dialog__body`},P(`section`,{class:`ui-help__intro`},P(`p`,{text:CT})),P(`section`,{},P(`h3`,{text:`Status`}),t),P(`section`,{},P(`h3`,{text:a(`Atividades`)}),n),this.shellSection(),this.socialSection(),this.avatarSection(),this.githubSection(),P(`section`,{},P(`h3`,{text:a(`Controles`)}),P(`ul`,{class:`ui-help__list`},P(`li`,{text:a(`Arraste o escritório para mover a câmera e use a rolagem do mouse (ou pinça) para dar zoom.`)}),P(`li`,{text:a(`Clique em um personagem ou sala para ver os detalhes; duplo clique aproxima a câmera.`)}),P(`li`,{text:a(`Passe o mouse sobre um personagem para ver o que ele está fazendo.`)}),P(`li`,{text:a(`Nos detalhes de um agente, “Abrir terminal” mostra a conversa da sessão como no Claude Code (ou no Codex), ao vivo (precisa do acesso local, bind 127.0.0.1).`)}),P(`li`,{text:a(`Com o plugin busybits-messages (npm run mod:install), dá para mandar mensagens ao agente principal pelos detalhes dele ou pela caixa no rodapé do terminal: o texto entra na sessão como se você o tivesse digitado. Enter manda, Shift+Enter quebra a linha.`)}),P(`li`,{text:a(`No terminal: busca (lupa ou Ctrl/⌘+F), filtro “Tudo / Só prompts / Sem ferramentas” e um botão de copiar em cada entrada. O relógio da barra superior abre o histórico das sessões dos últimos 7 dias, inclusive as já encerradas.`)}),P(`li`,{text:a(`Com o mod do Habblaud instalado (npm run mod:install, que inclui o plugin de permissões), quem “pede permissão” mostra nos detalhes o comando ou a edição e os botões Aprovar, Recusar e Responder no terminal; quem faz uma pergunta mostra as opções (e um “Outro” para escrever) para responder por aqui. O diálogo continua no terminal: vale o que você responder primeiro.`)})),r),this.usageSection(),this.codexSection())),this.el.addEventListener(`click`,e=>{e.target===this.el&&this.el.close()})}open(e){this.el.open||this.el.showModal();let t=e?this.sections.get(e):void 0;t&&requestAnimationFrame(()=>{t.scrollIntoView({block:`start`,behavior:ht()?`auto`:`smooth`}),t.classList.remove(`is-highlight`),t.offsetWidth,t.classList.add(`is-highlight`),t.querySelector(`h3`)?.focus({preventScroll:!0})})}shellSection(){let e=(e,t)=>P(`li`,{},P(`span`,{class:`ui-icon-legend__icon`,text:e,attrs:{"aria-hidden":`true`}}),P(`span`,{text:t}));return P(`section`,{class:`ui-help__shell`},P(`h3`,{text:a(`Esperando o shell`)}),P(`p`,{class:`ui-help__lead`,text:a(`Quando o agente termina o turno com um comando rodando em segundo plano (ou fica mais de 10 s parado num comando), ele não sai para passear: `)+a(`fica na mesa com a ampulheta virando, o monitor mostra o progresso e um balão diz qual shell ele espera e há quanto tempo. Quanto mais demora…`)}),P(`ul`,{class:`ui-shell-legend`},..._b.map(t=>e(t.emoji,t.help)),...ST.map(([t,n])=>e(t,n))))}socialSection(){let e=(e,t)=>P(`li`,{},P(`span`,{class:`ui-icon-legend__icon`,text:e,attrs:{"aria-hidden":`true`}}),P(`span`,{text:t}));return P(`section`,{class:`ui-help__shell`},P(`h3`,{text:a(`Vida social`)}),P(`p`,{class:`ui-help__lead`,text:a(`Quando dois ou mais agentes estão à toa (ociosos, ou esperando um shell há mais de 40 s), eles se juntam. Cada um tem 2 ou 3 traços de personalidade `)+a(`(competição, fofoca, vaidade, sonecas…), amizades e rivalidades, e isso decide o que preferem fazer, com quem e o que falam. `)+a(`Os detalhes do agente mostram a personalidade, a carteira e o extrato; as partidas e apostas aparecem no feed.`)}),P(`ul`,{class:`ui-shell-legend`},...yT.map(([t,n])=>e(t,n))))}avatarSection(){return P(`section`,{class:`ui-help__shell`},P(`h3`,{text:a(`Meu avatar`)}),P(`p`,{class:`ui-help__lead`,text:a(`Você também está no escritório: seu avatar espera à porta quem precisa de você (com o carimbo da sua resposta e “+N esperando” quando a fila passa de 6), `)+a(`fica em pé ao lado do agente que você está atendendo, vai tomar café ou cochilar quando você sai e, na volta, mostra o que aconteceu enquanto esteve fora. `)+a(`Nas Configurações você escolhe o visual e depois de quantos minutos ele vai ao café ou cochila.`)}))}githubSection(){let e=(e,t)=>P(`li`,{},P(`span`,{class:`ui-icon-legend__icon`,text:e,attrs:{"aria-hidden":`true`}}),P(`span`,{text:t}));return P(`section`,{class:`ui-help__shell`},P(`h3`,{text:a(`GitHub no escritório`)}),P(`p`,{class:`ui-help__lead`,text:a(`O que os agentes fazem no GitHub (gh pr create/merge, git push, gh run watch, gh pr checks, gh release create e o MCP do GitHub) vira aviso, `)+a(`entra no feed e anima a sala do projeto. Só o que acontece ao vivo: o que já estava nos transcripts quando o Habblaud abriu fica só no histórico.`)}),P(`ul`,{class:`ui-shell-legend`},...bT.map(([t,n])=>e(t,n))))}usageSection(){let e=P(`section`,{class:`ui-help__usage`,attrs:{"aria-labelledby":`ui-help-usage`}},P(`h3`,{text:a(`Contas e uso`),tabIndex:-1,attrs:{id:`ui-help-usage`}}),P(`ul`,{class:`ui-help__list`},P(`li`,{text:a(`O chip colorido com a letra (C, D…) mostra de qual conta do Claude Code é cada agente: cada atalho de terminal usa uma pasta de configuração diferente.`)}),P(`li`,{},DT(`C`,`#f08a3c`),a(` Conta do Claude Code · `),DT(`X`,`#a77bf3`,!0),a(` Conta do Codex (chip vazado, com o selo CODEX onde há espaço).`)),P(`li`,{text:a(`No topo, cada conta mostra o uso da sessão de 5 horas e da semana. O ↻ indica quando cada limite reinicia (contagem regressiva se faltar menos de um dia). Verde abaixo de 50%, âmbar até 80% e vermelho a partir daí.`)}),P(`li`,{text:a(`Números antigos ficam acinzentados com a idade ao lado (ex.: “há 3 h”); uma janela que já reiniciou desde a leitura mostra “—” e “renovada”.`)})),P(`p`,{class:`ui-help__lead`,text:a(`Para ver o uso de uma conta (“sem dados de uso”), em ordem de preferência:`)}),Nw());return this.sections.set(`usage`,e),e}codexSection(){let e=P(`section`,{class:`ui-help__usage`,attrs:{"aria-labelledby":`ui-help-codex`}},P(`h3`,{text:`Codex`,tabIndex:-1,attrs:{id:`ui-help-codex`}}),P(`ul`,{class:`ui-help__list`},...xT.map(e=>P(`li`,{},...Ow(e)))));return this.sections.set(`codex`,e),e}get isOpen(){return this.el.open}};function DT(e,t,n=!1){let r=yx(`sm`);return bx(r,{id:e,short:e,name:n?`Codex`:a(`Conta {0}`,[e]),color:t,configDir:``,sessions:0,usageStatus:`disabled`,...n?{provider:`codex`}:{}}),r.setAttribute(`aria-hidden`,`true`),r}var OT=`/api/sessions/recent`,kT=250,AT=new Intl.DateTimeFormat(e(),{weekday:`short`,day:`2-digit`,month:`short`});function jT(e){return typeof e==`string`&&e.trim()?e:void 0}function MT(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function NT(e){let t=e&&typeof e==`object`?e.sessions:void 0;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(!e||typeof e!=`object`)continue;let t=e,r=jT(t.account),i=jT(t.sessionId),a=MT(t.lastAt);if(!r||!i||a===void 0)continue;let o={account:r,sessionId:i,projectDir:jT(t.projectDir)??``,lastAt:a,size:MT(t.size)??0,open:t.open===!0},s=jT(t.project),c=jT(t.title),l=MT(t.firstAt),u=jT(t.agentId);t.provider===`codex`&&(o.provider=`codex`),s&&(o.project=s),c&&(o.title=c),l!==void 0&&(o.firstAt=l),o.open&&u&&(o.agentId=u),n.push(o)}return n.sort((e,t)=>t.lastAt-e.lastAt)}function PT(e,t,n=e=>e){let r=Mt(t).split(/\s+/).filter(Boolean);return r.length?e.filter(e=>{let t=Mt([e.title??``,e.project??``,e.projectDir,n(e.account),Ub(e)?`Codex`:``].join(` `));return r.every(e=>t.includes(e))}):e.slice()}function FT(e,t){let n=Vt(e,t);if(n===0)return a(`Hoje`);if(n===-1)return a(`Ontem`);let r=AT.format(e);return r.charAt(0).toUpperCase()+r.slice(1)}function IT(e,t){let n=new Map;for(let r of[...e].sort((e,t)=>t.lastAt-e.lastAt)){let e=new Date(r.lastAt);e.setHours(0,0,0,0);let i=e.getTime(),a=n.get(i);a||(a={key:i,label:FT(r.lastAt,t),sessions:[]},n.set(i,a)),a.sessions.push(r)}return[...n.values()].sort((e,t)=>t.key-e.key)}function LT(e){return e<1048576?`${Math.max(1,Math.round(e/1024))} KB`:`${(e/1048576).toFixed(1).replace(`.`,`,`)} MB`}var RT=class{ctx;terminal;el;button;input;listEl;stateEl;stateText;retryBtn;footEl;noteEl;note=``;sessions=[];state=`idle`;error=``;query=``;request=0;closedAt=-1/0;drawn=``;constructor(e,t){this.ctx=e,this.terminal=t,this.button=j(Q.clock,a(`Histórico de sessões`),()=>this.toggle(),`ui-hist-btn`),N(this.button,`aria-haspopup`,`dialog`),N(this.button,`aria-expanded`,`false`);let n=P(`span`,{class:`ui-search__icon`,attrs:{"aria-hidden":`true`}});n.innerHTML=Q.search,this.input=P(`input`,{class:`ui-search__input`,type:`search`,attrs:{placeholder:a(`Buscar por título, projeto ou conta`),"aria-label":a(`Buscar sessões por título, projeto ou conta`),autocomplete:`off`,spellcheck:`false`}}),this.input.addEventListener(`input`,()=>{this.query=this.input.value,this.renderList()}),this.input.addEventListener(`keydown`,e=>{e.key===`ArrowDown`?(e.preventDefault(),this.items()[0]?.focus()):e.key===`Enter`?(e.preventDefault(),this.items()[0]?.click()):e.key===`Escape`&&this.input.value&&(e.preventDefault(),e.stopPropagation(),this.input.value=``,this.query=``,this.renderList())}),this.stateText=P(`span`),this.retryBtn=P(`button`,{class:`ui-link-btn`,type:`button`,text:a(`Tentar de novo`),hidden:!0,on:{click:()=>void this.load()}}),this.stateEl=P(`p`,{class:`ui-hist__state`,role:`status`},this.stateText,this.retryBtn),this.listEl=P(`div`,{class:`ui-hist__list`,attrs:{"aria-label":a(`Sessões recentes`)}}),this.listEl.addEventListener(`keydown`,e=>this.onListKey(e)),this.footEl=P(`p`,{class:`ui-hist__foot`}),this.noteEl=P(`p`,{class:`ui-partial-note`,role:`status`,hidden:!0});let r=j(Q.close,a(`Fechar histórico`),()=>this.hide(),`ui-icon-btn--sm`);this.el=P(`div`,{class:`ui-popover ui-hist`,role:`dialog`,tabIndex:-1,attrs:{"aria-label":a(`Histórico de sessões`),id:`ui-history`,popover:`auto`}},P(`div`,{class:`ui-popover__head`},P(`h2`,{text:a(`Histórico de sessões`)}),r),P(`p`,{class:`ui-hist__hint`,text:a(`Últimos 7 dias, de todas as contas. Clique para ler a conversa no terminal.`)}),P(`label`,{class:`ui-search ui-hist__search`},n,this.input),this.stateEl,this.listEl,this.footEl,this.noteEl),this.el.addEventListener(`toggle`,()=>{N(this.button,`aria-expanded`,String(this.isOpen)),this.button.classList.toggle(`is-on`,this.isOpen),this.isOpen||(this.closedAt=performance.now()),this.ctx.root.classList.toggle(`has-popover`,this.isOpen)})}get isOpen(){try{return this.el.matches(`:popover-open`)}catch{return this.el.classList.contains(`is-open`)}}get available(){return!!this.ctx.store.snapshot?.meta.terminal&&I().terminal&&!this.ctx.store.mock}toggle(){if(this.isOpen)return this.hide();if(!this.available){this.ctx.announce(`${US}.`);return}if(performance.now()-this.closedAt<kT)return;let e=this.button.getBoundingClientRect();this.el.style.top=`${Math.round(e.bottom+8)}px`,this.el.style.right=`${Math.max(8,Math.round(innerWidth-e.right-4))}px`,typeof this.el.showPopover==`function`?this.el.showPopover():this.el.classList.add(`is-open`),N(this.button,`aria-expanded`,`true`),this.button.classList.add(`is-on`),this.ctx.root.classList.add(`has-popover`),this.renderList(),this.input.focus(),this.input.select(),this.load()}hide(){typeof this.el.hidePopover==`function`&&this.isOpen&&this.el.hidePopover(),this.el.classList.remove(`is-open`),N(this.button,`aria-expanded`,`false`),this.button.classList.remove(`is-on`),this.ctx.root.classList.remove(`has-popover`)}render(){let e=this.available;if(N(this.button,`aria-disabled`,e?null:`true`),this.button.classList.toggle(`is-disabled`,!e),A(this.button,e?a(`Histórico de sessões (últimos 7 dias)`):US),N(this.button,`aria-label`,e?a(`Histórico de sessões`):a(`Histórico de sessões: {0}`,[US])),this.isOpen){if(!e)return this.hide();this.renderList()}}async load(){let e=++this.request;this.error=``,this.note=``,this.state=this.sessions.length?`ready`:`loading`,this.renderList();try{let t=await fetch(OT,{headers:{Accept:`application/json`}});if(!t.ok)throw this.error=t.status===403?`${US}.`:a(`Não foi possível carregar o histórico.`),Error(String(t.status));let n=await t.json(),r=NT(n);if(e!==this.request)return;this.sessions=r,this.note=Et(n,this.ctx.store.snapshot?.machines),this.state=`ready`}catch{if(e!==this.request)return;this.error||=a(`Não foi possível falar com o servidor.`),this.state=`error`}this.renderList()}renderList(){let e=this.ctx.now(),t=PT(this.sessions,this.query,e=>this.accountLabel(e)),n=IT(t,e),r=this.query.trim(),i=this.state===`loading`||this.state===`idle`,o=``;this.state===`error`?o=this.error||a(`Não foi possível carregar o histórico.`):i?o=a(`Carregando as sessões…`):this.sessions.length?t.length||(o=a(`Nenhuma sessão encontrada para “{0}”.`,[r])):o=a(`Nenhuma sessão nos últimos 7 dias.`),M(this.stateText,o),F(this.stateEl,!o),F(this.retryBtn,this.state!==`error`),M(this.footEl,this.sessions.length?r?`${t.length} de ${Lt(this.sessions.length,a(`sessão`),a(`sessões`))}`:Lt(this.sessions.length,a(`sessão`),a(`sessões`)):``),F(this.footEl,!this.sessions.length),M(this.noteEl,this.note),F(this.noteEl,!this.note);let s=JSON.stringify([n.map(e=>[e.key,e.label]),t.map(e=>[e.account,e.sessionId,e.title,e.lastAt,e.open,e.agentId&&!!this.ctx.agent(e.agentId)])]);if(s===this.drawn)return;let c=document.activeElement?.dataset?.session;this.drawn=s;let l=document.createDocumentFragment();for(let t of n){let n=P(`section`,{class:`ui-hist__day`,attrs:{"aria-label":t.label}},P(`h3`,{class:`ui-hist__day-label`,text:t.label}));for(let r of t.sessions)n.append(this.item(r,e));l.append(n)}this.listEl.replaceChildren(l),c&&this.items().find(e=>e.dataset.session===c)?.focus()}item(e,t){let n=this.ctx.account(e.account),r=yx(`sm`);bx(r,n,e.account,e.provider);let i=e.title?.trim()||a(`Sessão sem título`),o=aC(e),s=e.open&&!!e.agentId&&!!this.ctx.agent(e.agentId),c=Ub(e),l=P(`span`,{class:`ui-hist__meta`},c?P(`span`,{class:`ui-prov ui-prov--xs`,text:`Codex`}):null,P(`span`,{class:`ui-hist__project`,text:o}),P(`span`,{class:`ui-hist__time`,text:Ft(e.lastAt,!1)}));s&&l.append(P(`span`,{class:`ui-hist__live`,text:a(`aberta`)}));let u=P(`button`,{class:`ui-hist__item${s?` is-live`:``}`,type:`button`},r,P(`span`,{class:`ui-hist__text`},P(`span`,{class:`ui-hist__title`,text:i}),l));u.dataset.session=`${e.account}:${e.sessionId}`;let d=e.firstAt!==void 0&&Vt(e.firstAt,e.lastAt)!==0?`${kt(e.firstAt)} → ${kt(e.lastAt)}`:e.firstAt===void 0?kt(e.lastAt):`${kt(e.firstAt)} → ${Ft(e.lastAt,!1)}`;return A(u,[i,Ot(e.project??e.projectDir),`${n?.name??e.account}${c?` (Codex)`:``} · ${d} · ${LT(e.size)}`,a(s?`Ainda aberta: abre o terminal ao vivo do agente`:`Encerrada: abre a conversa no terminal`)].join(`
18
- `)),N(u,`aria-label`,`${i}, ${o}, ${n?.name??e.account}${c?`, Codex`:``}, ${s?a(`aberta`):a(`última atividade {0} às {1}`,[FT(e.lastAt,t).toLowerCase(),Ft(e.lastAt,!1)])}`),u.addEventListener(`click`,()=>{this.hide(),this.terminal.openSession(e,this.button)}),u}items(){return[...this.listEl.querySelectorAll(`.ui-hist__item`)]}onListKey(e){if(![`ArrowDown`,`ArrowUp`,`Home`,`End`].includes(e.key))return;let t=this.items(),n=t.indexOf(document.activeElement);if(!(n<0)){if(e.preventDefault(),e.key===`ArrowUp`&&n===0)return this.input.focus();t[e.key===`Home`?0:e.key===`End`?t.length-1:Math.max(0,Math.min(t.length-1,n+(e.key===`ArrowDown`?1:-1)))]?.focus()}}accountLabel(e){let t=this.ctx.account(e);return t?`${t.name} ${t.short}`:e}},zT=`/api/deliveries`,BT=3e4,VT=`habblaud.deliveries.seen`,HT=9e3,UT=new Set([`image`,`pdf`,`video`,`page`,`text`,`file`]);function WT(e){let t=e;return!!t&&typeof t.id==`string`&&/^[a-f0-9]{8,64}$/.test(t.id)&&typeof t.name==`string`&&UT.has(t.kind)}function GT(e){let t=e?.deliveries;return Array.isArray(t)?t.filter(e=>{let t=e;return!!t&&typeof t.id==`string`&&typeof t.headline==`string`&&typeof t.text==`string`&&typeof t.finishedAt==`number`&&Array.isArray(t.attachments)}).map(e=>({...e,attachments:e.attachments.filter(WT)})):[]}function KT(e,t){return e.filter(e=>e.finishedAt>t).length}function qT(e,t){return t?e.filter(e=>e.finishedAt>t):[]}function JT(e){return`/api/deliveries/file/${encodeURIComponent(e.id)}`}function YT(e){return e?e.split(/[\\/]/).filter(Boolean).pop()??e:``}function XT(e){let t=[e.tools===1?a(`1 passo`):a(`{0} passos`,[e.tools])];e.edited&&t.push(e.edited===1?a(`1 arquivo alterado`):a(`{0} arquivos alterados`,[e.edited]));let n=e.finishedAt-e.startedAt;return n>=6e4&&t.push(zt(n)),t.join(` · `)}function ZT(e){switch(e){case`image`:return a(`IMG`);case`pdf`:return`PDF`;case`video`:return a(`VÍDEO`);case`page`:return a(`PÁGINA`);case`text`:return a(`TEXTO`);default:return a(`ARQ`)}}function QT(){try{return Number(localStorage.getItem(VT))||0}catch{return 0}}function $T(e){try{localStorage.setItem(VT,String(e))}catch{}}var eE=class{ctx;terminal;button;el;badge;panel;listEl;noteEl;empty;modal;modalBody;viewer;viewerBody;viewerTitle;viewerCount;viewerOpen;prevBtn;nextBtn;toast;list=[];seenAt=QT();newestKnown=0;loading=!1;loaded=!1;error=``;timer=null;toastTimer=null;current=null;viewIndex=0;available=!1;constructor(e,t){this.ctx=e,this.terminal=t,this.badge=P(`span`,{class:`ui-deliv-badge`,hidden:!0,attrs:{"aria-hidden":`true`}}),this.button=j(Q.delivery,a(`Entregas: o que os agentes terminaram`),()=>this.togglePanel(),`ui-btn-deliv`),this.button.setAttribute(`aria-haspopup`,`dialog`),this.button.append(this.badge),this.button.hidden=!0,this.noteEl=P(`p`,{class:`ui-partial-note`,role:`status`,hidden:!0}),this.listEl=P(`ul`,{class:`ui-deliv-list`,attrs:{"aria-label":a(`Entregas`)}}),this.empty=P(`p`,{class:`ui-deliv-empty`,text:a(`Carregando as entregas…`)}),this.panel=P(`div`,{class:`ui-popover ui-deliv`,role:`dialog`,tabIndex:-1,attrs:{"aria-label":a(`Entregas`),id:`ui-deliveries`,popover:`auto`}},P(`div`,{class:`ui-popover__head`},P(`h2`,{text:a(`Entregas`)}),j(Q.close,a(`Fechar`),()=>this.hidePanel(),`ui-icon-btn--sm`)),P(`p`,{class:`ui-deliv-lead`,text:a(`O que cada agente terminou, em poucas palavras. Toque para ver o pedido, a resposta e os anexos.`)}),this.empty,this.noteEl,this.listEl),this.panel.addEventListener(`toggle`,()=>{this.button.setAttribute(`aria-expanded`,String(this.panelOpen)),this.button.classList.toggle(`is-on`,this.panelOpen)}),this.modalBody=P(`div`,{class:`ui-deliv-modal__body`}),this.modal=P(`dialog`,{class:`ui-deliv-modal`,attrs:{"aria-label":a(`Entrega`)}},this.modalBody),this.modal.addEventListener(`click`,e=>{e.target===this.modal&&this.modal.close()}),this.viewerTitle=P(`span`,{class:`ui-deliv-viewer__title`}),this.viewerCount=P(`span`,{class:`ui-deliv-viewer__count`}),this.viewerOpen=P(`a`,{class:`ui-btn ui-deliv-viewer__open`,text:a(`Abrir`),attrs:{target:`_blank`,rel:`noopener`}}),this.prevBtn=j(Q.chevronLeft,a(`Anterior`),()=>this.step(-1),`ui-deliv-viewer__nav`),this.nextBtn=j(Q.chevronRight,a(`Próximo`),()=>this.step(1),`ui-deliv-viewer__nav`),this.viewerBody=P(`div`,{class:`ui-deliv-viewer__body`}),this.viewer=P(`dialog`,{class:`ui-deliv-viewer`,attrs:{"aria-label":a(`Anexo`)}},P(`div`,{class:`ui-deliv-viewer__bar`},this.prevBtn,P(`div`,{class:`ui-deliv-viewer__label`},this.viewerTitle,this.viewerCount),this.nextBtn,this.viewerOpen,j(Q.close,a(`Fechar`),()=>this.viewer.close(),`ui-icon-btn--sm`)),this.viewerBody),this.viewer.addEventListener(`keydown`,e=>{e.key===`ArrowLeft`?this.step(-1):e.key===`ArrowRight`&&this.step(1)}),this.viewer.addEventListener(`close`,()=>this.viewerBody.replaceChildren()),this.wireSwipe(),this.toast=P(`button`,{class:`ui-deliv-toast`,type:`button`,hidden:!0,on:{click:()=>this.onToast()}}),this.el=P(`div`,{class:`ui-deliv-root`},this.panel,this.modal,this.viewer,this.toast),document.addEventListener(`visibilitychange`,()=>{!document.hidden&&this.available&&this.refresh()})}get panelOpen(){try{return this.panel.matches(`:popover-open`)}catch{return this.panel.classList.contains(`is-open`)}}render(){let e=this.ctx.store,t=I().remote&&I().terminal&&!!e.snapshot?.meta.terminal&&!e.mock&&!e.replaying;t!==this.available&&(this.available=t,F(this.button,!t),t?(this.refresh(),this.timer??=setInterval(()=>{document.hidden||this.refresh()},BT)):this.timer&&=(clearInterval(this.timer),null))}async openById(e){let t=this.list.find(t=>t.id===e);return t||=(await this.refresh(),this.list.find(t=>t.id===e)),t?this.openDelivery(t):this.openPanel(),!!t}openPanel(){this.panelOpen||this.togglePanel()}note=``;nameOf(e){return e.agentName?yt(this.ctx,e.agentId,e.agentName):a(`Agente`)}async refresh(){if(!this.loading){this.loading=!0;try{let e=await fetch(zT,{credentials:`same-origin`,cache:`no-store`}),t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error??a(`erro {0}`,[e.status]));let n=GT(t);this.note=Et(t,this.ctx.store.snapshot?.machines);let r=this.loaded?qT(n,this.newestKnown):[];this.list=n,this.loaded=!0,this.error=``,this.newestKnown=Math.max(this.newestKnown,...n.map(e=>e.finishedAt),0),this.seenAt||(this.seenAt=this.newestKnown,$T(this.seenAt)),r.length&&this.showToast(r[0],r.length)}catch(e){this.error=e.message||a(`não deu para carregar`)}finally{this.loading=!1,this.updateBadge(),this.panelOpen&&this.renderList()}}}updateBadge(){let e=this.panelOpen?0:KT(this.list,this.seenAt);M(this.badge,e>9?`9+`:String(e)),F(this.badge,e===0),this.button.setAttribute(`aria-label`,e>1?a(`Entregas: {0} novas`,[e]):a(e===1?`Entregas: 1 nova`:`Entregas: o que os agentes terminaram`))}togglePanel(){if(this.panelOpen)return this.hidePanel();let e=this.seenAt;this.renderList(e);let t=this.button.getBoundingClientRect();this.panel.style.top=`${Math.round(t.bottom+8)}px`,this.panel.style.right=`${Math.max(8,Math.round(innerWidth-t.right-4))}px`,typeof this.panel.showPopover==`function`?this.panel.showPopover():this.panel.classList.add(`is-open`),this.seenAt=Math.max(this.seenAt,this.newestKnown),$T(this.seenAt),this.updateBadge(),this.refresh()}hidePanel(){typeof this.panel.hidePopover==`function`&&this.panelOpen&&this.panel.hidePopover(),this.panel.classList.remove(`is-open`)}renderList(e=this.seenAt){let t=Date.now();F(this.empty,this.list.length>0),M(this.empty,this.error?a(`Não deu para carregar: {0}`,[this.error]):this.loaded?a(`Nenhuma entrega nos últimos 7 dias.`):a(`Carregando as entregas…`)),M(this.noteEl,this.note),F(this.noteEl,!this.note),this.listEl.replaceChildren(...this.list.map(n=>P(`li`,{},this.card(n,t,n.finishedAt>e))))}who(e,t){let n=e.agentId?this.ctx.agent(e.agentId):void 0;if(n)return bv(n,t);let r=(e.agentName??YT(e.project)??`?`).trim().charAt(0).toUpperCase()||`?`;return P(`span`,{class:`ui-deliv-initial ui-deliv-initial--${t}`,text:r,attrs:{"aria-hidden":`true`}})}card(e,t,n){let r=e.attachments.slice(0,4),i=e.attachments.length-r.length;return P(`button`,{class:`ui-deliv-card${n?` is-new`:``}`,type:`button`,on:{click:()=>this.openDelivery(e)}},P(`span`,{class:`ui-deliv-card__who`},this.who(e,`sm`),P(`span`,{class:`ui-deliv-card__name`,text:this.nameOf(e)}),e.project?P(`span`,{class:`ui-deliv-card__project`,text:YT(e.project)}):null,P(`span`,{class:`ui-deliv-card__when`,text:Nt(e.finishedAt,t)}),n?P(`span`,{class:`ui-deliv-card__new`,text:a(`nova`)}):null),P(`span`,{class:`ui-deliv-card__headline`,text:e.headline}),e.summary?P(`span`,{class:`ui-deliv-card__summary`,text:e.summary}):null,r.length?P(`span`,{class:`ui-deliv-card__thumbs`},...r.map(e=>this.thumb(e)),i>0?P(`span`,{class:`ui-deliv-thumb ui-deliv-thumb--more`,text:`+${i}`}):null):null,P(`span`,{class:`ui-deliv-card__meta`,text:XT(e)}))}thumb(e,t=!1){let n=`ui-deliv-thumb${t?` ui-deliv-thumb--big`:``}`;return e.kind===`image`?P(`img`,{class:n,attrs:{src:JT(e),alt:e.caption??e.name,loading:`lazy`,decoding:`async`}}):P(`span`,{class:`${n} ui-deliv-thumb--doc ui-deliv-thumb--${e.kind}`,title:e.name},P(`b`,{text:ZT(e.kind)}),t?P(`span`,{text:e.name}):null)}openDelivery(e){this.current=e;let t=Date.now(),n=e.agentId?this.ctx.agent(e.agentId):void 0,r=!!n&&n.status!==`offline`,i=P(`div`,{class:`ui-deliv-md`});i.append(SS(e.text));let o=[];if(r&&e.agentId){let t=e.agentId;o.push(P(`button`,{class:`ui-btn`,type:`button`,text:a(`Abrir terminal`),on:{click:()=>(this.closeAll(),this.ctx.select({type:`agent`,id:t}),(this.ctx.terminals??this.terminal).open(t))}}),P(`button`,{class:`ui-btn ui-perm__btn--allow`,type:`button`,text:a(`Responder`),on:{click:()=>(this.closeAll(),this.ctx.select({type:`agent`,id:t},{focus:!0}))}}))}let s=[P(`header`,{class:`ui-deliv-modal__head`},this.who(e,`md`),P(`div`,{class:`ui-deliv-modal__who`},P(`strong`,{text:this.nameOf(e)}),P(`span`,{text:[YT(e.project),Nt(e.finishedAt,t),XT(e)].filter(Boolean).join(` · `)})),j(Q.close,a(`Fechar`),()=>this.modal.close(),`ui-icon-btn--sm`)),P(`h2`,{class:`ui-deliv-modal__headline`,text:e.headline}),e.summary?P(`div`,{class:`ui-deliv-modal__summary`},P(`span`,{class:`ui-deliv-modal__label`,text:a(`Em resumo`)}),P(`p`,{text:e.summary})):null,e.attachments.length?P(`div`,{class:`ui-deliv-modal__atts`},...e.attachments.map((e,t)=>P(`button`,{class:`ui-deliv-att`,type:`button`,attrs:{"aria-label":a(`Ver {0}`,[e.name])},on:{click:()=>this.openViewer(t)}},this.thumb(e,!0),P(`span`,{class:`ui-deliv-att__caption`,text:e.caption??e.name})))):null,P(`div`,{class:`ui-deliv-modal__request`},P(`span`,{class:`ui-deliv-modal__label`,text:a(`Pedido`)}),P(`p`,{text:e.request||a(`(sem texto)`)})),P(`details`,{class:`ui-deliv-modal__full`},P(`summary`,{text:a(`Resposta completa`)}),i),o.length?P(`div`,{class:`ui-deliv-modal__actions`},...o):null];this.modalBody.replaceChildren(...s.filter(e=>!!e)),this.modal.open||this.modal.showModal(),this.modalBody.scrollTop=0}closeAll(){this.viewer.open&&this.viewer.close(),this.modal.open&&this.modal.close(),this.hidePanel()}openViewer(e){let t=this.current;if(!t||!t.attachments.length)return;this.viewIndex=(e+t.attachments.length)%t.attachments.length;let n=t.attachments[this.viewIndex],r=JT(n);M(this.viewerTitle,n.caption??n.name),M(this.viewerCount,t.attachments.length>1?a(`{0} de {1}`,[this.viewIndex+1,t.attachments.length]):``),F(this.prevBtn,t.attachments.length<2),F(this.nextBtn,t.attachments.length<2),this.viewerOpen.href=r;let i;if(this.viewerBody.classList.remove(`is-zoomed`),n.kind===`image`){let e=P(`img`,{class:`ui-deliv-viewer__img`,attrs:{src:r,alt:n.caption??n.name}});e.addEventListener(`click`,t=>this.toggleZoom(e,t)),i=e}else if(n.kind===`video`)i=P(`video`,{class:`ui-deliv-viewer__video`,attrs:{src:r,controls:!0,playsinline:!0}});else if(n.kind===`pdf`||n.kind===`page`)i=P(`iframe`,{class:`ui-deliv-viewer__frame`,attrs:{src:r,title:n.name}});else if(n.kind===`text`){i=P(`pre`,{class:`ui-deliv-viewer__text`,text:a(`Carregando…`)});let e=i;fetch(r,{credentials:`same-origin`}).then(async e=>e.ok?e.text():Promise.reject(Error((await e.json().catch(()=>({}))).error??a(`erro {0}`,[e.status])))).then(t=>M(e,t.slice(0,2e5)),t=>M(e,a(`Não deu para abrir: {0}`,[t.message])))}else i=P(`div`,{class:`ui-deliv-viewer__file`},P(`p`,{text:n.name}),P(`a`,{class:`ui-btn`,text:a(`Baixar`),attrs:{href:r,download:n.name}}));(i instanceof HTMLImageElement||i instanceof HTMLIFrameElement)&&i.addEventListener(`error`,()=>this.viewerBody.replaceChildren(P(`p`,{class:`ui-deliv-viewer__err`,text:a(`Não deu para abrir este anexo (o arquivo mudou de lugar ou o computador não respondeu).`)}))),this.viewerBody.replaceChildren(i),this.viewer.open||this.viewer.showModal()}toggleZoom(e,t){let n=e.getBoundingClientRect();if(!this.viewerBody.classList.toggle(`is-zoomed`)||!n.width||!n.height)return;let r=(t.clientX-n.left)/n.width,i=(t.clientY-n.top)/n.height,a=this.viewerBody;a.scrollLeft=r*e.offsetWidth-a.clientWidth/2,a.scrollTop=i*e.offsetHeight-a.clientHeight/2}step(e){this.viewer.open&&(this.current?.attachments.length??0)>1&&this.openViewer(this.viewIndex+e)}wireSwipe(){let e=0,t=0;this.viewerBody.addEventListener(`touchstart`,n=>{n.touches.length===1&&(e=n.touches[0].clientX,t=n.touches[0].clientY)},{passive:!0}),this.viewerBody.addEventListener(`touchend`,n=>{let r=n.changedTouches[0];if(!r||(window.visualViewport?.scale??1)>1.05||this.viewerBody.classList.contains(`is-zoomed`))return;let i=r.clientX-e;Math.abs(i)>60&&Math.abs(i)>Math.abs(r.clientY-t)*1.5&&this.step(i<0?1:-1)})}showToast(e,t){this.current=e,this.toast.replaceChildren(P(`span`,{class:`ui-deliv-toast__icon`,attrs:{"aria-hidden":`true`}}),P(`span`,{class:`ui-deliv-toast__text`},P(`b`,{text:e.agentName?a(`{0} entregou`,[this.nameOf(e)]):a(`Um agente entregou`)}),P(`span`,{text:t>1?`${e.headline} (+${t-1})`:e.headline}))),this.toast.firstChild.innerHTML=Q.delivery,F(this.toast,!1),this.toast.classList.remove(`is-in`),this.toast.offsetWidth,this.toast.classList.add(`is-in`),this.toastTimer&&clearTimeout(this.toastTimer),this.toastTimer=setTimeout(()=>F(this.toast,!0),HT)}onToast(){F(this.toast,!0),this.current&&this.openDelivery(this.current)}},tE=class{ctx;el;id=null;raf=0;name;chip;prov;dot;status;activity;mood;task;since;constructor(e){this.ctx=e,this.name=P(`strong`,{class:`ui-tip__name`}),this.chip=yx(`sm`),this.prov=xx(`ui-prov--xs`),this.dot=Cx(),this.status=P(`span`,{class:`ui-tip__status`}),this.activity=kx(),this.mood=P(`div`,{class:`ui-tip__mood`,hidden:!0}),this.task=P(`div`,{class:`ui-tip__task`,hidden:!0}),this.since=P(`span`,{class:`ui-tip__since`}),this.el=P(`div`,{class:`ui-tip`,attrs:{"aria-hidden":`true`}},P(`div`,{class:`ui-tip__top`},this.name,this.chip,this.prov),this.task,P(`div`,{class:`ui-tip__line`},this.dot,this.status,this.since),this.activity,this.mood),e.world.onHover(e=>this.setTarget(e))}setTarget(e){e!==this.id&&(this.id=e,this.el.classList.toggle(`is-visible`,!!e),cancelAnimationFrame(this.raf),e&&(this.render(),this.follow()))}follow=()=>{if(!this.id)return;let e=this.ctx.world.screenPositionOf(this.id);if(!e)this.el.classList.remove(`is-visible`);else{this.el.classList.add(`is-visible`);let t=this.el.offsetWidth,n=this.el.offsetHeight,r=Math.round(Math.min(innerWidth-t-8,Math.max(8,e.x-t/2))),i=e.y-n-10<72,a=Math.round(i?e.y+46:e.y-n-10);this.el.style.transform=`translate3d(${r}px, ${a}px, 0)`}this.raf=requestAnimationFrame(this.follow)};render(){if(!this.id)return;let e=this.ctx.agent(this.id);if(!e){this.setTarget(null);return}M(this.name,xt(e,this.ctx.store.snapshot?.machines)),bx(this.chip,this.ctx.account(e.account),e.account,e.provider),Sx(this.prov,Vb(e));let t=this.ctx.now(),n=lb(e,this.ctx.store.snapshot?.agents??[],t),r=n?`shell`:e.status;wx(this.dot,r),M(this.status,e.status===`waiting`&&e.waitingFor?`${Jy(e.status)}: ${e.waitingFor}`:`${Jy(r)}${e.kind===`sub`?` · ${e.role}`:``}`),vt(this.el,`is-`,r);let i=e.title?.trim();F(this.task,!i),i&&M(this.task,i);let o=t-e.statusSince;if(M(this.since,e.statusSince&&o>=6e4?a(`há {0}`,[zt(o)]):``),n?Mx(this.activity,n,t):jx(this.activity,e.activity),F(this.mood,!n),n){let e=vb(t-n.since);M(this.mood,`${e.emoji} ${e.text}`)}}},nE=[`alerts`,`keys`,`elevator`,`social`],rE={chime:`alerts`,siren:`alerts`,pop:`alerts`,keys:`keys`,elevator:`elevator`,pingpong:`social`,table:`social`,arcade:`social`},iE={chime:1200,siren:1e4,pop:1200,keys:600,elevator:1500,pingpong:200,table:200,arcade:450},aE={chime:`alerts`,siren:`siren`,pop:`alerts`,keys:`keys`,elevator:`elevator`,pingpong:`pingpong`,table:`pingpong`,arcade:`arcade`},oE={volume:.6,alerts:!0,keys:!0,elevator:!0,social:!0};function sE(e){let t=e&&typeof e==`object`?e:{},n=oE,r=(e,t)=>typeof e==`boolean`?e:t;return{volume:typeof t.volume==`number`&&Number.isFinite(t.volume)?Math.min(1,Math.max(0,t.volume)):n.volume,alerts:r(t.alerts,n.alerts),keys:r(t.keys,n.keys),elevator:r(t.elevator,n.elevator),social:r(t.social,n.social)}}function cE(e){let t=Math.min(1,Math.max(0,e));return t*t}var lE=class{enabled=!1;settings={...oE};last=new Map;recent=[];configure(e,t){this.enabled=e,this.settings=t}allowed(e){return this.enabled&&this.settings.volume>0&&this.settings[rE[e]]}decide(e,t,n={}){if(!this.allowed(e))return null;let r=e===`chime`||e===`siren`;if(n.hidden&&!r)return null;let i=aE[e],a=this.last.get(i);if(a!==void 0&&t-a<iE[e])return null;for(;this.recent.length&&t-this.recent[0]>=1e3;)this.recent.shift();if(!r&&this.recent.length>=7)return null;let o=cE(this.settings.volume)*Math.min(1,Math.max(0,n.gain??1));return o<=5e-4?null:(this.last.set(i,t),this.recent.push(t),o)}};function uE(e){if(e.level===`alert`)return e.id.startsWith(`intrusion:`)?`siren`:`chime`;if(e.level===`success`)return`pop`}var dE=6e4;function fE(e,t,n){return t!==`siren`&&t!==`chime`?[...e]:[...e.filter(e=>e.kind!==t),{kind:t,at:n}].sort((e,t)=>e.at-t.at)}function pE(e,t){let n=new Set(e.filter(e=>t-e.at<dE).map(e=>e.kind));return[`siren`,`chime`].filter(e=>n.has(e))}var mE=`Busybits`;function hE(){return typeof Notification>`u`?`unsupported`:Notification.permission}var gE=class{ctx;sounds;lastTitle=``;constructor(e,t){this.ctx=e,this.sounds=t,e.store.on(`notice`,e=>this.onNotice(e)),e.store.on(`inbox`,e=>{Es(e)&&this.sounds.play(`chime`)})}async enableBrowserNotifications(){let e=hE();if(e===`unsupported`||e===`denied`||e===`granted`)return e;try{return await Notification.requestPermission()}catch{return hE()}}render(){let e=ib(this.ctx.store.liveSnapshot).waiting,t=e>0?`(${e}) ${mE}`:mE;t!==this.lastTitle&&(this.lastTitle=t,document.title=t)}onNotice(e){let t=this.ctx.prefs,n=uE(e);if(n&&this.sounds.play(n),e.level===`alert`&&t.browserNotifications&&document.hidden&&hE()===`granted`)try{let t=new Notification(a(`Habblaud — precisa de você`),{body:e.text,tag:e.agentId??e.id,icon:`/assets/brand/favicon-32.png`});t.onclick=()=>{window.focus(),e.agentId&&this.ctx.agent(e.agentId)&&this.ctx.select({type:`agent`,id:e.agentId},{focus:!0}),t.close()}}catch{}}},_E=`habblaud:prefs`,vE={showNames:ue.showNames,bubbles:ue.bubbles,liveliness:ue.liveliness,daylight:`auto`,theme:`auto`,sound:!1,sounds:oE,browserNotifications:!1,sidebarOpen:!0,feedOpen:!0,sidebarView:`rooms`,hiddenAccounts:[],worldVisitNotify:!0,awayCoffeeMin:5,awayNapMin:20,fpsCap:60,pauseOnHidden:!0,pixelEmoji:!0},yE=(e,t,n)=>typeof e==`string`&&t.includes(e)?e:n,bE=(e,t)=>typeof e==`boolean`?e:t,xE={min:1,max:60},SE=(e,t,n,r)=>typeof e==`number`&&Number.isFinite(e)?Math.min(n,Math.max(t,Math.round(e))):r;function CE(e,t){let n=SE(e,xE.min,xE.max,vE.awayCoffeeMin);return{coffeeMin:n,napMin:SE(t,n+1,240,Math.max(vE.awayNapMin,n+1))}}function wE(e){let{coffeeMin:t,napMin:n}=CE(e.awayCoffeeMin,e.awayNapMin);return{coffeeMs:t*6e4,napMs:n*6e4}}function TE(e){let t=e&&typeof e==`object`?e:{},n=vE,r=CE(t.awayCoffeeMin,t.awayNapMin);return{showNames:bE(t.showNames,n.showNames),bubbles:yE(t.bubbles,[`all`,`important`,`none`],n.bubbles),liveliness:yE(t.liveliness,[`calm`,`normal`,`lively`],n.liveliness),daylight:yE(t.daylight,[`auto`,`day`,`night`],t.dayNight===!1?`day`:n.daylight),theme:yE(t.theme,[`auto`,`none`,`christmas`,`halloween`],n.theme),sound:bE(t.sound,n.sound),sounds:sE(t.sounds),browserNotifications:bE(t.browserNotifications,n.browserNotifications),sidebarOpen:bE(t.sidebarOpen,n.sidebarOpen),feedOpen:bE(t.feedOpen,n.feedOpen),sidebarView:yE(t.sidebarView,[`rooms`,`recent`],n.sidebarView),hiddenAccounts:Array.isArray(t.hiddenAccounts)?t.hiddenAccounts.filter(e=>typeof e==`string`).slice(0,20):[],worldVisitNotify:bE(t.worldVisitNotify,n.worldVisitNotify),awayCoffeeMin:r.coffeeMin,awayNapMin:r.napMin,fpsCap:[60,30,15,0].find(e=>e===t.fpsCap)??n.fpsCap,pauseOnHidden:bE(t.pauseOnHidden,n.pauseOnHidden),pixelEmoji:bE(t.pixelEmoji,n.pixelEmoji)}}function EE(e){if(!e)return{...vE};try{let t=e.getItem(_E);return TE(t?JSON.parse(t):null)}catch{return{...vE}}}function DE(e,t){if(e)try{e.setItem(_E,JSON.stringify(t))}catch{}}function OE(e){return{showNames:e.showNames,bubbles:e.bubbles,liveliness:e.liveliness,dayNight:e.daylight!==`day`,daylight:e.daylight,theme:e.theme,fpsCap:e.fpsCap,pauseOnHidden:e.pauseOnHidden}}function kE(){try{return typeof localStorage>`u`?null:localStorage}catch{return null}}var AE=`codetown`,jE=[`${AE}:`,`${AE}.`],ME=`habblaud`;function NE(e){if(!e)return 0;let t=[];try{for(let n=0;n<e.length;n++){let r=e.key(n);r&&jE.some(e=>r.startsWith(e))&&t.push(r)}}catch{return 0}let n=0;for(let r of t)try{let t=e.getItem(r),i=ME+r.slice(8);t!==null&&e.getItem(i)===null&&(e.setItem(i,t),n++),e.removeItem(r)}catch{}return n}var PE=1e4,FE=`never`;function IE(e){return{retentionDays:e===FE?null:Number(e)}}function LE(){return[[`1`,a(`1 dia`)],[`3`,a(`3 dias`)],[`7`,a(`7 dias (padrão)`)],[`30`,a(`30 dias`)],[FE,a(`Nunca apagar`)]]}var RE=class{ctx;el;select;error;saved=null;loading=!1;saving=!1;failedAt=0;constructor(e){this.ctx=e,this.select=new zv({label:a(`Apagar anexos salvos depois de`),className:`ui-day__select`,options:LE().map(([e,t])=>({value:e,label:t})),onChange:()=>void this.save()}),this.error=P(`p`,{class:`ui-char__error`,role:`alert`,hidden:!0}),this.el=P(`div`,{class:`ui-set-group ui-att-set`,hidden:!0},P(`h3`,{text:a(`Anexos salvos`)}),P(`label`,{class:`ui-set ui-set--stack`},P(`span`,{class:`ui-set__label`,text:a(`Apagar depois de`)}),this.select.el,P(`span`,{class:`ui-set__hint`,text:a(`Imagens e arquivos enviados pelo escritório ficam em ~/.habblaud/attachments/. As pastas mais velhas que o prazo são apagadas ao iniciar e a cada hora.`)})),this.error)}render(){let e=this.ctx.store,t=!e.mock&&!e.replaying;if(t&&!this.saved&&!this.loading&&Date.now()-this.failedAt>=PE&&this.load(),F(this.el,!t||!this.saved),this.select.disabled=!I().local||this.saving,this.saved&&!this.saving){let e=this.saved.retentionDays===null?FE:String(this.saved.retentionDays),t=LE().find(([t])=>t===e)?.[0];t&&(this.select.value=t)}}async load(){this.loading=!0;let e=await this.ctx.store.loadAttachmentSettings();this.loading=!1,e?this.saved=e:this.failedAt=Date.now(),this.ctx.invalidate()}async save(){if(this.saving)return;let e=this.select.value;if(!e)return;let t=IE(e);this.saving=!0,F(this.error,!0);let n=await this.ctx.store.saveAttachmentSettings(t);this.saving=!1,n?(M(this.error,n),F(this.error,!1)):this.saved=t,this.ctx.invalidate()}};function zE(e,t){return e.map(e=>{let n=e.state===`online`,r=n?a(`online`):e.lastSeenAt>0?a(`offline {0}`,[Nt(e.lastSeenAt,t)]):a(`offline`);return{id:e.id,label:ft(e.label),stateText:r,online:n,canRevoke:!0}}).sort((e,t)=>e.label.localeCompare(t.label)||e.id.localeCompare(t.id))}function BE(e,t){let n=e-t;return{text:Ht(Math.max(0,n)),expired:n<=0}}function VE(e){switch(e.status){case`up`:return{state:a(`Conectada`),hint:a(`Esta máquina aparece no escritório da central {0} como "{1}".`,[e.url,ft(e.label)])};case`down`:return{state:a(`Sem conexão`),hint:a(`A central {0} não responde agora. Esta máquina tenta de novo sozinha.`,[e.url])};case`revoked`:return{state:a(`Pareamento revogado`),hint:a(`A central não reconhece mais esta máquina. Gere um código novo nas Configurações da central, rode npm run satellite:pair e cole o texto.`)};default:return{state:a(`Não pareada`),hint:a(`Gere um código nas Configurações da central, rode npm run satellite:pair e cole o texto de pareamento. Depois reinicie o servidor.`)}}}var HE=`npm run satellite:pair`;function UE(e,t){return e.state===`online`?a(`online`):e.lastSeenAt>0?a(`offline {0}`,[Nt(e.lastSeenAt,t)]):a(`offline`)}function WE(e,t){return e?.length?[...e].sort((e,t)=>e.label.localeCompare(t.label)||e.id.localeCompare(t.id)).map(e=>({label:ft(e.label),online:e.state===`online`,title:`${ft(e.label)}: ${UE(e,t)}`})):[]}var GE=5e3,KE=5e3,qE=class{ctx;el;centralGroup;satelliteGroup;genBtn;pairBox;pairText;copyBtn;countdown;fingerprint;list;empty;error;satState;satHint;machines=null;link=null;pairing=null;confirming=null;open=!1;busy=!1;refreshTimer;clockTimer;confirmTimer;shownKey=``;constructor(e){this.ctx=e,this.genBtn=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Gerar código de pareamento`),on:{click:()=>void this.generate()}}),this.pairText=P(`code`,{class:`ui-mach__code`,attrs:{"aria-label":a(`Texto de pareamento`)}}),this.copyBtn=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Copiar`),on:{click:()=>void this.copy()}}),this.countdown=P(`span`,{class:`ui-set__hint`}),this.fingerprint=P(`span`,{class:`ui-set__hint ui-mach__fp`}),this.pairBox=P(`div`,{class:`ui-mach__pair`,hidden:!0},P(`span`,{class:`ui-set__label`,text:a(`Texto de pareamento`)}),this.pairText,P(`div`,{class:`ui-mach__row`},this.copyBtn,this.countdown),P(`span`,{class:`ui-set__hint`,text:a(`Na outra máquina, rode {0} e cole este texto (ele é lido pela entrada padrão, nunca vai na linha de comando). Aparece só aqui e vale uma vez.`,[HE])}),this.fingerprint),this.list=P(`ul`,{class:`ui-mach__list`}),this.empty=P(`p`,{class:`ui-set__hint`,text:a(`Nenhuma máquina pareada ainda.`)}),this.error=P(`p`,{class:`ui-char__error`,role:`alert`,hidden:!0}),this.centralGroup=P(`div`,{class:`ui-set-group ui-mach-set`,hidden:!0},P(`h3`,{text:a(`Máquinas`)}),P(`div`,{class:`ui-set ui-set--stack`},P(`span`,{class:`ui-set__hint`,text:a(`Outras máquinas mandam o escritório delas para esta central. Gere um código e pareie cada uma; "Revogar" tira a máquina na hora.`)}),this.genBtn),this.pairBox,this.list,this.empty,this.error),this.satState=P(`span`,{class:`ui-set__label`}),this.satHint=P(`span`,{class:`ui-set__hint`}),this.satelliteGroup=P(`div`,{class:`ui-set-group ui-mach-set`,hidden:!0},P(`h3`,{text:a(`Link com a central`)}),P(`div`,{class:`ui-set__text ui-mach__sat`},this.satState,this.satHint)),this.el=P(`div`,{class:`ui-mach-root`},this.centralGroup,this.satelliteGroup)}setOpen(e){this.open=e,e?(this.refresh(),this.refreshTimer??=setInterval(()=>void this.refresh(),GE)):(this.refreshTimer&&clearInterval(this.refreshTimer),this.refreshTimer=void 0,this.clearPairing(),this.confirming=null,this.render())}render(){let e=this.ctx.store,t=!e.mock&&!e.replaying,n=I(),r=t&&!!n.central,i=t&&!!n.satellite;if(F(this.centralGroup,!r),F(this.satelliteGroup,!i),r&&this.renderCentral(),i&&this.link){let e=VE(this.link);M(this.satState,e.state),M(this.satHint,e.hint)}F(this.satelliteGroup,!i||!this.link)}renderCentral(){let e=Date.now(),t=zE(this.machines??[],e),n=JSON.stringify([t.map(e=>[e.id,e.label,e.stateText]),this.confirming,this.busy]);n!==this.shownKey&&(this.shownKey=n,this.list.replaceChildren(...t.map(e=>this.row(e)))),F(this.empty,t.length>0||this.machines===null),this.genBtn.disabled=this.busy,F(this.pairBox,!this.pairing)}row(e){let t=this.confirming===e.id,n=P(`button`,{class:`ui-btn ui-btn--sm ui-btn--danger${t?` is-confirm`:``}`,type:`button`,text:a(t?`Confirmar revogação`:`Revogar`),attrs:{"aria-label":a(t?`Confirmar a revogação de {0}`:`Revogar {0}`,[e.label])},on:{click:()=>void this.revoke(e.id)}});return n.disabled=this.busy,P(`li`,{class:`ui-mach__item`},P(`div`,{class:`ui-set__text`},P(`span`,{class:`ui-set__label`,text:e.label}),P(`span`,{class:`ui-set__hint ui-mach__state${e.online?` is-online`:``}`,text:e.stateText})),n)}async refresh(){if(!this.open)return;let e=I();if(e.central){let e=await this.ctx.store.loadMachines();e&&(this.machines=e)}if(e.satellite){let e=await this.ctx.store.loadSatelliteLink();e&&(this.link=e)}this.open&&this.ctx.invalidate()}async generate(){if(this.busy)return;this.busy=!0,this.showError(void 0);let e=await this.ctx.store.createPairing();this.busy=!1,`error`in e?this.showError(e.error):this.open&&(this.pairing={pairing:e.pairing,expiresAt:e.expiresAt},this.pairText.textContent=e.pairing,M(this.fingerprint,a(`Impressão digital da CA: {0}`,[e.fingerprint])),M(this.copyBtn,a(`Copiar`)),this.tickClock(),this.clockTimer??=setInterval(()=>this.tickClock(),1e3)),this.ctx.invalidate()}tickClock(){if(!this.pairing)return;let e=BE(this.pairing.expiresAt,Date.now());e.expired?(this.clearPairing(),this.showError(a(`O código venceu. Gere um novo.`)),this.ctx.invalidate()):M(this.countdown,a(`Vale por {0}`,[e.text]))}clearPairing(){this.pairing=null,this.pairText.textContent=``,M(this.fingerprint,``),this.clockTimer&&clearInterval(this.clockTimer),this.clockTimer=void 0,F(this.pairBox,!0)}async copy(){if(!this.pairing)return;let e=await St(this.pairing.pairing);M(this.copyBtn,a(e?`Copiado`:`Copiar`)),e||this.showError(a(`Não deu para copiar: selecione o texto e copie à mão.`))}async revoke(e){if(this.busy)return;if(this.confirming!==e){this.confirming=e,this.confirmTimer&&clearTimeout(this.confirmTimer),this.confirmTimer=setTimeout(()=>{this.confirming===e&&(this.confirming=null,this.ctx.invalidate())},KE),this.ctx.invalidate();return}this.confirmTimer&&clearTimeout(this.confirmTimer),this.confirming=null,this.busy=!0,this.showError(void 0),this.ctx.invalidate();let t=await this.ctx.store.revokeMachine(e);this.busy=!1,t?this.showError(t):this.machines&&=this.machines.filter(t=>t.id!==e),await this.refresh(),this.ctx.invalidate()}showError(e){e&&M(this.error,e),F(this.error,!e)}},JE=1e4;function YE(){return crypto.getRandomValues(new Uint32Array(1))[0]}var XE=class{ctx;el;editor;fields=new Wv(()=>this.dirty=!0);nameInput;coffeeInput;napInput;note;loadFail;error;saveBtn;rollBtn;resetBtn;saved=null;seed=0;body=`f`;base=null;dirty=!1;busy=!1;loading=!1;failedAt=0;retryTimer=null;confirmingReset=!1;constructor(e){this.ctx=e,this.nameInput=P(`input`,{class:`ui-char__name ui-avatar-set__name`,type:`text`,attrs:{maxlength:24,autocomplete:`off`,spellcheck:`false`,"aria-label":a(`Nome`)}}),this.nameInput.addEventListener(`input`,()=>this.dirty=!0),this.rollBtn=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Sortear`),title:a(`Sortear outra aparência (desfaz as peças escolhidas)`),on:{click:()=>this.roll()}}),this.note=P(`p`,{class:`ui-set__hint ui-avatar-set__note`,hidden:!0,text:a(`Só o próprio computador edita o avatar: aqui você vê o visual atual.`)}),this.loadFail=P(`p`,{class:`ui-set__hint ui-avatar-set__load-fail`,hidden:!0,role:`status`,text:a(`Não foi possível carregar o avatar. Vamos tentar de novo em instantes.`)}),this.error=P(`p`,{class:`ui-char__error`,role:`alert`,hidden:!0}),this.saveBtn=P(`button`,{class:`ui-btn ui-btn--primary`,type:`button`,text:a(`Salvar`),on:{click:()=>void this.save()}}),this.resetBtn=P(`button`,{class:`ui-link-btn ui-char__reset`,type:`button`,text:a(`Voltar ao sorteio`),on:{click:()=>void this.reset()}}),this.editor=P(`div`,{class:`ui-avatar-set__editor`,hidden:!0},P(`div`,{class:`ui-char__top`},this.fields.preview,P(`div`,{class:`ui-char__head`},P(`div`,{class:`ui-char__label`},this.nameInput),this.rollBtn)),this.note,this.fields.groups,this.error,P(`div`,{class:`ui-char__actions`},this.saveBtn,this.resetBtn)),this.coffeeInput=this.numberInput(`ui-avatar-set__coffee`,xE.min,xE.max),this.napInput=this.numberInput(`ui-avatar-set__nap`,xE.min+1,240),this.el=P(`div`,{class:`ui-set-group ui-avatar-set`},P(`h3`,{text:a(`Meu avatar`)}),this.loadFail,this.editor,this.awayRow(a(`Café depois de (min)`),a(`Minutos parado até o avatar ir tomar um café (1 a 60).`),this.coffeeInput),this.awayRow(a(`Cochilo depois de (min)`),a(`Minutos parado até o avatar tirar um cochilo (maior que o do café, até 240).`),this.napInput)),e.store.on(`avatar`,e=>this.adopt(e))}render(){let e=this.ctx.store,t=!e.mock&&!e.replaying,n=t&&I().local;t&&!this.saved&&!this.loading&&Date.now()-this.failedAt>=JE&&this.load(),F(this.editor,!t||!this.saved),F(this.loadFail,!t||!!this.saved||this.loading),F(this.note,n);for(let e of[this.saveBtn,this.rollBtn])F(e,!n);F(this.fields.groups,!n),this.nameInput.disabled=!n,F(this.resetBtn,!n||!this.hasCustomLook());let r=this.ctx.prefs;this.setNumber(this.coffeeInput,r.awayCoffeeMin),this.setNumber(this.napInput,r.awayNapMin)}numberInput(e,t,n){let r=P(`input`,{class:`ui-char__name ${e}`,type:`number`,attrs:{min:t,max:n,step:1,inputmode:`numeric`}});return r.addEventListener(`change`,()=>this.onAwayChange()),r}awayRow(e,t,n){return P(`label`,{class:`ui-set ui-set--stack`},P(`span`,{class:`ui-set__label`,text:e}),n,P(`span`,{class:`ui-set__hint`,text:t}))}setNumber(e,t){let n=String(t);e.value!==n&&(e.value=n)}onAwayChange(){let{coffeeMin:e,napMin:t}=CE(parseFloat(this.coffeeInput.value),parseFloat(this.napInput.value));this.setNumber(this.coffeeInput,e),this.setNumber(this.napInput,t),this.ctx.updatePrefs({awayCoffeeMin:e,awayNapMin:t})}hasCustomLook(){return!!this.saved&&!!this.saved.parts&&Object.keys(this.saved.parts).length>0}async load(){this.loading=!0;let e=await this.ctx.store.loadAvatar();this.loading=!1,e?this.saved||this.adopt(e):(this.failedAt=Date.now(),this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.ctx.invalidate()},JE)),this.ctx.invalidate()}adopt(e){this.saved=e,this.dirty||this.loadDraft(e),this.ctx.invalidate()}loadDraft(e){this.seed=e.seed,this.body=e.look,this.base=rs(e.seed,{look:e.look}),this.nameInput.value=e.name,this.confirmingReset=!1,M(this.resetBtn,a(`Voltar ao sorteio`)),this.fields.set({...this.base,...e.parts}),this.dirty=!1}roll(){this.seed=YE(),this.base=rs(this.seed,{look:this.body}),this.fields.set({...this.base}),this.dirty=!0}async save(){let e=this.fields.value;if(this.busy||!this.base||!e||!I().local)return;let t=this.nameInput.value.trim();if(!t)return this.showError(a(`Dê um nome ao personagem.`));let n={name:t,look:this.body,seed:this.seed,parts:wv(this.base,e)};if(this.saved&&this.sameLook(this.saved,n))return this.showError(null);this.busy=!0,this.saveBtn.disabled=!0;let r=n,i=await this.ctx.store.saveAvatar(r);if(this.busy=!1,this.saveBtn.disabled=!1,i)return this.showError(i);this.showError(null),this.saved=r,this.dirty=!1,this.ctx.announce(a(`Avatar salvo: {0}.`,[t])),this.ctx.invalidate()}sameLook(e,t){return e.name===t.name&&e.look===t.look&&e.seed===t.seed&&k({...e.parts})===k({...t.parts})}async reset(){if(this.busy||!I().local)return;if(!this.confirmingReset){this.confirmingReset=!0,M(this.resetBtn,a(`Confirmar: voltar ao sorteio`));return}this.busy=!0;let e=await this.ctx.store.resetAvatar();if(this.busy=!1,this.confirmingReset=!1,M(this.resetBtn,a(`Voltar ao sorteio`)),e)return this.showError(e);this.showError(null),this.saved&&this.loadDraft(this.saved),this.dirty=!1,this.ctx.announce(a(`O avatar voltou ao sorteio.`))}showError(e){M(this.error,e??``),F(this.error,!e)}},ZE=[{seed:42,look:`f`},{seed:107,look:`m`},{seed:333,look:`f`,sub:!0},{seed:777,look:`m`},{seed:999,look:`f`}],QE=2,$E=`ui-default-look-confirm-title`,eD=class{ctx;el;preview;groups;note;error;saveBtn;applyAllBtn;resetBtn;confirmDialog;saved=null;draftParts={};dirty=!1;busy=!1;constructor(e){this.ctx=e,this.preview=P(`canvas`,{class:`ui-char__preview ui-default-look__preview`,role:`img`,attrs:{"aria-label":a(`Prévia do estilo padrão`)}}),this.groups=P(`div`,{class:`ui-char__groups`}),this.note=P(`p`,{class:`ui-set__hint ui-default-look__note`,hidden:!0,text:a(`Só o próprio computador edita o estilo padrão: aqui você vê o visual atual.`)}),this.error=P(`p`,{class:`ui-char__error`,role:`alert`,hidden:!0}),this.saveBtn=P(`button`,{class:`ui-btn ui-btn--primary`,type:`button`,text:a(`Salvar`),on:{click:()=>void this.save({applyToAll:!1})}}),this.applyAllBtn=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Aplicar a todos`),on:{click:()=>this.openConfirmDialog()}}),this.resetBtn=P(`button`,{class:`ui-link-btn ui-char__reset`,type:`button`,text:a(`Restaurar`),on:{click:()=>void this.reset()}});let t=P(`button`,{class:`ui-btn ui-btn--primary`,type:`button`,text:a(`Aplicar a todos`),on:{click:()=>{this.closeConfirmDialog(),this.save({applyToAll:!0})}}}),n=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Cancelar`),on:{click:()=>this.closeConfirmDialog()}}),r=j(Q.close,a(`Fechar`),()=>this.closeConfirmDialog(),`ui-icon-btn--sm`);this.confirmDialog=P(`dialog`,{class:`ui-dialog ui-confirm-dialog`,attrs:{"aria-labelledby":$E}},P(`div`,{class:`ui-dialog__head`},P(`h2`,{attrs:{id:$E},text:a(`Aplicar estilo a todos os agentes?`)}),r),P(`div`,{class:`ui-dialog__body`,style:`display: block;`},P(`p`,{text:a(`Esta ação vai aplicar as peças definidas a todos os agentes existentes no escritório. Agentes personalizados à mão não serão alterados.`)})),P(`div`,{class:`ui-char__actions`,style:`padding: 16px 22px;`},t,n)),this.el=P(`div`,{class:`ui-set-group ui-default-look-set`},P(`h3`,{text:a(`Personagens`)}),P(`span`,{class:`ui-set__label`,text:a(`Estilo padrão`)}),P(`p`,{class:`ui-set__hint`,text:a(`Define a aparência padrão para novos agentes. Peças em "Aleatório" continuam variando por agente.`)}),this.note,P(`div`,{class:`ui-char__top`,style:`justify-content: center; margin-bottom: 12px;`},this.preview),this.groups,this.error,P(`div`,{class:`ui-char__actions`},this.saveBtn,this.applyAllBtn,this.resetBtn),this.confirmDialog),e.store.on(`defaultLook`,e=>this.adopt(e))}render(){let e=this.ctx.store,t=!e.mock&&!e.replaying&&I().local,n=e.defaultLook;(!this.saved||!this.dirty&&!this.busy)&&this.adopt(n,!1),F(this.note,t);for(let e of[this.saveBtn,this.applyAllBtn])F(e,!t);F(this.resetBtn,!t||!this.hasAnyFixedPart()),this.paint()}hasAnyFixedPart(){return Object.keys(this.draftParts).some(e=>this.draftParts[e]!==void 0)}pick(e,t){t===``?delete this.draftParts[e]:this.draftParts={...this.draftParts,[e]:t};let n=rs(1,{defaultParts:this.draftParts}),r=re(n);this.draftParts.top&&this.draftParts.top!==r.top&&(this.draftParts.top=r.top),this.draftParts.topAccent&&this.draftParts.topAccent!==r.topAccent&&(this.draftParts.topAccent=r.topAccent),this.draftParts.accessoryColor&&this.draftParts.accessoryColor!==r.accessoryColor&&(this.draftParts.accessoryColor=r.accessoryColor),!this.draftParts.face||this.draftParts.face===`none`?delete this.draftParts.faceColor:this.draftParts.faceColor!==r.faceColor&&r.faceColor&&(this.draftParts.faceColor=r.faceColor),this.dirty=!0,this.paint(e)}paint(e){this.drawPreview();let t=rs(1,{defaultParts:this.draftParts}),n=Te(t),r=new Set(kv),i=[];for(let e of Tv){let a=e.rows.filter(e=>r.has(e.key)&&Ov(e,t));a.length&&i.push(P(`fieldset`,{class:`ui-char__group`},P(`legend`,{text:e.title}),...a.map(r=>this.row(e.title,r,t,n[r.key]))))}this.groups.replaceChildren(...i),e&&this.groups.querySelector(`[data-key="${e}"] [aria-checked="true"]`)?.focus()}row(e,t,n,r){let i=this.draftParts[t.key]??``,o=t.kind===`color`,s=[{value:``,label:a(`Aleatório`),className:`ui-char__chip`,title:a(`Aleatório`)},...r.map(e=>{let r=b(n,t.key,e),i=o?e:Dv(t.key,e);return{value:e,label:i,className:o?`ui-char__swatch`:`ui-char__chip`,title:r??i,style:o?`--swatch: ${e}`:void 0,ariaLabel:o?e:void 0,content:o?P(`span`,{attrs:{"aria-hidden":`true`}}):void 0,disabled:!!r}})],c=new Bv({label:`${e}: ${t.label}`,options:s,value:i,indicator:!1,className:`ui-char__opts ui-char__opts--${t.kind}`,onChange:e=>this.pick(t.key,e)});return c.el.setAttribute(`data-key`,t.key),P(`div`,{class:`ui-char__row`},P(`span`,{class:`ui-char__row-label`,text:t.label}),c.el)}drawPreview(){try{let e=ZE.map(e=>ss({appearance:rs(e.seed,{look:e.look,sub:e.sub,defaultParts:this.draftParts}),dir:`down`,pose:`stand`,frame:0})),t=this.preview,n=e[0]?.canvas?.width??16,r=e[0]?.canvas?.height??24,i=e.length*(n*QE)+(e.length-1)*8,a=r*QE;t.width=i,t.height=a;let o=t.getContext(`2d`);if(!o)return;o.imageSmoothingEnabled=!1,o.clearRect(0,0,i,a);for(let t=0;t<e.length;t++){let r=t*(n*QE+8);e[t]?.canvas&&o.drawImage(e[t].canvas,r,0,n*QE,a)}}catch{}}adopt(e,t=!0){this.saved=e,this.dirty||(this.draftParts={...e.parts}),t&&this.ctx.invalidate()}async save(e={}){if(this.busy||!I().local)return;this.busy=!0,this.saveBtn.disabled=!0,this.applyAllBtn.disabled=!0,this.resetBtn.disabled=!0;let t={parts:{...this.draftParts},applyToAll:e.applyToAll??!1},n=await this.ctx.store.saveDefaultLook(t);if(this.busy=!1,this.saveBtn.disabled=!1,this.applyAllBtn.disabled=!1,this.resetBtn.disabled=!1,n)return this.showError(n);this.showError(null),this.dirty=!1,e.applyToAll?this.ctx.announce(a(`Estilo padrão aplicado a todos os agentes.`)):this.ctx.announce(a(`Estilo padrão salvo para novos agentes.`)),this.render()}async reset(){if(this.busy||!I().local)return;this.busy=!0,this.saveBtn.disabled=!0,this.applyAllBtn.disabled=!0,this.resetBtn.disabled=!0;let e=await this.ctx.store.resetDefaultLook();if(this.busy=!1,this.saveBtn.disabled=!1,this.applyAllBtn.disabled=!1,this.resetBtn.disabled=!1,e)return this.showError(e);this.showError(null),this.draftParts={},this.dirty=!1,this.ctx.announce(a(`Estilo padrão restaurado para aleatório.`)),this.render()}openConfirmDialog(){typeof this.confirmDialog.showModal==`function`?this.confirmDialog.open||this.confirmDialog.showModal():this.confirmDialog.setAttribute(`open`,``)}closeConfirmDialog(){typeof this.confirmDialog.close==`function`?this.confirmDialog.close():this.confirmDialog.removeAttribute(`open`)}showError(e){M(this.error,e??``),F(this.error,!e)}},tD={alerts:{label:a(`Avisos`),hint:a(`Sino quando alguém precisa de você; estalo quando uma tarefa termina.`),sample:`chime`},keys:{label:a(`Teclado`),hint:a(`Digitação baixinha de quem trabalha nas salas à vista.`),sample:`keys`},elevator:{label:a(`Elevador`),hint:a(`"Ding" quando alguém chega ou vai embora.`),sample:`elevator`},social:{label:a(`Rodas`),hint:a(`Pingue-pongue e fliperama no lounge.`),sample:`pingpong`}},nD=class{ctx;sound;el;master;volume;volumeOut;chips=new Map;details;constructor(e,t){this.ctx=e,this.sound=t;let n=`ui-snd-master`;this.master=P(`button`,{class:`ui-switch`,type:`button`,role:`switch`,attrs:{"aria-checked":`false`,"aria-labelledby":n}},P(`span`,{class:`ui-switch__knob`})),this.master.addEventListener(`click`,()=>{let t=!e.prefs.sound;e.updatePrefs({sound:t}),t&&this.sound.preview(`pop`)}),this.volume=P(`input`,{class:`ui-snd__range`,type:`range`,attrs:{min:0,max:100,step:5,"aria-label":a(`Volume dos sons`)}}),this.volume.addEventListener(`input`,()=>{e.updatePrefs({sounds:{...e.prefs.sounds,volume:Number(this.volume.value)/100}}),M(this.volumeOut,`${this.volume.value}%`)}),this.volume.addEventListener(`change`,()=>this.sound.preview(`pop`)),this.volumeOut=P(`span`,{class:`ui-snd__value`,attrs:{"aria-hidden":`true`}});let r=P(`div`,{class:`ui-snd__chips`,role:`group`,attrs:{"aria-label":a(`Categorias de som`)}});for(let t of nE){let n=tD[t],i=P(`button`,{class:`ui-snd__chip`,type:`button`,text:n.label,title:n.hint,attrs:{"aria-pressed":`true`}});i.addEventListener(`click`,()=>{let r=!e.prefs.sounds[t];e.updatePrefs({sounds:{...e.prefs.sounds,[t]:r}}),r&&this.sound.preview(n.sample)}),this.chips.set(t,i),r.append(i)}this.details=P(`div`,{class:`ui-snd__details`},P(`div`,{class:`ui-set ui-snd__vol`},P(`span`,{class:`ui-set__label`,text:a(`Volume`)}),this.volume,this.volumeOut),P(`div`,{class:`ui-set ui-set--stack`},P(`span`,{class:`ui-set__label`,text:a(`Tocar`)}),r,P(`span`,{class:`ui-set__hint`,text:a(`Avisos: sino e estalo · Teclado: quem digita nas salas à vista · Elevador: chegadas e saídas · Rodas: pingue-pongue e fliperama.`)}))),this.el=P(`div`,{class:`ui-set-group ui-snd`},P(`h3`,{text:a(`Sons`)}),P(`div`,{class:`ui-set`},P(`div`,{class:`ui-set__text`},P(`span`,{class:`ui-set__label`,text:a(`Sons do escritório`),attrs:{id:n}}),P(`span`,{class:`ui-set__hint`,text:a(`Sintetizados no navegador e baixinhos. Com a aba oculta, só o sino de "precisa de você".`)})),this.master),this.details)}render(){let e=this.ctx.prefs;N(this.master,`aria-checked`,String(e.sound));let t=String(Math.round(e.sounds.volume*100));document.activeElement!==this.volume&&this.volume.value!==t&&(this.volume.value=t),M(this.volumeOut,`${this.volume.value}%`),this.volume.disabled=!e.sound;for(let[t,n]of this.chips)N(n,`aria-pressed`,String(e.sounds[t])),n.disabled=!e.sound;this.details.classList.toggle(`is-off`,!e.sound)}},rD=`habblaud:update-seen`,iD={up:Z([`...##...`,`..####..`,`.######.`,`########`,`..####..`,`..####..`,`..####..`,`..####..`])};function aD(e){let t=e?.meta.version;return!t||!/^\d+\.\d+\.\d+/.test(t)?null:{version:t,updates:e.meta.updates}}function oD(e){return e===`packaged`?[]:e===`docker`?[a(`Para atualizar, na pasta do Habblaud: `),{code:`git pull`},a(` e de novo `),{code:`npm run docker:up`},`.`]:[a(`Para atualizar, na pasta do Habblaud: `),{code:`git pull`},a(` e de novo `),{code:`npm run setup`},`.`]}function sD(e){return e&&/^(https:\/\/www\.npmjs\.com\/package\/|https:\/\/github\.com\/)[^\s"'<>]+$/.test(e)?e:void 0}function cD(e,t,n){return t?.meta.version!==e.version||t?.meta.startedAt!==e.startedAt||n-e.at>=18e4}function lD(e,t,n){if(!t)return{tone:`off`,text:a(`Este servidor não verifica versões novas.`)};let r=t.checkedAt?` · verificado ${Nt(t.checkedAt,n)}`:``;switch(t.state){case`off`:return{tone:`off`,text:t.package?a(`Verificação de versão nova no npm desligada (padrão no clone e no Docker; HABBLAUD_UPDATE_CHECK=1 liga).`):a(`Verificação de versão nova no npm desligada.`)};case`pending`:return{tone:`pending`,text:a(`Verificando se há versão nova…`)};case`error`:return t.available&&t.latest?{tone:`new`,text:a(`Nova versão disponível: v{0}. A última verificação falhou ({1}).`,[t.latest,t.error??a(`erro`)])}:{tone:`warn`,text:a(`Não deu para verificar agora: {0}{1}.`,[t.error??a(`erro desconhecido`),t.checkedAt?a(` · última verificação {0}`,[Nt(t.checkedAt,n)]):``])};case`ok`:return t.available&&t.latest?{tone:`new`,text:a(`Nova versão disponível: v{0}{1}.`,[t.latest,t.publishedAt?a(`, publicada em {0}`,[kt(t.publishedAt)]):``])}:t.latest?t.latest===e?{tone:`ok`,text:a(`Você está na versão mais recente{0}.`,[r])}:{tone:`ok`,text:a(`Você está à frente da última versão publicada (v{0}){1}.`,[t.latest,r])}:{tone:`ok`,text:a(`Nenhuma versão publicada no npm ainda{0}.`,[r])}}}function uD(e,t,n){return t?.available&&t.latest?a(`Nova versão do Habblaud: v{0} (você usa a v{1}). Clique para ver as novidades e como atualizar.`,[t.latest,e]):a(`Habblaud v{0}. {1} Clique para ver detalhes.`,[e,lD(e,t,n).text])}var dD=class{ctx;settingsBtn;el;text;constructor(e,t){this.ctx=e,this.settingsBtn=t;let n=P(`span`,{class:`ui-version__icon`,attrs:{"aria-hidden":`true`}});n.innerHTML=iD.up,this.text=P(`span`,{class:`ui-version__text`}),this.el=P(`button`,{class:`ui-version`,type:`button`,hidden:!0,on:{click:()=>e.openAbout()}},n,this.text)}render(){let e=aD(this.ctx.store.liveSnapshot);F(this.el,!e);let t=!!e?.updates?.available&&!!e.updates.latest;this.settingsBtn.classList.toggle(`has-update`,t);let n=a(t?`Configurações (nova versão disponível)`:`Configurações`);if(N(this.settingsBtn,`aria-label`,n),A(this.settingsBtn,n),!e)return;this.el.classList.toggle(`is-new`,t),M(this.text,t?a(`Nova versão`):`v${e.version}`);let r=uD(e.version,e.updates,this.ctx.now());A(this.el,r),N(this.el,`aria-label`,r)}},fD=class{ctx;push;constructor(e,t){this.ctx=e,this.push=t}shown;render(){if(this.ctx.store.connection!==`open`)return;let e=aD(this.ctx.store.liveSnapshot)?.updates;if(!e?.available||!e.latest||this.shown===e.latest)return;this.shown=e.latest;let t=kE();try{if(t?.getItem(`habblaud:update-seen`)===e.latest)return;t?.setItem(rD,e.latest)}catch{}this.push({id:`update:${e.latest}`,level:`success`,text:a(`Nova versão do Busybits: v{0}. Atualize em Configurações › Sobre.`,[e.latest]),at:this.ctx.now()})}},pD=class{ctx;el;name;status;checkBtn;fresh;notes;checking=!1;failure;hint=P(`p`,{class:`ui-set__hint`});updateBtn;updating=!1;updatingFrom;applyError;constructor(e){this.ctx=e,this.name=P(`strong`,{class:`ui-about__version`}),this.checkBtn=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Verificar agora`),on:{click:()=>void this.check()}}),this.status=P(`p`,{class:`ui-about__status`,role:`status`}),this.notes=P(`a`,{class:`ui-link-btn`,attrs:{target:`_blank`,rel:`noopener noreferrer`}}),this.updateBtn=P(`button`,{class:`ui-btn ui-btn--primary`,type:`button`,text:a(`Atualizar agora`),hidden:!0,on:{click:()=>void this.apply()}}),this.fresh=P(`div`,{class:`ui-about__new`,hidden:!0},this.notes,this.updateBtn,this.hint),this.el=P(`div`,{class:`ui-set-group ui-about`,attrs:{id:`ui-about`}},P(`h3`,{text:a(`Sobre`),tabIndex:-1}),P(`div`,{class:`ui-about__head`},P(`span`,{class:`ui-about__name`},`Busybits `,this.name),this.checkBtn),this.status,this.fresh)}render(){let e=aD(this.ctx.store.liveSnapshot);if(F(this.el,!e),!e)return;this.updating&&this.updatingFrom&&cD(this.updatingFrom,this.ctx.store.liveSnapshot,this.ctx.now())&&(this.updating=!1,this.updatingFrom=void 0);let t=e.updates;M(this.name,`v${e.version}`);let n=this.failure?{tone:`warn`,text:this.failure}:lD(e.version,t,this.ctx.now());M(this.status,this.checking?a(`Consultando o npm…`):n.text),vt(this.status,`is-`,this.checking?`pending`:n.tone),F(this.checkBtn,!t||t.state===`off`),this.checkBtn.disabled=this.checking||this.ctx.store.connection!==`open`;let r=!!t?.available&&!!t.latest;if(F(this.fresh,!r),r){M(this.notes,a(`Ver o que mudou na v{0}`,[t.latest]));let e=sD(t.url);F(this.notes,!e),e&&N(this.notes,`href`,e);let n=this.ctx.store.liveSnapshot?.meta.install===`packaged`;F(this.updateBtn,!n||this.updating),this.updateBtn.disabled=this.ctx.store.connection!==`open`;let r=oD(this.ctx.store.liveSnapshot?.meta.install);F(this.hint,!r.length),this.hint.replaceChildren(...r.map(e=>typeof e==`string`?document.createTextNode(e):P(`code`,{class:`ui-usage-setup__cmd`,text:e.code}))),this.updating?M(this.status,a(`Atualizando para a v{0}… o Busybits vai reiniciar sozinho.`,[t.latest])):this.applyError&&M(this.status,this.applyError)}}highlight(){this.el.scrollIntoView({block:`nearest`}),this.el.classList.remove(`is-highlight`),this.el.offsetWidth,this.el.classList.add(`is-highlight`)}async apply(){if(this.updating)return;this.updating=!0;let e=this.ctx.store.liveSnapshot?.meta;this.updatingFrom={version:e?.version,startedAt:e?.startedAt,at:this.ctx.now()},this.applyError=void 0,this.render();try{let e=await this.ctx.store.applyUpdate();e.ok||(this.updating=!1,this.applyError=e.error??a(`Não deu para falar com o servidor do Habblaud.`))}catch{this.updating=!1,this.applyError=a(`Não deu para falar com o servidor do Habblaud.`)}finally{this.render(),this.ctx.invalidate()}}async check(){if(!this.checking){this.checking=!0,this.failure=void 0,this.render();try{await this.ctx.store.checkUpdates()||(this.failure=a(`Não deu para falar com o servidor do Habblaud.`))}catch{this.failure=a(`Não deu para falar com o servidor do Habblaud.`)}finally{this.checking=!1,this.render(),this.ctx.invalidate()}}}};function mD(){try{return r(localStorage.getItem(`habblaud:locale`))??`auto`}catch{return`auto`}}function hD(e){if(e!==mD()){try{e===`auto`?localStorage.removeItem(i):localStorage.setItem(i,e)}catch{return}location.reload()}}function gD(e,t,n){let r=new Bv({label:e,options:t.map(([e,t])=>({value:e,label:t,className:`ui-seg__opt`})),indicator:!1,onChange:n,className:`ui-seg`});return{row:P(`div`,{class:`ui-set ui-set--stack`},P(`span`,{class:`ui-set__label`,text:e}),r.el),set(e){r.value=e}}}var _D=class{ctx;notifier;world;el;switches=new Map;bubbles;liveliness;daylight;fpsCap;theme;language;soundGroup;avatarGroup;defaultLookGroup;attachmentsGroup;machinesGroup;demoGroup;remoteGroup;logoutBtn;about;demoBusy=!1;anchor=null;constructor(e,t,r,i){this.ctx=e,this.notifier=t,this.world=i;let o=(e,t,n,r)=>{let i=Hv(t,n,r);return this.switches.set(e,i),i.row},s=t=>()=>e.updatePrefs({[t]:!e.prefs[t]});this.bubbles=gD(a(`Balões de atividade`),[[`all`,a(`Todos`)],[`important`,a(`Importantes`)],[`none`,a(`Nenhum`)]],t=>e.updatePrefs({bubbles:t})),this.liveliness=gD(a(`Movimento pelo escritório`),[[`calm`,a(`Calmo`)],[`normal`,a(`Normal`)],[`lively`,a(`Agitado`)]],t=>e.updatePrefs({liveliness:t})),this.daylight=gD(a(`Ciclo dia/noite`),[[`auto`,a(`Automático`)],[`day`,a(`Sempre dia`)],[`night`,a(`Sempre noite`)]],t=>e.updatePrefs({daylight:t})),this.daylight.row.append(P(`span`,{class:`ui-set__hint`,text:a(`Automático: céu, luzes e sol nas janelas seguem a hora local.`)})),this.fpsCap=gD(a(`Limite de FPS`),[[`60`,`60 FPS`],[`30`,`30 FPS`],[`15`,`15 FPS`]],t=>e.updatePrefs({fpsCap:Number(t)||60})),this.theme=gD(a(`Tema do escritório`),[[`auto`,a(`Automático`)],[`none`,a(`Nenhum`)],[`christmas`,a(`Natal`)],[`halloween`,a(`Halloween`)]],t=>{e.updatePrefs({theme:t}),this.world.onThemePicked(t)}),this.theme.row.append(P(`span`,{class:`ui-set__hint`,text:a(`Automático: Halloween em outubro e Natal de 1º de novembro a 26 de dezembro; no resto do ano, o visual original. Nenhum: sempre o original.`)})),this.soundGroup=new nD(e,r),this.avatarGroup=new XE(e),this.defaultLookGroup=new eD(e),this.attachmentsGroup=new RE(e),this.machinesGroup=new qE(e),this.language=gD(a(`Idioma da interface`),[[`auto`,a(`Automático`)],...n.map(e=>[e.id,e.name])],e=>hD(e)),this.language.row.append(P(`span`,{class:`ui-set__hint`,text:a(`Os textos das atividades vêm do servidor: seguem HABBLAUD_LANG ou o idioma do sistema onde o Habblaud roda (sem nenhum dos dois, inglês).`)})),this.demoGroup=P(`div`,{class:`ui-set-group`},P(`h3`,{text:a(`Dados`)}),o(`demo`,a(`Modo demonstração`),a(`Coloca agentes fictícios no escritório, junto com os reais.`),()=>void this.toggleDemo())),this.logoutBtn=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Sair`),on:{click:()=>void this.logout()}}),this.remoteGroup=P(`div`,{class:`ui-set-group`,hidden:!0},P(`h3`,{text:a(`Acesso pelo celular`)}),P(`div`,{class:`ui-set`},P(`div`,{class:`ui-set__text`},P(`span`,{class:`ui-set__label`,text:a(`Sair deste aparelho`)}),P(`span`,{class:`ui-set__hint`,text:a(`Encerra o login aqui (uma cópia do cookie também deixa de valer). Para voltar, entre com usuário e senha.`)})),this.logoutBtn)),this.theme.row.append(i.themeNote),this.about=new pD(e);let c=j(Q.close,a(`Fechar configurações`),()=>this.hide(),`ui-icon-btn--sm`);this.el=P(`div`,{class:`ui-popover ui-settings`,role:`dialog`,tabIndex:-1,attrs:{"aria-label":a(`Configurações`),id:`ui-settings`,popover:`auto`}},P(`div`,{class:`ui-popover__head`},P(`h2`,{text:a(`Configurações`)}),c),P(`div`,{class:`ui-set-group`},P(`h3`,{text:a(`Aparência`)}),this.theme.row),P(`div`,{class:`ui-set-group`},P(`h3`,{text:a(`Escritório`)}),o(`showNames`,a(`Mostrar nomes`),a(`Etiqueta com o nome acima de cada personagem.`),s(`showNames`)),this.bubbles.row,this.liveliness.row,this.daylight.row,this.fpsCap.row,o(`pauseOnHidden`,a(`Pausar quando a aba está oculta`),a(`Economiza CPU e bateria interrompendo a renderização com a página em segundo plano.`),s(`pauseOnHidden`)),o(`pixelEmoji`,a(`Emoji em pixel art`),a(`Desenha os emojis do escritório e da interface como pixel art. Desligado, usa os emojis do sistema.`),s(`pixelEmoji`))),P(`div`,{class:`ui-set-group`},P(`h3`,{text:a(`Avisos`)}),o(`browserNotifications`,a(`Notificações do navegador`),a(`Avisa quando alguém precisa de você e a aba está em segundo plano.`),()=>void this.toggleNotifications())),this.avatarGroup.el,this.defaultLookGroup.el,this.soundGroup.el,this.attachmentsGroup.el,this.machinesGroup.el,P(`div`,{class:`ui-set-group`},P(`h3`,{text:a(`Idioma`)}),this.language.row),this.demoGroup,this.remoteGroup,this.about.el),this.el.addEventListener(`toggle`,()=>{this.anchor?.setAttribute(`aria-expanded`,String(this.isOpen)),this.syncRootClass(),this.machinesGroup.setOpen(this.isOpen),this.isOpen&&this.render()})}get isOpen(){try{return this.el.matches(`:popover-open`)}catch{return this.el.classList.contains(`is-open`)}}toggle(e){if(this.anchor=e,this.isOpen)return this.hide();let t=e.getBoundingClientRect();this.el.style.top=`${Math.round(t.bottom+8)}px`,this.el.style.right=`${Math.max(8,Math.round(innerWidth-t.right-4))}px`,typeof this.el.showPopover==`function`?this.el.showPopover():this.el.classList.add(`is-open`),e.setAttribute(`aria-expanded`,`true`),this.syncRootClass(),this.el.focus()}showAbout(e){this.isOpen||this.toggle(e),this.render(),requestAnimationFrame(()=>this.about.highlight())}hide(){typeof this.el.hidePopover==`function`&&this.isOpen&&this.el.hidePopover(),this.el.classList.remove(`is-open`),this.anchor?.setAttribute(`aria-expanded`,`false`),this.syncRootClass()}syncRootClass(){this.ctx.root.classList.toggle(`has-popover`,this.isOpen)}async logout(){this.logoutBtn.disabled=!0,await an()||(this.logoutBtn.disabled=!1,this.ctx.announce(a(`Não foi possível sair: sem resposta do servidor.`)))}render(){let e=this.ctx.prefs;for(let[t,n]of this.switches){let r=t===`demo`?!!this.ctx.store.liveSnapshot?.meta.demo:e[t];N(n.btn,`aria-checked`,String(r)),n.btn.disabled=t===`demo`&&this.demoBusy}this.bubbles.set(e.bubbles),this.liveliness.set(e.liveliness),this.daylight.set(e.daylight),this.fpsCap.set(String(e.fpsCap||60)),this.theme.set(e.theme),this.language.set(mD()),this.avatarGroup.render(),this.defaultLookGroup.render(),this.soundGroup.render(),this.attachmentsGroup.render(),this.machinesGroup.render(),F(this.demoGroup,this.ctx.store.mock||I().remote),F(this.remoteGroup,!I().remote),this.about.render();let t=this.switches.get(`browserNotifications`),n=hE(),r=a(n===`unsupported`?`Este navegador não oferece notificações.`:n===`denied`?`Bloqueadas pelo navegador: libere nas permissões do site.`:`Avisa quando alguém precisa de você e a aba está em segundo plano.`);M(t.hint,r),t.btn.disabled=n===`unsupported`}async toggleNotifications(){if(this.ctx.prefs.browserNotifications){this.ctx.updatePrefs({browserNotifications:!1});return}let e=await this.notifier.enableBrowserNotifications();this.ctx.updatePrefs({browserNotifications:e===`granted`}),e===`denied`&&this.ctx.announce(a(`Notificações bloqueadas pelo navegador.`))}async toggleDemo(){if(this.demoBusy)return;this.demoBusy=!0,this.render();let e=!this.ctx.store.snapshot?.meta.demo;try{let t=await this.ctx.store.setDemo(e);this.ctx.announce(a(t?e?`Modo demonstração ligado.`:`Modo demonstração desligado.`:`Não foi possível mudar o modo demonstração.`))}catch{this.ctx.announce(a(`Não foi possível falar com o servidor.`))}finally{this.demoBusy=!1,this.ctx.invalidate()}}};function vD(e,t,n,r={}){let i=r.margin??8,a=r.gap??6,o=r.preferredPlacement??`top`,s=e.left,c=e.top,l=e.width,u=e.height,d=e.right??e.left+e.width,f=e.bottom??e.top+e.height,p=t.width,m=t.height,h=c-a-i,g=n.height-i-(f+a),_=s-a-i,v=n.width-i-(d+a),y=o;o===`top`?y=h>=m?`top`:g>=m||g>h?`bottom`:`top`:o===`bottom`?y=g>=m?`bottom`:h>=m||h>g?`top`:`bottom`:o===`left`?y=_>=p?`left`:v>=p||v>_?`right`:`left`:o===`right`&&(y=v>=p?`right`:_>=p||_>v?`left`:`right`);let b=s+(l-p)/2,x=i,S=Math.max(i,n.width-p-i),C=Math.max(x,Math.min(b,S)),w=c+(u-m)/2,ee=i,te=Math.max(i,n.height-m-i),T=Math.max(ee,Math.min(w,te));return y===`top`?(T=c-m-a,T+m>c&&(T=c-m),T=Math.max(i,T),T+m>c&&(T=c-m)):y===`bottom`?(T=f+a,T<f&&(T=f),T=Math.min(T,Math.max(f,n.height-m-i)),T<f&&(T=f)):y===`left`?(C=s-p-a,C+p>s&&(C=s-p),C=Math.max(i,C),C+p>s&&(C=s-p)):y===`right`&&(C=d+a,C<d&&(C=d),C=Math.min(C,Math.max(d,n.width-p-i)),C<d&&(C=d)),{x:Math.round(C),y:Math.round(T),placement:y}}var yD=class{host;currentTarget=null;pendingTarget=null;pendingTimer=null;isVisible=!1;hoverDelay;touchDelay;constructor(e,t){this.host=e,this.hoverDelay=t?.hoverDelay??400,this.touchDelay=t?.touchDelay??500}get visibleTarget(){return this.isVisible?this.currentTarget:null}get activePendingTarget(){return this.pendingTarget}onPointerOver(e,t=`mouse`){if(t===`touch`)return;let n=this.host.getTipText(e);if(!n){this.hide();return}this.isVisible&&this.currentTarget===e||(this.cancelPending(),this.pendingTarget=e,this.pendingTimer=this.host.schedule(()=>{this.pendingTimer=null,this.pendingTarget=null,this.showFor(e,n)},this.hoverDelay))}onPointerOut(e){this.pendingTarget===e&&this.cancelPending(),this.isVisible&&this.currentTarget===e&&this.hide()}onFocusIn(e){let t=this.host.getTipText(e);t&&(this.cancelPending(),this.showFor(e,t))}onFocusOut(e){(this.currentTarget===e||this.pendingTarget===e)&&(this.cancelPending(),this.hide())}onKeyDown(e){e===`Escape`&&(this.cancelPending(),this.hide())}onScroll(){this.cancelPending(),this.hide()}onResize(){this.cancelPending(),this.hide()}onTouchStart(e){let t=this.host.getTipText(e);t&&(this.cancelPending(),this.pendingTarget=e,this.pendingTimer=this.host.schedule(()=>{this.pendingTimer=null,this.pendingTarget=null,this.showFor(e,t)},this.touchDelay))}onTouchEnd(){this.pendingTarget&&this.cancelPending()}onTouchMove(){this.pendingTarget&&this.cancelPending()}checkTargetConnected(){this.currentTarget&&this.host.isConnected&&!this.host.isConnected(this.currentTarget)&&this.hide(),this.pendingTarget&&this.host.isConnected&&!this.host.isConnected(this.pendingTarget)&&this.cancelPending()}showFor(e,t){this.currentTarget=e,this.isVisible=!0,this.host.show(e,t)}hide(){if(!this.isVisible&&!this.currentTarget)return;let e=this.currentTarget;this.currentTarget=null,this.isVisible=!1,e?this.host.hide(e):this.host.hide()}cancelPending(){this.pendingTimer!==null&&(this.host.cancel(this.pendingTimer),this.pendingTimer=null),this.pendingTarget=null}destroy(){this.cancelPending(),this.hide()}};function bD(e){if(!e||typeof e.closest!=`function`)return null;let t=e.closest(`[data-tip]`);return typeof HTMLElement<`u`&&t instanceof HTMLElement,t}function xD(e){if(!e||typeof e.getAttribute!=`function`)return null;let t=e.getAttribute(`data-tip`)?.trim();if(t)return t;if(e.getAttribute(`title`)!==null){let t=e.getAttribute(`title`)?.trim();return typeof e.removeAttribute==`function`&&e.removeAttribute(`title`),`title`in e&&(e.title=``),t||null}return null}var SD=class{root;el;stateMachine;originalDescribedBy=null;currentDescribedTarget=null;observer=null;cleanupFns=[];constructor(e){this.root=e,this.root=e??(typeof document<`u`&&document.body?document.body:null),this.el=typeof document<`u`&&typeof document.createElement==`function`?P(`div`,{class:`ui-tooltip`,role:`tooltip`,hidden:!0,attrs:{id:`ui-tooltip`,"aria-hidden":`true`}}):null;let t={schedule:(e,t)=>setTimeout(e,t),cancel:e=>clearTimeout(e),show:(e,t)=>this.show(e,t),hide:e=>this.hide(e),getTipText:e=>xD(e),isConnected:e=>!!e?.isConnected};this.stateMachine=new yD(t,{hoverDelay:400,touchDelay:500}),this.bindEvents()}get visibleTarget(){return this.stateMachine.visibleTarget}bindEvents(){if(typeof window>`u`||typeof document>`u`||typeof document.addEventListener!=`function`||typeof window.addEventListener!=`function`)return;let e=e=>{let t=bD(e.target);t&&this.stateMachine.onPointerOver(t,e.pointerType)},t=e=>{let t=bD(e.target);if(!t)return;let n=e.relatedTarget;n&&t.contains?.(n)||this.stateMachine.onPointerOut(t)},n=e=>{let t=bD(e.target);t&&this.stateMachine.onFocusIn(t)},r=e=>{let t=bD(e.target);t&&this.stateMachine.onFocusOut(t)},i=e=>{e.key===`Escape`&&this.stateMachine.onKeyDown(`Escape`)},a=()=>{this.stateMachine.onScroll()},o=()=>{this.stateMachine.onResize()},s=null,c=!1,l=e=>{if(e.pointerType===`touch`){let t=bD(e.target);c=!1,t?(s=t,this.stateMachine.onTouchStart(t)):this.stateMachine.onKeyDown(`Escape`)}},u=e=>{e.pointerType===`touch`&&s&&!c&&(c=!0,this.stateMachine.onTouchMove())},d=e=>{e.pointerType===`touch`&&(s=null,this.stateMachine.onTouchEnd())},f=e=>{e.pointerType===`touch`&&(s=null,this.stateMachine.onTouchEnd())};document.addEventListener(`pointerover`,e),document.addEventListener(`pointerout`,t),document.addEventListener(`focusin`,n),document.addEventListener(`focusout`,r),document.addEventListener(`keydown`,i),window.addEventListener(`scroll`,a,{capture:!0,passive:!0}),window.addEventListener(`resize`,o,{passive:!0}),document.addEventListener(`pointerdown`,l,{passive:!0}),document.addEventListener(`pointermove`,u,{passive:!0}),document.addEventListener(`pointerup`,d,{passive:!0}),document.addEventListener(`pointercancel`,f,{passive:!0}),typeof MutationObserver<`u`&&typeof document<`u`&&document.body&&(this.observer=new MutationObserver(()=>{this.stateMachine.checkTargetConnected()}),this.observer.observe(document.body,{childList:!0,subtree:!0})),this.cleanupFns.push(()=>typeof document<`u`&&document.removeEventListener?.(`pointerover`,e),()=>typeof document<`u`&&document.removeEventListener?.(`pointerout`,t),()=>typeof document<`u`&&document.removeEventListener?.(`focusin`,n),()=>typeof document<`u`&&document.removeEventListener?.(`focusout`,r),()=>typeof document<`u`&&document.removeEventListener?.(`keydown`,i),()=>typeof window<`u`&&window.removeEventListener?.(`scroll`,a,{capture:!0}),()=>typeof window<`u`&&window.removeEventListener?.(`resize`,o),()=>typeof document<`u`&&document.removeEventListener?.(`pointerdown`,l),()=>typeof document<`u`&&document.removeEventListener?.(`pointermove`,u),()=>typeof document<`u`&&document.removeEventListener?.(`pointerup`,d),()=>typeof document<`u`&&document.removeEventListener?.(`pointercancel`,f),()=>this.observer?.disconnect())}show(e,t){if(!e.isConnected||!this.el)return;this.currentDescribedTarget&&this.currentDescribedTarget!==e&&this.clearAriaDescribedBy(this.currentDescribedTarget),this.currentDescribedTarget=e,this.originalDescribedBy=typeof e.getAttribute==`function`?e.getAttribute(`aria-describedby`):null;let n=this.originalDescribedBy?`${this.originalDescribedBy} ui-tooltip`:`ui-tooltip`;typeof e.setAttribute==`function`&&e.setAttribute(`aria-describedby`,n),M(this.el,t),this.el.hidden=!1,typeof this.el.setAttribute==`function`&&this.el.setAttribute(`aria-hidden`,`false`);let r=vD(typeof e.getBoundingClientRect==`function`?e.getBoundingClientRect():{left:0,top:0,width:0,height:0,right:0,bottom:0},{width:this.el.offsetWidth||120,height:this.el.offsetHeight||26},{width:typeof document<`u`&&document.documentElement?.clientWidth||(typeof window<`u`?window.innerWidth:800),height:typeof document<`u`&&document.documentElement?.clientHeight||(typeof window<`u`?window.innerHeight:600)});this.el.style&&(this.el.style.transform=`translate3d(${r.x}px, ${r.y}px, 0)`),this.el.classList?.add(`is-visible`)}hide(e){let t=e??this.currentDescribedTarget;t&&this.clearAriaDescribedBy(t),this.currentDescribedTarget=null,this.originalDescribedBy=null,this.el&&(this.el.classList?.remove(`is-visible`),this.el.hidden=!0,typeof this.el.setAttribute==`function`&&this.el.setAttribute(`aria-hidden`,`true`))}clearAriaDescribedBy(e){if(typeof e.getAttribute==`function`){if(this.originalDescribedBy!==null)this.originalDescribedBy?e.setAttribute?.(`aria-describedby`,this.originalDescribedBy):e.removeAttribute?.(`aria-describedby`);else{let t=e.getAttribute(`aria-describedby`);if(t===`ui-tooltip`)e.removeAttribute?.(`aria-describedby`);else if(t){let n=t.replace(/\bui-tooltip\b/,``).trim();n?e.setAttribute?.(`aria-describedby`,n):e.removeAttribute?.(`aria-describedby`)}}}}render(){this.stateMachine.visibleTarget&&this.stateMachine.checkTargetConnected()}destroy(){for(let e of this.cleanupFns)e();this.cleanupFns.length=0,this.stateMachine.destroy(),this.hide(),this.el?.remove?.()}},CD=null;function wD(e){return CD&&(!e||CD.el?.parentElement===e)?CD:(CD?.destroy(),CD=new SD(e),e&&CD.el&&(typeof e.contains!=`function`||!e.contains(CD.el))&&e.append?.(CD.el),CD)}var TD=`habblaud.rooms.order`,ED=100;function DD(e,t){let n=kD();if(!n.length)return e.slice();let r=new Map(n.map((e,t)=>[e,t]));return e.map((e,n)=>({item:e,i:n,r:r.get(t(e))})).sort((e,t)=>(e.r??1/0)-(t.r??1/0)||e.i-t.i).map(e=>e.item)}function OD(e,t,n,r){if(t===n||!e.includes(t)||!e.includes(n))return!1;let i=e.filter(e=>e!==t);i.splice(i.indexOf(n)+ +!!r,0,t);let a=kD().filter(e=>!i.includes(e));return AD([...i,...a].slice(0,ED)),!0}function kD(){try{let e=JSON.parse(localStorage.getItem(TD)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}catch{return[]}}function AD(e){try{localStorage.setItem(TD,JSON.stringify(e))}catch{}}var jD=e=>e.lastEventAt||e.statusSince;function MD(e,t){if(!e)return[];let n=new Map(e.accounts.map(e=>[e.id,e])),r=new Map(e.rooms.map(e=>[e.id,e])),i=t?.query.trim()??``,a=t?.hiddenAccounts??new Set,o=e=>!a.has(e.account)&&Cb(e,r.get(e.roomId),n.get(e.account),i),s=new Map;for(let t of e.agents){if(t.kind!==`sub`||!t.parentId)continue;let e=s.get(t.parentId);e?e.push(t):s.set(t.parentId,[t])}let c=[];for(let t of e.agents){if(t.kind!==`main`)continue;let e=s.get(t.id)??[];if(!o(t)&&!e.some(o))continue;let n=r.get(t.roomId);c.push({agent:t,...n?{room:n}:{},subTotal:e.length})}return c.sort((e,t)=>jD(t.agent)-jD(e.agent)||e.agent.name.localeCompare(t.agent.name)||e.agent.id.localeCompare(t.agent.id))}var ND=class{ctx;el;input;query=``;filters;filterList;scroller;rooms;recent;roomsList;recentList;viewSwitch;roomRefs=new WeakMap;nodeRefs=new WeakMap;shown=new Map;dragging=null;draggingRoom=null;shownRooms=[];empty;emptyText;clearBtn;lastSelKey=``;manageRoomsBtn;constructor(e){this.ctx=e,this.input=P(`input`,{class:`ui-search__input`,type:`search`,attrs:{placeholder:a(`Buscar agente, projeto ou conta`),"aria-label":a(`Buscar agente, projeto ou conta`),autocomplete:`off`,spellcheck:`false`}}),this.input.addEventListener(`input`,()=>{this.query=this.input.value,this.ctx.invalidate()}),this.input.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.stopPropagation(),this.input.value?(this.input.value=``,this.query=``,this.ctx.invalidate()):this.input.blur())});let t=P(`span`,{class:`ui-search__icon`,attrs:{"aria-hidden":`true`}});t.innerHTML=Q.search;let n=P(`label`,{class:`ui-search`},t,this.input,P(`kbd`,{class:`ui-kbd`,text:`/`,title:a(`Atalho: /`)}));this.filters=P(`div`,{class:`ui-acc-filters`,role:`group`,attrs:{"aria-label":a(`Filtrar por conta`)}}),this.filterList=new wt(this.filters,{animate:!1,key:e=>e.id,create:e=>{let t=yx(`sm`),n=P(`button`,{class:`ui-acc-filter`,type:`button`},t,P(`span`,{class:`ui-acc-filter__name`}));return n.addEventListener(`click`,()=>this.toggleAccount(e.id)),n},update:(e,t)=>{let n=this.ctx.prefs.hiddenAccounts.includes(t.id);bx(e.firstElementChild,t),M(e.lastElementChild,t.name),N(e,`aria-pressed`,String(!n)),N(e,`data-tip`,t.name),N(e,`aria-label`,a(n?`Mostrar a {0} na lista, no feed e nos avisos`:`Ocultar a {0} na lista, no feed e nos avisos (o escritório continua mostrando todos)`,[t.name])),e.classList.toggle(`is-off`,n)}}),this.scroller=P(`div`,{class:`ui-side__scroll`});let r=P(`div`,{class:`ui-rooms`,role:`list`,attrs:{"aria-label":a(`Salas`)}});this.roomsList=r,this.recentList=P(`ul`,{class:`ui-nodes ui-nodes--recent`,hidden:!0,attrs:{"aria-label":a(`Recentes`)}}),this.scroller.append(r,this.recentList),this.recent=new wt(this.recentList,{key:e=>e.agent.id,create:e=>this.createNode(e),update:(e,t)=>this.updateNode(e,t)}),this.viewSwitch=new Bv({label:a(`Modo de exibição da lista`),options:[{value:`rooms`,label:a(`Salas`),className:`ui-seg__opt`},{value:`recent`,label:a(`Recentes`),className:`ui-seg__opt`}],value:e.prefs.sidebarView,indicator:!1,className:`ui-seg ui-side__view`,onChange:t=>e.updatePrefs({sidebarView:t})}),this.rooms=new wt(r,{key:e=>e.room.id,create:e=>this.createRoom(e),update:(e,t)=>this.updateRoom(e,t)}),this.emptyText=P(`p`),this.clearBtn=P(`button`,{class:`ui-link-btn`,type:`button`,text:a(`Limpar filtros`),on:{click:()=>{this.input.value=``,this.query=``,this.ctx.updatePrefs({hiddenAccounts:[]})}}}),this.empty=P(`div`,{class:`ui-side__empty`,hidden:!0},this.emptyText,this.clearBtn),this.scroller.append(this.empty),this.manageRoomsBtn=P(`button`,{class:`ui-btn ui-btn--sm ui-side__custom-rooms`,type:`button`,text:a(`Criar sala`),on:{click:()=>e.manageCustomRooms?.()}});let i=j(Q.close,a(`Fechar painel lateral`),()=>e.togglePanel(`sidebar`,!1),`ui-side__close`);this.el=P(`aside`,{class:`ui-panel ui-sidebar`,attrs:{"aria-label":a(`Salas e agentes`),id:`ui-sidebar`}},P(`div`,{class:`ui-side__head`},P(`div`,{class:`ui-side__title`},P(`h2`,{text:a(`Escritório`)}),i),n,this.viewSwitch.el,this.filters,this.manageRoomsBtn),this.scroller)}focusSearch(){this.input.focus(),this.input.select()}render(){let e=this.ctx.store.snapshot;F(this.manageRoomsBtn,!nv(this.ctx));let t=e?.accounts??[],n=new Set(this.ctx.prefs.hiddenAccounts);this.filterList.sync(t.length>1?t:[]),F(this.filters,t.length<=1);let r=this.ctx.prefs.sidebarView,i=r===`recent`;this.viewSwitch.value=r,F(this.roomsList,i),F(this.recentList,!i);let o=i?[]:DD(Tb(e,{query:this.query,hiddenAccounts:n}),e=>e.room.id),s=i?MD(e,{query:this.query,hiddenAccounts:n}).map(e=>({agent:e.agent,subs:[],subTotal:e.subTotal,flat:!0,...e.room?{room:e.room}:{}})):[];this.shownRooms=o.map(e=>e.room.id),this.rooms.sync(o),this.recent.sync(s);let c=this.query.trim().length>0||n.size>0,l=e?.agents.length??0,u=(i?s.length:o.length)===0&&(c||!pT(this.ctx));F(this.empty,!u),u&&(M(this.emptyText,c&&l>0?this.query.trim()?a(`Nenhum agente encontrado para “{0}”.`,[this.query.trim()]):a(`Nenhum agente nas contas selecionadas.`):a(`Nenhuma sessão aberta no momento.`)),F(this.clearBtn,!(c&&l>0)));let d=this.ctx.selection(),f=d?`${d.type}:${d.id}`:``;f!==this.lastSelKey&&(this.lastSelKey=f,d&&(d.type===`agent`?this.el.querySelector(`.ui-agent[data-id="${CSS.escape(d.id)}"]`):this.el.querySelector(`.ui-room[data-key="${CSS.escape(d.id)}"] .ui-room__head`))?.scrollIntoView({block:`nearest`,behavior:`smooth`}))}toggleAccount(e){let t=new Set(this.ctx.prefs.hiddenAccounts);t.has(e)?t.delete(e):t.add(e),this.ctx.updatePrefs({hiddenAccounts:[...t]})}createRoom(e){let t=P(`span`,{class:`ui-room__name`}),n=P(`span`,{class:`ui-room__count`}),r=P(`span`,{class:`ui-room__accs`}),i=P(`span`,{class:`ui-room__path`}),o=Dx(a(`Progresso das tarefas da sala`)),s=P(`span`,{class:`ui-room__tasks-text`}),c=P(`span`,{class:`ui-room__tasks`},o,s),l=P(`span`,{class:`ui-room__swatch`,attrs:{"aria-hidden":`true`}}),u=P(`button`,{class:`ui-room__head`,type:`button`},l,P(`span`,{class:`ui-room__line`},t,n,r),i,c);u.addEventListener(`click`,()=>this.ctx.select({type:`room`,id:e.room.id},{focus:!0})),this.wireRoomDrag(u,e.room.id),u.addEventListener(`contextmenu`,t=>{if(e.room.custom?!this.ctx.customRoomMenu:!this.ctx.renameRoom)return;t.preventDefault();let n=u.getBoundingClientRect();e.room.custom?this.ctx.customRoomMenu?.(e.room.id,{x:n.left+12,y:n.bottom+4}):this.ctx.renameRoom?.(e.room.id,{x:n.left+12,y:n.bottom+4})});try{_t(u,`--room`,fs(e.room.seed).accent)}catch{}let d=P(`ul`,{class:`ui-nodes`}),f=P(`section`,{class:`ui-room`,role:`listitem`},u,d),p=new wt(r,{animate:!1,key:e=>typeof e==`string`?e:e.id,create:()=>yx(`sm`),update:(e,t)=>typeof t==`string`?bx(e,void 0,t):bx(e,t)}),m=new wt(d,{key:e=>e.agent.id,create:e=>this.createNode(e),update:(e,t)=>this.updateNode(e,t)});return this.roomRefs.set(f,{head:u,name:t,count:n,path:i,accs:p,tasks:c,tasksBar:o,tasksText:s,nodes:m}),f}updateRoom(e,t){let n=this.roomRefs.get(e),r=this.ctx.selection(),i=Dt(t.room,this.ctx.store.snapshot?.machines),o=i.tag?`${i.text} (${i.tag})`:i.text;M(n.name,o),N(n.name,`data-tip`,o),e.classList.toggle(`is-machine-offline`,i.dim);let s=t.agents.filter(e=>e.status!==`offline`).length;M(n.count,String(s)),A(n.count,Lt(s,a(`agente`),a(`agentes`))),M(n.path,Ot(t.room.path)),A(n.head,a(`{0}
19
- Clique para ver a sala`,[t.room.path])),N(n.head,`aria-label`,a(`Sala {0}, {1}`,[i.text,Lt(s,a(`agente`),a(`agentes`))])),n.accs.sync(t.accounts.map(e=>this.ctx.account(e)??e));let c=r?.type===`room`&&r.id===t.room.id;n.head.classList.toggle(`is-selected`,c),N(n.head,`aria-current`,c?`true`:null),e.classList.toggle(`is-empty`,s===0);let l=t.tasks;F(n.tasks,l.total===0),l.total>0&&(Ox(n.tasksBar,l.completed,l.total,l.inProgress),M(n.tasksText,a(`{0}/{1} tarefas`,[l.completed,l.total])));let u=hx(t.room.id,t.nodes,e=>e.agent.sessionId);this.shown.set(t.room.id,u),n.nodes.sync(u)}wireRoomDrag(e,t){e.draggable=!0;let n=t=>{let n=e.getBoundingClientRect();return t.clientY>n.top+n.height/2},r=()=>{for(let e of this.el.querySelectorAll(`.ui-room__head.is-drop-before, .ui-room__head.is-drop-after`))e.classList.remove(`is-drop-before`,`is-drop-after`)};e.addEventListener(`dragstart`,n=>{this.draggingRoom=t,e.classList.add(`is-dragging`),n.dataTransfer&&(n.dataTransfer.effectAllowed=`move`,n.dataTransfer.setData(`text/plain`,t))}),e.addEventListener(`dragend`,()=>{this.draggingRoom=null,e.classList.remove(`is-dragging`),r()}),e.addEventListener(`dragover`,i=>{let a=this.draggingRoom;a&&a!==t&&(i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect=`move`),r(),e.classList.add(n(i)?`is-drop-after`:`is-drop-before`))}),e.addEventListener(`dragleave`,()=>e.classList.remove(`is-drop-before`,`is-drop-after`)),e.addEventListener(`drop`,e=>{let i=this.draggingRoom;r(),i&&i!==t&&(e.preventDefault(),OD(this.shownRooms,i,t,n(e))&&this.ctx.invalidate())})}wireDrag(e){e.draggable=!0;let t=()=>e.dataset.id??``,n=()=>e.dataset.room??``,r=t=>{let n=e.getBoundingClientRect();return t.clientY>n.top+n.height/2},i=()=>{for(let e of this.el.querySelectorAll(`.ui-node__head.is-drop-before, .ui-node__head.is-drop-after`))e.classList.remove(`is-drop-before`,`is-drop-after`)};e.addEventListener(`dragstart`,r=>{this.dragging={id:t(),room:n()},e.classList.add(`is-dragging`),r.dataTransfer&&(r.dataTransfer.effectAllowed=`move`,r.dataTransfer.setData(`text/plain`,t()))}),e.addEventListener(`dragend`,()=>{this.dragging=null,e.classList.remove(`is-dragging`),i()}),e.addEventListener(`dragover`,a=>{let o=this.dragging;o&&o.room===n()&&o.id!==t()&&(a.preventDefault(),a.dataTransfer&&(a.dataTransfer.dropEffect=`move`),i(),e.classList.add(r(a)?`is-drop-after`:`is-drop-before`))}),e.addEventListener(`dragleave`,()=>e.classList.remove(`is-drop-before`,`is-drop-after`)),e.addEventListener(`drop`,e=>{let a=this.dragging;if(i(),!a||a.room!==n()||a.id===t())return;e.preventDefault();let o=this.shown.get(a.room)??[];gx(a.room,o,e=>e.agent.id,e=>e.agent.sessionId,a.id,t(),r(e))&&this.ctx.invalidate()})}createNode(e){let t=uw(e.agent,e=>this.pick(e));t.querySelector(`.ui-agent__main`)?.append(P(`span`,{class:`ui-agent__room-label`,hidden:!0}));let n=P(`span`,{class:`ui-subs__caption`}),r=P(`ul`,{class:`ui-subs__list`}),i=P(`div`,{class:`ui-subs`,hidden:!0},n,r),a=P(`button`,{class:`ui-node__term`,type:`button`});a.innerHTML=Q.terminal,a.addEventListener(`click`,e=>{e.stopPropagation();let n=t.dataset.id;n&&this.ctx.terminals?.toggle(n,a)});let o=P(`div`,{class:`ui-node__head`},t,a);this.wireDrag(o);let s=P(`li`,{class:`ui-node`},o,i),c=new wt(r,{key:e=>e.id,create:e=>P(`li`,{class:`ui-subs__item`},uw(e,e=>this.pick(e),`sm`)),update:(e,t)=>this.updateRow(e.firstElementChild,t)});return this.nodeRefs.set(s,{row:t,head:o,term:a,subsWrap:i,subsCaption:n,subs:c}),s}updateNode(e,t){let n=this.nodeRefs.get(e);this.updateRow(n.row,t.agent);let r=n.row.querySelector(`.ui-agent__room-label`);if(r){let e=t.flat?t.room:t.projectRoom,n=t.flat?e?Dt(e,this.ctx.store.snapshot?.machines).text:t.agent.project??``:t.agent.project??(e?Dt(e,this.ctx.store.snapshot?.machines).text:``),i=n?t.flat?n:a(`Projeto: {0}`,[n]):``;M(r,i),A(r,t.agent.project??e?.path??``),N(r,`data-tip`,i),F(r,!n)}n.head.draggable=!t.flat,n.head.dataset.id=t.agent.id,n.head.dataset.room=t.agent.roomId;let i=this.ctx.terminals,o=t.agent,s=!!i?.available&&o.status!==`offline`;if(F(n.term,!s),s&&i){let e=i.openAgentId===o.id,t=i.interactive(o.id);n.term.classList.toggle(`is-on`,e),n.term.classList.toggle(`is-live`,t);let r=a(t?`interativo`:`ao vivo`),s=xt(o,this.ctx.store.snapshot?.machines);A(n.term,e?a(`Fechar o terminal`):a(`Abrir o terminal de {0} ({1})`,[s,r])),N(n.term,`aria-label`,a(e?`Fechar o terminal de {0}`:`Abrir o terminal de {0}`,[s]))}let c=t.subTotal>0;if(F(n.subsWrap,!c),c){let e=t.subs.length;M(n.subsCaption,t.flat||e===t.subTotal?Lt(t.subTotal,a(`subagente`),a(`subagentes`)):`${e} de ${Lt(t.subTotal,a(`subagente`),a(`subagentes`))}`)}n.subs.sync(t.subs)}updateRow(e,t){let n=this.ctx.selection();dw(e,t,this.ctx.account(t.account),n?.type===`agent`&&n.id===t.id,this.ctx.now(),this.ctx.store.snapshot?.agents,this.ctx.store.snapshot?.machines)}pick(e){this.ctx.select({type:`agent`,id:e},{focus:!0});let t=this.ctx.terminals;t&&t.openAgentId!==null&&t.openAgentId!==e&&this.ctx.agent(e)&&t.open(e),this.ctx.isNarrow()&&this.ctx.togglePanel(`sidebar`,!1)}};function PD(e,t,n,r,i){e.gain.setValueAtTime(1e-4,t),e.gain.exponentialRampToValueAtTime(Math.max(2e-4,n),t+r),e.gain.exponentialRampToValueAtTime(1e-4,t+r+i)}function FD(e,t,n,r,i,a,o,s,c){let l=e.createOscillator(),u=e.createGain();l.type=n,l.frequency.setValueAtTime(r,i),c&&l.frequency.exponentialRampToValueAtTime(c,i+Math.min(s,.08)),PD(u,i,a,o,s),l.connect(u).connect(t),l.start(i),l.stop(i+o+s+.05)}function ID(e){try{let t=Math.floor(e.sampleRate*.06),n=e.createBuffer(1,t,e.sampleRate),r=n.getChannelData(0);for(let e=0;e<t;e++)r[e]=Math.random()*2-1;return n}catch{return null}}function LD(e,t,n,r,i){let a=t;if(i.pan&&typeof e.createStereoPanner==`function`){let n=e.createStereoPanner();n.pan.value=Math.max(-1,Math.min(1,i.pan)),n.connect(t),a=n}let o=i.gain;switch(n){case`chime`:FD(e,a,`sine`,880,r,.16*o,.012,1.1),FD(e,a,`sine`,1318.5,r,.08*o,.012,1.1),FD(e,a,`sine`,1174.7,r+.14,.1*o,.012,1.1);return;case`siren`:zD(e,a,r,o);return;case`pop`:FD(e,a,`triangle`,740,r,.14*o,.008,.15,330);return;case`elevator`:FD(e,a,`sine`,784,r,.11*o,.004,1.5),FD(e,a,`sine`,1568,r,.025*o,.004,.7),FD(e,a,`sine`,2164,r,.012*o,.004,.25);return;case`keys`:RD(e,a,r,i);return;case`pingpong`:FD(e,a,`sine`,1250,r,.09*o,.002,.06,880);return;case`table`:FD(e,a,`sine`,760,r,.06*o,.002,.045,520);return;case`arcade`:{let t=e.createBiquadFilter();t.type=`lowpass`,t.frequency.value=2600,t.connect(a);let n=[1046.5,1318.5,1568,1760,2093];for(let a=0;a<3;a++){let s=n[Math.floor(i.rng()*n.length)];FD(e,t,`square`,s,r+a*.055,.03*o,.003,.05)}return}}}function RD(e,t,n,r){if(!r.noise)return;let i=Math.max(1,Math.min(8,r.count??4)),a=n;for(let n=0;n<i;n++){let n=e.createBufferSource();n.buffer=r.noise;let i=e.createBiquadFilter();i.type=`bandpass`,i.frequency.value=1900+r.rng()*1500,i.Q.value=1.4;let o=e.createGain();PD(o,a,.08*r.gain*(.6+r.rng()*.4),.0015,.022+r.rng()*.012),n.connect(i).connect(o).connect(t),n.start(a,r.rng()*.02,.04),a+=.06+r.rng()*.08+(r.rng()<.15?.12:0)}}function zD(e,t,n,r){let i=3.6,a=1.2,o=e.createBiquadFilter();o.type=`lowpass`,o.frequency.value=2400;let s=e.createGain();s.gain.setValueAtTime(1e-4,n),s.gain.exponentialRampToValueAtTime(.11*r,n+.08),s.gain.setValueAtTime(.11*r,n+i-.25),s.gain.exponentialRampToValueAtTime(1e-4,n+i),o.connect(s).connect(t);for(let[t,r,s]of[[`sawtooth`,0,.6],[`square`,6,.4]]){let c=e.createOscillator();c.type=t,c.detune.value=r,c.frequency.setValueAtTime(620,n);for(let e=0;e<i/a;e++){let t=n+e*a;c.frequency.linearRampToValueAtTime(1380,t+a*.55),c.frequency.linearRampToValueAtTime(620,t+a)}let l=e.createGain();l.gain.value=s,c.connect(l).connect(o),c.start(n),c.stop(n+i+.05)}}var BD=class{scheduler=new lE;ac=null;out=null;noise=null;enabled=!1;pending=[];configure(e,t){this.enabled=e,this.scheduler.configure(e,t)}unlock(){if(!this.enabled)return Promise.resolve();try{if(!this.ac){let e=window.AudioContext??window.webkitAudioContext;if(!e)return Promise.resolve();let t=new e,n=t.createDynamicsCompressor();n.threshold.value=-18,n.knee.value=12,n.ratio.value=6,n.connect(t.destination),this.ac=t,this.out=n,this.noise=ID(t)}if(this.ac.state===`suspended`)return this.ac.resume().then(()=>this.flush(),()=>void 0);this.flush()}catch{this.ac=null,this.out=null}return Promise.resolve()}play(e,t={}){let n=this.ac;if(!n||!this.out||n.state!==`running`)return this.enabled&&(this.pending=fE(this.pending,e,performance.now())),!1;let r=typeof document<`u`&&document.hidden,i=this.scheduler.decide(e,performance.now(),{hidden:r,gain:t.gain});if(i===null)return!1;try{return LD(n,this.out,e,n.currentTime+.01,{gain:i,pan:t.pan,count:t.count,rng:Math.random,noise:this.noise}),!0}catch{return!1}}flush(){let e=pE(this.pending,performance.now());this.pending=[];for(let t of e)this.play(t)}},VD=class{ctx;board=new BD;previewAt=0;constructor(e){this.ctx=e,this.sync(),e.world.onSound?.(e=>this.board.play(e.kind,e));let t=()=>{this.ctx.prefs.sound&&this.board.unlock()};addEventListener(`pointerdown`,t,{passive:!0}),addEventListener(`keydown`,t),t()}render(){this.sync()}sync(){this.board.configure(this.ctx.prefs.sound,this.ctx.prefs.sounds)}preview(e=`pop`){this.sync();let t=performance.now(),n=this.board.unlock();t-this.previewAt<250||(this.previewAt=t,n.then(()=>this.board.play(e)))}},HD=class{ctx;el;pane=null;loading=null;info=null;external=null;screen;away;awayTitle;nameEl;accEl;roomEl;stateEl;machineEl;actions;tabs;movable;onShow=null;pendingSelect=null;constructor(e){this.ctx=e;let t=P(`span`,{class:`ui-term__icon`,attrs:{"aria-hidden":`true`}});t.innerHTML=Q.terminal,this.accEl=yx(`sm`),this.nameEl=P(`strong`,{class:`ui-term__name`}),this.roomEl=P(`span`,{class:`ui-term__room`}),this.stateEl=P(`span`,{class:`ui-pty__state`,role:`status`}),this.machineEl=P(`span`,{class:`ui-pty__machine`,hidden:!0}),this.actions=new fx(e,this,!1,async()=>{this.info&&await ux(this.info.id)}),this.tabs=new Ix(e);let n=j(Q.close,a(`Fechar a janela (a sessão continua rodando)`),()=>this.close(),`ui-icon-btn--sm ui-term__close`),r=P(`div`,{class:`ui-term__bar`},t,P(`span`,{class:`ui-term__kind`,text:a(`terminal`)}),P(`div`,{class:`ui-term__who`},this.accEl,this.nameEl,this.roomEl),this.stateEl,this.machineEl,P(`span`,{class:`ui-pty__live`,text:a(`interativo`)}),this.actions.el,Ib(()=>this.movable,()=>requestAnimationFrame(()=>this.pane?.refit(!0))),n);this.screen=P(`div`,{class:`ui-pty__body`}),this.awayTitle=P(`p`,{class:`ui-pty__away-title`}),this.away=P(`div`,{class:`ui-pty__away`,hidden:!0},P(`strong`,{text:a(`Esta sessão está aberta em outro terminal`)}),this.awayTitle,P(`p`,{class:`ui-muted`,text:a(`Use "Assumir daqui" (no topo) para encerrar lá e continuar a mesma conversa nesta janela, podendo digitar.`)})),this.el=P(`section`,{class:`ui-term ui-pty`,role:`dialog`,hidden:!0,attrs:{"aria-label":a(`Terminal`)}},r,this.tabs.el,this.screen,this.away),this.el.addEventListener(`keydown`,e=>e.stopPropagation()),this.movable=new Fb(this.el,r,{key:`habblaud.move.term`,enabled:()=>!e.isNarrow(),onMove:()=>this.pane?.refit(!0)}),this.el.addEventListener(`keyup`,e=>e.stopPropagation())}get enabled(){return!!this.ctx.store.snapshot?.meta.pty?.enabled&&!this.ctx.store.replaying}get reason(){return this.ctx.store.replaying?a(`Sem terminal no timelapse`):this.ctx.store.snapshot?.meta.pty?.reason??a(`Terminal interativo desligado`)}get isOpen(){return this.info!==null||this.external!==null}get agentId(){return this.info?.agentId??this.external}ptyOf(e){return this.ctx.store.snapshot?.ptys?.find(t=>t.agentId===e&&t.exitedAt===void 0)}openAgent(e){let t=this.ptyOf(e);if(t)return this.show(t);this.pane?.detach(),this.info=null,this.external=e,this.reveal(),this.render(),this.ctx.invalidate()}close(){this.isOpen&&(this.pane?.detach(),this.info=null,this.external=null,this.el.hidden=!0,this.ctx.invalidate())}async takeover(e){let t=this.ctx.agent(e),n=!t||Vb(t)===`claude`;if(I().spawn)try{let t=await ix(e);if(t){let e=a(`Aberto no herdr (painel {0}).`,[t.paneId]);return this.ctx.announce(e),e}}catch(e){if(!n)throw e}if(!n){let e=a(`Esta sessão não foi aberta pelo herdr.`);return this.ctx.announce(e),e}let r=await cx(e);r&&this.show(r,!0)}async newSession(e,t){let n=await sx(e,t);n&&this.show(n,!0)}async stop(e){await lx(e),this.ctx.announce(a(`Sessão encerrada.`))}render(){if(this.external)return this.renderExternal(this.external);let e=this.info;if(!e)return;let t=this.ctx.store.snapshot?.ptys?.find(t=>t.id===e.id);t&&(this.info=t);let n=this.info??e,r=this.ctx.agent(n.agentId);r&&this.pendingSelect===n.agentId&&(this.pendingSelect=null,this.ctx.select({type:`agent`,id:r.id})),M(this.nameEl,r?.name??`Claude Code`),bx(this.accEl,this.ctx.account(n.account),n.account),M(this.roomEl,r?.title??n.cwd);let i=n.machine?this.ctx.store.snapshot?.machines?.find(e=>e.id===n.machine)?.label??n.machine:``;M(this.machineEl,i),F(this.machineEl,!i);let o=n.exitedAt!==void 0;M(this.stateEl,o?a(`encerrado`):r?``:n.resumed?a(`retomando…`):a(`iniciando…`)),this.actions.withTakeover=!1,this.actions.render(o?null:r??null),this.tabs.render(r?r.id:null),this.setMode(!1)}renderExternal(e){let t=this.ptyOf(e);if(t)return this.show(t);let n=this.ctx.agent(e);M(this.nameEl,n?.name??a(`Agente`)),n&&bx(this.accEl,this.ctx.account(n.account),n.account);let r=n?this.ctx.store.room(n.roomId):void 0;M(this.roomEl,r?.name??``),M(this.stateEl,a(n?`em outro terminal`:`saiu do escritório`)),M(this.awayTitle,n?.title??``),F(this.awayTitle,!n?.title);let i=n?.machine??ut(e)?.machine,o=i?this.ctx.store.snapshot?.machines?.find(e=>e.id===i)?.label??i:``;M(this.machineEl,o),F(this.machineEl,!o),this.actions.withTakeover=!0,this.actions.render(n??null),this.tabs.render(n?e:null),this.setMode(!0)}setMode(e){F(this.away,!e),F(this.screen,e),this.el.classList.toggle(`is-away`,e)}reveal(){this.el.hidden&&this.movable.restore(),this.el.hidden=!1,this.onShow?.()}show(e,t=!1){this.info=e,this.external=null,t&&(this.pendingSelect=e.agentId),this.reveal(),this.render(),this.ensurePane().then(t=>{this.info?.id===e.id&&(t.attach(e.id),requestAnimationFrame(()=>{t.refit(!0),t.focus()}))}),this.ctx.invalidate()}ensurePane(){return this.pane?Promise.resolve(this.pane):(this.loading??=o(async()=>{let{PtyPane:e}=await import(`./ptypane-DAVYBQ48.js`);return{PtyPane:e}},__vite__mapDeps([6,1,7])).then(({PtyPane:e})=>(this.pane=new e(()=>this.ctx.invalidate()),this.screen.append(this.pane.el),this.pane)),this.loading)}},UD=2e3,WD=120;function GD(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:e<1073741824?`${(e/1048576).toFixed(1)} MB`:`${(e/1073741824).toFixed(2)} GB`}function KD(e,t){let n=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);n.setAttribute(`class`,`ui-perf__spark ${t?`is-warn`:``}`),n.setAttribute(`viewBox`,`0 0 96 20`),n.setAttribute(`width`,`96`),n.setAttribute(`height`,`20`),n.setAttribute(`aria-hidden`,`true`);let r=document.createElementNS(`http://www.w3.org/2000/svg`,`polyline`);return r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,t?`var(--lv-warn, #ffb547)`:`var(--ui-accent, #7cc8ff)`),r.setAttribute(`stroke-width`,`1.5`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`points`,e),n.appendChild(r),n}var qD=class{ctx;el;openerBtn;pollTimer=null;abortController=null;offFrame=null;longTaskObserver=null;longTaskCount=0;frameTimes=[];frameTimestamps=[];data=null;error=null;machinesList;browserCard;browserMetrics;fpsGroup;pauseSwitch;visibilityHandler;constructor(e,t){this.ctx=e,this.openerBtn=t;let n=j(Q.close,a(`Fechar desempenho`),()=>this.close(),`ui-icon-btn--sm`);this.machinesList=P(`div`,{class:`ui-perf__machines`}),this.browserMetrics=P(`div`,{class:`ui-perf__browser-metrics`}),this.browserCard=P(`div`,{class:`ui-card ui-perf__card ui-perf__browser`}),this.fpsGroup=new Bv({label:a(`Limite de FPS`),options:[{value:`60`,label:`60 FPS`,className:`ui-seg__opt`},{value:`30`,label:`30 FPS`,className:`ui-seg__opt`},{value:`15`,label:`15 FPS`,className:`ui-seg__opt`}],indicator:!1,className:`ui-seg ui-perf__fps-seg`,onChange:e=>{let t=Number(e);this.ctx.updatePrefs({fpsCap:t})}}),this.pauseSwitch=Hv(a(`Pausar quando a aba está oculta`),a(`Economiza CPU e bateria interrompendo a renderização com a página em segundo plano.`),()=>{this.ctx.updatePrefs({pauseOnHidden:!this.ctx.prefs.pauseOnHidden}),this.syncPrefs()}),this.browserCard.append(this.browserMetrics,P(`div`,{class:`ui-perf__controls`},P(`div`,{class:`ui-set ui-set--stack`},P(`span`,{class:`ui-set__label`,text:a(`Limite de FPS`)}),this.fpsGroup.el),this.pauseSwitch.row)),this.el=P(`dialog`,{class:`ui-dialog ui-perf`,attrs:{"aria-labelledby":`ui-perf-title`}},P(`div`,{class:`ui-dialog__head`},P(`h2`,{attrs:{id:`ui-perf-title`},text:a(`Desempenho`)}),n),P(`div`,{class:`ui-dialog__body ui-perf__body`},this.machinesList,this.browserCard)),this.el.addEventListener(`click`,e=>{e.target===this.el&&this.close()}),this.el.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.stopPropagation(),this.close())}),this.el.addEventListener(`close`,()=>this.onClosed()),this.visibilityHandler=()=>{this.isOpen&&(typeof document<`u`&&document.hidden?this.stopPolling():this.startPolling())},typeof document<`u`&&document.addEventListener(`visibilitychange`,this.visibilityHandler)}get isOpen(){return this.el.open}open(){this.el.open||(this.el.showModal(),this.openerBtn?.setAttribute(`aria-expanded`,`true`),this.startPolling(),this.startMetrics(),this.syncPrefs(),this.render())}close(){this.el.open&&this.el.close()}toggle(){this.isOpen?this.close():this.open()}onClosed(){this.stopPolling(),this.stopMetrics(),this.openerBtn?.setAttribute(`aria-expanded`,`false`),this.openerBtn?.isConnected&&this.openerBtn.focus({preventScroll:!0})}startPolling(){this.pollTimer||typeof document<`u`&&document.hidden||(this.fetchPerf(),this.pollTimer=setInterval(()=>{this.fetchPerf()},UD))}stopPolling(){this.pollTimer&&=(clearInterval(this.pollTimer),null),this.abortController?.abort(),this.abortController=null}startMetrics(){if(this.frameTimes=[],this.frameTimestamps=[],this.longTaskCount=0,this.ctx.world.onFrameMetric&&(this.offFrame=this.ctx.world.onFrameMetric(e=>{let t=performance.now();this.frameTimes.push(e),this.frameTimestamps.push(t),this.frameTimes.length>WD&&(this.frameTimes.shift(),this.frameTimestamps.shift())})),typeof PerformanceObserver<`u`&&PerformanceObserver.supportedEntryTypes?.includes(`longtask`))try{this.longTaskObserver=new PerformanceObserver(e=>{this.longTaskCount+=e.getEntries().length}),this.longTaskObserver.observe({entryTypes:[`longtask`]})}catch{this.longTaskObserver=null}}stopMetrics(){this.offFrame?.(),this.offFrame=null,this.longTaskObserver?.disconnect(),this.longTaskObserver=null,this.frameTimes=[],this.frameTimestamps=[]}async fetchPerf(){this.abortController?.abort(),this.abortController=new AbortController;try{let e=await fetch(`/api/perf`,{cache:`no-store`,signal:this.abortController.signal});if(!e.ok)throw Error(a(`erro {0}`,[e.status]));this.data=await e.json(),this.error=null}catch(e){e.name!==`AbortError`&&(this.error=e.message)}this.render()}syncPrefs(){let e=this.ctx.prefs.fpsCap||60;this.fpsGroup.value=String(e);let t=this.ctx.prefs.pauseOnHidden;this.pauseSwitch.btn.setAttribute(`aria-checked`,String(t)),this.pauseSwitch.btn.classList.toggle(`is-checked`,t)}render(){if(this.isOpen){if(this.machinesList.replaceChildren(),this.error&&(!this.data||!this.data.machines.length))this.machinesList.append(P(`p`,{class:`ui-perf__error`,text:this.error}));else if(this.data?.machines)for(let e of this.data.machines)this.machinesList.append(this.renderMachineCard(e));this.renderBrowserCard()}}renderMachineCard(e){let t=e.current,n=e.history??[],r=s_(t.cpu.oneCore),i=c_(t.eventLoop.p99),o=u_(n.map(e=>e.cpu.oneCore)),s=u_(n.map(e=>e.memory.rss)),c=u_(n.map(e=>e.eventLoop.p99)),l=P(`span`,{class:`ui-chip ${e.isCentral?`ui-chip--central`:`ui-chip--satellite`}`,text:e.isCentral?a(`Central`):a(`Satélite`)});return P(`div`,{class:`ui-card ui-perf__card`},P(`div`,{class:`ui-perf__card-head`},P(`h3`,{class:`ui-perf__card-title`,text:e.label}),l),P(`div`,{class:`ui-perf__grid`},P(`div`,{class:`ui-perf__metric ${r?`is-warn`:``}`},P(`span`,{class:`ui-perf__label`,text:`CPU`}),P(`span`,{class:`ui-perf__val`,text:`${t.cpu.oneCore}% (${t.cpu.allCores}% total)`}),o?KD(o,r):``),P(`div`,{class:`ui-perf__metric`},P(`span`,{class:`ui-perf__label`,text:`RSS`}),P(`span`,{class:`ui-perf__val`,text:GD(t.memory.rss)}),s?KD(s,!1):``),P(`div`,{class:`ui-perf__metric ${i?`is-warn`:``}`},P(`span`,{class:`ui-perf__label`,text:a(`Event loop (p99)`)}),P(`span`,{class:`ui-perf__val`,text:`${t.eventLoop.p99} ms`}),c?KD(c,i):``),P(`div`,{class:`ui-perf__metric`},P(`span`,{class:`ui-perf__label`,text:a(`Heap JS`)}),P(`span`,{class:`ui-perf__val`,text:`${GD(t.memory.heapUsed)} (${GD(t.memory.external)} ext)`})),P(`div`,{class:`ui-perf__metric`},P(`span`,{class:`ui-perf__label`,text:a(`Tempo de atividade`)}),P(`span`,{class:`ui-perf__val`,text:zt(t.uptime*1e3)}))),P(`div`,{class:`ui-perf__work`},P(`span`,{class:`ui-perf__work-item`,text:`${a(`Transcripts acompanhados`)}: ${t.work.watchedTranscripts}`}),P(`span`,{class:`ui-perf__work-item`,text:`${a(`Lido no intervalo`)}: ${GD(t.work.bytesRead)}`}),P(`span`,{class:`ui-perf__work-item`,text:`${a(`Snapshots construídos`)}: ${t.work.snapshotBuilds} (${a(`{0} ms em média`,[t.work.snapshotBuildTimeMs])})`}),P(`span`,{class:`ui-perf__work-item`,text:`${a(`Tamanho do snapshot`)}: ${GD(t.work.snapshotBytes)}`}),P(`span`,{class:`ui-perf__work-item`,text:`${a(`Clientes SSE`)}: ${t.work.sseClients}`})))}renderBrowserCard(){let e=o_(this.frameTimes,this.frameTimestamps),t=l_(e.fps),n=typeof performance<`u`?performance.memory:void 0,r=n?.usedJSHeapSize?`${GD(n.usedJSHeapSize)} / ${GD(n.totalJSHeapSize??0)}`:a(`não disponível`),i=typeof document<`u`&&typeof document.querySelectorAll==`function`?document.querySelectorAll(`*`).length:0,o=typeof window<`u`&&window.devicePixelRatio?window.devicePixelRatio:1,s=typeof document<`u`&&typeof document.getElementById==`function`?document.getElementById(`world`):null,c=s?`${s.width}×${s.height}`:`—`,l=`${o.toFixed(1)}x (${c})`;this.browserMetrics.replaceChildren(P(`div`,{class:`ui-perf__card-head`},P(`h3`,{class:`ui-perf__card-title`,text:a(`Navegador`)})),P(`div`,{class:`ui-perf__grid`},P(`div`,{class:`ui-perf__metric ${t?`is-warn`:``}`},P(`span`,{class:`ui-perf__label`,text:`FPS`}),P(`span`,{class:`ui-perf__val`,text:e.fps>0?String(e.fps):`—`})),P(`div`,{class:`ui-perf__metric`},P(`span`,{class:`ui-perf__label`,text:a(`Tempo de quadro`)}),P(`span`,{class:`ui-perf__val`,text:`${e.p50} ms (p95: ${e.p95} ms)`})),P(`div`,{class:`ui-perf__metric`},P(`span`,{class:`ui-perf__label`,text:a(`Tarefas longas (>50 ms)`)}),P(`span`,{class:`ui-perf__val`,text:String(this.longTaskCount)})),P(`div`,{class:`ui-perf__metric`},P(`span`,{class:`ui-perf__label`,text:a(`Heap JS`)}),P(`span`,{class:`ui-perf__val`,text:r})),P(`div`,{class:`ui-perf__metric`},P(`span`,{class:`ui-perf__label`,text:a(`Nós do DOM`)}),P(`span`,{class:`ui-perf__val`,text:At(i)})),P(`div`,{class:`ui-perf__metric`},P(`span`,{class:`ui-perf__label`,text:a(`Escala de renderização`)}),P(`span`,{class:`ui-perf__val`,text:l}))),P(`p`,{class:`ui-perf__gpu-note`,text:a(`* uso de GPU não é exposto pelo navegador (o tempo de quadro serve de indicador).`)}))}};async function JD(e){let t=await fetch(`/api/timeline/days`,{signal:e});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json(),r=Array.isArray(n.days)?n.days.filter(e=>j_(e?.day)&&Number.isFinite(e.from)&&Number.isFinite(e.to)):[];return{recording:n.recording===!0,days:r}}async function YD(e,t){if(!j_(e))throw Error(a(`dia inválido`));let n=await fetch(`/api/timeline/${e}`,{signal:t});if(!n.ok)throw Error(`HTTP ${n.status}`);return B_(await n.text())}var XD=6e4,ZD=8,QD=6e4,$D=4,eO=e=>Math.min(36e5,Math.max(6e5,e/8)),tO=(e,t)=>t.includeDemo||!e,nO=class{day;records;from;to;hasDemo;hasReal;keys=[];frame=I_();cursor=-1;every=3e5;recent=new Map;rev=0;createdAt=Date.now();bucketCache=new Map;constructor(e,t){this.day=e,this.records=t;let n=!1,r=!1;t.forEach((e,t)=>{if(e.t===`k`){this.keys.push(t);for(let t of e.agents)t.demo?n=!0:r=!0}else if(e.t===`d`)for(let[,t]of e.agents??[])t&&typeof t.id==`string`&&(t.demo?n=!0:r=!0)}),this.hasDemo=n,this.hasReal=r,this.from=t[0]?.at??0,this.to=t[t.length-1]?.at??this.from}get empty(){return this.records.length===0}moveTo(e){let t=this.indexAt(e);if(t===this.cursor)return;if(t<0){this.frame=I_(),this.recent.clear(),this.cursor=-1;return}let n;if(t<this.cursor||this.cursor<0)n=this.keyAtOrBefore(t),this.recent.clear(),n<0&&(this.frame=I_(),n=0);else{n=this.cursor+1;let e=this.keyAtOrBefore(t);e>this.cursor&&(n=e)}for(let e=n;e<=t;e++)this.apply(e);this.cursor=t}isOff(e){if(this.cursor<0)return!0;let t=this.records[this.cursor];return t.t===`end`||e-t.at>this.every*1.5+QD}get limited(){let e=this.records[this.cursor];return e?.t===`end`&&e.reason===`limit`}snapshot(e,t){let n=this.isOff(e),r=n?[]:[...this.frame.agents.values()].filter(e=>tO(e.demo,t)).map(e=>G_(e,this.recent.get(e.id)??[])),i=n?[]:[...this.frame.rooms.values()].filter(e=>tO(e.demo,t)).map(K_),a=[...this.frame.accounts.values()].filter(e=>tO(e.demo,t)).map(t=>q_(t,e));return{rev:++this.rev,serverTime:e,rooms:i.sort((e,t)=>e.slot-t.slot),agents:r,accounts:a,meta:{demo:r.some(e=>this.frame.agents.get(e.id)?.demo),sources:[],startedAt:this.createdAt,version:`timelapse`,terminal:!1}}}buckets(e){let t=this.bucketCache.get(e.includeDemo);if(t)return t;let n=[];if(this.empty)return n;let r=Math.floor(this.from/XD)*XD,i=Math.min(2882,Math.floor((this.to-r)/XD)+1);for(let e=0;e<i;e++)n.push({at:r+e*XD,present:0,working:0,waiting:0});let a=I_(),o=3e5,s=!1,c={present:0,working:0,waiting:0},l=this.from,u=(e,t,a)=>{let c=s?e:Math.min(t,e+o*1.5+QD);for(let t=Math.max(0,Math.floor((e-r)/XD));t<i&&r+t*6e4<=c;t++){let e=n[t];e.present=Math.max(e.present,a.present),e.working=Math.max(e.working,a.working),e.waiting=Math.max(e.waiting,a.waiting)}};for(let t of this.records){if(u(l,t.at,c),t.t===`k`){let e=F_(t);a.agents=e.agents,a.rooms=e.rooms,a.accounts=e.accounts,o=t.every,s=!1}else t.t===`d`?(R_(a,t),s=!1):s=!0;c=s?{present:0,working:0,waiting:0}:rO(a,e),l=t.at,u(t.at,t.at,c)}return this.bucketCache.set(e.includeDemo,n),n}peaks(e){let t=this.buckets(e).filter(e=>e.working>0).sort((e,t)=>t.working-e.working||t.present-e.present||e.at-t.at),n=[],r=eO(this.to-this.from);for(let e of t){if(n.length>=$D)break;n.some(t=>Math.abs(t.at-e.at)<r)||n.push({at:e.at,working:e.working,present:e.present})}return n.sort((e,t)=>e.at-t.at)}apply(e){let t=this.records[e];if(t.t===`k`){this.frame=F_(t),this.every=t.every;for(let e of[...this.recent.keys()])this.frame.agents.has(e)||this.recent.delete(e);for(let e of t.agents)this.remember(e)}else if(t.t===`d`){R_(this.frame,t);for(let[e,n]of t.agents??[])if(!n)this.recent.delete(e);else if(n.activity){let t=this.frame.agents.get(e);t&&this.remember(t)}}}remember(e){if(!e.activity)return;let t=W_(e.id,e.activity),n=this.recent.get(e.id)??[];n[n.length-1]?.id!==t.id&&(n.push(t),n.length>ZD&&n.splice(0,n.length-ZD),this.recent.set(e.id,n))}indexAt(e){let t=0,n=this.records.length-1,r=-1;for(;t<=n;){let i=t+n>>1;this.records[i].at<=e?(r=i,t=i+1):n=i-1}return r}keyAtOrBefore(e){let t=-1;for(let n of this.keys){if(n>e)break;t=n}return t}};function rO(e,t){let n=0,r=0,i=0;for(let a of e.agents.values())tO(a.demo,t)&&a.status!==`offline`&&a.status!==`done`&&(n++,a.status===`working`?r++:a.status===`waiting`&&i++);return{present:n,working:r,waiting:i}}var iO=[60,180,600],aO=180,oO=200,sO=120,cO=60,lO={timelapse:Z([`....#####..`,`..##.....#.`,`##.#......#`,`.###..#...#`,`..##..#...#`,`......###.#`,`#.........#`,`.#.......#.`,`..#######..`]),play:Z([`##......`,`####....`,`######..`,`########`,`######..`,`####....`,`##......`]),pause:Z([`###..###`,`###..###`,`###..###`,`###..###`,`###..###`,`###..###`,`###..###`]),peak:Z([`#####`,`.###.`,`..#..`])},uO=new Intl.DateTimeFormat(e(),{weekday:`short`,day:`numeric`,month:`short`}),dO=e=>Ft(e,!1);function fO(e,t){return e===t?a(`Hoje`):e===N_(t,-1)?a(`Ontem`):uO.format(M_(e))}function pO(e,t){let n=(t-e)/36e5,r=[1,2,3,4,6].find(e=>n/e<=6)??12,i=[],a=new Date(e);a.setMinutes(0,0,0);for(let n=a.getTime();n<=t;)n>e&&new Date(n).getHours()%r===0&&i.push(n),a.setHours(a.getHours()+1),n=a.getTime();return i}var mO=class{ctx;el;badge;vignette;open=!1;lapseH=-1;status=`idle`;message=``;days=[];loadSeq=0;replay=null;cache=new Map;active=!1;t=0;playing=!1;speed=aO;includeDemo=!0;raf=0;lastReal=0;lastPush=0;lastSeek=0;seekTimer=null;abort=null;chartSig=``;daysSig=``;playback={clock:()=>this.t,scale:()=>this.playing?vu(this.speed):0};playBtn;timeEl;spanEl;daySel;speedGroup;demoBtn;msgEl;track;chart;range;peaksEl;ticksEl;badgeTime;badgeDay;badgeNote;constructor(e){this.ctx=e,this.playBtn=j(lO.play,a(`Reproduzir`),()=>this.togglePlay(),`ui-lapse__play`),this.timeEl=P(`strong`,{class:`ui-lapse__time`,text:`--:--`}),this.spanEl=P(`span`,{class:`ui-lapse__span`}),this.daySel=new zv({label:a(`Dia gravado`),className:`ui-lapse__day`,onChange:e=>void this.loadDay(e)}),this.speedGroup=new Bv({label:a(`Velocidade`),options:iO.map(e=>({value:String(e),label:`${e}×`,title:hO(e),className:`ui-seg__opt`})),value:String(aO),className:`ui-seg ui-lapse__speed`,indicator:!1,onChange:e=>{let t=iO.find(t=>String(t)===e);t!==void 0&&(this.speed=t,this.ctx.invalidate())}}),this.demoBtn=P(`button`,{class:`ui-btn ui-btn--sm ui-lapse__demo`,type:`button`,text:a(`Demonstração`),title:a(`Mostrar também os agentes do modo demonstração gravados neste dia`),hidden:!0}),this.demoBtn.addEventListener(`click`,()=>{this.includeDemo=!this.includeDemo,this.active&&this.seek(this.t),this.ctx.invalidate()});let t=P(`button`,{class:`ui-btn ui-btn--sm ui-lapse__live`,type:`button`,title:a(`Sair do timelapse e voltar ao escritório ao vivo (L)`)},P(`span`,{class:`ui-lapse__live-dot`,attrs:{"aria-hidden":`true`}}),a(`Voltar ao vivo`));t.addEventListener(`click`,()=>this.close()),this.chart=P(`canvas`,{class:`ui-lapse__chart`,attrs:{"aria-hidden":`true`}}),this.range=P(`input`,{class:`ui-lapse__range`,type:`range`,attrs:{min:0,max:0,step:cO,value:0,"aria-label":a(`Momento da reprodução`)}}),this.range.addEventListener(`input`,()=>this.scrub(this.rangeTime(),!1)),this.range.addEventListener(`change`,()=>this.scrub(this.rangeTime(),!0)),this.range.addEventListener(`keydown`,e=>{e.key===` `&&(e.preventDefault(),this.togglePlay())}),this.peaksEl=P(`div`,{class:`ui-lapse__peaks`}),this.ticksEl=P(`div`,{class:`ui-lapse__ticks`,attrs:{"aria-hidden":`true`}}),this.track=P(`div`,{class:`ui-lapse__track`},this.chart,this.peaksEl,this.range),this.msgEl=P(`p`,{class:`ui-lapse__msg`,role:`status`,hidden:!0}),this.el=P(`section`,{class:`ui-panel ui-lapse`,hidden:!0,attrs:{"aria-label":a(`Timelapse do dia`)}},P(`div`,{class:`ui-lapse__row`},this.playBtn,P(`div`,{class:`ui-lapse__clock`},this.timeEl,this.spanEl),this.daySel.el,P(`span`,{class:`ui-lapse__grow`}),this.speedGroup.el,this.demoBtn,t),this.msgEl,P(`div`,{class:`ui-lapse__timeline`},this.track,this.ticksEl)),this.el.addEventListener(`keydown`,e=>{e.key===`Escape`&&!e.defaultPrevented&&(e.preventDefault(),this.close())}),this.badgeTime=P(`strong`,{class:`ui-lapse-badge__time`}),this.badgeDay=P(`span`,{class:`ui-lapse-badge__day`}),this.badgeNote=P(`span`,{class:`ui-lapse-badge__note`}),this.badge=P(`div`,{class:`ui-lapse-badge`,hidden:!0,role:`status`,attrs:{"aria-live":`off`}},P(`span`,{class:`ui-lapse-badge__rec`,attrs:{"aria-hidden":`true`}}),P(`span`,{class:`ui-lapse-badge__label`,text:`REPLAY`}),this.badgeTime,this.badgeDay,this.badgeNote),this.vignette=P(`div`,{class:`ui-lapse-vignette`,hidden:!0,attrs:{"aria-hidden":`true`}}),typeof ResizeObserver==`function`&&(new ResizeObserver(()=>this.drawChart(!0)).observe(this.track),new ResizeObserver(()=>this.syncHeight()).observe(this.el))}syncHeight(){let e=this.open?Math.round(this.el.getBoundingClientRect().height):0;e!==this.lapseH&&(this.lapseH=e,this.ctx.root.style.setProperty(`--lapse-h`,`${e}px`))}get isOpen(){return this.open}get replayTime(){return this.active?this.t:null}toggle(){this.open?this.close():this.show()}async show(){if(this.open)return;this.open=!0,this.cache.clear(),this.status=`loading`,this.message=a(`Carregando os dias gravados…`),this.ctx.invalidate(),this.abort?.abort();let e=this.abort=new AbortController;try{let t=await JD(e.signal);if(!this.open||e.signal.aborted)return;if(this.days=t.days,!t.days.length){this.status=`empty`,this.message=t.recording?a(`Nada gravado ainda: o Habblaud grava o escritório enquanto está ligado. Volte daqui a pouco.`):a(`A gravação está desligada neste servidor (HABBLAUD_TIMELINE=0) e não há dias gravados.`),this.ctx.invalidate();return}let n=A_(Date.now());await this.loadDay(t.days.find(e=>e.day===n)?.day??t.days[0].day,!0)}catch(t){if(e.signal.aborted)return;this.status=`error`,this.message=a(`Não foi possível buscar a linha do tempo no servidor.`),console.warn(`[timelapse]`,t),this.ctx.invalidate()}}close(){this.open&&(this.open=!1,this.abort?.abort(),this.abort=null,this.exit(),this.status=`idle`,this.ctx.invalidate(),this.ctx.announce(a(`De volta ao escritório ao vivo.`)))}syncSpeed(e){this.speedGroup.value=String(this.speed),e!==void 0&&this.speedGroup.buttons[iO.indexOf(e)]?.focus()}render(){F(this.el,!this.open);let e=this.active;if(F(this.badge,!e),F(this.vignette,!e),this.ctx.root.classList.toggle(`is-replay`,e),document.documentElement.classList.toggle(`is-replay`,e),!this.open)return;let t=this.replay,n=this.status===`ready`&&!!t;F(this.msgEl,n||!this.message),M(this.msgEl,this.message),this.el.classList.toggle(`is-loading`,this.status===`loading`),this.playBtn.disabled=!n,this.range.disabled=!n,this.daySel.disabled=!this.days.length,this.playBtn.innerHTML=this.playing?lO.pause:lO.play;let r=this.playing?a(`Pausar`):t&&this.t>=t.to?a(`Reproduzir de novo`):a(`Reproduzir`);if(N(this.playBtn,`aria-label`,r),A(this.playBtn,a(`{0} (espaço na linha do tempo)`,[r])),this.syncSpeed(),F(this.demoBtn,!(t?.hasDemo&&t.hasReal)),this.demoBtn.classList.toggle(`is-on`,this.includeDemo),N(this.demoBtn,`aria-pressed`,String(this.includeDemo)),this.renderDays(),t){let e=Math.max(0,Math.round((t.to-t.from)/1e3));N(this.range,`max`,String(e)),M(this.spanEl,`${dO(t.from)}–${dO(t.to)}`)}this.drawChart(!1),this.renderClock()}renderDays(){let e=A_(Date.now()),t=`${e}|${this.days.map(e=>`${e.day}:${e.from}:${e.to}`).join(`,`)}`;t!==this.daysSig&&(this.daysSig=t,this.daySel.setOptions(this.days.map(t=>({value:t.day,label:`${fO(t.day,e)} · ${dO(t.from)}–${dO(t.to)}`})),this.replay?.day)),this.replay&&this.daySel.value!==this.replay.day&&(this.daySel.value=this.replay.day)}async loadDay(e,t=!1){let n=this.playing||t,r=++this.loadSeq;this.pause();let i=this.cache.get(e);if(!i){this.status=`loading`,this.message=a(`Carregando o dia…`),this.ctx.invalidate();let t=this.abort??new AbortController;try{i=new nO(e,await YD(e,t.signal))}catch(e){if(t.signal.aborted||!this.open||r!==this.loadSeq)return;this.status=`error`,this.message=a(`Não foi possível carregar este dia.`),console.warn(`[timelapse]`,e),this.ctx.invalidate();return}if(!this.open||(this.cache.set(e,i),r!==this.loadSeq))return}if(i.empty){this.status=`empty`,this.message=a(`Nada gravado neste dia.`),this.ctx.invalidate();return}this.replay=i,this.includeDemo=!i.hasReal,this.status=`ready`,this.message=``,this.chartSig=``,this.seek(i.from),n&&this.play(),this.ctx.invalidate()}togglePlay(){this.playing?this.pause():this.play(),this.ctx.invalidate()}play(){let e=this.replay;e&&!this.playing&&(this.t>=e.to&&this.seek(e.from),this.playing=!0,this.lastReal=performance.now(),this.lastPush=this.lastReal,this.raf||=requestAnimationFrame(this.loop))}pause(){this.playing=!1,this.raf&&cancelAnimationFrame(this.raf),this.raf=0,this.active&&this.push()}loop=()=>{this.raf=0;let e=this.replay;if(!this.playing||!e)return;let t=performance.now(),n=Math.min(250,Math.max(0,t-this.lastReal));this.lastReal=t,this.t=Math.min(e.to,this.t+n*this.speed);let r=this.t>=e.to;if((r||t-this.lastPush>=oO)&&(this.lastPush=t,this.push()),this.renderClock(),r){this.playing=!1,this.ctx.announce(a(`Fim da gravação deste dia.`)),this.ctx.invalidate();return}this.raf=requestAnimationFrame(this.loop)};push(){let e=this.replay;e&&(e.moveTo(this.t),this.ctx.store.pushReplay(e.snapshot(this.t,{includeDemo:this.includeDemo})))}seek(e){let t=this.replay;t&&(this.t=Math.min(t.to,Math.max(t.from,e)),this.active=!0,this.ctx.world.setPlayback?.(this.playback),this.push(),this.lastPush=performance.now(),this.renderClock())}scrub(e,t){if(!this.replay)return;this.t=e,this.renderClock(),this.seekTimer&&clearTimeout(this.seekTimer),this.seekTimer=null;let n=sO-(performance.now()-this.lastSeek);if(t||n<=0){this.lastSeek=performance.now(),this.seek(e);return}this.seekTimer=setTimeout(()=>{this.seekTimer=null,this.lastSeek=performance.now(),this.seek(this.t)},n)}exit(){this.pause(),this.seekTimer&&clearTimeout(this.seekTimer),this.seekTimer=null,this.active&&(this.active=!1,this.ctx.world.setPlayback?.(null),this.ctx.store.stopReplay(),this.replay=null)}rangeTime(){return(this.replay?.from??0)+Number(this.range.value)*1e3}renderClock(){let e=this.replay;if(!e){M(this.timeEl,`--:--`);return}let t=dO(this.t);M(this.timeEl,t),M(this.badgeTime,t);let n=A_(Date.now());M(this.badgeDay,e.day===n?``:fO(e.day,n)),e.moveTo(this.t),M(this.badgeNote,e.isOff(this.t)?e.limited?a(`gravação pausada (limite do dia)`):a(`sem dados (servidor desligado)`):``);let r=String(Math.round((this.t-e.from)/1e3));this.range.value!==r&&document.activeElement!==this.range&&(this.range.value=r);let i=e.to>e.from?(this.t-e.from)/(e.to-e.from)*100:0;_t(this.track,`--p`,`${i.toFixed(2)}%`),N(this.range,`aria-valuetext`,`${t}${e.day===n?``:`, ${fO(e.day,n)}`}`)}drawChart(e){let t=this.replay,n=this.chart.clientWidth,r=this.chart.clientHeight,i=`${t?.day}|${t?.records.length}|${this.includeDemo}|${n}x${r}`;if(!e&&i===this.chartSig)return;this.chartSig=i;let o=this.chart.getContext(`2d`);if(!o||!n||!r)return;let s=Math.min(2,window.devicePixelRatio||1);if(this.chart.width=Math.round(n*s),this.chart.height=Math.round(r*s),o.setTransform(s,0,0,s,0,0),o.clearRect(0,0,n,r),this.peaksEl.replaceChildren(),this.ticksEl.replaceChildren(),!t)return;let c={includeDemo:this.includeDemo},l=Math.max(1,t.to-t.from),u=e=>(e-t.from)/l*n,d=t.buckets(c),f=Math.max(1,...d.map(e=>e.present)),p=Math.max(1,XD/l*n+.5),m=getComputedStyle(this.ctx.root),h=m.getPropertyValue(`--st-working`).trim()||`#4fd18b`,g=m.getPropertyValue(`--st-waiting`).trim()||`#ffb547`;for(let e of d){let t=u(e.at),n=Math.round(e.present/f*(r-3)),i=Math.round(e.working/f*(r-3));n&&(o.fillStyle=`rgba(160, 176, 210, 0.28)`,o.fillRect(t,r-n,p,n)),i&&(o.globalAlpha=.8,o.fillStyle=h,o.fillRect(t,r-i,p,i),o.globalAlpha=1),e.waiting&&(o.fillStyle=g,o.fillRect(t,r-Math.max(n,i)-2,p,2))}for(let e of t.peaks(c)){let n=a(`Pico às {0}: {1} {2}`,[dO(e.at),e.working,e.working===1?a(`agente trabalhando`):a(`agentes trabalhando`)]),r=P(`button`,{class:`ui-lapse__peak`,type:`button`,title:n,attrs:{"aria-label":n},style:`left: ${(e.at-t.from)/l*100}%`});r.innerHTML=lO.peak,r.addEventListener(`click`,()=>{this.seek(e.at),this.ctx.invalidate()}),this.peaksEl.append(r)}for(let e of pO(t.from,t.to))this.ticksEl.append(P(`span`,{class:`ui-lapse__tick`,text:dO(e),style:`left: ${(e-t.from)/l*100}%`}))}};function hO(e){return a(`{0}× — 1 min de reprodução = {1} h do dia`,[e,e/60])}var gO=4,_O=2e4,vO={info:5e3,success:6e3,warn:9e3,alert:1/0},yO=class{ctx;el;toasts=[];constructor(e){this.ctx=e,this.el=P(`div`,{class:`ui-toasts`,attrs:{"aria-live":`polite`,"aria-relevant":`additions`,"aria-label":a(`Avisos`)}}),e.store.on(`notice`,e=>this.push(e))}push(e){if(e.level!==`alert`&&e.agentId){let t=this.ctx.agent(e.agentId)?.account;if(t&&this.ctx.prefs.hiddenAccounts.includes(t))return}let t=`${e.level}|${e.agentId??``}|${e.text}`,n=this.toasts.find(n=>n.key===t&&e.at-n.notice.at<_O);if(n){n.repeats++,n.notice=e,M(n.count,`×${n.repeats}`),F(n.count,!1),n.el.classList.remove(`is-bump`),n.el.offsetWidth,n.el.classList.add(`is-bump`),this.arm(n,vO[e.level]);return}e.level===`alert`&&e.agentId&&this.toasts.filter(t=>t.notice.level===`alert`&&t.notice.agentId===e.agentId).forEach(e=>this.dismiss(e));let r=this.create(e,t);for(this.toasts.push(r),this.el.prepend(r.el),this.arm(r,vO[e.level]);this.toasts.length>gO;){let e=this.toasts.find(e=>e.notice.level!==`alert`)??this.toasts[0];this.dismiss(e)}}render(){for(let e of[...this.toasts]){if(e.notice.level!==`alert`||!e.notice.agentId)continue;let t=this.ctx.agent(e.notice.agentId);!t||t.status!==`waiting`?this.dismiss(e):e.answer&&F(e.answer,!t.permission)}}create(e,t){let n=e.agentId?this.ctx.agent(e.agentId):void 0,r=P(`span`,{class:`ui-toast__count`,hidden:!0}),i=P(`button`,{class:`ui-toast__body`,type:`button`,title:e.agentId||e.roomId?a(`Mostrar no escritório`):``},n?bv(n,`xs`):null,P(`span`,{class:`ui-toast__text`,text:e.text}),r);i.addEventListener(`click`,()=>{e.agentId&&this.ctx.agent(e.agentId)?this.ctx.select({type:`agent`,id:e.agentId},{focus:!0}):e.roomId&&this.ctx.store.room(e.roomId)&&this.ctx.select({type:`room`,id:e.roomId},{focus:!0})});let o=P(`div`,{class:`ui-toast ui-toast--${e.level}`,role:e.level===`alert`?`alert`:`status`},i),s={key:t,notice:e,el:o,count:r,repeats:1,timer:null,remaining:0,startedAt:0};if(e.level===`alert`&&e.agentId){let t=e.agentId;s.answer=P(`button`,{class:`ui-toast__answer`,type:`button`,text:a(`Responder`),title:a(`Responder pelo escritório (aprovar, recusar ou responder a pergunta)`),hidden:!n?.permission,on:{click:()=>ew(this.ctx,t)}}),o.append(s.answer)}return o.append(j(Q.close,a(`Fechar aviso`),()=>this.dismiss(s),`ui-icon-btn--sm ui-toast__close`)),o.addEventListener(`mouseenter`,()=>this.pause(s)),o.addEventListener(`mouseleave`,()=>this.arm(s,s.remaining)),s}arm(e,t){e.timer&&clearTimeout(e.timer),e.timer=null,e.remaining=t,Number.isFinite(t)&&(e.startedAt=Date.now(),e.timer=setTimeout(()=>this.dismiss(e),t))}pause(e){e.timer&&(clearTimeout(e.timer),e.timer=null,e.remaining=Math.max(1500,e.remaining-(Date.now()-e.startedAt)))}dismiss(e){let t=this.toasts.indexOf(e);if(t<0)return;this.toasts.splice(t,1),e.timer&&clearTimeout(e.timer),e.el.classList.add(`is-leaving`);let n=()=>e.el.remove();if(typeof e.el.animate!=`function`||ht())return n();let r=e.el.animate([{opacity:1,transform:`translateX(0)`,height:`${e.el.offsetHeight}px`},{opacity:0,transform:`translateX(24px)`,height:`${e.el.offsetHeight}px`,offset:.6},{opacity:0,transform:`translateX(24px)`,height:`0px`,marginBottom:`0px`}],{duration:280,easing:`cubic-bezier(.4,0,.2,1)`,fill:`forwards`});r.onfinish=n}},bO=`habblaud.spawn.provider`,xO=`habblaud.spawn.destination`,SO=[`claude`,`gentle-shell`,`codex`];function CO(e,t){let n=[...e];if(n.length<=t||t<3)return e;let r=t-1,i=Math.ceil(r/2);return`${n.slice(0,i).join(``).trimEnd()}…${n.slice(n.length-(r-i)).join(``).trimStart()}`}function wO(e,t=52){let n=new Map(e.workspaces.map(e=>[e.id,e.label||e.id])),r=new Map(e.tabs.map(e=>[e.id,e.label||e.id]));return e.panes.map(e=>{let i=n.get(e.workspaceId)??e.workspaceId,a=r.get(e.tabId)??e.tabId,o=e.label||e.agent||e.id;return{id:e.id,text:CO(`${i} › ${a} · ${o}`,t),title:`${i} › ${a} › ${o}`}})}function TO(e,t,n=!1){return{background:e===`claude`,window:n,herdr:t}}function EO(e,t,n,r,i=!1){let a=TO(t,r&&!!n,i);return e.kind===`background`?a.background:e.kind===`window`?a.window:!a.herdr||!n?!1:e.kind===`tab`?n.workspaces.some(t=>t.id===e.workspaceId):n.panes.some(t=>t.id===e.paneId)}function DO(e,t,n,r,i=!1){let a=t.filter(e=>e.available).map(e=>e.id),o=a.find(t=>t===e.provider)??a[0]??`claude`;if(e.dest&&EO(e.dest,o,n,r,i))return{provider:o,dest:e.dest};let s=r?n?.workspaces[0]:void 0;return s?{provider:o,dest:{kind:`tab`,workspaceId:s.id}}:i?{provider:o,dest:{kind:`window`}}:{provider:o,dest:{kind:`background`}}}function OO(){try{return globalThis.localStorage}catch{return}}function kO(e){if(!e||typeof e!=`object`)return;let t=e;if(t.kind===`background`)return{kind:`background`};if(t.kind===`window`)return{kind:`window`};if(t.kind===`tab`&&typeof t.workspaceId==`string`&&t.workspaceId)return{kind:`tab`,workspaceId:t.workspaceId};if(t.kind===`split`&&typeof t.paneId==`string`&&t.paneId&&(t.direction===`right`||t.direction===`down`))return{kind:`split`,paneId:t.paneId,direction:t.direction}}function AO(e=OO()){let t={};try{let n=e?.getItem(bO);n&&SO.includes(n)&&(t.provider=n);let r=e?.getItem(xO),i=r?kO(JSON.parse(r)):void 0;i&&(t.dest=i)}catch{}return t}function jO(e,t,n=OO()){try{n?.setItem(bO,e),n?.setItem(xO,JSON.stringify(t))}catch{}}var MO=`habblaud.spawn.models`,NO=/^[A-Za-z0-9][A-Za-z0-9._/:-]*$/;function PO(e){let t={value:``,label:a(`Padrão`)};return e?e.free?{kind:`text`,options:[t],state:e.state}:{kind:`select`,options:[t,...e.models.map(e=>({value:e,label:e}))],state:e.state}:{kind:`select`,options:[t],state:`unavailable`}}function FO(e){return e.length<=100&&NO.test(e)}function IO(e,t){return e?t.kind===`text`?FO(e)?e:``:t.options.some(t=>t.value===e)?e:``:``}var LO=[`claude`,`gentle-shell`,`codex`];function RO(){try{return localStorage}catch{return}}function zO(e=RO()){let t={};try{let n=e?.getItem(MO),r=n?JSON.parse(n):void 0;if(r&&typeof r==`object`)for(let e of LO){let n=r[e];typeof n==`string`&&FO(n)&&(t[e]=n)}}catch{}return t}function BO(e,t,n=RO()){try{let r={...zO(n)};t?r[e]=t:delete r[e],n?.setItem(MO,JSON.stringify(r))}catch{}}var VO=8e3,HO=15728640,UO=700,WO=9e4,GO=2e3,KO=8,qO=`habblaud.spawn.folder`;function JO(e){if(!e)return[];let t=new Map;for(let n of e.agents)t.set(n.roomId,Math.max(t.get(n.roomId)??0,n.lastEventAt??0));let n=[...e.rooms].filter(e=>!P_(e.id)&&!e.machine&&/^(\/|[A-Za-z]:[\\/])/.test(e.path??``)).sort((e,n)=>(t.get(n.id)??0)-(t.get(e.id)??0)).map(e=>e.path);return[...new Set(n)]}function YO(e){return e.replace(/^\/(Users|home)\/[^/]+(?=\/|$)/,`~`).replace(/^[A-Za-z]:\\Users\\[^\\]+(?=\\|$)/i,`~`)}function XO(e,t=Date.now()){if(!e)return``;let n=Math.max(0,Math.round((t-e)/6e4));if(n<1)return a(`agora`);if(n<60)return`${n} min`;let r=Math.round(n/60);return r<48?`${r} h`:`${Math.round(r/24)} d`}function ZO(e){return e<1024?`${e} B`:e<1048576?`${Math.round(e/1024)} KB`:`${(e/1024/1024).toFixed(1).replace(`.`,`,`)} MB`}async function QO(e,t){let n;try{n=await fetch(e,{credentials:`same-origin`,cache:`no-store`,...t})}catch{throw Error(a(`o Habblaud não respondeu`))}let r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.error??a(`erro {0}`,[n.status]));return r}function $O(){try{return localStorage.getItem(qO)??``}catch{return``}}function ek(e){try{localStorage.setItem(qO,e)}catch{}}var tk=class{ctx;el;folderList;otherBtn;folder;prompt;fileInput;fileList;dictate;submitBtn;status;anchor;busy=!1;folders=[];selected=``;typing=!1;files=[];providerList;destGroup;wsSelect;paneSelect;dirSelect;herdrHint;gsHint;modelSelect;modelText;modelHint;modelListing=null;modelPrefs=zO();model=``;modelSeq=0;modelTimer;providers=[{id:`claude`,available:!0}];herdrAvailable=!1;herdrReason=``;windowAvailable=!1;listing=null;provider;dest;saved;constructor(e){this.ctx=e,this.saved=AO();let t=DO(this.saved,this.providers,null,!1);this.provider=t.provider,this.dest=t.dest,this.providerList=new Bv({label:a(`Ferramenta`),options:[{value:`claude`,label:Bb.claude,className:`ui-spawn__provider`}],value:this.provider,className:`ui-spawn__providers`,onChange:e=>this.pickProvider(e)}),this.destGroup=new Bv({label:a(`Onde abrir`),options:[{value:`background`,label:a(`Em segundo plano`),className:`ui-spawn__dest-radio`},{value:`window`,label:a(`Em uma nova janela de terminal`),className:`ui-spawn__dest-radio`},{value:`tab`,label:a(`Nova aba em`),className:`ui-spawn__dest-radio`},{value:`split`,label:a(`Dividir painel`),className:`ui-spawn__dest-radio`}],value:this.dest.kind,className:`ui-spawn__dest-options`,onChange:e=>this.pickDest(e)}),this.wsSelect=new zv({label:a(`Espaço do herdr`),className:`ui-spawn__select ui-spawn__select--workspace`,onChange:()=>this.pickDest(`tab`)}),this.paneSelect=new zv({label:a(`Painel para dividir`),className:`ui-spawn__select ui-spawn__select--pane`,onChange:()=>this.pickDest(`split`)}),this.dirSelect=new zv({label:a(`Direção`),className:`ui-spawn__select ui-spawn__select--dir`,options:[{value:`right`,label:a(`à direita`)},{value:`down`,label:a(`para baixo`)}]}),this.modelSelect=new zv({label:a(`Modelo`),className:`ui-spawn__select ui-spawn__select--model`,options:[{value:``,label:a(`Padrão`)}],value:``,onChange:e=>{this.model=e}}),this.modelText=P(`input`,{class:`ui-rename__input ui-spawn__model-text`,type:`text`,hidden:!0,attrs:{placeholder:a(`Padrão (ou escreva o modelo, ex.: gpt-5.5)`),maxlength:100,spellcheck:`false`,autocomplete:`off`,autocapitalize:`none`,"aria-label":a(`Outro modelo`)}}),this.modelText.addEventListener(`input`,()=>{this.model=this.modelText.value.trim()}),this.modelText.addEventListener(`keydown`,e=>e.stopPropagation()),this.modelText.addEventListener(`keyup`,e=>e.stopPropagation()),this.modelHint=P(`p`,{class:`ui-rename__hint`,hidden:!0}),this.herdrHint=P(`p`,{class:`ui-rename__hint`,hidden:!0,text:a(`Para abrir em abas e painéis, abra o herdr`)}),this.gsHint=P(`p`,{class:`ui-rename__hint`,hidden:!0,text:a(`O chat do Gentle Shell não volta quando o herdr reinicia (veja herdr integration install pi)`)});let n=P(`div`,{class:`ui-spawn__dests`},this.destGroup.el,this.wsSelect.el,this.paneSelect.el,this.dirSelect.el);this.folderList=new Bv({label:a(`Projetos recentes`),options:[],indicator:!1,className:`ui-spawn__folders`,onChange:e=>this.pick(e)}),this.otherBtn=P(`button`,{class:`ui-spawn__other`,type:`button`,on:{click:()=>this.showOther(!0)}},a(`+ Outra pasta`)),this.folder=P(`input`,{class:`ui-rename__input ui-spawn__path`,type:`text`,hidden:!0,attrs:{id:`ui-spawn-folder`,placeholder:`/Users/voce/projeto`,spellcheck:`false`,autocomplete:`off`,autocapitalize:`none`,"aria-label":a(`Caminho da pasta`)}}),this.prompt=P(`textarea`,{class:`ui-rename__input ui-spawn__prompt`,attrs:{id:`ui-spawn-prompt`,rows:5,maxlength:VO,placeholder:a(`O que o agente deve fazer (opcional)`)}}),this.fileInput=P(`input`,{type:`file`,hidden:!0,attrs:{multiple:!0,"aria-hidden":`true`,tabindex:`-1`}}),this.fileInput.addEventListener(`change`,()=>{this.addFiles([...this.fileInput.files??[]]),this.fileInput.value=``});let r=P(`button`,{class:`ui-btn ui-spawn__attach`,type:`button`,title:a(`Anexar imagens ou arquivos ao pedido`),attrs:{"aria-label":a(`Anexar imagens ou arquivos ao pedido`)},on:{click:()=>this.fileInput.click()}}),i=P(`span`,{attrs:{"aria-hidden":`true`}});i.innerHTML=Q.attach,r.append(i,P(`span`,{text:a(`Anexar`)})),this.dictate=new My(e=>{let{value:t,caret:n}=wy(this.prompt.value,this.prompt.selectionStart??this.prompt.value.length,this.prompt.selectionEnd??this.prompt.value.length,e.text);this.prompt.value=t.slice(0,VO),this.prompt.setSelectionRange(n,n)},(e,t)=>this.say(e,t)),F(this.dictate.el,!0),this.fileList=P(`ul`,{class:`ui-spawn__files`,attrs:{"aria-label":a(`Anexos`)}}),this.submitBtn=P(`button`,{class:`ui-btn ui-perm__btn ui-perm__btn--allow ui-spawn__go`,type:`button`,on:{click:()=>void this.submit()}},a(`Começar`)),this.status=P(`p`,{class:`ui-rename__hint ui-spawn__status`,attrs:{role:`status`,"aria-live":`polite`}});for(let e of[this.folder,this.prompt])e.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),this.submit())}),e.addEventListener(`keyup`,e=>e.stopPropagation());this.folder.addEventListener(`input`,()=>{this.selected=this.folder.value.trim(),this.renderFolders()});let o=j(Q.close,a(`Fechar`),()=>this.hide(),`ui-icon-btn--sm`);this.el=P(`div`,{class:`ui-popover ui-spawn`,role:`dialog`,tabIndex:-1,attrs:{"aria-label":a(`Novo agente`),id:`ui-spawn`,popover:`auto`}},P(`div`,{class:`ui-popover__head`},P(`h2`,{text:a(`Novo agente`)}),o),P(`div`,{class:`ui-set-group ui-spawn__body`},P(`p`,{class:`ui-spawn__label`,attrs:{id:`ui-spawn-folders-label`},text:a(`Projeto`)}),this.folderList.el,this.otherBtn,this.folder,P(`p`,{class:`ui-spawn__label`,attrs:{id:`ui-spawn-provider-label`},text:a(`Ferramenta`)}),this.providerList.el,P(`p`,{class:`ui-spawn__label`,attrs:{id:`ui-spawn-model-label`},text:a(`Modelo`)}),this.modelSelect.el,this.modelText,this.modelHint,P(`p`,{class:`ui-spawn__label`,attrs:{id:`ui-spawn-dest-label`},text:a(`Onde abrir`)}),n,this.herdrHint,this.gsHint,P(`label`,{class:`ui-spawn__label`,attrs:{for:`ui-spawn-prompt`},text:a(`Pedido`)}),this.prompt,P(`div`,{class:`ui-spawn__tools`},this.dictate.el,r,this.fileInput),this.fileList,P(`p`,{class:`ui-rename__hint`,text:a(`Começa na hora uma sessão nova no computador, na pasta, com a ferramenta e no lugar escolhidos; as permissões chegam aqui. Em segundo plano, pasta que o Claude Code ainda não conhece abre no app do Claude e espera o Enter lá. Sem herdr, "Em uma nova janela de terminal" abre o terminal do computador já com a ferramenta rodando. Anexos vão para ~/.habblaud/attachments e o pedido leva os caminhos.`)}),this.submitBtn,this.status)),this.el.addEventListener(`toggle`,()=>{this.anchor?.setAttribute(`aria-expanded`,String(this.isOpen)),this.isOpen||this.dictate.cancel()}),this.renderTargets(),this.loadModels()}get isOpen(){try{return this.el.matches(`:popover-open`)}catch{return this.el.classList.contains(`is-open`)}}toggle(e){if(this.anchor=e,this.isOpen)return this.hide();this.folders.length||this.setFolders(JO(this.ctx.store.snapshot).map(e=>({path:e,name:e.split(/[\\/]/).pop()||e,lastAt:0}))),this.loadFolders(),this.loadTargets(),this.checkDictation(),this.busy||M(this.status,``);let t=e.getBoundingClientRect();this.el.style.top=`${Math.round(t.bottom+8)}px`,this.el.style.right=`${Math.max(8,Math.round(innerWidth-t.right-4))}px`,typeof this.el.showPopover==`function`?this.el.showPopover():this.el.classList.add(`is-open`),e.setAttribute(`aria-expanded`,`true`),matchMedia(`(pointer: coarse)`).matches||this.prompt.focus()}hide(){this.dictate.cancel(),typeof this.el.hidePopover==`function`&&this.isOpen&&this.el.hidePopover(),this.el.classList.remove(`is-open`),this.anchor?.setAttribute(`aria-expanded`,`false`)}async loadFolders(){try{let e=await QO(`/api/spawn/folders`);Array.isArray(e.folders)&&e.folders.length&&this.setFolders(e.folders)}catch{}}async loadTargets(){let e={provider:this.provider,dest:this.dest};try{let t=await QO(`/api/spawn`);Array.isArray(t.providers)&&t.providers.length&&(this.providers=t.providers),this.herdrAvailable=!!t.herdr?.available,this.herdrReason=t.herdr?.reason??``,this.windowAvailable=!!t.terminal?.available,this.saved&&(e=this.saved),this.saved=void 0}catch{}if(this.listing=null,this.herdrAvailable)try{this.listing=await QO(`/api/spawn/herdr`)}catch(e){this.herdrAvailable=!1,this.herdrReason=e.message}let t=DO(e,this.providers,this.listing,this.herdrAvailable,this.windowAvailable);this.provider=t.provider,this.dest=t.dest,this.renderTargets(),this.loadModels()}pickProvider(e){this.provider=e,this.model=``,this.dest=DO({provider:e,dest:this.dest},this.providers,this.listing,this.herdrAvailable,this.windowAvailable).dest,this.renderTargets(),this.loadModels()}async loadModels(e=KO){clearTimeout(this.modelTimer);let t=++this.modelSeq,n=this.provider;e===KO&&(this.modelListing=null,this.renderModel());let r=null;try{r=await QO(`/api/spawn/models?provider=${encodeURIComponent(n)}`)}catch{}t===this.modelSeq&&(this.modelListing=r,this.renderModel(),r?.state===`loading`&&e>0&&(this.modelTimer=setTimeout(()=>void this.loadModels(e-1),GO)))}renderModel(){let e=PO(this.modelListing),t=this.model&&IO(this.model,e)===this.model?this.model:IO(this.modelPrefs[this.provider],e);this.model=t;let n=e.kind===`text`;this.modelSelect.setOptions(e.options,t),this.modelSelect.disabled=e.options.length<2,F(this.modelSelect.el,n),F(this.modelText,!n),n&&(this.modelText.value=t);let r=e.state===`loading`?a(`Carregando a lista de modelos…`):e.state===`unavailable`&&!n?a(`Lista de modelos indisponível: usa o padrão`):``;M(this.modelHint,r),F(this.modelHint,!r)}pickDest(e){e===`background`||e===`window`?this.dest={kind:e}:e===`tab`&&this.wsSelect.value?this.dest={kind:e,workspaceId:this.wsSelect.value}:e===`split`&&this.paneSelect.value&&(this.dest={kind:e,paneId:this.paneSelect.value,direction:this.dirSelect.value===`down`?`down`:`right`}),this.renderTargets()}renderTargets(){let e=this.providers.filter(e=>e.available);this.providerList.setOptions(e.map(e=>({value:e.id,label:Bb[e.id],className:`ui-spawn__provider`})),this.provider);let t=this.herdrAvailable&&!!this.listing,n=this.listing,r=(e,t,n)=>{let r=n??e.value,i=t.map(e=>({value:e.id,label:e.text,title:e.title}));e.setOptions(i,i.some(e=>e.value===r)?r:i[0]?.value)};r(this.wsSelect,(n?.workspaces??[]).map(e=>({id:e.id,text:e.label||e.id})),this.dest.kind===`tab`?this.dest.workspaceId:void 0),r(this.paneSelect,n?wO(n):[],this.dest.kind===`split`?this.dest.paneId:void 0),this.dest.kind===`split`&&(this.dirSelect.value=this.dest.direction);let i=t&&!!n?.workspaces.length,o=t&&!!n?.panes.length;this.destGroup.setOptions([{value:`background`,label:a(`Em segundo plano`),disabled:this.provider!==`claude`,className:`ui-spawn__dest-radio`},{value:`window`,label:a(`Em uma nova janela de terminal`),disabled:!this.windowAvailable,className:`ui-spawn__dest-radio`},{value:`tab`,label:a(`Nova aba em`),disabled:!i,className:`ui-spawn__dest-radio`},{value:`split`,label:a(`Dividir painel`),disabled:!o,className:`ui-spawn__dest-radio`}],this.dest.kind),this.wsSelect.disabled=!i,this.paneSelect.disabled=this.dirSelect.disabled=!o,F(this.herdrHint,t),A(this.herdrHint,this.herdrReason),F(this.gsHint,this.provider!==`gentle-shell`)}async checkDictation(){F(this.dictate.el,!await jy())}setFolders(e){if(this.folders=e,!this.selected){let t=$O();this.selected=e.some(e=>e.path===t)?t:e[0]?.path??``}this.renderFolders()}renderFolders(){let e=Date.now(),t=this.folders.some(e=>e.path===this.selected);this.folderList.setOptions(this.folders.map(t=>{let n=XO(t.lastAt,e);return{value:t.path,label:t.name,title:t.path,className:`ui-spawn__folder${t.path===this.selected&&!this.typing?` is-on`:``}`,content:P(`span`,{class:`ui-spawn__folder-content`},P(`span`,{class:`ui-spawn__folder-name`,text:t.name}),P(`span`,{class:`ui-spawn__folder-path`,text:YO(t.path)}),n?P(`span`,{class:`ui-spawn__folder-when`,text:n}):null)}}),this.typing?``:this.selected),this.folders.length?!t&&this.selected&&!this.typing&&this.showOther(!0,this.selected):this.showOther(!0)}pick(e){this.selected=e,this.typing=!1,F(this.folder,!0),this.otherBtn.classList.remove(`is-on`),this.renderFolders()}showOther(e,t){this.typing=e,F(this.folder,!e),this.otherBtn.classList.toggle(`is-on`,e),e&&(t!==void 0&&(this.folder.value=t),this.selected=this.folder.value.trim(),this.folderList.value=``,this.folderList.buttons.forEach(e=>e.classList.remove(`is-on`)),t===void 0&&this.folder.focus())}addFiles(e){for(let t of e){if(this.files.length>=8){this.say(a(`No máximo {0} anexos por pedido.`,[8]),!0);break}if(t.size>15728640){this.say(a(`{0} passa de {1} MB.`,[t.name,HO/1024/1024]),!0);continue}if(!t.size)continue;let e=t.type.startsWith(`image/`)?URL.createObjectURL(t):void 0,n={file:t,url:e,el:P(`li`,{class:`ui-spawn__file`})},r=e?P(`img`,{class:`ui-spawn__thumb`,attrs:{src:e,alt:``}}):P(`span`,{class:`ui-spawn__thumb ui-spawn__thumb--doc`,attrs:{"aria-hidden":`true`},text:(t.name.split(`.`).pop()??``).slice(0,4).toUpperCase()||a(`ARQ`)}),i=j(Q.close,a(`Tirar {0}`,[t.name]),()=>this.removeFile(n),`ui-icon-btn--sm ui-spawn__file-x`);n.el.append(r,P(`span`,{class:`ui-spawn__file-name`,text:t.name,title:t.name}),P(`span`,{class:`ui-spawn__file-size`,text:ZO(t.size)}),i),this.files.push(n),this.fileList.append(n.el)}}removeFile(e){e.url&&URL.revokeObjectURL(e.url),e.el.remove(),this.files=this.files.filter(t=>t!==e)}clearFiles(){for(let e of[...this.files])this.removeFile(e)}say(e,t=!1){M(this.status,e),this.status.classList.toggle(`is-error`,t)}async submit(){if(this.busy)return;if(this.dictate.busy)return this.say(a(`Espere o ditado terminar.`),!0);let e=(this.typing?this.folder.value:this.selected).trim();if(!e)return this.say(a(`Escolha o projeto.`),!0);let t=this.provider,n=this.dest;if(!EO(n,t,this.listing,this.herdrAvailable,this.windowAvailable))return this.say(a(`Escolha onde abrir.`),!0);let r=this.model;if(r&&!FO(r))return this.say(a(`Modelo inválido: use letras, dígitos e . - _ / :`),!0);this.busy=!0,this.submitBtn.disabled=!0;try{let i=[];for(let[e,t]of this.files.entries()){this.say(this.files.length>1?a(`Enviando anexos ({0} de {1})…`,[e+1,this.files.length]):a(`Enviando o anexo…`));let n=await QO(`/api/spawn/attachments`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:t.file.name,type:t.file.type,data:await $e(t.file)})});i.push(n.id)}this.say(a(`Começando no computador…`));let o=await QO(`/api/spawn`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({folder:e,prompt:this.prompt.value,provider:t,destination:n,...r?{model:r}:{},...i.length?{attachments:i}:{}})}),s=Date.now()+WO;for(;(o.status===`queued`||o.status===`sent`)&&Date.now()<s;)await new Promise(e=>setTimeout(e,UO)),o=await QO(`/api/spawn/${encodeURIComponent(o.id)}`);if(o.status===`opened`&&o.how===`herdr`)this.say(a(`Aberto no herdr (painel {0}).`,[o.herdr?.paneId??`?`])),this.prompt.value=``,this.clearFiles(),ek(e),jO(t,n),BO(t,r),this.modelPrefs=zO(),this.ctx.announce(a(`Agente novo aberto no herdr.`)),this.loadTargets();else if(o.status===`opened`&&o.how===`window`)this.say(a(`Aberto em uma nova janela de terminal.`)),this.prompt.value=``,this.clearFiles(),ek(e),jO(t,n),BO(t,r),this.modelPrefs=zO(),this.ctx.announce(a(`Agente novo aberto numa janela de terminal.`));else if(o.status===`opened`){let i=o.how===`cli`;this.say(i?a(`Rodando: a sessão já começou no computador e aparece no escritório em instantes.`):o.note?a(`Abri no app do Claude: aperte Enter lá para começar. Não rodou sozinho: {0}.`,[o.note]):a(`Abri no app do Claude: aperte Enter lá para começar.`),!i&&!!o.note),this.prompt.value=``,this.clearFiles(),ek(e),jO(t,n),BO(t,r),this.modelPrefs=zO(),this.ctx.announce(a(i?`Agente novo rodando.`:`Agente novo aberto no app do Claude.`))}else o.stale?(this.say(a(`Esse lugar do herdr não existe mais; a lista foi atualizada, escolha de novo.`),!0),this.loadTargets()):this.say(o.error?a(`Não abriu: {0}`,[o.error]):a(`O computador não confirmou a abertura.`),!0)}catch(e){this.say(a(`Não abriu: {0}`,[e.message]),!0),n.kind!==`background`&&this.loadTargets()}finally{this.busy=!1,this.submitBtn.disabled=!1}}},nk=[{key:`rooms`,singular:a(`sala`),plural:a(`salas`),hint:a(`Salas abertas (uma por projeto)`)},{key:`agents`,singular:a(`agente`),plural:a(`agentes`),hint:a(`Agentes no escritório (principais e subagentes)`)},{key:`working`,singular:a(`trabalhando`),plural:a(`trabalhando`),hint:a(`Agentes processando um pedido agora`)},{key:`subagents`,singular:a(`subagente`),plural:a(`subagentes`),hint:a(`Subagentes em atividade`)},{key:`waiting`,singular:a(`precisa de você`),plural:a(`precisam de você`),hint:a(`Agentes esperando sua resposta no terminal`)}],rk=a(`Conversas abertas em mais de um terminal`),ik=nk.find(e=>e.key===`waiting`).hint,ak=class{ctx;el;pill;pillText;demoBadge;machinesEl;machinesSig=``;status;counters=new Map;shellsBtn;dupBtn;counterWrap;dupCursor=0;shellCursor=0;usage;version;hadOpen=!1;sidebarBtn;feedBtn;timelapseBtn;settingsBtn;perfBtn;worldBtn;spawnBtn;spawnPanel;panelGroup;constructor(e){this.ctx=e;let t=P(`span`,{class:`ui-brand__mark`}),n=P(`img`,{attrs:{src:`/assets/brand/logo-mark.png`,srcset:`/assets/brand/logo-mark@4x.png 4x`,alt:``,width:32,height:32,draggable:`false`}});n.addEventListener(`error`,()=>{t.innerHTML=$_}),t.append(n),this.pillText=P(`span`,{class:`ui-pill__text`}),this.pill=P(`span`,{class:`ui-pill`,role:`status`,attrs:{"aria-live":`polite`}},P(`span`,{class:`ui-pill__dot`}),this.pillText),this.demoBadge=P(`span`,{class:`ui-demo-badge`,text:a(`Demonstração`),title:a(`Agentes de demonstração ligados (desligue em Configurações)`),hidden:!0});let r=P(`div`,{class:`ui-counters`,role:`group`,attrs:{"aria-label":a(`Resumo do escritório`)}});this.counterWrap=r;for(let e of nk){let t=P(`span`,{class:`ui-counter__value`,text:`0`}),n=P(`span`,{class:`ui-counter__label`,text:e.plural}),i;if(e.key===`waiting`){let r=P(`span`,{class:`ui-counter__icon`,attrs:{"aria-hidden":`true`}});r.innerHTML=Q.hand,i=P(`button`,{class:`ui-counter ui-counter--waiting`,type:`button`,title:a(`{0}. Clique para ir até o primeiro.`,[e.hint]),attrs:{"aria-label":a(`{0}. Clique para ir até o primeiro.`,[e.hint])},on:{click:()=>this.focusFirstWaiting()}},r,t,n)}else i=P(`div`,{class:`ui-counter ui-counter--${e.key}`,title:e.hint},t,n);this.counters.set(e.key,{el:i,value:t,label:n}),r.append(i)}{let e=P(`span`,{class:`ui-counter__icon ui-hourglass`,attrs:{"aria-hidden":`true`}});e.innerHTML=Q.hourglass;let t=P(`span`,{class:`ui-counter__value`,text:`0`}),n=P(`span`,{class:`ui-counter__label`,text:`shells`});this.shellsBtn=P(`button`,{class:`ui-counter ui-counter--shells`,type:`button`,hidden:!0,on:{click:()=>this.focusNextShell()}},e,P(`span`,{class:`ui-counter__stack`},t,n)),this.counters.set(`shells`,{el:this.shellsBtn,value:t,label:n}),r.insertBefore(this.shellsBtn,this.counters.get(`waiting`).el)}{let e=P(`span`,{class:`ui-counter__icon`,attrs:{"aria-hidden":`true`},text:`🚨`}),t=P(`span`,{class:`ui-counter__value`,text:`0`}),n=P(`span`,{class:`ui-counter__label`,text:a(`duplicadas`)});this.dupBtn=P(`button`,{class:`ui-counter ui-counter--dup`,type:`button`,hidden:!0,on:{click:()=>this.focusNextDuplicate()}},e,P(`span`,{class:`ui-counter__stack`},t,n)),this.counters.set(`duplicates`,{el:this.dupBtn,value:t,label:n}),r.insertBefore(this.dupBtn,this.counters.get(`waiting`).el)}this.usage=new Uw(e),this.sidebarBtn=j(Q.sidebar,a(`Painel lateral ( [ )`),()=>e.togglePanel(`sidebar`),`ui-btn-sidebar`),this.feedBtn=j(Q.feed,a(`Feed de atividade ( ] )`),()=>e.togglePanel(`feed`),`ui-btn-feed`),this.timelapseBtn=j(lO.timelapse,a(`Timelapse: reproduzir o dia (L)`),()=>e.toggleTimelapse(),`ui-btn-timelapse`),this.worldBtn=j(Q.city,a(`Habblaud World`),()=>e.toggleWorld(),`ui-btn-world`),this.worldBtn.setAttribute(`aria-haspopup`,`dialog`),this.worldBtn.hidden=!0,this.perfBtn=j(Q.perf,a(`Desempenho: uso de recursos e limites`),()=>e.togglePerf?.(),`ui-btn-perf`),this.perfBtn.setAttribute(`aria-haspopup`,`dialog`),this.settingsBtn=j(Q.settings,a(`Configurações`),()=>e.toggleSettings()),this.settingsBtn.setAttribute(`aria-haspopup`,`dialog`),this.spawnPanel=new tk(e),e.root.append(this.spawnPanel.el),this.spawnBtn=j(Q.newAgent,a(`Novo agente: começa uma sessão do Claude Code no computador`),()=>this.spawnPanel.toggle(this.spawnBtn),`ui-btn-spawn`),this.spawnBtn.setAttribute(`aria-haspopup`,`dialog`),this.spawnBtn.hidden=!0,this.version=new dD(e,this.settingsBtn),this.machinesEl=P(`span`,{class:`ui-machines`,role:`group`,hidden:!0,attrs:{"aria-label":a(`Máquinas`)}}),this.status=P(`div`,{class:`ui-topbar__status`},this.pill,this.version.el,this.demoBadge,this.machinesEl);let i=P(`div`,{class:`ui-btn-group`,role:`group`,attrs:{"aria-label":a(`Câmera`)}},j(Q.overview,a(`Visão geral (O)`),()=>e.camera(`overview`)),j(Q.zoomOut,a(`Afastar (−)`),()=>e.camera(`zoomOut`)),j(Q.zoomIn,a(`Aproximar (+)`),()=>e.camera(`zoomIn`))),o=P(`div`,{class:`ui-btn-group`,role:`group`,attrs:{"aria-label":a(`Painéis`)}},this.spawnBtn,this.timelapseBtn,this.feedBtn,this.worldBtn,this.perfBtn,this.settingsBtn,j(Q.help,a(`Ajuda (?)`),()=>e.openHelp()));this.panelGroup=o,this.el=P(`header`,{class:`ui-topbar`,role:`banner`},P(`div`,{class:`ui-topbar__left`},this.sidebarBtn,P(`div`,{class:`ui-brand`},t,P(`div`,{class:`ui-brand__text`},Nx(),this.status))),r,this.usage.el,P(`div`,{class:`ui-topbar__right`},i,o))}addStatus(e){this.status.append(e)}addSceneButton(e){this.panelGroup.insertBefore(e,this.timelapseBtn)}addPanelButton(e){this.panelGroup.prepend(e)}addCounterButton(e){this.counterWrap.insertBefore(e,this.counters.get(`waiting`).el)}render(){let{store:e}=this.ctx,t=e.snapshot,n=e.connection;n===`open`&&(this.hadOpen=!0);let r=n===`open`?a(`Conectado`):n===`mock`?a(`Simulação`):n===`closed`?a(`Desconectado`):this.hadOpen?a(`Reconectando…`):a(`Conectando…`);M(this.pillText,r),vt(this.pill,`is-`,n),A(this.pill,a(n===`mock`?`Dados simulados no navegador (?mock=1)`:n===`open`?`Recebendo eventos do servidor em tempo real`:`Sem conexão com o servidor do Habblaud`)),F(this.demoBadge,!(n===`open`&&t?.meta.demo));let i=this.ctx.now(),o=ib(t,i);for(let e of nk){let t=this.counters.get(e.key),n=o[e.key];M(t.value,At(n)),M(t.label,n===1?e.singular:e.plural),N(t.el,`aria-label`,`${At(n)} ${n===1?e.singular:e.plural}`)}let s=this.counters.get(`waiting`).el;s.classList.toggle(`is-active`,o.waiting>0),s.disabled=o.waiting===0;let c=QC(t?.agents??[]).length;s.classList.toggle(`has-answer`,c>0),A(s,c?a(`{0}. {1} para responder por aqui: clique para ir até {2} (P).`,[ik,c===1?a(`1 pedido (permissão ou pergunta) dá`):a(`{0} pedidos (permissões ou perguntas) dão`,[c]),a(c===1?`ele`:`cada um`)]):a(`{0}. Clique para ir até o primeiro.`,[ik])),this.renderShells(o.shells,i),this.renderDuplicates(i),this.renderMachines(i),this.usage.render(),this.version.render(),F(this.spawnBtn,!I().spawn||e.mock||e.replaying),this.sidebarBtn.setAttribute(`aria-pressed`,String(this.ctx.isPanelOpen(`sidebar`))),this.feedBtn.setAttribute(`aria-pressed`,String(this.ctx.isPanelOpen(`feed`))),this.timelapseBtn.setAttribute(`aria-pressed`,String(this.ctx.isTimelapseOpen())),this.perfBtn.setAttribute(`aria-expanded`,String(this.ctx.isPerfOpen?.()??!1)),F(this.timelapseBtn,e.mock)}renderMachines(e){let t=WE(this.ctx.store.snapshot?.machines,e);F(this.machinesEl,t.length===0);let n=JSON.stringify(t);n!==this.machinesSig&&(this.machinesSig=n,this.machinesEl.replaceChildren(...t.map(e=>P(`span`,{class:`ui-machine${e.online?``:` is-offline`}`,title:e.title,attrs:{"aria-label":e.title}},P(`span`,{class:`ui-machine__dot`,attrs:{"aria-hidden":`true`}}),P(`span`,{class:`ui-machine__name`,text:e.label})))))}renderShells(e,t){let n=this.counters.get(`shells`);if(F(this.shellsBtn,e===0),e===0){this.shellCursor=0;return}let r=this.ctx.store.snapshot?.agents??[],i=db(r,t);M(n.value,At(e)),M(n.label,e===1?`shell`:`shells`);let o=i.length===1?i[0].name:a(`{0} agentes`,[At(i.length)]);N(n.el,`aria-label`,a(`{0} {1}; {2} esperando. Ir até o próximo.`,[At(e),a(e===1?`shell rodando`:`shells rodando`),o]));let s=i.slice(0,6).map(e=>{let n=lb(e,r,t);return`${e.name}: ${mb(n,t).label} (${zt(t-n.since)})`});i.length>6&&s.push(a(`… e mais {0}`,[i.length-6])),A(n.el,a(`Shells rodando: {0} terminar.
20
- {1}
21
- Clique para ir até {2}.`,[i.length===1?a(`o agente espera`):a(`os agentes esperam`),s.join(`
22
- `),i.length>1?a(`cada um`):a(`ele`)]))}renderDuplicates(e){let t=this.counters.get(`duplicates`),n=this.ctx.store.snapshot,r=ab(n?.agents??[]).length;if(F(this.dupBtn,r===0),r===0){this.dupCursor=0,this.dupBtn.classList.remove(`is-alert`);return}let i=n?.meta.buildingEffect;this.dupBtn.classList.toggle(`is-alert`,i?.kind===`intrusion`&&i.until>e);let o=a(r===1?`duplicada`:`duplicadas`);M(t.value,At(r)),M(t.label,o),N(t.el,`aria-label`,a(`{0} {1}. Ir até o mais novo.`,[At(r),o])),A(t.el,a(`{0}.
23
- Clique para ir até {1}.`,[rk,a(r===1?`ele`:`cada um`)]))}focusNextDuplicate(){let e=ab(this.ctx.store.snapshot?.agents??[]);if(!e.length)return;let t=this.ctx.selection(),n=this.dupCursor%e.length;t?.type===`agent`&&e[n].newest.id===t.id&&(n=(n+1)%e.length),this.dupCursor=n+1,this.ctx.select({type:`agent`,id:e[n].newest.id},{focus:!0})}focusNextShell(){let e=db(this.ctx.store.snapshot?.agents??[],this.ctx.now());if(!e.length)return;let t=this.ctx.selection(),n=this.shellCursor%e.length;t?.type===`agent`&&e[n].id===t.id&&(n=(n+1)%e.length),this.shellCursor=n+1,this.ctx.select({type:`agent`,id:e[n].id},{focus:!0})}focusFirstWaiting(){let e=this.ctx.store.snapshot?.agents??[],t=this.ctx.selection(),n=$C(e,t?.type===`agent`?t.id:void 0);if(n)return ew(this.ctx,n.id);let r=bu(e)[0];r&&this.ctx.select({type:`agent`,id:r.id},{focus:!0})}},ok=5,sk=class{reload;el;text;timer=null;left=ok;constructor(e,t=()=>location.reload()){this.reload=t,this.text=P(`span`);let n=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Recarregar agora`),on:{click:()=>this.reload()}}),r=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Depois`),on:{click:()=>this.postpone()}});this.el=P(`div`,{class:`ui-banner ui-banner--update`,role:`status`,hidden:!0},P(`span`,{class:`ui-banner__dot`,attrs:{"aria-hidden":`true`}}),P(`span`,{class:`ui-banner__text`},this.text),n,r),e.on(`update`,()=>this.start())}start(){F(this.el,!1),this.tick(),this.timer=setInterval(()=>this.tick(),1e3)}tick(){if(this.left<=0){this.stop(),this.reload();return}M(this.text,a(`O Habblaud foi atualizado. Recarregando em {0} s…`,[this.left])),this.left--}postpone(){this.stop(),M(this.text,a(`O Habblaud foi atualizado. Recarregue a página quando quiser.`))}stop(){this.timer&&clearInterval(this.timer),this.timer=null}},ck=`https://habblaud.com/world/termos`,lk=`https://habblaud.com/world/privacidade`;function uk(e,t){return P(`a`,{class:`ui-link-btn`,text:e,attrs:{href:t,target:`_blank`,rel:`noopener noreferrer`}})}var dk=[...st,`offline`,`forbidden`],fk=[`off`,`logged_out`,`waiting`,`approved`];function pk(e){let t=e?.meta.world;if(!t||typeof t!=`object`||typeof t.enabled!=`boolean`)return;let n=fk.includes(t.state)?t.state:`off`,r={enabled:t.enabled,configured:t.configured===!0,state:n},i=xk(t.building);return i&&(r.building=i),mk(t.scene)&&typeof t.scene.available==`boolean`&&(r.scene={available:t.scene.available}),r}function mk(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function hk(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):0}function gk(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function _k(e){return typeof e==`string`&&T.includes(e)?e:`internal`}function vk(e){if(mk(e)&&typeof e.ok==`boolean`)return e.ok?{ok:!0}:{ok:!1,error:_k(e.error)}}function yk(e){let t=vk(e),n=mk(e)?gk(e.at):void 0;if(!t||!n)return;let r={...t,at:n};return t.ok&&mk(e)&&typeof e.bytes==`number`&&Number.isFinite(e.bytes)&&e.bytes>=0&&(r.bytes=Math.floor(e.bytes)),r}var bk=me.filter(e=>e!==`deploy`);function xk(e){if(!mk(e))return;let t={connected:e.connected===!0,paused:e.paused===!0,floors:hk(e.floors),agents:hk(e.agents)},n=gk(e.lastUplinkAt);return n&&(t.lastUplinkAt=n),e.left===!0&&(t.left=!0),e.stopped===!0&&(t.stopped=!0),typeof e.visitors==`number`&&Number.isInteger(e.visitors)&&e.visitors>=0&&(t.visitors=Math.min(e.visitors,999)),typeof e.likesToday==`number`&&Number.isInteger(e.likesToday)&&e.likesToday>=0&&(t.likesToday=e.likesToday),hk(e.knocks)>0&&(t.knocks=hk(e.knocks)),e.awaySummary===!0&&(t.awaySummary=!0),t}function Sk(e){let t=xk(e);if(!t||!mk(e))return;let{stopped:n,...r}=t,i=r,a=vk(e.lastAck);a&&(i.lastAck=a),bk.includes(e.stopped)&&(i.stopped=e.stopped),e.unverified===!0&&(i.unverified=!0);let o=se(e.summary);return o&&Oe(o)&&(i.summary=o),typeof e.code==`string`&&/^HB-[2-9A-HJKMNP-TV-Z]{4}$/.test(e.code)&&(i.code=e.code),i}function Ck(e){if(Array.isArray(e))return e.filter(e=>mk(e)&&typeof e.id==`string`&&!!e.id&&typeof e.name==`string`).map(e=>({id:e.id,name:e.name}))}function wk(e){if(!e)return;let{stopped:t,...n}=e;return n}function Tk(e){if(!mk(e))return;if(e.at===void 0&&e.uplink===void 0)return null;let t=gk(e.at);if(!t||typeof e.bytes!=`number`||!Number.isFinite(e.bytes)||!mk(e.uplink))return;let n={at:t,bytes:Math.max(0,Math.floor(e.bytes)),uplink:e.uplink},r=yk(e.ack);return r&&(n.ack=r),n}function Ek(e){let t=Array.isArray(e)?e:mk(e)&&Array.isArray(e.devices)?e.devices:null;return t?t.filter(e=>mk(e)&&typeof e.id==`string`&&typeof e.label==`string`).map(e=>({...e,current:e.current===!0})):null}function Dk(e){if(!mk(e)||!fk.includes(e.state))return null;let t={available:e.available!==!1,configured:e.configured===!0,state:e.state},n=e.account;mk(n)&&typeof n.emailMasked==`string`&&(t.account={emailMasked:n.emailMasked,access:n.access===`approved`?`approved`:`waiting`},typeof n.id==`string`&&/^[A-Za-z0-9_-]{1,64}$/.test(n.id)&&(t.account.id=n.id),typeof n.reservedName==`string`&&n.reservedName&&n.reservedName.length<=64&&(t.account.reservedName=n.reservedName));let r=e.player;mk(r)&&typeof r.name==`string`&&mk(r.parts)&&Array.isArray(r.traits)&&(t.player={...r,look:r.look===`m`?`m`:`f`,visibility:{...Xe,...mk(r.visibility)?r.visibility:{}}},r.mustRename!==!0&&delete t.player.mustRename);let i=e.devices===void 0?null:Ek(e.devices);i&&(t.devices=i),typeof e.lastError==`string`&&e.lastError&&(t.lastError=e.lastError);let a=Sk(e.building);a&&(t.building=a),S(e.theme)&&(t.theme=e.theme);let o=Ck(e.blocked);return o&&(t.blocked=o),t}function Ok(e,t){let n=mk(t)?t.error:void 0,r=mk(n)?n.code:void 0;return typeof r==`string`&&dk.includes(r)?r:e===404?`not_configured`:e===429?`rate_limited`:e===403?`forbidden`:`unknown`}var kk=45e3,Ak=class{fetchImpl;base;constructor(e=(e,t)=>fetch(e,t),t=`/api/world`){this.fetchImpl=e,this.base=t}async call(e,t,n){let r={method:e,credentials:`same-origin`,cache:`no-store`,signal:AbortSignal.timeout(kk)};e!==`GET`&&Object.assign(r,{headers:{"Content-Type":`application/json`},body:JSON.stringify(n??{})});let i;try{i=await this.fetchImpl(`${this.base}${t}`,r)}catch{return{ok:!1,code:`offline`,status:0}}let a=null;try{let e=await i.text();a=e?JSON.parse(e):null}catch{a=null}return i.ok?{ok:!0,data:a}:{ok:!1,code:Ok(i.status,a),status:i.status}}async done(e){let t=await e;return t.ok?{ok:!0,data:null}:t}async status(e=!1){let t=await this.call(`GET`,e?`/status?refresh=1`:`/status`);if(!t.ok)return t;let n=Dk(t.data);return n?{ok:!0,data:n}:{ok:!1,code:`unknown`,status:200}}register(e){return this.done(this.call(`POST`,`/register`,e))}verify(e){return this.done(this.call(`POST`,`/verify`,e))}login(e){return this.done(this.call(`POST`,`/login`,e))}logout(){return this.done(this.call(`POST`,`/logout`))}resend(e){return this.done(this.call(`POST`,`/resend`,e))}forgotPassword(e){return this.done(this.call(`POST`,`/password/forgot`,e))}resetPassword(e){return this.done(this.call(`POST`,`/password/reset`,e))}saveCharacter(e){return this.done(this.call(`PUT`,`/character`,e))}saveVisibility(e){return this.done(this.call(`PUT`,`/visibility`,e))}async devices(){let e=await this.call(`GET`,`/devices`);if(!e.ok)return e;let t=Ek(e.data);return t?{ok:!0,data:t}:{ok:!1,code:`unknown`,status:200}}revokeDevice(e){return this.done(this.call(`POST`,`/devices/${encodeURIComponent(e)}/revoke`))}async lastUplink(){let e=await this.call(`GET`,`/last-uplink`);if(!e.ok)return e;let t=Tk(e.data);return t===void 0?{ok:!1,code:`unknown`,status:200}:{ok:!0,data:t}}pause(){return this.paused(`/pause`,!0)}resume(){return this.paused(`/resume`,!1)}leave(){return this.done(this.call(`POST`,`/leave`))}join(){return this.done(this.call(`POST`,`/join`))}setTheme(e){return this.done(this.call(`PUT`,`/theme`,{theme:e}))}requestAccountDeletion(){return this.done(this.call(`POST`,`/delete-account`))}confirmAccountDeletion(e){return this.done(this.call(`POST`,`/delete-account/confirm`,e))}async exportData(){let e=await this.call(`GET`,`/export`);return e.ok?mk(e.data)?{ok:!0,data:`${JSON.stringify(e.data,null,2)}\n`}:{ok:!1,code:`unknown`,status:200}:e}summarySeen(){return this.done(this.call(`POST`,`/summary/seen`))}unblock(e){return this.done(this.call(`POST`,`/unblock`,{playerId:e}))}async paused(e,t){let n=await this.call(`POST`,e);if(!n.ok)return n;let r=mk(n.data)?n.data.building:void 0;return{ok:!0,data:{paused:mk(r)&&typeof r.paused==`boolean`?r.paused:t}}}};function jk(e){return e<8e3?0:e<2e4?1:2}var Mk={since:`2026-10-14`,visits:5,likes:12,stamps:[{stampId:`visited`,count:2},{stampId:`coffee`,count:1},{stampId:`rocket`,count:1}]},Nk=[{id:`p_spam`,name:`Spam Bot 3000`},{id:`p_troll`,name:`Troll da Esquina`}],Pk={v:1,version:`1.0.0`,theme:`halloween`,floors:[{id:`f_8c1e5f7a2b`,agents:[{id:`a_3f9d2c7e`,kind:`main`,provider:`claude`,status:`working`,look:`f`,name:`Marina`,parts:{skin:`#e8b48c`,hair:`#2b1d14`,hairStyle:`bob`,eyes:`#3b5a7a`,top:`#4a6fa5`,topStyle:`hoodie`,bottom:`#2f3542`,bottomStyle:`pants`,shoes:`#ffffff`,accessory:`glasses`,accessoryColor:`#222222`,facialHair:`none`}},{id:`a_71c0b5a9`,kind:`sub`,parentId:`a_3f9d2c7e`,provider:`claude`,status:`working`,look:`m`,name:`Caio`,parts:{skin:`#c68642`,hair:`#1c1c1c`,hairStyle:`short`,eyes:`#4a3728`,top:`#3d8b5f`,topStyle:`tshirt`,bottom:`#2c2c35`,bottomStyle:`pants`,shoes:`#3a2a20`,accessory:`headphones`,accessoryColor:`#1f1f24`,facialHair:`stubble`}}]},{id:`f_02aa91c4de`,agents:[{id:`a_b2e74d10`,kind:`main`,provider:`codex`,status:`idle`,look:`m`,name:`Rafael`,parts:{skin:`#8d5524`,hair:`#0f0f0f`,hairStyle:`buzz`,eyes:`#2b1d14`,top:`#a5463d`,topStyle:`polo`,bottom:`#4b5563`,bottomStyle:`shorts`,shoes:`#f2f2f2`,accessory:`none`,accessoryColor:`#222222`,facialHair:`beard`}}]}]};function Fk(e){return new TextEncoder().encode(JSON.stringify(e)).length}var Ik=`voce@exemplo.com`,Lk=`uma senha bem comprida`,Rk=`123456`,zk=[`marina`,`caio`,`rafael`];function Bk(e){let[t,n=``]=e.split(`@`);return`${t.slice(0,2)}***@${n}`}var Vk=class e{accounts=new Map;session=null;configured;delayMs;now;failures=[];listeners=new Set;resends=[];deviceSeq=0;theme=`auto`;rejectCode=null;lastError=null;constructor(e={}){this.delayMs=e.delayMs??450,this.now=e.now??Date.now;let t=e.state??`logged_out`;if(this.configured=t!==`off`,t===`waiting`||t===`approved`){let e=this.now(),n={email:Ik,password:Lk,verified:!0,access:t,devices:[],reservedName:`Pixel Dev`};t===`approved`&&(delete n.reservedName,n.player={name:`Pixel Dev`,look:`f`,parts:{skin:`#d69f78`,hair:`#2b2530`,hairStyle:`bob`,eyes:`#2f5f9e`,top:`#4a86d8`,topAccent:`#f4f4f0`,topStyle:`hoodie`,bottom:`#2c2c35`,bottomStyle:`pants`,shoes:`#ececec`,accessory:`glasses`,accessoryColor:`#2b2b33`,facialHair:`none`},traits:[`cafeina`,`games`],intro:`night_owl`,country:`BR`,visibility:{...Xe},updatedAt:e},this.ensureBuilding(n)),this.accounts.set(Ik,n);let r=this.addDevice(n);n.devices.unshift({id:`fake-old`,label:`Dispositivo 2`,createdAt:e-18144e5,lastSeenAt:e-2592e5,current:!1}),this.session={email:Ik,deviceId:r.id}}}meta(){let e={enabled:this.configured,configured:this.configured,state:this.state()},t=this.buildingOf(this.current());if(t){let{lastAck:n,stopped:r,summary:i,code:a,...o}=t;e.building=r?{...o,stopped:!0}:o,i&&(e.building.awaySummary=!0)}return t&&(e.scene={available:!0}),e}worldTheme(){return this.theme}setVisitors(e){let t=this.current()?.building;t&&(e===null?delete t.visitors:t.visitors=Math.max(0,Math.floor(e)),this.changed())}rejectUplinks(e){this.rejectCode=e;let t=this.current();t?.building?.connected&&this.sendUplink(t),this.changed()}stopBuilding(e){let t=this.current()?.building;t&&!t.paused&&(t.connected=!1,t.stopped=e,this.changed())}markUnverified(e){let t=this.current()?.building;t&&(e?t.unverified=!0:delete t.unverified,this.changed())}setMaintenance(e){let t=this.current()?.building;this.lastError=e?`maintenance`:null,t&&!t.paused&&!t.stopped&&(t.connected=!e),this.changed()}dropConnection(){let e=this.current()?.building;e&&!e.paused&&(e.connected=!1,this.changed())}onChange(e){return this.listeners.add(e),()=>void this.listeners.delete(e)}failNext(e){this.failures.push(e)}forceRename(){let e=this.current();e?.player&&(e.player={...e.player,name:`???`,mustRename:!0},this.changed())}approve(){let e=this.current();e&&(e.access=`approved`,this.ensureBuilding(e),this.changed())}ensureBuilding(e){!e.building&&e.access===`approved`&&e.player&&(e.building={connected:!0,paused:!1,last:null,code:`HB-4F2K`,summary:structuredClone(Mk),blocked:[...Nk],since:this.now()},this.sendUplink(e))}sendUplink(e){let t=e.building;if(!t||t.paused)return;let n=this.now(),r={...structuredClone(Pk),theme:ye(this.theme,new Date(n))},i=Fk(r);t.last={at:n,bytes:i,uplink:r,ack:this.rejectCode?{ok:!1,error:this.rejectCode,at:n}:{ok:!0,at:n,bytes:i}}}buildingOf(e){let t=e?.building;if(!t)return;let n=t.last?.uplink.floors??[],r={connected:t.connected,paused:t.paused,floors:n.length,agents:n.reduce((e,t)=>e+t.agents.length,0)};t.last&&(r.lastUplinkAt=t.last.at,t.last.ack&&(r.lastAck=t.last.ack.ok?{ok:!0}:{ok:!1,error:t.last.ack.error})),t.left&&(r.left=!0),t.stopped&&(r.stopped=t.stopped),t.connected&&!t.paused&&!t.left&&!e?.player?.visibility.closed&&(r.visitors=t.visitors??jk(this.now()-t.since)),t.unverified&&(r.unverified=!0);let i=this.now();if(r.likesToday=3+Math.floor(Math.max(0,i-t.since)/6e4),t.knocksOn!==void 0&&e.player?.visibility.knocks&&t.connected){let e=Math.floor((i-t.knocksOn-8e3)/45e3)+1;e>0&&(r.knocks=e)}return t.summary&&(r.summary=structuredClone(t.summary)),r.code=t.code,r}state(){if(!this.configured)return`off`;let e=this.current();return e?e.access:`logged_out`}current(){return this.session?this.accounts.get(this.session.email):void 0}changed(){this.listeners.forEach(e=>e())}addDevice(e){let t=this.now();e.devices.forEach(e=>e.current=!1);let n=new Set(e.devices.map(e=>e.label)),r=1;for(;n.has(`Dispositivo ${r}`);)r++;let i={id:`fake-${++this.deviceSeq}`,label:`Dispositivo ${r}`,createdAt:t,lastSeenAt:t,current:!0};return e.devices.push(i),i}async reply(e,t=!0){this.delayMs>0&&await new Promise(e=>setTimeout(e,this.delayMs));let n=this.failures.shift();if(n)return{ok:!1,code:n,status:n===`offline`?0:400};if(!this.configured)return{ok:!1,code:`not_configured`,status:404};let r=e();return r.ok&&t&&this.changed(),r}static ok(){return{ok:!0,data:null}}static fail(e,t=400){return{ok:!1,code:e,status:t}}status(){return this.reply(()=>{let e=this.current(),t=this.state(),n={available:!0,configured:this.configured,state:t};if(e){n.account={emailMasked:Bk(e.email),access:e.access},!e.player&&e.reservedName&&(n.account.reservedName=e.reservedName),e.player&&(n.player=structuredClone(e.player)),n.devices=structuredClone(e.devices);let t=this.buildingOf(e);t&&(n.building=t),e.building&&(n.blocked=structuredClone(e.building.blocked))}return this.theme!==`auto`&&(n.theme=this.theme),this.lastError&&(n.lastError=this.lastError),{ok:!0,data:n}},!1)}register(t){return this.reply(()=>{let n=je(t.name);if(!n.ok)return e.fail(n.code,422);if(this.nameTaken(n.key,void 0))return e.fail(`name_taken`,409);if(!ot(t.email)||Be(t.password,t.email))return e.fail(`invalid`,422);let r=t.email.trim().toLowerCase();return this.accounts.has(r)||this.accounts.set(r,{email:r,password:t.password,verified:!1,access:`waiting`,devices:[],reservedName:n.name}),e.ok()})}nameTaken(e,t){if(zk.includes(e))return!0;for(let n of this.accounts.values()){if(n===t)continue;let r=n.player?.name??n.reservedName;if(r&&nt(r)===e)return!0}return!1}verify(t){return this.reply(()=>{let n=this.accounts.get(t.email.trim().toLowerCase());return!n||t.code!==`123456`?e.fail(`invalid_code`):(n.verified=!0,this.session={email:n.email,deviceId:this.addDevice(n).id},this.lastError=null,e.ok())})}login(t){return this.reply(()=>{let n=t.email.trim().toLowerCase();if(n.startsWith(`banido@`))return e.fail(`banned`,403);let r=this.accounts.get(n);return!r||r.password!==t.password?e.fail(`invalid_credentials`,401):r.verified?(this.session={email:n,deviceId:this.addDevice(r).id},this.lastError=null,e.ok()):e.fail(`email_not_verified`,403)})}logout(){return this.reply(()=>{let t=this.current();if(t&&this.session){let e=this.session.deviceId;t.devices=t.devices.filter(t=>t.id!==e)}return this.session=null,e.ok()})}resend(t){return this.reply(()=>{let t=this.now();return this.resends=this.resends.filter(e=>t-e<36e5),this.resends.length>=3?e.fail(`rate_limited`,429):(this.resends.push(t),e.ok())})}forgotPassword(t){return this.reply(()=>e.ok())}resetPassword(t){return this.reply(()=>{let n=this.accounts.get(t.email.trim().toLowerCase());return!n||t.code!==`123456`?e.fail(`invalid_code`):Be(t.password,t.email)?e.fail(`invalid`,422):(n.password=t.password,n.verified=!0,n.devices=[],this.session?.email===n.email&&(this.session=null),e.ok())})}saveCharacter(t){return this.reply(()=>{let n=this.current();if(!n)return e.fail(`unknown`,401);let r=!n.player&&n.reservedName?n.reservedName:t.name===void 0&&n.player?n.player.name:t.name,i=je(r);return i.ok?this.nameTaken(i.key,n)&&nt(n.player?.name??``)!==i.key?e.fail(`name_taken`,409):ve(t.traits)?(delete n.reservedName,n.player={name:i.name,look:t.look,parts:{...t.parts},traits:[...t.traits],intro:t.intro,country:`BR`,visibility:n.player?.visibility??{...Xe},updatedAt:this.now()},this.ensureBuilding(n),e.ok()):e.fail(`invalid`,422):e.fail(i.code,422)})}saveVisibility(t){return this.reply(()=>{let n=this.current();if(!n?.player)return e.fail(`invalid`,422);let r=n.player.visibility.knocks;return n.player.visibility={...t},t.hideCountry?delete n.player.country:n.player.country=`BR`,n.building&&t.knocks&&!r&&(n.building.knocksOn=this.now()),e.ok()})}devices(){return this.reply(()=>{let t=this.current();return t?{ok:!0,data:structuredClone(t.devices)}:e.fail(`unknown`,401)},!1)}revokeDevice(t){return this.reply(()=>{let n=this.current();return n?n.devices.some(e=>e.id===t)?(n.devices=n.devices.filter(e=>e.id!==t),this.session?.deviceId===t&&(this.session=null),e.ok()):e.fail(`invalid`,404):e.fail(`unknown`,401)})}lastUplink(){return this.reply(()=>{let t=this.current();return t?{ok:!0,data:t.building?.last?structuredClone(t.building.last):null}:e.fail(`not_logged_in`,401)},!1)}pause(){return this.setPaused(!0)}resume(){return this.setPaused(!1)}setPaused(t){return this.reply(()=>{let n=this.current();if(!n)return e.fail(`not_logged_in`,401);let r=n.building;return r?(r.paused=t,r.connected=!t,t||(delete r.left,delete r.stopped),this.sendUplink(n),{ok:!0,data:{paused:t}}):e.fail(`no_player`,409)})}join(){return this.reply(()=>{let t=this.current();if(!t)return e.fail(`not_logged_in`,401);let n=t.building;return n?(n.left&&(delete n.left,delete n.stopped,n.paused=!1,n.connected=!0,this.sendUplink(t)),e.ok()):e.fail(`no_player`,409)})}leave(){return this.reply(()=>{let t=this.current();if(!t)return e.fail(`not_logged_in`,401);let n=t.building;return n?(n.paused=!0,n.connected=!1,n.left=!0,delete n.stopped,e.ok()):e.fail(`no_player`,409)})}setTheme(t){return this.reply(()=>{if(!xe.includes(t))return e.fail(`invalid`,422);this.theme=t;let n=this.current();return n?.building?.connected&&this.sendUplink(n),e.ok()})}requestAccountDeletion(){return this.reply(()=>{let t=this.current();return t?(t.deleteRequested=!0,e.ok()):e.fail(`not_logged_in`,401)},!1)}confirmAccountDeletion(t){return this.reply(()=>{let n=this.current();return n?!n.deleteRequested||t.code!==`123456`?e.fail(`invalid_code`):(this.accounts.delete(n.email),this.session=null,this.theme=`auto`,this.lastError=`account_deleted`,e.ok()):e.fail(`not_logged_in`,401)})}summarySeen(){return this.reply(()=>{let t=this.current()?.building;return t?(delete t.summary,e.ok()):e.fail(`not_logged_in`,401)})}exportData(){return this.reply(()=>{let t=this.current();if(!t)return e.fail(`not_logged_in`,401);if(t.exports=(t.exports??0)+1,t.exports>1)return e.fail(`rate_limited`,429);let n={format:`habblaud-world-export`,version:1,exportedAt:new Date(this.now()).toISOString(),account:{email:t.email,access:t.access,notifyInactivity:t.player?.visibility.notifyInactivity!==!1},player:t.player??null,visibility:t.player?.visibility??null,devices:t.devices.map(e=>({label:e.label,createdAt:e.createdAt,lastSeenAt:e.lastSeenAt,revokedAt:null})),building:t.building?{floors:t.building.last?.uplink.floors.length??0,likes:0}:null,likesGiven:[],blocks:[],reportsMade:[],stampsReceived:[]};return{ok:!0,data:`${JSON.stringify(n,null,2)}\n`}},!1)}unblock(t){return this.reply(()=>{let n=this.current()?.building;return n?n.connected?(n.blocked=n.blocked.filter(e=>e.id!==t),e.ok()):e.fail(`not_connected`,409):e.fail(`not_logged_in`,401)})}};function Hk(e){let t=new URLSearchParams(e);if(!t.has(`world`))return null;let n=t.get(`world`)??``;return fk.includes(n)?n:`logged_out`}function Uk(e,t=typeof location>`u`?``:location.search){if(e.mock){let e=Hk(t);if(!e)return{client:null,fake:!0,meta:()=>void 0};let n=new Vk({state:e});return{client:n,fake:!0,meta:()=>n.meta(),onChange:e=>n.onChange(e)}}return{client:new Ak,fake:!1,meta:()=>pk(e.liveSnapshot)}}var Wk={hello:{icon:`👋`,label:()=>a(`Olá!`)},nice_building:{icon:`👍`,label:()=>a(`Prédio bonito!`)},coffee:{icon:`☕`,label:()=>a(`Bora um café?`)},congrats:{icon:`🎉`,label:()=>a(`Parabéns pela entrega!`)},nice_to_meet:{icon:`🤝`,label:()=>a(`Prazer!`)},bye:{icon:`✌️`,label:()=>a(`Até mais!`)},thanks:{icon:`🙏`,label:()=>a(`Valeu!`)},good_luck:{icon:`🍀`,label:()=>a(`Boa sorte!`)},wave:{icon:`🙋`,label:()=>a(`Oi, oi!`)},clap:{icon:`👏`,label:()=>a(`Mandou bem!`)}},Gk={visited:{icon:`👣`,label:()=>a(`Passei por aqui`)},nice_building:{icon:`🏢`,label:()=>a(`Prédio lindo`)},keep_going:{icon:`💪`,label:()=>a(`Continue assim`)},coffee:{icon:`☕`,label:()=>a(`Fica o café`)},wave:{icon:`👋`,label:()=>a(`Um aceno`)},star:{icon:`⭐`,label:()=>a(`Nota 10`)},heart:{icon:`💖`,label:()=>a(`Com carinho`)},rocket:{icon:`🚀`,label:()=>a(`Decolando!`)}},Kk={offensive_name:{icon:`🤬`,label:()=>a(`Nome ofensivo`)},impersonation:{icon:`🎭`,label:()=>a(`Fingindo ser outra pessoa`)},harassment:{icon:`🚫`,label:()=>a(`Perseguição`)},greeting_spam:{icon:`📢`,label:()=>a(`Spam de cumprimentos`)},fake_building:{icon:`🏚️`,label:()=>a(`Prédio falso`)},other:{icon:`❔`,label:()=>a(`Outro motivo`)}},qk={agent_hours_10k:1e4,agent_hours_50k:5e4,agent_hours_100k:1e5},Jk=(e,t)=>Object.prototype.hasOwnProperty.call(e,t)?e[t]:void 0;function Yk(e){return Jk(Wk,e)?.label()??String(e)}function Xk(e){return Jk(Wk,e)?.icon??`💬`}function Zk(e){return Jk(Gk,e)?.label()??String(e)}function Qk(e){return Jk(Gk,e)?.icon??`🏷️`}function $k(e){return Jk(Kk,e)?.label()??String(e)}function eA(t){let n=Number.isFinite(t)?Math.max(0,t):0;try{return new Intl.NumberFormat(e(),{notation:`compact`,maximumFractionDigits:+(n<1e4&&n>=1e3)}).format(n)}catch{return String(Math.round(n))}}function tA(e,t){let n=t??(Object.prototype.hasOwnProperty.call(qk,e)?qk[e]:0);return a(`{0} horas de agentes trabalhando`,[eA(n)])}function nA(e){switch(e){case 1:return a(`até 100 mil tokens`);case 2:return a(`até 1 milhão de tokens`);case 3:return a(`até 10 milhões de tokens`);case 4:return a(`até 100 milhões de tokens`);case 5:return a(`mais de 100 milhões de tokens`);default:return a(`quase nada de tokens`)}}function rA(t){let n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n)return``;try{return new Intl.DateTimeFormat(e(),{day:`numeric`,month:`long`,timeZone:`UTC`}).format(Date.UTC(Number(n[1]),Number(n[2])-1,Number(n[3])))}catch{return`${n[3]}/${n[2]}`}}var iA=t=>t.toLocaleString(e());function aA(e){let t=e.stamps.reduce((e,t)=>e+t.count,0),n=rA(e.since),r=e.visits===1?a(`1 visita`):a(`{0} visitas`,[iA(e.visits)]),i=e.likes===1?a(`1 like`):a(`{0} likes`,[iA(e.likes)]),o=t===1?a(`1 carimbo`):a(`{0} carimbos`,[iA(t)]);return{since:n?a(`desde {0}`,[n]):``,stats:[{key:`visits`,icon:`🚶`,value:iA(e.visits),label:e.visits===1?a(`visita`):a(`visitas`)},{key:`likes`,icon:`❤️`,value:iA(e.likes),label:e.likes===1?a(`like`):a(`likes`)},{key:`stamps`,icon:`📮`,value:iA(t),label:a(t===1?`carimbo`:`carimbos`)}],stamps:[...e.stamps].filter(e=>e.count>0).sort((e,t)=>t.count-e.count).map(e=>({id:e.stampId,icon:Qk(e.stampId),label:Zk(e.stampId),count:e.count})),sentence:a(`Enquanto você estava fora: {0}, {1} e {2}.`,[r,i,o])}}function oA(e,t){return e!==`live`||!t||t<1?null:{text:a(`❤️ {0} hoje`,[t]),title:t===1?a(`Seu prédio ganhou 1 like hoje.`):a(`Seu prédio ganhou {0} likes hoje.`,[t])}}function sA(e){return e?`${e.since}|${e.visits}|${e.likes}|${e.stamps.map(e=>`${e.stampId}:${e.count}`).join(`,`)}`:``}function cA(e,t){let n=t??0;return e===null||n<e?{last:n,fresh:0}:{last:n,fresh:n-e}}function lA(e,t){let n=P(`ul`,{class:`ui-away__stats`,attrs:{"aria-label":e.sentence}},...e.stats.map(e=>P(`li`,{class:`ui-away__stat is-${e.key}`},P(`span`,{class:`ui-away__icon`,text:e.icon,attrs:{"aria-hidden":`true`}}),P(`b`,{text:e.value}),P(`span`,{text:e.label})))),r=e.stamps.length?P(`ul`,{class:`ui-away__stamps`,attrs:{"aria-label":a(`Carimbos na portaria`)}},...e.stamps.map((e,n)=>P(`li`,{class:`ui-away__stamp`,title:e.label,style:`--i:${n};--r:${n*37%11-5}deg`},P(`span`,{class:`ui-away__stamp-icon`,text:e.icon,attrs:{"aria-hidden":`true`}}),t?null:P(`span`,{class:`ui-away__stamp-label`,text:e.label}),e.count>1?P(`span`,{class:`ui-away__stamp-count`,text:`×${e.count}`}):null))):null;return P(`div`,{class:`ui-away__body`},n,r)}var uA=class{host;el;codeRow;code;copyBtn;summary;summaryBody;since;seenBtn;error;key=``;busy=!1;constructor(e){this.host=e,this.code=P(`code`,{class:`ui-away__code`}),this.copyBtn=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Copiar`),on:{click:()=>void this.copy()}}),this.codeRow=P(`div`,{class:`ui-away__coderow`,hidden:!0},P(`span`,{class:`ui-away__codelabel`,text:a(`Código do prédio`)}),this.code,this.copyBtn,P(`span`,{class:`ui-set__hint ui-away__codehint`,text:a(`Mande a um amigo: na cidade, "Ir para" leva direto à sua porta.`)})),this.since=P(`span`,{class:`ui-away__since`}),this.summaryBody=P(`div`),this.seenBtn=P(`button`,{class:`ui-btn ui-btn--sm ui-btn--primary`,type:`button`,text:a(`Ok, vi`),on:{click:()=>void this.seen()}}),this.error=P(`p`,{class:`ui-world__error`,role:`alert`,hidden:!0}),this.summary=P(`section`,{class:`ui-away ui-away--inline`,hidden:!0,attrs:{"aria-label":a(`Enquanto você estava fora`)}},P(`div`,{class:`ui-away__head`},P(`span`,{class:`ui-away__badge`,text:`📬`,attrs:{"aria-hidden":`true`}}),P(`div`,{class:`ui-away__titles`},P(`strong`,{class:`ui-away__title`,text:a(`Enquanto você estava fora`)}),this.since)),this.summaryBody,P(`div`,{class:`ui-away__actions`},this.seenBtn),this.error),this.el=P(`div`,{class:`ui-away__wrap`},this.summary,this.codeRow),this.sync()}sync(){let e=this.host.building();F(this.codeRow,!e?.code),M(this.code,e?.code??``);let t=e?.summary,n=sA(t);if(n!==this.key){if(this.key=n,t){let e=aA(t);M(this.since,e.since),this.summaryBody.replaceChildren(lA(e,!1))}F(this.error,!0)}F(this.summary,!t)}async copy(){let e=this.host.building()?.code;if(!e)return;let t=await St(e);M(this.copyBtn,a(t?`Copiado`:`Copiar`)),setTimeout(()=>M(this.copyBtn,a(`Copiar`)),1600)}async seen(){let e=this.host.client;if(!e||this.busy)return;this.busy=!0,this.seenBtn.disabled=!0;let t=await e.summarySeen();if(this.busy=!1,this.seenBtn.disabled=!1,!t.ok){M(this.error,O(t.code,`summary`)),F(this.error,!1);return}F(this.summary,!0),this.host.refresh()}},dA=class{ctx;src;hooks;el;since;body;error;seenBtn;knocksSeen=null;shownKey=``;dismissedKey=``;loading=!1;busy=!1;constructor(e,t,n){this.ctx=e,this.src=t,this.hooks=n;let r=`ui-away-title`;this.since=P(`span`,{class:`ui-away__since`}),this.body=P(`div`),this.error=P(`p`,{class:`ui-world__error`,role:`alert`,hidden:!0}),this.seenBtn=P(`button`,{class:`ui-btn ui-btn--sm ui-btn--primary`,type:`button`,text:a(`Ok, vi`),on:{click:()=>void this.dismiss()}});let i=P(`button`,{class:`ui-away__close`,type:`button`,text:`×`,title:a(`Fechar`),attrs:{"aria-label":a(`Fechar`)},on:{click:()=>void this.dismiss()}});this.el=P(`section`,{class:`ui-away ui-away--float`,hidden:!0,role:`dialog`,attrs:{"aria-labelledby":r,"aria-modal":`false`}},P(`div`,{class:`ui-away__head`},P(`span`,{class:`ui-away__badge`,text:`📬`,attrs:{"aria-hidden":`true`}}),P(`div`,{class:`ui-away__titles`},P(`strong`,{class:`ui-away__title`,text:a(`Enquanto você estava fora`),attrs:{id:r}}),this.since),i),this.body,P(`div`,{class:`ui-away__actions`},P(`button`,{class:`ui-link-btn`,type:`button`,text:a(`Ver o meu prédio`),on:{click:()=>this.hooks.openWorld()}}),this.seenBtn),this.error),this.el.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.stopPropagation(),this.dismiss())})}active(){return this.hooks.active()&&this.src.meta()?.state===`approved`&&!this.ctx.store.replaying}render(){if(!this.active()){F(this.el,!0);return}let e=this.src.meta()?.building,t=cA(this.knocksSeen,e?.knocks);if(this.knocksSeen=t.last,t.fresh>0){let e=t.fresh===1?a(`Alguém bateu na porta do seu prédio.`):a(`Bateram {0} vezes na porta do seu prédio.`,[t.fresh]);this.hooks.toast({id:`world-knock-${Date.now()}`,level:`info`,text:`🚪 ${e}`,at:Date.now()}),this.ctx.announce(e)}if(!e?.awaySummary){this.shownKey&&this.hide();return}!this.shownKey&&!this.loading&&this.load()}async load(){let e=this.src.client;if(!e)return;this.loading=!0;let t=await e.status();this.loading=!1;let n=t.ok?t.data.building?.summary:void 0,r=sA(n);if(!n||!r||r===this.dismissedKey||!this.active())return;this.shownKey=r;let i=aA(n);M(this.since,i.since),this.body.replaceChildren(lA(i,!0)),F(this.error,!0),this.el.classList.toggle(`is-calm`,ht()),F(this.el,!1),this.ctx.announce(i.sentence)}hide(){this.shownKey=``,F(this.el,!0)}async dismiss(){let e=this.src.client;if(!e||this.busy)return;this.busy=!0,this.seenBtn.disabled=!0;let t=this.shownKey,n=await e.summarySeen();if(this.busy=!1,this.seenBtn.disabled=!1,!n.ok){M(this.error,O(n.code,`summary`)),F(this.error,!1);return}this.dismissedKey=t,this.hide()}},fA=class{host;el;badge;desc;stats;rejected;rejectedReason;actions;toggleBtn;sentBtn;visitBtn;hint;error;leaveRow;leaveBtn;unverified;appealRow;appealLink;appealHint;social;statsKey=``;busy=!1;action=null;confirmingLeave=!1;constructor(e){this.host=e;let t=`ui-world-building-title`;this.badge=P(`span`,{class:`ui-world__bstate`}),this.desc=P(`p`,{class:`ui-world__bdesc`}),this.stats=P(`ul`,{class:`ui-world__bstats`,attrs:{"aria-label":a(`Seu prédio agora`)}}),this.rejectedReason=P(`span`),this.rejected=P(`p`,{class:`ui-world__brejected`,role:`status`,hidden:!0},P(`strong`,{text:a(`O mundo recusou a última remessa.`)}),` `,this.rejectedReason),this.toggleBtn=P(`button`,{class:`ui-btn`,type:`button`,on:{click:()=>void this.toggle()}}),this.sentBtn=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Ver o que foi enviado`),attrs:{"aria-haspopup":`dialog`},on:{click:()=>e.openSent(this.sentBtn)}}),this.visitBtn=P(`button`,{class:`ui-btn`,type:`button`,text:`👁 ${a(`Ver como os outros veem`)}`,title:a(`Entrar no seu prédio pela cidade e ver o que quem visita vê (sem nada do escritório real)`),hidden:!0,on:{click:()=>e.visitOwn?.()?.()}}),this.actions=P(`div`,{class:`ui-world__actions`},this.toggleBtn,this.sentBtn,this.visitBtn),this.hint=P(`p`,{class:`ui-set__hint`}),this.error=P(`p`,{class:`ui-world__error`,role:`alert`,hidden:!0}),this.leaveBtn=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Sair do mundo`),on:{click:()=>void this.leave()}}),this.leaveRow=P(`div`,{class:`ui-world__leave`},P(`p`,{class:`ui-set__hint`,text:x()}),P(`div`,{class:`ui-world__actions`},this.leaveBtn)),this.unverified=P(`p`,{class:`ui-world__unverified`,role:`status`,hidden:!0}),this.appealLink=P(`a`,{class:`ui-btn`,attrs:{href:Je()}}),this.appealHint=P(`span`,{class:`ui-set__hint`}),this.appealRow=P(`div`,{class:`ui-world__appeal`,hidden:!0},this.appealHint,P(`div`,{class:`ui-world__actions`},this.appealLink)),this.social=new uA({client:e.client,building:()=>e.building(),refresh:()=>e.refresh()}),this.el=P(`section`,{class:`ui-world__building`,attrs:{"aria-labelledby":t}},P(`div`,{class:`ui-world__bhead`},P(`span`,{class:`ui-world__bart`,attrs:{"aria-hidden":`true`}}),P(`div`,{class:`ui-world__btitle`},P(`h4`,{text:a(`Seu prédio`),attrs:{id:t}}),this.badge)),this.desc,this.unverified,this.stats,this.social.el,this.rejected,this.appealRow,this.actions,this.hint,this.leaveRow,this.error),this.sync()}sync(){let e=We(this.host.building(),this.host.hasPlayer(),this.host.now(),{maintenance:this.host.maintenance?.()});vt(this.el,`is-`,e.state),M(this.badge,e.label),M(this.desc,e.desc);let t=e.stats.join(`
24
- `);t!==this.statsKey&&(this.statsKey=t,this.stats.replaceChildren(...e.stats.map(e=>P(`li`,{text:e})))),F(this.stats,!e.stats.length),F(this.rejected,!e.rejected),M(this.rejectedReason,e.rejected??``),F(this.toggleBtn,!e.toggle),F(this.hint,!e.toggle),e.toggle&&!this.busy&&(this.action=e.toggle.action,M(this.toggleBtn,e.toggle.text),M(this.hint,e.toggle.hint)),F(this.visitBtn,e.state!==`connected`&&e.state!==`paused`&&e.state!==`reconnecting`||!this.host.visitOwn?.()),F(this.leaveRow,!e.leave),!e.leave&&this.confirmingLeave&&this.resetLeave(),M(this.unverified,e.unverified??``),F(this.unverified,!e.unverified),F(this.appealRow,!e.appeal),e.appeal&&(M(this.appealLink,e.appeal.text),M(this.appealHint,e.appeal.hint),N(this.appealLink,`href`,Je(this.host.accountId?.()))),this.social.sync()}resetLeave(){this.confirmingLeave=!1,M(this.leaveBtn,a(`Sair do mundo`)),this.leaveBtn.classList.remove(`is-danger`)}async leave(){let e=this.host.client;if(this.busy||!e)return;if(!this.confirmingLeave){this.confirmingLeave=!0,M(this.leaveBtn,a(`Confirmar: sair do mundo`)),this.leaveBtn.classList.add(`is-danger`);return}this.busy=!0,this.leaveBtn.disabled=!0,this.toggleBtn.disabled=!0,N(this.leaveBtn,`aria-busy`,`true`),F(this.error,!0);let t=await e.leave();this.busy=!1,this.leaveBtn.disabled=!1,this.toggleBtn.disabled=!1,N(this.leaveBtn,`aria-busy`,null),this.resetLeave(),t.ok||(M(this.error,O(t.code,`leave`)),F(this.error,!1)),this.host.refresh()}async toggle(){let e=this.host.client,t=this.action;if(this.busy||!e||!t)return;this.busy=!0,this.toggleBtn.disabled=!0,N(this.toggleBtn,`aria-busy`,`true`),F(this.error,!0);let n=t===`pause`?await e.pause():t===`join`?await e.join():await e.resume();this.busy=!1,this.toggleBtn.disabled=!1,N(this.toggleBtn,`aria-busy`,null),n.ok||(M(this.error,O(n.code,t)),F(this.error,!1)),this.host.refresh()}},pA=class{client;now;el;body;req=0;opener=null;constructor(e,t){this.client=e,this.now=t;let n=`ui-world-sent-title`;this.body=P(`div`,{class:`ui-world-sent__content`});let r=j(Q.close,a(`Fechar`),()=>this.close(),`ui-icon-btn--sm`);this.el=P(`dialog`,{class:`ui-world-sent`,attrs:{"aria-labelledby":n}},P(`div`,{class:`ui-world-sent__body`},P(`div`,{class:`ui-world-sent__head`},P(`h2`,{class:`ui-world-sent__title`,text:a(`O que foi enviado`),attrs:{id:n}}),r),this.body)),this.el.addEventListener(`click`,e=>{e.target===this.el&&this.close()}),this.el.addEventListener(`close`,()=>{this.req++,this.opener?.focus(),this.opener=null})}get isOpen(){return this.el.open}async open(e){if(this.opener=e??null,!this.el.open)try{this.el.showModal()}catch{this.el.setAttribute(`open`,``)}await this.load()}close(){this.el.open&&this.el.close()}async load(){let e=this.client();if(!e)return;let t=++this.req;this.body.replaceChildren(P(`p`,{class:`ui-set__hint`,text:a(`Carregando…`)}));let n=await e.lastUplink();if(t===this.req){if(!n.ok){let e=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Tentar de novo`),on:{click:()=>void this.load()}});this.body.replaceChildren(P(`p`,{class:`ui-world__error`,role:`alert`,text:O(n.code,`sent`)}),P(`div`,{class:`ui-world__actions`},e));return}this.body.replaceChildren(...n.data?this.sent(n.data):this.nothing())}}nothing(){return[P(`p`,{class:`ui-world-sent__lead`,text:a(`Nada saiu deste computador ainda: o prédio entra no mundo com a primeira remessa.`)}),P(`p`,{class:`ui-set__hint`},uk(a(`O que pode sair e o que nunca sai`),lk))]}sent(e){let t=fe(e.uplink),n=Fe(e.ack,e.bytes),r=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Copiar`)}),i;r.addEventListener(`click`,async()=>{let e=await St(t);M(r,a(e?`Copiado!`:`Não deu para copiar`)),clearTimeout(i),i=setTimeout(()=>M(r,a(`Copiar`)),1600)});let o=P(`p`,{class:`ui-world-sent__ack is-${n.kind}`},P(`strong`,{text:n.label}),n.reason?` `:null,n.reason);return[P(`ul`,{class:`ui-world-sent__meta`},P(`li`,{text:a(`Enviada {0} ({1})`,[Nt(e.at,this.now()),Ft(e.at)])}),P(`li`,{text:Re(e.bytes)})),o,P(`p`,{class:`ui-world-sent__lead`},a(`Isto é tudo o que saiu do seu computador. Nenhum caminho, nome de projeto, texto ou horário do escritório.`),` `,uk(a(`O que pode sair e o que nunca sai`),lk)),P(`pre`,{class:`ui-world-sent__json`,tabIndex:0,text:t,attrs:{"aria-label":a(`Pacote enviado (JSON)`)}}),P(`div`,{class:`ui-world__actions`},r,P(`button`,{class:`ui-btn`,type:`button`,text:a(`Fechar`),on:{click:()=>this.close()}}))]}};function mA(e,t){let n=P(`ul`,{class:`ui-world__blocked`}),r=P(`p`,{class:`ui-set__hint`,text:a(`Carregando…`)}),i=P(`p`,{class:`ui-world__error`,role:`alert`,hidden:!0}),o=new Set,s=``,c=!1,l=e=>{let n=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Desbloquear`),attrs:{"aria-label":a(`Desbloquear {0}`,[e.name])}});return n.addEventListener(`click`,async()=>{let r=t.client;if(!r||n.disabled)return;n.disabled=!0,N(n,`aria-busy`,`true`),F(i,!0);let s=await r.unblock(e.id);if(t.current()){if(n.disabled=!1,N(n,`aria-busy`,null),!s.ok){M(i,O(s.code,`unblock`)),F(i,!1);return}o.add(e.id),t.announce(a(`{0} desbloqueado.`,[e.name])),u()}}),P(`li`,{class:`ui-set ui-world__blocked-row`},P(`div`,{class:`ui-set__text`},P(`span`,{class:`ui-world__blocked-name`},P(`span`,{text:`🚫`,attrs:{"aria-hidden":`true`}}),` ${e.name}`)),n)},u=()=>{let e=t.list(),i=(e??[]).filter(e=>!o.has(e.id)),u=`${c}|${e?`y`:`n`}|${i.map(e=>`${e.id}:${e.name}`).join(`,`)}`;if(u!==s){if(s=u,!e&&!c){M(r,a(`Carregando…`)),F(r,!1),n.replaceChildren();return}M(r,i.length?``:a(`Ninguém bloqueado.`)),F(r,i.length>0),n.replaceChildren(...i.map(l))}};return t.refresh().finally(()=>{t.current()&&(c=!0,u())}),u(),{el:P(`div`,{class:`ui-world__stack`},e,P(`p`,{class:`ui-set__hint`,text:a(`Quem você bloqueia não te vê e você não vê a pessoa: na rua, nos prédios, nos cumprimentos e nos carimbos. Para bloquear alguém, abra o cartão da pessoa na cidade.`)}),r,n,i),sync:u}}var hA=3e4;function gA(e,t){return e.split(/(\{\d+\})/).map(e=>{let n=/^\{(\d+)\}$/.exec(e);return n&&t[Number(n[1])]?t[Number(n[1])]:e})}function $(e,...t){return P(`p`,{class:e},...t)}function _A(e){return P(`button`,{class:`ui-link-btn ui-world__back`,type:`button`,text:a(`← Voltar`),on:{click:e}})}function vA(e,t){return P(`div`,{class:`ui-world__head`},_A(t),P(`h4`,{class:`ui-world__title`,text:e}))}var yA=0;function bA(e,t,n){let r=`ui-world-f${++yA}`;t.id=r;let i=n?P(`span`,{class:`ui-set__hint`,text:n,attrs:{id:`${r}-hint`}}):null;return i&&N(t,`aria-describedby`,i.id),{label:P(`div`,{class:`ui-world__field`},P(`label`,{class:`ui-world__label`,text:e,attrs:{for:r}}),t,i),input:t}}function xA(e,t,n={}){return P(`input`,{class:`ui-world__input`,type:e,attrs:{autocomplete:t,spellcheck:`false`,autocapitalize:`off`,...n}})}function SA(e,t,n){let r=xA(`password`,t,{maxlength:256}),i=bA(e,r,n),o=P(`button`,{class:`ui-link-btn ui-world__peek`,type:`button`,text:a(`Mostrar senha`)});return o.addEventListener(`click`,()=>{let e=r.type===`password`;r.type=e?`text`:`password`,M(o,a(e?`Esconder senha`:`Mostrar senha`)),N(o,`aria-pressed`,String(e))}),N(o,`aria-pressed`,`false`),i.label.append(o),i}function CA(){return bA(a(`E-mail`),xA(`email`,`email`,{inputmode:`email`,maxlength:254}))}function wA(){let e=xA(`text`,`one-time-code`,{inputmode:`numeric`,maxlength:9,placeholder:`000000`});return e.classList.add(`ui-world__code`),e.addEventListener(`input`,()=>{let t=C(e.value);t!==e.value&&/^\d*$/.test(t)&&(e.value=t)}),bA(a(`Código de 6 dígitos`),e)}var TA=class{busyText;el;error;submit;label;constructor(e,t,n){this.busyText=n,this.label=e,this.submit=P(`button`,{class:`ui-btn ui-btn--primary`,type:`submit`,text:e}),this.error=P(`p`,{class:`ui-world__error`,role:`alert`,hidden:!0}),this.el=P(`form`,{class:`ui-world__form`,attrs:{novalidate:!0}}),this.el.addEventListener(`submit`,e=>{e.preventDefault(),this.submit.disabled||t()})}setBusy(e){this.submit.disabled=e,N(this.submit,`aria-busy`,e?`true`:null),M(this.submit,e?this.busyText:this.label)}setError(e,t){M(this.error,e??``),F(this.error,!e),e&&t?.focus()}};function EA(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}function DA(e){let t=/^Dispositivo (\d+)$/.exec(e);return t?a(`Dispositivo {0}`,[t[1]]):e}function OA(t){try{return new Intl.DisplayNames([e()],{type:`region`}).of(t.toUpperCase())??t}catch{return t}}function kA(){return crypto.getRandomValues(new Uint32Array(1))[0]}function AA(e){switch(e){case`code_sent`:return``;case`code_resent`:return a(`Mandamos outro código.`);case`password_changed`:return a(`Senha trocada. Entre com a senha nova.`);case`signed_out`:return a(`Você saiu da conta do Habblaud World neste computador.`);case`character_saved`:return a(`Personagem salvo.`);case`device_revoked`:return a(`Dispositivo revogado.`)}}function jA(e){switch(e){case`closed`:return{label:a(`Fechado a visitas`),hint:a(`Dá para ver o prédio por fora, mas ninguém entra.`)};case`hideCountry`:return{label:a(`Esconder o país`),hint:a(`No lugar da bandeira do país (visto pelo IP da conexão) aparece uma bandeira neutra.`)};case`tokensVisible`:return{label:a(`Mostrar o consumo de tokens`),hint:a(`Total do dia e da semana do prédio inteiro, só em faixas (até 100 mil, 1 milhão…). Nunca o custo.`)};case`leaderboard`:return{label:a(`Entrar no placar`),hint:a(`O prédio pode aparecer nos placares de tokens da cidade.`)};case`compactions`:return{label:a(`Mostrar as compactações`),hint:a(`Quando um agente compacta o contexto, a lixeira da sala enche. Sai só o fato, nada do conteúdo.`)};case`knocks`:return{label:a(`Avisar quando baterem na porta`),hint:a(`Quem estiver na porta do seu prédio pode bater; o aviso chega aqui no Habblaud, sem o nome de quem bateu.`)}}}function MA(e,t){let n=I();return{remote:n.remote,local:n.local,terminal:!!e.store.liveSnapshot?.meta.terminal,fake:t.fake}}var NA=class{ctx;src;el;chip;flashEl;body;ui=be();mode=`hidden`;status=null;statusRev=0;statusSig=``;statusError=null;loading=!1;stale=!0;statusReq=0;metaState;wasOpen=!1;builtKey=``;view=null;epoch=0;lastFlash=null;resendUntil=0;metaBuildingSig=``;sent;themeNote;themeError;themeLinked=!1;themeReq=0;themeInflight=0;themePickedAt=0;themeClock=0;constructor(e,t){this.ctx=e,this.src=t,this.chip=P(`span`,{class:`ui-world__chip`}),this.flashEl=P(`p`,{class:`ui-world__flash`,role:`status`,hidden:!0}),this.body=P(`div`,{class:`ui-world__body`}),this.sent=new pA(()=>this.client,()=>this.ctx.now()),this.el=P(`div`,{class:`ui-world`,hidden:!0,attrs:{id:`ui-world`}},this.flashEl,this.body,this.sent.el),this.themeError=P(`span`,{class:`ui-world__error`,role:`alert`,hidden:!0}),this.themeNote=P(`span`,{class:`ui-set__hint ui-world-theme`,hidden:!0},P(`span`,{text:a(`O tema também vale para o seu prédio no Habblaud World.`)}),this.themeError),t.onChange?.(()=>{this.stale=!0,e.invalidate()})}get client(){return this.src.client}render(e){let t=this.src.meta(),n=MA(this.ctx,this.src);if(this.mode=Ce(t,n),F(this.el,this.mode===`hidden`),this.themeLinked=te(t,n),F(this.themeNote,!this.themeLinked),this.mode===`active`&&t){t.state!==this.metaState&&(this.metaState=t.state,this.stale=!0,this.status||(this.ui=ne(this.ui,{type:`server`,state:t.state})));let n=JSON.stringify(t.building??null);n!==this.metaBuildingSig&&(this.metaBuildingSig=n,this.stale=!0),e&&!this.wasOpen&&(this.stale=!0),e&&this.stale&&!this.loading&&this.refresh()}this.wasOpen=e,this.paint()}show(e){e&&(this.ui=ne(this.ui,{type:`go`,screen:e})),this.ctx.invalidate()}async onThemePicked(e){let t=this.client;if(this.themePickedAt=++this.themeClock,!this.themeLinked||!t)return;let n=++this.themeReq;this.themeInflight++;let r=await t.setTheme(e).finally(()=>this.themeInflight--);n===this.themeReq&&(M(this.themeError,r.ok?``:` ${a(`Não deu para mandar o tema para o prédio: {0}`,[O(r.code,`theme`)])}`),F(this.themeError,r.ok))}syncTheme(e,t){if(!this.themeLinked||e.state!==`approved`||this.themeInflight>0||t<this.themePickedAt)return;let n=this.ctx.prefs.theme;e.theme&&e.theme!==n?this.ctx.updatePrefs({theme:e.theme}):!e.theme&&n!==`auto`&&this.onThemePicked(n)}scrollToTop(){let e=this.el.parentElement;e&&(e.scrollTop=0)}dispatch(e){this.ui=ne(this.ui,e),this.ctx.invalidate()}go(e){this.dispatch({type:`go`,screen:e})}async refresh(e=!1){let t=this.client;if(!t)return;let n=++this.statusReq,r=this.themeClock;this.loading=!0,this.stale=!1;let i=await t.status(e);if(n===this.statusReq){if(this.loading=!1,i.ok){this.status=i.data,this.syncTheme(i.data,r);let{building:e,...t}=i.data,n=JSON.stringify(t);n!==this.statusSig&&(this.statusSig=n,this.statusRev++),this.statusError=null,this.ui=ne(this.ui,{type:`server`,state:i.data.state})}else this.statusError=i.code;this.ctx.invalidate()}}async run(e,t,n,r){let i=this.client;if(!i)return null;let a=this.epoch;e.setBusy(!0),e.setError(null);let o=await n(i);return a===this.epoch?(e.setBusy(!1),o.ok||e.setError(O(o.code,t),r),o):null}viewKey(){return this.mode===`active`?(this.ui.server===`waiting`||this.ui.server===`approved`)&&!this.status?this.statusError?`error:${this.statusError}`:`loading`:`screen:${this.ui.screen}`:this.mode}paint(){let e=this.viewKey();e===this.builtKey?this.view?.sync?.():(this.builtKey=e,this.epoch++,this.view=this.build(),this.body.replaceChildren(this.view.el),this.scrollToTop()),M(this.chip,this.chipText()),vt(this.chip,`is-`,this.mode===`active`?this.ui.server??`loading`:this.mode);let t=this.ui.flash?AA(this.ui.flash):``;M(this.flashEl,t),F(this.flashEl,!t),this.ui.flash!==this.lastFlash&&(this.lastFlash=this.ui.flash,t&&this.ctx.announce(t))}chipText(){if(this.mode===`local_only`)return a(`Só pelo computador`);switch(this.ui.server){case`logged_out`:return a(`Sem conta`);case`waiting`:return a(`Na lista de espera`);case`approved`:return a(`Liberado`);default:return``}}build(){if(this.mode===`local_only`)return{el:$(`ui-set__hint`,a(`A conta do Habblaud World só pode ser mexida no próprio computador, com o Habblaud em acesso local (bind 127.0.0.1) e aberto por http://localhost.`))};if(this.mode!==`active`)return{el:P(`div`)};let e=this.builtKey;if(e===`loading`)return{el:$(`ui-set__hint`,a(`Carregando…`))};if(e.startsWith(`error:`))return this.buildStatusError();switch(this.ui.screen){case`welcome`:return this.buildWelcome();case`register`:return this.buildRegister();case`login`:return this.buildLogin();case`verify`:return this.buildVerify();case`forgot`:return this.buildForgot();case`reset`:return this.buildReset();case`home`:return this.buildHome();case`character`:return this.buildCharacter();case`visibility`:return this.buildVisibility();case`devices`:return this.buildDevices();case`account`:return this.buildAccount();case`blocked`:return this.buildBlocked()}}buildStatusError(){let e=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Tentar de novo`),on:{click:()=>void this.refresh()}});return{el:P(`div`,{class:`ui-world__stack`},$(`ui-world__error`,O(this.statusError??`unknown`,`status`)),P(`div`,{class:`ui-world__actions`},e))}}privacyLine(){return $(`ui-world__privacy`,a(`Nada do seu trabalho sai do computador: só o tema, quantos andares e se cada personagem está ocupado ou à toa.`),` `,uk(a(`Ver a lista`),lk))}buildWelcome(){let e=P(`button`,{class:`ui-btn ui-btn--primary`,type:`button`,text:a(`Criar conta`),on:{click:()=>this.go(`register`)}}),t=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Já tenho conta`),on:{click:()=>this.go(`login`)}}),n=this.status?.lastError===`account_deleted`?$(`ui-world__notice`,O(`account_deleted`,`status`)):null;return{el:P(`div`,{class:`ui-world__stack`},n,$(`ui-world__lead`,a(`Leve o seu escritório para uma cidade em pixel art: um prédio seu, aceso enquanto os agentes trabalham, e um personagem para passear e visitar os prédios de outras pessoas.`)),this.privacyLine(),$(`ui-set__hint`,a(`O acesso é liberado aos poucos: quem cria a conta entra numa lista de espera.`)),P(`div`,{class:`ui-world__actions`},e,t))}}privacySummary(){return P(`section`,{class:`ui-world__summary`,attrs:{"aria-label":a(`O que sai do seu computador`)}},P(`h4`,{class:`ui-world__summary-title`,text:a(`O que sai do seu computador`)}),$(`ui-world__official`,a(`Quem visita o mundo vê, ao vivo, quantos projetos e agentes você está rodando e o que cada personagem está fazendo (trabalhando, esperando, à toa). Ninguém vê quais projetos são, o que os agentes fazem, nem quem você é: só o nickname e o avatar que você escolheu.`)),P(`ul`,{class:`ui-world__list`},P(`li`,{},P(`strong`,{text:a(`Sai:`)}),` `,a(`o tema do escritório; um andar por sala aberta, com um código aleatório que muda todo dia; de cada agente, se é principal ou subagente, a ferramenta, o status, a aparência, um nome sorteado e a faixa de tarefas concluídas no dia; os tokens do prédio arredondados em faixas (dá para desligar); se você ligar, o fato de um agente ter compactado o contexto; a versão e o commit do Habblaud, com a marca de cópia modificada; e o idioma da interface, só para os e-mails.`)),P(`li`,{},P(`strong`,{text:a(`Nunca sai:`)}),` `,a(`caminhos e nomes de projetos, títulos de sessão, comandos, mensagens, código, custo, a sua conta do Claude, o seu e-mail e o nome do computador.`))),$(`ui-world__key`,a(`Com os dados que saem não dá para saber quem você é nem em que trabalha.`)),$(`ui-set__hint`,a(`Os agentes trabalham sem você: prédio aceso não quer dizer que você está no computador. Se preferir, use o modo discreto ou feche o prédio a visitas.`)),uk(a(`Ver a lista completa`),lk))}buildRegister(){let e=CA();e.input.value=this.ui.email;let n=bA(a(`Nome de jogador`),xA(`text`,`nickname`,{maxlength:Ve.max*2}),a(`3 a 20 caracteres; é o nome do seu personagem e fica reservado para você, mesmo na lista de espera. Único no mundo.`));n.input.value=this.ui.name;let r=SA(a(`Senha`),`new-password`,a(`Pelo menos 12 caracteres. Uma frase longa vale mais do que símbolos; senhas que já vazaram são recusadas.`)),i=new Vv({label:a(`Li e aceito os {0} e a {1} do Habblaud World.`,[a(`Termos de Uso`),a(`Política de Privacidade`)]),className:`ui-world__checkbox`,tag:`span`,content:P(`span`,{},...gA(a(`Li e aceito os {0} e a {1} do Habblaud World.`),[uk(a(`Termos de Uso`),ck),uk(a(`Política de Privacidade`),lk)]))}),o=new TA(a(`Criar conta`),()=>void s(),a(`Criando a conta…`)),s=async()=>{let s=pe(e.input.value);if(!ot(s))return o.setError(a(`Digite um e-mail válido.`),e.input);let c=je(n.input.value);if(!c.ok)return o.setError(rt(c.problem),n.input);let l=Be(r.input.value,s);if(l)return o.setError(de(l),r.input);if(!i.value)return o.setError(a(`Para criar a conta, aceite os Termos de Uso e a Política de Privacidade.`),i.el);let u=await this.run(o,`register`,e=>e.register({email:s,password:r.input.value.normalize(`NFC`),name:c.name,locale:t()}),e.input);if(u){if(u.ok)return this.dispatch({type:`code_sent`,email:s,name:c.name});u.code===`name_taken`?o.setError(a(`Esse nome já está em uso. Escolha outro.`),n.input):(u.code===`name_invalid`||u.code===`name_blocked`)&&o.setError(O(u.code,`register`),n.input)}};return o.el.append(e.label,n.label,r.label,this.privacySummary(),$(`ui-world__truth`,a(`O World só funciona se os prédios forem verdadeiros. Mandar dados inventados quebra os termos e bane a conta.`)),P(`div`,{class:`ui-world__accept`},i.el),o.error,P(`div`,{class:`ui-world__actions`},o.submit,P(`button`,{class:`ui-btn`,type:`button`,text:a(`Já tenho conta`),on:{click:()=>this.go(`login`)}}))),{el:P(`div`,{class:`ui-world__stack`},vA(a(`Criar conta`),()=>this.go(`welcome`)),o.el)}}buildLogin(){let e=CA();e.input.value=this.ui.email;let t=SA(a(`Senha`),`current-password`),n=new TA(a(`Entrar`),()=>void r(),a(`Entrando…`)),r=async()=>{let r=pe(e.input.value);if(!ot(r))return n.setError(a(`Digite um e-mail válido.`),e.input);if(!t.input.value)return n.setError(a(`Digite a senha.`),t.input);let i=await this.run(n,`login`,e=>e.login({email:r,password:t.input.value.normalize(`NFC`)}),t.input);if(i){if(i.ok){this.dispatch({type:`signed_in`}),this.refresh();return}i.code===`email_not_verified`&&this.dispatch({type:`code_sent`,email:r})}},i=P(`button`,{class:`ui-link-btn`,type:`button`,text:a(`Esqueci a senha`),on:{click:()=>{this.ui={...this.ui,email:pe(e.input.value)},this.go(`forgot`)}}});return n.el.append(e.label,t.label,n.error,P(`div`,{class:`ui-world__actions`},n.submit,i)),{el:P(`div`,{class:`ui-world__stack`},vA(a(`Entrar na conta`),()=>this.go(`welcome`)),n.el,$(`ui-set__hint`,a(`Ainda não tem conta?`),` `,P(`button`,{class:`ui-link-btn`,type:`button`,text:a(`Criar conta`),on:{click:()=>this.go(`register`)}})))}}demoCodeHint(){return this.src.fake?$(`ui-world__demo`,a(`Demonstração: o código é {0}.`,[Rk])):null}resendButton(e,t){let n=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Reenviar código`)}),r=()=>{n.disabled=Date.now()<this.resendUntil};return n.addEventListener(`click`,async()=>{n.disabled=!0;let i=this.epoch;e.setError(null);let a=this.client;if(!a)return;let o=await t(a);i===this.epoch&&(o.ok?(this.resendUntil=Date.now()+hA,setTimeout(()=>this.ctx.invalidate(),30050),this.dispatch({type:`flash`,flash:`code_resent`})):e.setError(O(o.code,`resend`)),r())}),r(),{el:n,sync:r}}buildVerify(){let e=this.ui.email,t=wA(),n=new TA(a(`Confirmar e-mail`),()=>void r(),a(`Conferindo…`)),r=async()=>{if(!Ae(t.input.value))return n.setError(a(`Digite os 6 dígitos do código.`),t.input);(await this.run(n,`verify`,n=>n.verify({email:e,code:C(t.input.value)}),t.input))?.ok&&(this.dispatch({type:`signed_in`}),this.refresh())},i=this.resendButton(n,t=>t.resend({email:e}));return n.el.append(t.label,n.error,P(`div`,{class:`ui-world__actions`},n.submit,i.el)),{el:P(`div`,{class:`ui-world__stack`},vA(a(`Confirmar o e-mail`),()=>this.go(`welcome`)),$(`ui-world__lead`,...gA(a(`Mandamos um código de 6 dígitos para {0}. Ele vale por 10 minutos.`),[P(`strong`,{class:`ui-world__email`,text:e})])),$(`ui-set__hint`,a(`Não chegou? Confira o spam ou peça outro. Se este e-mail já tinha conta, a mensagem avisa: aí é só entrar com a senha.`)),this.demoCodeHint(),n.el,P(`button`,{class:`ui-link-btn`,type:`button`,text:a(`Usar outro e-mail`),on:{click:()=>this.go(`register`)}})),sync:i.sync}}buildForgot(){let e=CA();e.input.value=this.ui.email;let t=new TA(a(`Mandar código`),()=>void n(),a(`Mandando…`)),n=async()=>{let n=pe(e.input.value);if(!ot(n))return t.setError(a(`Digite um e-mail válido.`),e.input);(await this.run(t,`forgot`,e=>e.forgotPassword({email:n}),e.input))?.ok&&this.dispatch({type:`reset_code_sent`,email:n})};return t.el.append(e.label,t.error,P(`div`,{class:`ui-world__actions`},t.submit)),{el:P(`div`,{class:`ui-world__stack`},vA(a(`Esqueci a senha`),()=>this.go(`login`)),$(`ui-set__hint`,a(`Digite o e-mail da conta. Se ele estiver cadastrado, chega um código para criar uma senha nova.`)),t.el)}}buildReset(){let e=this.ui.email,t=wA(),n=SA(a(`Senha nova`),`new-password`,a(`Pelo menos 12 caracteres. Uma frase longa vale mais do que símbolos; senhas que já vazaram são recusadas.`)),r=new TA(a(`Trocar a senha`),()=>void i(),a(`Trocando…`)),i=async()=>{if(!Ae(t.input.value))return r.setError(a(`Digite os 6 dígitos do código.`),t.input);let i=Be(n.input.value,e);if(i)return r.setError(de(i),n.input);(await this.run(r,`reset`,r=>r.resetPassword({email:e,code:C(t.input.value),password:n.input.value.normalize(`NFC`)}),t.input))?.ok&&(this.dispatch({type:`password_changed`}),this.refresh())},o=this.resendButton(r,t=>t.forgotPassword({email:e}));return r.el.append(t.label,n.label,$(`ui-set__hint`,a(`Trocar a senha desconecta todos os dispositivos da conta.`)),r.error,P(`div`,{class:`ui-world__actions`},r.submit,o.el)),{el:P(`div`,{class:`ui-world__stack`},vA(a(`Senha nova`),()=>this.go(`login`)),$(`ui-world__lead`,...gA(a(`Se {0} tiver conta, chegou um código de 6 dígitos. Digite o código e a senha nova.`),[P(`strong`,{class:`ui-world__email`,text:e})])),this.demoCodeHint(),r.el),sync:o.sync}}buildHome(){let e=P(`div`,{class:`ui-world__stack`}),t=new fA({client:this.client,building:()=>this.status?.building??wk(this.src.meta()?.building),hasPlayer:()=>!!this.status?.player,refresh:()=>void this.refresh(),openSent:e=>void this.sent.open(e),now:()=>this.ctx.now(),visitOwn:()=>{let e=this.ctx.visitOwnBuilding;return e&&this.src.meta()?.scene?.available===!0?()=>e():null},accountId:()=>this.status?.account?.id,maintenance:()=>this.status?.lastError===`maintenance`}),n=Hv(a(`Avisar quando alguém visitar`),a(`Um aviso quando o primeiro visitante entra no seu prédio. Você vê só quantos estão lá dentro, nunca quem.`),()=>this.ctx.updatePrefs({worldVisitNotify:!this.ctx.prefs.worldVisitNotify})),r=-1,i=()=>{r!==this.statusRev&&(r=this.statusRev,e.replaceChildren(...this.homeContent(t,n.row))),t.sync(),N(n.btn,`aria-checked`,String(this.ctx.prefs.worldVisitNotify))};return i(),{el:e,sync:i}}homeContent(e,t){let n=this.status,r=this.ui.server===`approved`,i=[];i.push($(`ui-world__notice`,a(r?`Acesso liberado!`:`Você está na lista de espera. Estamos liberando o acesso aos poucos e avisamos por e-mail quando chegar a sua vez.`)));let o=n?.lastError===`maintenance`;o&&!r&&i.push($(`ui-world__maint`,O(`maintenance`,`status`))),r?i.push(e.el):i.push(P(`div`,{class:`ui-world__lot`},P(`span`,{class:`ui-world__lot-art`,attrs:{"aria-hidden":`true`}}),P(`span`,{class:`ui-world__lot-text`,text:a(`Seu prédio vai aparecer aqui`)})));let s=n?.player;if(s?.mustRename&&i.push($(`ui-world__warn`,a(`Escolha um nome novo: a moderação trocou o seu nome de jogador. O nome novo entra na hora, sem esperar os 30 dias.`))),s){let e=P(`span`,{class:`ui-world__traits`},...s.traits.filter(e=>it[e]).map(e=>P(`span`,{class:`ui-world__trait`,text:`${it[e].emoji} ${it[e].label}`}))),t=s.country?OA(s.country):s.visibility.hideCountry?a(`país escondido`):``;i.push(P(`div`,{class:`ui-world__player`},bv({seed:0,look:s.look,kind:`main`,parts:s.parts},`lg`),P(`div`,{class:`ui-world__player-text`},P(`strong`,{class:`ui-world__player-name`,text:s.name}),P(`span`,{class:`ui-world__player-intro`,text:`“${Ee(s.intro)}”`}),e,t?P(`span`,{class:`ui-set__hint`,text:t}):null)),P(`div`,{class:`ui-world__actions`},s.mustRename?P(`button`,{class:`ui-btn ui-btn--primary`,type:`button`,text:a(`Escolher nome novo`),on:{click:()=>this.go(`character`)}}):P(`button`,{class:`ui-btn`,type:`button`,text:a(`Editar personagem`),on:{click:()=>this.go(`character`)}})))}else{let e=n?.account?.reservedName;e&&i.push($(`ui-world__reserved`,...gA(a(`Seu nome de jogador: {0} (reservado)`),[P(`strong`,{class:`ui-world__player-name`,text:e})]))),i.push($(`ui-set__hint`,a(r?`Crie o seu personagem para entrar no mundo.`:`Enquanto espera, já dá para criar o seu personagem.`)),P(`div`,{class:`ui-world__actions`},P(`button`,{class:`ui-btn ui-btn--primary`,type:`button`,text:a(`Criar meu personagem`),attrs:{"data-world":`create-character`},on:{click:()=>this.go(`character`)}})))}let c=P(`div`,{class:`ui-world__nav`});if(s){let e=s.visibility,t=[e.mode===`discreet`?a(`Discreto`):a(`Ao vivo`),e.closed?a(`fechado a visitas`):null].filter(Boolean).join(` · `);c.append(this.navRow(a(`Visibilidade do prédio`),t,()=>this.go(`visibility`)))}let l=n?.devices?.length;return c.append(this.navRow(a(`Dispositivos`),l?a(`{0} de 3`,[l]):``,()=>this.go(`devices`))),s&&r&&c.append(this.navRow(a(`Bloqueados`),n?.blocked?.length?String(n.blocked.length):``,()=>this.go(`blocked`))),c.append(this.navRow(a(`Conta e dados`),``,()=>this.go(`account`))),i.push(c),r&&s&&i.push(t),n?.lastError&&!o&&i.push($(`ui-world__warn`,a(`Último problema com o mundo: {0}`,[O(n.lastError,`status`)]))),i.push(this.signOutRow()),n?.account&&i.push($(`ui-set__hint ui-world__email`,a(`Conta: {0}`,[n.account.emailMasked]))),i.push(P(`p`,{class:`ui-world__links`},uk(a(`Termos de Uso`),ck),uk(a(`Política de Privacidade`),lk))),i}navRow(e,t,n){return P(`button`,{class:`ui-world__navrow`,type:`button`,on:{click:n}},P(`span`,{class:`ui-set__label`,text:e}),P(`span`,{class:`ui-world__navval`,text:t}),P(`span`,{class:`ui-world__chev`,text:`›`,attrs:{"aria-hidden":`true`}}))}signOutRow(){let e=!1,t=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Sair da conta`)}),n=P(`span`,{class:`ui-set__hint`,text:a(`Este computador deixa de entrar no mundo; a conta e o personagem continuam.`)}),r=P(`p`,{class:`ui-world__error`,role:`alert`,hidden:!0});return t.addEventListener(`click`,async()=>{if(!e){e=!0,M(t,a(`Confirmar: sair da conta`)),t.classList.add(`is-danger`);return}let n=this.client;if(!n)return;t.disabled=!0,N(t,`aria-busy`,`true`);let i=this.epoch,o=await n.logout();if(i===this.epoch){if(t.disabled=!1,N(t,`aria-busy`,null),!o.ok){M(r,O(o.code,`logout`)),F(r,!1);return}this.dispatch({type:`flash`,flash:`signed_out`}),this.refresh()}}),P(`div`,{class:`ui-world__signout`},P(`div`,{class:`ui-set`},P(`div`,{class:`ui-set__text`},n),t),r)}buildCharacter(){let e=this.status?.player,t=e?.look??(kA()%2?`m`:`f`),n=e?e.traits.filter(e=>ge.includes(e)):[],r=new Wv(void 0,{worldSafe:!0});r.set(e?tt(t,e.parts):tt(t,void 0,kA()));let i=P(`input`,{class:`ui-char__name`,type:`text`,attrs:{maxlength:Ve.max*2,autocomplete:`nickname`,spellcheck:`false`,"aria-describedby":`ui-world-name-hint`}}),o=e?.mustRename===!0,s=e?void 0:this.status?.account?.reservedName;i.value=o?``:e?.name??s??``,s&&(i.readOnly=!0,i.classList.add(`is-fixed`)),o&&requestAnimationFrame(()=>i.isConnected&&i.focus());let c=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Sortear`),title:a(`Sortear outra aparência (desfaz as peças escolhidas)`),on:{click:()=>r.set(tt(t,void 0,kA()))}}),l=gD(a(`Dica visual`),[[`f`,a(`Feminina`)],[`m`,a(`Masculina`)]],e=>{t=e,l.set(e);let n=r.value;n&&r.set({...n,look:e})});l.set(t),l.row.append(P(`span`,{class:`ui-set__hint`,text:a(`Muda detalhes do rosto e o sorteio de cabelo e roupa; tudo dá para trocar nas peças abaixo.`)}));let u=P(`span`,{class:`ui-world__count`}),d=new Map,f=()=>{M(u,a(`{0} de 3`,[n.length]));for(let[e,t]of d){let r=n.includes(e),i=le(n,e);N(t,`aria-pressed`,String(r)),N(t,`aria-disabled`,i?`true`:null),A(t,i?i.reason===`full`?a(`Já são 3 traços: desmarque um para trocar.`):a(`Não combina com {0}.`,[it[i.with].label]):it[e].desc)}};for(let e of ge){let t=it[e],r=P(`button`,{class:`ui-world__trait-opt`,type:`button`,text:`${t.emoji} ${t.label}`});r.addEventListener(`click`,()=>{r.getAttribute(`aria-disabled`)!==`true`&&(n=ie(n,e),f())}),d.set(e,r)}f();let p=new zv({label:a(`Frase de apresentação`),className:`ui-world__select`,options:[{value:``,label:a(`Escolha uma frase…`)},...v.map(e=>({value:e,label:Ee(e)}))],value:e?.intro??``}),m=new TA(a(`Salvar personagem`),()=>void g(),a(`Salvando…`)),h=P(`div`,{class:`ui-world__traitopts`,role:`group`,attrs:{"aria-label":a(`Personalidade`)}},...d.values()),g=async()=>{let e=r.value;if(!e)return;let o=E(p.value)?p.value:null,c=Le({name:s??i.value,traits:n,intro:o});if(c?.field===`name`)return m.setError(rt(c.problem),i);if(c?.field===`traits`)return m.setError(a(`Escolha 2 ou 3 traços de personalidade.`),d.get(ge[0]));if(c||!o)return m.setError(a(`Escolha uma frase de apresentação.`),p.button);let l=je(i.value),u={...s?{}:{name:l.ok?l.name:i.value},look:t,parts:at(e),traits:[...n],intro:o};(await this.run(m,`character`,e=>e.saveCharacter(u),i))?.ok&&(this.dispatch({type:`go`,screen:`home`}),this.dispatch({type:`flash`,flash:`character_saved`}),this.refresh())};return m.el.append(o?$(`ui-world__warn`,a(`Escolha um nome novo`)):``,P(`div`,{class:`ui-char__top`},r.preview,P(`div`,{class:`ui-char__head`},P(`label`,{class:`ui-char__label`},P(`span`,{text:a(`Nome de jogador`)}),i),c)),s?$(`ui-set__hint`,P(`span`,{attrs:{id:`ui-world-name-hint`}},a(`Escolhido no cadastro. Dá para trocar depois, uma vez a cada 30 dias.`))):$(`ui-set__hint`,P(`span`,{attrs:{id:`ui-world-name-hint`}},a(`De 3 a 20 caracteres: letras de um só alfabeto, números, espaço, _ - e . É o seu nome no mundo e não pode repetir o de ninguém.`)),o?` ${a(`Desta vez o nome novo entra na hora, sem esperar os 30 dias.`)}`:e?` ${a(`Dá para trocar uma vez a cada 30 dias.`)}`:``),l.row,r.groups,P(`fieldset`,{class:`ui-char__group ui-world__traitset`},P(`legend`,{},a(`Personalidade`),` `,u),$(`ui-set__hint`,a(`Escolha 2 ou 3 traços. Os que não combinam com os já escolhidos ficam apagados.`)),h),P(`label`,{class:`ui-world__field`},P(`span`,{class:`ui-world__label`,text:a(`Frase de apresentação`)}),p.el,P(`span`,{class:`ui-set__hint`,text:a(`Aparece no seu perfil, traduzida para quem lê. No mundo não há texto livre além do nome.`)})),m.error,P(`div`,{class:`ui-world__actions`},m.submit,P(`button`,{class:`ui-btn`,type:`button`,text:a(`Cancelar`),on:{click:()=>this.go(`home`)}}))),{el:P(`div`,{class:`ui-world__stack ui-world__character`},vA(a(e?`Editar personagem`:`Criar personagem`),()=>this.go(`home`)),m.el)}}buildVisibility(){let e=this.status?.player;if(!e)return{el:P(`div`,{class:`ui-world__stack`},vA(a(`Visibilidade do prédio`),()=>this.go(`home`)),$(`ui-set__hint`,a(`Disponível depois de criar o personagem.`)))};let t={...Xe,...e.visibility},n=!1,r=P(`p`,{class:`ui-world__error`,role:`alert`,hidden:!0}),i=new Map,o=async e=>{let i=this.client;if(n||!i)return;let a=t;t=e,n=!0,F(r,!0),u();let o=this.epoch,s=await i.saveVisibility(e);o===this.epoch&&(n=!1,s.ok?this.refresh():(t=a,M(r,O(s.code,`visibility`)),F(r,!1)),u())},s=gD(a(`Modo do prédio`),[[`live`,a(`Ao vivo`)],[`discreet`,a(`Discreto`)]],e=>void o({...t,mode:e}));s.row.append(P(`span`,{class:`ui-set__hint`,text:a(`Ao vivo: andares, contadores e o que cada personagem está fazendo, em tempo real. Discreto: só aceso ou apagado e o número de andares.`)}));let c=Pe.map(e=>{let n=jA(e),r=Hv(n.label,n.hint,()=>void o({...t,[e]:!t[e]}));return i.set(e,r.btn),r.row}),l=P(`p`,{class:`ui-set__hint`}),u=()=>{s.set(t.mode);for(let[e,r]of i)N(r,`aria-checked`,String(t[e])),r.disabled=n;let e=this.status?.player?.country;M(l,t.hideCountry?a(`País: escondido (aparece uma bandeira neutra).`):e?a(`País visto na última conexão: {0}.`,[OA(e)]):a(`País: aparece depois da primeira conexão com o mundo.`))};return u(),{el:P(`div`,{class:`ui-world__stack`},vA(a(`Visibilidade do prédio`),()=>this.go(`home`)),s.row,...c,l,r,$(`ui-set__hint`,a(`As mudanças valem na hora.`)))}}buildBlocked(){let e=this.epoch;return mA(vA(a(`Bloqueados`),()=>this.go(`home`)),{client:this.client,list:()=>this.status?.blocked,refresh:()=>this.refresh(!0),current:()=>e===this.epoch,announce:e=>this.ctx.announce(e)})}buildDevices(){let e=P(`ul`,{class:`ui-world__devices`}),t=P(`p`,{class:`ui-set__hint`,text:a(`Carregando…`)}),n=P(`p`,{class:`ui-world__error`,role:`alert`,hidden:!0}),r=this.status?.devices??null,i=()=>{F(t,!!r),r&&e.replaceChildren(...r.map(e=>this.deviceRow(e,n,e=>{r=(r??[]).filter(t=>t.id!==e),i()})))};return i(),(async()=>{let e=this.client;if(!e)return;let a=this.epoch,o=await e.devices();a===this.epoch&&(o.ok?(r=o.data,F(n,!0)):r||(M(n,O(o.code,`devices`)),F(n,!1),F(t,!0)),i())})(),{el:P(`div`,{class:`ui-world__stack`},vA(a(`Dispositivos`),()=>this.go(`home`)),$(`ui-set__hint`,a(`Até 3 por conta. Revogar desconecta o dispositivo na hora; para voltar, ele entra de novo com a senha.`)),t,e,n)}}deviceRow(e,t,n){let r=Date.now(),i=EA(e.createdAt),o=EA(e.lastSeenAt),s=[i?a(`entrou em {0}`,[kt(i)]):null,!e.current&&o?a(`último acesso {0}`,[Nt(o,r)]):null].filter(Boolean).join(` · `),c=P(`span`,{class:`ui-world__device-name`},DA(e.label),e.current?P(`span`,{class:`ui-world__tag`,text:a(`este computador`)}):null),l=P(`div`,{class:`ui-set__text`},c,s?P(`span`,{class:`ui-set__hint`,text:s}):null);if(e.current)return P(`li`,{class:`ui-set ui-world__device`},l);let u=!1,d=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Revogar`),attrs:{"aria-label":a(`Revogar {0}`,[DA(e.label)])}});return d.addEventListener(`click`,async()=>{if(!u){u=!0,M(d,a(`Confirmar`)),d.classList.add(`is-danger`);return}let r=this.client;if(!r)return;d.disabled=!0,N(d,`aria-busy`,`true`);let i=this.epoch,o=await r.revokeDevice(e.id);if(i===this.epoch){if(d.disabled=!1,N(d,`aria-busy`,null),!o.ok){M(t,O(o.code,`revoke`)),F(t,!1);return}n(e.id),this.dispatch({type:`flash`,flash:`device_revoked`}),this.refresh()}}),P(`li`,{class:`ui-set ui-world__device`},l,d)}buildAccount(){let e=this.inactivitySection(),t=this.exportSection(),n=this.deletionSection();return{el:P(`div`,{class:`ui-world__stack`},vA(a(`Conta e dados`),()=>this.go(`home`)),e.el,t,n,$(`ui-set__hint`,a(`Dúvidas ou pedidos sobre os seus dados: {0}.`,[Qe]))),sync:e.sync}}inactivitySection(){let e=null,t=P(`p`,{class:`ui-world__error`,role:`alert`,hidden:!0}),n=Hv(a(`Avisar por e-mail antes de retirar meu prédio por inatividade`),a(`Sem notícias deste Habblaud por 7 dias, o prédio some do mapa e, 30 dias depois, é retirado. O e-mail chega 3 dias antes da retirada.`),()=>void o()),r=$(`ui-set__hint`,a(`O aviso de inatividade fica disponível depois de criar o personagem.`)),i=()=>{let t=this.status?.player;F(n.row,!t),F(r,!!t),N(n.btn,`aria-checked`,String(e??He(t?.visibility))),n.btn.disabled=e!==null},o=async()=>{let n=this.client,r=this.status?.player;if(!n||!r||e!==null)return;let a=!He(r.visibility);e=a,F(t,!0),i();let o=this.epoch,s=await n.saveVisibility({...Xe,...r.visibility,notifyInactivity:a});if(o===this.epoch){if(e=null,!s.ok)M(t,O(s.code,`inactivity`)),F(t,!1);else{let e=this.status?.player;e&&(e.visibility={...e.visibility,notifyInactivity:a}),this.refresh()}i()}};return i(),{el:P(`section`,{class:`ui-world__acct`},P(`h4`,{class:`ui-world__acct-title`,text:a(`Avisos`)}),n.row,r,t),sync:i}}exportSection(){let e=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Baixar meus dados`)}),t=P(`p`,{class:`ui-set__hint`,role:`status`,hidden:!0}),n=P(`p`,{class:`ui-world__error`,role:`alert`,hidden:!0});return e.addEventListener(`click`,async()=>{let r=this.client;if(!r||e.disabled)return;e.disabled=!0,N(e,`aria-busy`,`true`),F(n,!0),F(t,!0);let i=this.epoch,o=await r.exportData();if(i===this.epoch){if(e.disabled=!1,N(e,`aria-busy`,null),!o.ok){M(n,O(o.code,`export`)),F(n,!1);return}PA(this.el,o.data,Me),M(t,a(`Pronto: o arquivo {0} foi para a pasta de downloads.`,[Me])),F(t,!1)}}),P(`section`,{class:`ui-world__acct`},P(`h4`,{class:`ui-world__acct-title`,text:a(`Seus dados`)}),$(`ui-set__hint`,a(`Um arquivo JSON com o que o Habblaud World guarda da sua conta: e-mail, datas, personagem, visibilidade, dispositivos, prédio, likes dados, bloqueios e denúncias feitas. Dá para baixar uma vez por dia.`)),P(`div`,{class:`ui-world__actions`},e),t,n)}deletionSection(){let e=P(`div`,{class:`ui-world__stack`}),t=()=>this.status?.account?.emailMasked??``,n=()=>{let e=P(`button`,{class:`ui-btn`,type:`button`,text:a(`Excluir conta…`),on:{click:()=>o(r())}});return[$(`ui-set__hint`,a(`Excluir a conta tira você do Habblaud World:`)),P(`ul`,{class:`ui-world__list`},P(`li`,{},P(`strong`,{text:a(`Na hora:`)}),` `,a(`o prédio e o perfil somem do mundo, e este computador sai da conta.`)),P(`li`,{},P(`strong`,{text:a(`Em 7 dias:`)}),` `,a(`a conta, o personagem, os likes dados e recebidos, os bloqueios, as denúncias feitas e os dispositivos são apagados do banco.`)),P(`li`,{},P(`strong`,{text:a(`Em até 30 dias:`)}),` `,a(`somem também dos backups.`))),$(`ui-set__hint`,a(`Se quiser guardar uma cópia, baixe os seus dados antes.`)),P(`div`,{class:`ui-world__actions`},e)]},r=()=>{let e=new TA(a(`Mandar o código`),()=>void r(),a(`Mandando…`));e.submit.classList.add(`is-danger`);let r=async()=>{(await this.run(e,`delete`,e=>e.requestAccountDeletion()))?.ok&&o(i())};return e.el.append($(`ui-world__warn`,a(`Tem certeza? O prédio e o perfil saem do mundo assim que você digitar o código.`)),$(`ui-set__hint`,...gA(a(`Para confirmar, mandamos um código de 6 dígitos para o e-mail da conta ({0}).`),[P(`strong`,{class:`ui-world__email`,text:t()})])),e.error,P(`div`,{class:`ui-world__actions`},e.submit,P(`button`,{class:`ui-btn`,type:`button`,text:a(`Cancelar`),on:{click:()=>o(n())}}))),[e.el]},i=()=>{let e=wA(),r=new TA(a(`Excluir a conta`),()=>void i(),a(`Excluindo…`));r.submit.classList.add(`is-danger`);let i=async()=>{if(!Ae(e.input.value))return r.setError(a(`Digite os 6 dígitos do código.`),e.input);(await this.run(r,`delete`,t=>t.confirmAccountDeletion({code:C(e.input.value)}),e.input))?.ok&&(this.ctx.announce(O(`account_deleted`,`status`)),this.refresh())},s=this.resendButton(r,e=>e.requestAccountDeletion());return r.el.append($(`ui-world__lead`,...gA(a(`Mandamos um código de 6 dígitos para {0}. Digite o código para excluir a conta.`),[P(`strong`,{class:`ui-world__email`,text:t()})])),this.demoCodeHint()??``,e.label,r.error,P(`div`,{class:`ui-world__actions`},r.submit,s.el,P(`button`,{class:`ui-btn`,type:`button`,text:a(`Cancelar`),on:{click:()=>o(n())}}))),requestAnimationFrame(()=>e.input.isConnected&&e.input.focus()),[r.el]},o=t=>e.replaceChildren(...t);return o(n()),P(`section`,{class:`ui-world__acct ui-world__acct--danger`},P(`h4`,{class:`ui-world__acct-title`,text:a(`Excluir conta`)}),e)}};function PA(e,t,n){let r=URL.createObjectURL(new Blob([t],{type:`application/json`})),i=P(`a`,{hidden:!0,attrs:{href:r,download:n}});e.append(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}var FA=Z([`....####....`,`....#..#....`,`.##########.`,`.#.##.##.##.`,`.##########.`,`.#.##.##.##.`,`.##########.`,`.#.##.##.##.`,`.##########.`,`.####..####.`,`.####..####.`,`############`],{"#":`currentColor`},`ui-px-icon ui-world-popup__icon`),IA=`ui-world-popup-title`,LA=class{ctx;src;hooks;el;memory;open=null;opener=null;constructor(e,t,n){this.ctx=e,this.src=t,this.hooks=n,this.memory=this.load(),this.el=P(`dialog`,{class:`ui-world-popup`,attrs:{"aria-labelledby":IA}}),this.el.addEventListener(`click`,e=>{e.target===this.el&&this.close()}),this.el.addEventListener(`close`,()=>this.onClosed()),this.el.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.stopPropagation(),typeof this.el.showModal!=`function`&&(e.preventDefault(),this.close()))})}render(){let e=this.src.meta();if(this.open){this.open===`launch`&&e?.state!==`logged_out`&&this.close();return}let t={...MA(this.ctx,this.src),replaying:this.ctx.store.replaying},n=w(e,t,this.memory,Date.now());n.show===`launch`&&this.hooks.panelOpen()||(n.memory&&this.remember(n.memory),n.show&&this.show(n.show))}show(e){this.open=e;let t=P(`span`,{class:`ui-world-popup__badge`,attrs:{"aria-hidden":`true`}});t.innerHTML=FA;let{title:n,body:r,actions:i,primary:a}=this.content(e);this.el.className=`ui-world-popup is-${e}`,this.el.replaceChildren(P(`div`,{class:`ui-world-popup__head`},t,P(`h2`,{class:`ui-world-popup__title`,text:n,attrs:{id:IA}})),P(`div`,{class:`ui-world-popup__body`},...r),P(`div`,{class:`ui-world-popup__actions`},...i)),this.opener=typeof document<`u`&&document.activeElement instanceof HTMLElement?document.activeElement:null,typeof this.el.showModal==`function`?this.el.open||this.el.showModal():this.el.setAttribute(`open`,``),this.el.setAttribute(`aria-modal`,`true`),a.focus({preventScroll:!0})}content(e){let t=e=>P(`p`,{class:`ui-set__hint ui-world-popup__hint`,text:e}),n=e=>P(`p`,{class:`ui-world-popup__text`,text:e});if(e===`waitlist`){let e=P(`button`,{class:`ui-btn ui-btn--primary ui-world-popup__cta`,type:`button`,text:a(`Entendi`),attrs:{autofocus:!0},on:{click:()=>this.close()}});return{title:a(`Você está na lista de espera`),body:[n(a(`O acesso é liberado aos poucos, em lotes. Avisamos por e-mail quando chegar a sua vez.`)),t(a(`Enquanto isso, o Habblaud continua normal e nada do escritório é enviado.`))],actions:[e],primary:e}}if(e===`approved`){let e=P(`button`,{class:`ui-btn ui-btn--primary ui-world-popup__cta`,type:`button`,text:a(`Criar personagem`),attrs:{autofocus:!0},on:{click:()=>this.go(`character`)}});return{title:a(`Acesso liberado!`),body:[n(a(`Chegou a sua vez: crie o seu personagem e entre na cidade.`))],actions:[e,P(`button`,{class:`ui-btn`,type:`button`,text:a(`Depois`),on:{click:()=>this.close()}})],primary:e}}let r=P(`button`,{class:`ui-btn ui-btn--primary ui-world-popup__cta`,type:`button`,text:a(`Criar conta`),attrs:{autofocus:!0},on:{click:()=>this.go(`register`)}});return{title:a(`Novidade: Habblaud World`),body:[P(`p`,{class:`ui-world-popup__lead`,text:a(`Seu escritório agora pode virar um prédio numa cidade online, aceso enquanto os seus agentes trabalham.`)}),P(`ul`,{class:`ui-world-popup__perks`},P(`li`,{text:a(`Seu escritório vira um prédio numa cidade em pixel art, aceso enquanto os seus agentes trabalham.`)}),P(`li`,{text:a(`Crie um personagem, ande pela cidade e visite os prédios de outras pessoas.`)}),P(`li`,{text:a(`Cumprimente quem passa e deixe likes nos prédios, sem chat e sem spam.`)})),P(`p`,{class:`ui-world-popup__privacy`},a(`Nada do seu trabalho sai do computador: só o tema, quantos andares e se cada personagem está ocupado ou à toa.`),` `,uk(a(`Ver a lista`),lk)),t(a(`Nada é enviado enquanto você não criar a conta. O acesso é liberado aos poucos, por lista de espera.`))],actions:[r,P(`button`,{class:`ui-btn`,type:`button`,text:a(`Agora não`),on:{click:()=>this.close()}}),P(`button`,{class:`ui-link-btn`,type:`button`,text:a(`Não mostrar de novo`),on:{click:()=>this.never()}})],primary:r}}go(e){this.close(),this.hooks.openWorld(e)}never(){this.remember({...this.memory,launch:`never`}),this.close()}close(){this.el.open&&(typeof this.el.close==`function`?this.el.close():this.el.removeAttribute(`open`)),this.el.removeAttribute(`aria-modal`),this.open&&this.onClosed()}onClosed(){this.open&&(this.open=null,this.opener?.isConnected&&this.opener.focus({preventScroll:!0}),this.opener=null,this.ctx.invalidate())}load(){try{let e=kE();return e?_({launch:e.getItem(Ze),legacy:e.getItem(qe),waitlist:e.getItem(et),approved:e.getItem(Ge)}):{...ze}}catch{return{...ze}}}remember(e){this.memory=e;try{let t=kE();if(!t)return;let n=he(e);for(let[e,r]of[[Ze,n.launch],[et,n.waitlist],[Ge,n.approved]])r===null?t.removeItem(e):t.setItem(e,r)}catch{}}},RA={live:`🏙️`,paused:`⏸`,reconnecting:`🏙️`,stopped:`⚠️`},zA=class{ctx;src;notify;el;icon;text;visitors;alert=Ue;alertSeq=0;likes;lastLikes=null;constructor(e,t,n,r){this.ctx=e,this.src=t,this.notify=r,this.icon=P(`span`,{class:`ui-world-chip__icon`,attrs:{"aria-hidden":`true`}}),this.text=P(`span`,{class:`ui-world-chip__text`}),this.visitors=P(`span`,{class:`ui-world-chip__visitors`,hidden:!0}),this.likes=P(`span`,{class:`ui-world-chip__likes`,hidden:!0}),this.el=P(`button`,{class:`ui-world-chip`,type:`button`,hidden:!0,attrs:{"aria-haspopup":`dialog`},on:{click:n}},this.icon,this.text,this.visitors,this.likes)}render(){let e=this.src.meta(),t=y(e,MA(this.ctx,this.src)),n=t?e?.building?.visitors:void 0,r=Se(this.alert,n,this.ctx.prefs.worldVisitNotify);if(this.alert=r.state,r.notify&&this.notify?.({id:`world-visit-${++this.alertSeq}`,level:`info`,text:`👀 ${a(`Alguém entrou no seu prédio no Habblaud World.`)}`,at:Date.now()}),F(this.el,!t),F(this.visitors,!n),M(this.visitors,n?`👀 ${n}`:``),!t)return;let i=e?.building;vt(this.el,`is-`,t),M(this.icon,RA[t]);let[o,s]={live:[a(`no mundo`),a(`Seu prédio está aceso no Habblaud World: {0} e {1}. Clique para abrir o Habblaud World.`,[Ne(i?.floors??0),Ie(i?.agents??0)])],paused:[a(`pausado`),a(`Pausado: seu prédio está apagado, mas você pode andar pela cidade. Nada do escritório sai deste computador; clique para retomar.`)],reconnecting:[a(`reconectando…`),a(`Sem conexão com o Habblaud World agora; o Habblaud tenta de novo sozinho. Clique para ver o seu prédio.`)],stopped:[a(`parado`),a(`Seu prédio parou de subir ao Habblaud World. Clique para ver o motivo.`)]}[t],c=n?`${s} ${ct(n)}.`:s;M(this.text,o);let l=oA(t,i?.likesToday);F(this.likes,!l),M(this.likes,l?.text??``);let u=l?`${c} ${l.title}`:c;A(this.el,u),N(this.el,`aria-label`,u);let d=i?.likesToday??0;l&&this.lastLikes!==null&&d>this.lastLikes&&!ht()&&(this.likes.classList.remove(`is-bump`),this.likes.offsetWidth,this.likes.classList.add(`is-bump`)),this.lastLikes=d}},BA=`ui-world-dialog-title`,VA=class{ctx;src;button;el;group;body;title;opener=null;constructor(e,t,n){this.ctx=e,this.src=t,this.button=n,this.group=new NA(e,t);let r=P(`span`,{class:`ui-world-dialog__badge`,attrs:{"aria-hidden":`true`}});r.innerHTML=FA,this.title=P(`h2`,{class:`ui-world-dialog__title`,text:a(`Habblaud World`),tabIndex:-1,attrs:{id:BA}});let i=j(Q.close,a(`Fechar (Esc)`),()=>this.close(),`ui-icon-btn--sm`);this.body=P(`div`,{class:`ui-world-dialog__body`},this.group.el),this.el=P(`dialog`,{class:`ui-world-dialog`,attrs:{"aria-labelledby":BA}},P(`div`,{class:`ui-world-dialog__head`},r,P(`div`,{class:`ui-world-dialog__heading`},this.title,this.group.chip),i),this.body),this.el.addEventListener(`click`,e=>{e.target===this.el&&this.close()}),this.el.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Escape`&&typeof this.el.showModal!=`function`&&(e.preventDefault(),this.close())}),this.el.addEventListener(`close`,()=>this.onClosed())}get themeNote(){return this.group.themeNote}onThemePicked(e){return this.group.onThemePicked(e)}get isOpen(){return this.el.open}show(e,t){this.group.show(e),!this.el.open&&(this.opener=t??(document.activeElement instanceof HTMLElement?document.activeElement:null),typeof this.el.showModal==`function`?this.el.showModal():this.el.setAttribute(`open`,``),this.el.setAttribute(`aria-modal`,`true`),this.button.setAttribute(`aria-expanded`,`true`),this.body.scrollTop=0,this.title.focus({preventScroll:!0}),this.ctx.invalidate())}toggle(e){this.el.open?this.close():this.show(void 0,e)}close(){this.el.open&&(this.el.removeAttribute(`aria-modal`),typeof this.el.close==`function`?this.el.close():(this.el.removeAttribute(`open`),this.onClosed()))}onClosed(){this.button.setAttribute(`aria-expanded`,`false`),this.opener?.isConnected&&this.opener.focus({preventScroll:!0}),this.opener=null,this.ctx.invalidate()}render(){let e=Ce(this.src.meta(),MA(this.ctx,this.src))===`hidden`;F(this.button,e),e&&this.el.open&&this.close(),this.group.render(this.el.open)}};function HA(e,t,n=[]){let r=new Map;for(let i of e)r.has(i.agentId)||r.set(i.agentId,mt(i.agentId,i.agentName,t,n.find(e=>e.id===i.agentId)));return[...r.values()]}function UA(e){let t=e.feed.filter(t=>t.activity.at>=e.from&&t.activity.at<=e.to),n=e.feed.reduce((e,t)=>Math.min(e,t.activity.at),1/0),r=e.feed.length===0?e.from<e.pageLoadedAt:n>e.from&&(e.from<e.pageLoadedAt||e.feed.length>=200);return{finished:HA(t.filter(e=>e.activity.kind===`done`),e.machines,e.agents),ciFailed:HA(t.filter(e=>e.activity.tool===`GitHub`&&e.activity.error),e.machines,e.agents),waiting:bu(e.agents).map(t=>({name:xt(t,e.machines),sinceMs:Math.max(0,e.now-t.statusSince)})),partial:r}}function WA(t){try{return new Intl.ListFormat(e(),{style:`long`,type:`conjunction`}).format(t)}catch{return t.join(`, `)}}function GA(e){let t=[];return e.finished.length&&t.push(a(`Terminaram: {0}`,[WA(e.finished)])),e.ciFailed.length&&t.push(a(`CI falhou: {0}`,[WA(e.ciFailed)])),e.waiting.length&&t.push(a(`Esperando por você: {0}`,[WA(e.waiting.map(e=>a(`{0} (há {1})`,[e.name,zt(e.sinceMs)])))])),!t.length&&!e.partial&&t.push(a(`Nada aconteceu enquanto você estava fora.`)),e.partial&&t.push(a(`Parte do período não está coberta.`)),t}var KA=class{el;list;constructor(){this.list=P(`ul`,{class:`ui-while-away__list`});let e=P(`button`,{class:`ui-btn ui-btn--sm`,type:`button`,text:a(`Ok, vi`),on:{click:()=>this.hide()}});this.el=P(`div`,{class:`ui-while-away`,role:`status`,hidden:!0},P(`strong`,{class:`ui-while-away__title`,text:a(`Enquanto você estava fora`)}),this.list,e)}show(e){this.list.replaceChildren(...GA(e).map(e=>P(`li`,{text:e}))),F(this.el,!1)}hide(){F(this.el,!0)}render(){}};function qA(e,t){let n=e.meta();return n?.scene?.available===!0&&Ce(n,t)===`active`}var JA=class{ctx;src;host;onChange;button;icon;label;busy=!1;autoOpen;constructor(e,t,n,r){this.ctx=e,this.src=t,this.host=n,this.onChange=r,this.icon=P(`span`,{class:`ui-scene-btn__icon`,attrs:{"aria-hidden":`true`}}),this.label=P(`span`,{class:`ui-scene-btn__label`}),this.button=P(`button`,{class:`ui-scene-btn`,type:`button`,hidden:!0,on:{click:()=>void this.toggle()}},this.icon,this.label),this.autoOpen=typeof location<`u`&&new URLSearchParams(location.search).get(`scene`)===`city`}get inCity(){return this.host.open}available(){return qA(this.src,MA(this.ctx,this.src))&&!this.ctx.store.replaying&&!this.ctx.isTimelapseOpen()}async toggle(){this.host.open?this.close():await this.open()}async open(){if(!(this.busy||this.host.open||!this.available())){this.busy=!0;try{this.ctx.selection()&&this.ctx.select(null),await this.host.show(),this.ctx.announce(a(`Você está na cidade do Habblaud World. Esc volta ao escritório.`))}catch(e){console.error(`[ui] a cidade não abriu`,e)}finally{this.busy=!1,this.onChange()}}}async visitOwn(){this.host.open||await this.open(),this.host.open&&this.host.visitOwn?.()}close(){this.host.open&&(this.host.hide(),this.ctx.announce(a(`De volta ao escritório.`)),this.onChange())}leaveFor(e){e&&this.close()}render(){let e=this.available();!e&&this.host.open&&this.close(),F(this.button,!e&&!this.host.open);let t=this.host.open;this.icon.innerHTML=t?Q.office:Q.city,M(this.label,a(t?`Escritório`:`Mundo`));let n=a(t?`Voltar ao escritório (Esc)`:`Mundo: andar pela cidade do Habblaud World`);A(this.button,n),N(this.button,`aria-label`,n),N(this.button,`aria-pressed`,String(t)),this.button.classList.toggle(`is-city`,t),this.autoOpen&&e&&(this.autoOpen=!1,this.open())}},YA=480,XA=320,ZA=24,QA=6,$A=344,ej=280,tj=new Set([`ArrowLeft`,`ArrowRight`,`ArrowUp`,`ArrowDown`,`a`,`A`,`d`,`D`,`w`,`W`,`s`,`S`,`+`,`=`,`-`,`_`,`0`,`o`,`O`]);function nj(e,t,n){if(n-e-t>=120||e+t<=0)return[e,t];let r=Math.max(0,n-120)/(e+t);return[Math.floor(e*r),Math.floor(t*r)]}function rj(e,t,n=8){let r=Math.max(0,e.topBottom)+n,i=t.sidebar&&!t.narrow?Math.max(0,e.sideRight)+n:0,a=t.drawer&&!e.drawerSheet?Math.max(0,e.vw-e.drawerLeft)+n:0,o=t.feed?e.feedOpenH:e.feedClosedH,s=o>0?o+e.feedMargin+n:0;t.drawer&&e.drawerSheet&&(s=Math.max(s,e.vh-e.drawerTop+n));let[c,l]=nj(i,a,e.vw),[u,d]=nj(r,s,e.vh);return{top:Math.round(u),right:Math.round(l),bottom:Math.round(d),left:Math.round(c)}}function ij(e,t){return!!e&&Math.abs(e.top-t.top)<1&&Math.abs(e.right-t.right)<1&&Math.abs(e.bottom-t.bottom)<1&&Math.abs(e.left-t.left)<1}function aj(e,t){return e===t||!!e&&!!t&&e.type===t.type&&e.id===t.id}var oj=e=>e instanceof HTMLCanvasElement;function sj(e){return e instanceof HTMLElement?e.isContentEditable||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement:!1}var cj=class{world;panels;flags;applied=null;probe;probeFeedOpen;probeFeedClosed;probeGap;guardTimer=null;checkTimer=null;intent=null;toastPlace=``;raf=0;down=null;lastTap={t:0,x:0,y:0};constructor(e,t,n){if(this.world=e,this.panels=t,this.flags=n,this.probeFeedOpen=document.createElement(`span`),this.probeFeedClosed=document.createElement(`span`),this.probeGap=document.createElement(`span`),this.probeFeedOpen.className=`ui-probe__feed-open`,this.probeFeedClosed.className=`ui-probe__feed-closed`,this.probeGap.className=`ui-probe__gap`,this.probe=document.createElement(`div`),this.probe.className=`ui-probe`,this.probe.setAttribute(`aria-hidden`,`true`),this.probe.append(this.probeFeedOpen,this.probeFeedClosed,this.probeGap),t.root.append(this.probe),addEventListener(`resize`,()=>this.schedule()),t.feed.addEventListener(`transitionend`,e=>{e.target===t.feed&&this.schedule()}),typeof ResizeObserver==`function`){let e=new ResizeObserver(()=>this.schedule());e.observe(t.topbar),e.observe(this.probeFeedOpen),e.observe(this.probeGap),e.observe(t.sidebar),e.observe(t.drawer)}this.watchCanvas()}get insets(){return this.applied??{top:0,right:0,bottom:0,left:0}}get guarding(){return this.guardTimer!==null}schedule(){this.raf||=requestAnimationFrame(()=>{this.raf=0,this.sync()})}sync(e={}){this.raf&&=(cancelAnimationFrame(this.raf),0);let t=this.flags(),n=this.measure(),r=rj(n,{...t,drawer:t.drawer&&!this.guarding});if(this.placeToasts(r,n),ij(this.applied,r))return;this.applied=r;let i=this.panels.root.style;i.setProperty(`--free-top`,`${r.top}px`),i.setProperty(`--free-right`,`${r.right}px`),i.setProperty(`--free-bottom`,`${r.bottom}px`),i.setProperty(`--free-left`,`${r.left}px`);try{this.world.setViewInsets?.(r)}catch(e){console.error(`[ui] setViewInsets falhou`,e)}e.refocus!==!1&&this.refocus()}placeToasts(e,t){let n=this.panels.feed,r=Math.max(t.feedMargin,e.right),i=t.vw-r-(n.offsetLeft+n.offsetWidth)-t.feedMargin,a=!t.drawerSheet&&i>=ej,o=a?t.feedMargin:e.bottom,s=a?Math.min($A,i):Math.min($A,Math.max(240,t.vw-r-Math.max(t.feedMargin,e.left))),c=`${o}|${s}`;c!==this.toastPlace&&(this.toastPlace=c,this.panels.root.style.setProperty(`--toast-bottom`,`${o}px`),this.panels.root.style.setProperty(`--toast-w`,`${Math.round(s)}px`))}setIntent(e,t=`option`){this.intent={sel:e,follow:t}}clearIntent(){this.intent=null}selectionChangedExternally(e,t){this.intent&&!aj(this.intent.sel,t)&&(this.intent=null),!e&&t?this.beginGuard():t||this.endGuard(!1)}selectingFromUi(){this.endGuard(!1)}refocus(){let e=this.intent;e&&aj(e.sel,this.world.getSelection())&&(e.sel.type===`agent`?this.world.focusAgent(e.sel.id,{follow:e.follow===`option`?this.world.getOptions().followSelected:e.follow}):this.world.focusRoom(e.sel.id))}beginGuard(){this.endGuard(!1),this.panels.drawer.classList.add(`is-opening`),this.guardTimer=setTimeout(()=>this.endGuard(!0),380)}endGuard(e){this.guardTimer!==null&&(clearTimeout(this.guardTimer),this.guardTimer=null,this.panels.drawer.classList.remove(`is-opening`),this.sync(),e&&this.ensureVisibleSoon())}ensureVisibleSoon(){this.checkTimer&&clearTimeout(this.checkTimer),this.checkTimer=setTimeout(()=>{this.checkTimer=null;let e=this.world.getSelection();if(e?.type!==`agent`||this.intent)return;let t=this.world.screenPositionOf(e.id),n=this.insets;t&&t.x>=n.left&&t.x<=innerWidth-n.right&&t.y>=n.top&&t.y<=innerHeight-n.bottom||this.world.focusAgent(e.id,{follow:this.world.getOptions().followSelected})},YA)}onDoubleActivate(){let e=this.world.getSelection();e&&(this.intent={sel:e,follow:e.type===`agent`},this.guarding&&this.endGuard(!1))}watchCanvas(){addEventListener(`dblclick`,e=>oj(e.target)&&this.onDoubleActivate()),addEventListener(`pointerdown`,e=>{this.down=oj(e.target)?{x:e.clientX,y:e.clientY,id:e.pointerId}:null},!0),addEventListener(`pointermove`,e=>{this.down&&e.buttons!==0&&Math.hypot(e.clientX-this.down.x,e.clientY-this.down.y)>QA&&(this.intent=null,this.down=null,this.lastTap.t=0)},!0),addEventListener(`pointerup`,e=>{let t=this.down;if(this.down=null,!t||!oj(e.target)||e.pointerType===`mouse`)return;let n=performance.now();n-this.lastTap.t<XA&&Math.hypot(e.clientX-this.lastTap.x,e.clientY-this.lastTap.y)<ZA?(this.lastTap.t=0,queueMicrotask(()=>this.onDoubleActivate())):this.lastTap={t:n,x:e.clientX,y:e.clientY}},!0),addEventListener(`wheel`,e=>oj(e.target)&&(this.intent=null),{capture:!0,passive:!0}),addEventListener(`keydown`,e=>{e.ctrlKey||e.metaKey||e.altKey||sj(e.target)||tj.has(e.key)&&(this.intent=null)},!0)}measure(){let{topbar:e,sidebar:t,drawer:n}=this.panels,r=innerWidth,i=innerHeight,a=n.offsetWidth>=r-40&&n.offsetTop>e.offsetHeight+40;return{vw:r,vh:i,topBottom:e.offsetTop+e.offsetHeight,sideRight:t.offsetLeft+t.offsetWidth,drawerLeft:n.offsetLeft,drawerTop:n.offsetTop,drawerSheet:a,feedOpenH:this.probeFeedOpen.offsetHeight,feedClosedH:this.probeFeedClosed.offsetHeight,feedMargin:this.probeGap.offsetWidth}}},lj=5e3,uj=1e3,dj=`(max-width: 900px)`;function fj(e){return e instanceof HTMLElement?e.isContentEditable||e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement:!1}function pj(e,t,n,r){let i=kE(),o=EE(i);Tt((e,t)=>Us(e,t)),Bs(o.pixelEmoji);let s=n.getSelection(),c=0,l=typeof matchMedia==`function`?matchMedia(dj):null,u={sidebar:!l?.matches&&o.sidebarOpen,feed:!l?.matches&&o.feedOpen},d=P(`div`,{class:`ui-sr`,role:`status`,attrs:{"aria-live":`polite`}}),f,p,m,h,g,_,v,y,b,x=!1,S=null,C=()=>!!S?.inCity,w={store:t,world:n,root:e,get prefs(){return o},updatePrefs(e){o={...o,...e},DE(i,o),Bs(o.pixelEmoji),n.setOptions(OE(o)),n.avatar?.setThresholds(wE(o)),k()},now:()=>b?.replayTime??Date.now()+c,account:e=>t.snapshot?.accounts.find(t=>t.id===e),agent:e=>t.agent(e),selection:()=>s,select(e,t){S?.leaveFor(e),e&&t?.focus?y.setIntent(e):y.clearIntent();let r=s;s=e,y.selectingFromUi(),Ae({refocus:!1}),x=!0;try{n.select(e,t)}catch(e){throw s=r,Ae(),e}finally{x=!1}},focusSelection(){s&&w.select(s,{focus:!0})},camera(e){if(C()&&r){e===`overview`?r.recenter():r.zoomBy(e===`zoomIn`?1.25:1/1.25);return}y.clearIntent(),e===`overview`?n.overview():n.zoomBy(e===`zoomIn`?1.25:1/1.25)},invalidate:()=>k(),togglePanel(e,t){let n=t??!u[e];u[e]!==n&&(u[e]=n,w.isNarrow()||w.updatePrefs(e===`sidebar`?{sidebarOpen:n}:{feedOpen:n}),Ae(),k())},isPanelOpen:e=>u[e],isNarrow:()=>!!l?.matches,announce(e){d.textContent=``,requestAnimationFrame(()=>d.textContent=e)},focusSearch(){u.sidebar||w.togglePanel(`sidebar`,!0),requestAnimationFrame(()=>p.focusSearch())},openHelp:e=>v.open(e),toggleSettings:()=>h.toggle(f.settingsBtn),togglePerf:()=>g.toggle(),isPerfOpen:()=>g.isOpen,toggleWorld:()=>_.toggle(f.worldBtn),openAbout:()=>h.showAbout(f.settingsBtn),toggleTimelapse(){!b.isOpen&&D.isOpen&&D.close(),b.toggle()},isTimelapseOpen:()=>b.isOpen},ee=new VD(w),te=new gE(w,ee.board),T=new mv(w);f=new ak(w),f.addCounterButton(T.button),p=new ND(w);let E=new HD(w),D=new HC(w,E),ne=new RT(w,D);f.panelGroup.prepend(ne.button),E.onShow=()=>D.close();let re={get openAgentId(){return E.isOpen?E.agentId:D.agentId},get available(){return E.enabled||!!t.snapshot?.meta.terminal&&!t.replaying},interactive:e=>!!E.ptyOf(e),get interactiveEnabled(){return E.enabled},newSession:(e,t)=>E.newSession(e,t),open(e,n){let r=!!t.snapshot?.meta.terminal&&!t.replaying;E.ptyOf(e)||E.enabled&&!r&&w.agent(e)?.kind===`main`?E.openAgent(e):(E.close(),D.open(e,n))},toggle(e,t){re.openAgentId===e?(E.close(),D.close()):re.open(e,t)}};w.terminals=re;let ie=new eE(w,D);f.panelGroup.prepend(ie.button),typeof location<`u`&&(e=>{let n=e.searchParams.get(`agent`),r=e.searchParams.get(`delivery`);if(!n&&!r)return;let i=()=>{r?ie.openById(r):n&&w.agent(n)&&w.select({type:`agent`,id:n},{focus:!0})};if(t.snapshot)i();else{let e=t.on(`snapshot`,()=>{e(),setTimeout(i,300)})}e.search&&location.search===e.search&&window.history.replaceState(null,``,location.pathname)})(new URL(location.href)),m=new lT(w,D,E);let ae=new gT(w),oe=new yO(w),se=new fD(w,e=>oe.push(e)),ce=Uk(t);_=new VA(w,ce,f.worldBtn),h=new _D(w,te,ee,_),g=new qD(w,f.perfBtn);let le=new LA(w,ce,{openWorld:e=>_.show(e,f.worldBtn),panelOpen:()=>h.isOpen||_.isOpen}),ue=new zA(w,ce,()=>_.show(`home`),e=>oe.push(e));f.addStatus(ue.el);let de=new dA(w,ce,{active:()=>Ce(ce.meta(),MA(w,ce))===`active`,toast:e=>oe.push(e),openWorld:()=>_.show(`home`)});if(r){S=new JA(w,ce,r,()=>{let t=C();e.classList.toggle(`is-city`,t),t&&(D.isOpen&&D.close(),E.isOpen&&E.close(),w.isNarrow()&&u.sidebar&&w.togglePanel(`sidebar`,!1)),k()}),f.addSceneButton(S.button);let t=S;w.visitOwnBuilding=()=>{_.isOpen&&_.close(),h.isOpen&&h.hide(),t.visitOwn()}}v=new ET;let fe=new O_(w,t=>e.append(t));f.addPanelButton(fe.button);let pe=new Z_(w),me=new av(w),he=new ov(w);w.renameRoom=(e,t)=>pe.open(e,t),w.manageCustomRooms=(e,t,n)=>me.open(e,t,n),w.favoriteRoomsMenu=(e,n,r)=>he.openFavorites(t.snapshot?.rooms??[],n,r),w.customRoomMenu=(e,n)=>{let r=t.room(e);r?.custom&&he.openCustomRoom(r,n)},n.onRoomContextMenu?.((e,n)=>{let r=t.room(e);r?.custom?he.openCustomRoom(r,n):pe.open(e,n)});let ge=new mT(w),_e=new hT(w),ve=new sk(t),ye=new tE(w),be=new fT(w),xe=wD(e);b=new mO(w);let Se=P(`div`,{class:`ui-scrim`,attrs:{"aria-hidden":`true`},on:{click:()=>w.togglePanel(`sidebar`,!1)}});e.classList.add(`ui-root`),e.append(b.vignette,f.el,p.el,Se,ae.el,m.el,D.el,E.el,b.el,b.badge,oe.el,_e.el,ve.el,ge.el,le.el,ye.el,h.el,g.el,_.el,ne.el,ie.el,v.el,pe.el,me.el,he.el,d,be.el,xe.el),y=new cj(n,{root:e,topbar:f.el,sidebar:p.el,drawer:m.el,feed:ae.el},()=>({sidebar:u.sidebar,feed:u.feed,drawer:s!==null&&!m.floating,narrow:w.isNarrow()})),m.onLayoutChange=()=>Ae();let we=new S_({mock:t.mock});n.avatar?.bindAttention(we),n.avatar?.setThresholds(wE(o)),we.startHeartbeat(E_(globalThis,document).read);let O=new w_(w,we,t,()=>!t.replaying),Te=new KA;e.append(Te.el),n.avatar?.onReturned(e=>{if(t.replaying)return;let n=w.now(),r=we.serverOffsetMs;Te.show(UA({from:e.from+r,to:e.to+r,feed:t.feed,agents:t.snapshot?.agents??[],pageLoadedAt:n-performance.now(),now:n,machines:t.snapshot?.machines}))});let Ee=[f,p,m,D,E,ne,ie,ae,oe,h,g,ge,_e,ye,te,be,b,ee,fe,se,_,le,ue,O,me,T,xe];S&&Ee.push(S),e.append(de.el),Ee.push(de);let De=0,Oe=null;function ke(){De=0;for(let e of Ee)try{e.render()}catch(t){console.error(`[ui] falha ao renderizar`,e.constructor.name,t)}}function k(){if(document.hidden){Oe??=setTimeout(()=>{Oe=null,te.render(),oe.render()},500);return}De||=requestAnimationFrame(ke)}function Ae(t={}){e.classList.toggle(`has-sidebar`,u.sidebar),e.classList.toggle(`has-feed`,u.feed),e.classList.toggle(`has-drawer`,s!==null&&!m.floating),e.classList.toggle(`is-narrow`,w.isNarrow()),y.sync(t)}t.on(`snapshot`,e=>{_v(e.defaultLook??null),t.connection===`open`&&!t.replaying&&(c=e.serverTime-Date.now()),k()}),t.on(`connection`,()=>k()),t.on(`defaultLook`,e=>{_v(e),k()}),Zt(()=>k()),n.onSelect(e=>{let t=s;s=e,x||y.selectionChangedExternally(t,e),Ae(x?{refocus:!1}:{}),k()}),l?.addEventListener(`change`,e=>{e.matches?(u.sidebar=!1,u.feed=!1):(u.sidebar=o.sidebarOpen,u.feed=o.feedOpen),Ae(),k()}),document.addEventListener(`visibilitychange`,()=>{document.hidden||k()}),setInterval(()=>{document.hidden||k()},lj),setInterval(()=>{!document.hidden&&(fb(t.snapshot)||Zb(t.snapshot))&&k()},uj),addEventListener(`keydown`,e=>je(e));function je(e){if(!(e.defaultPrevented||e.ctrlKey||e.metaKey||e.altKey)){if(C()){if(e.key===`Escape`){if(v.isOpen||h.isOpen||g.isOpen||_.isOpen||ne.isOpen||document.querySelector(`dialog[open], :not(dialog)[aria-modal="true"]`))return;e.preventDefault(),r?.escape()||S?.close()}else e.key===`?`&&!fj(e.target)&&!v.isOpen&&(e.preventDefault(),v.open());return}if(e.key===`Escape`){if(v.isOpen||h.isOpen||g.isOpen||_.isOpen||ne.isOpen)return;D.isOpen?(D.escape(),e.preventDefault()):w.isNarrow()&&u.sidebar?(w.togglePanel(`sidebar`,!1),e.preventDefault()):s&&(w.select(null),e.preventDefault());return}if(!(fj(e.target)||v.isOpen||_.isOpen))switch(e.key){case`/`:e.preventDefault(),w.focusSearch();break;case`?`:e.preventDefault(),v.open();break;case`f`:case`F`:e.preventDefault(),s?.type===`agent`?m.toggleFollow():w.announce(a(`Selecione um agente para seguir.`));break;case`t`:case`T`:e.preventDefault(),Me();break;case`l`:case`L`:if(t.mock)break;e.preventDefault(),w.toggleTimelapse();break;case`p`:case`P`:{e.preventDefault();let n=$C(t.snapshot?.agents??[],s?.type===`agent`?s.id:void 0);n?ew(w,n.id):w.announce(a(`Nenhum pedido de permissão ou pergunta para responder agora.`));break}case`o`:case`O`:e.preventDefault(),w.camera(`overview`);break;case`m`:case`M`:e.preventDefault(),fe.toggle();break;case`[`:e.preventDefault(),w.togglePanel(`sidebar`);break;case`]`:e.preventDefault(),w.togglePanel(`feed`)}}}function Me(){let e=s?.type===`agent`?s.id:null;if(e!==null&&E.enabled&&w.agent(e)?.kind===`main`)return re.toggle(e);if(e===null&&E.isOpen)return E.close();D.isOpen&&(e===null||D.agentId===e)?D.close():e===null?w.announce(a(`Selecione um agente para abrir o terminal.`)):!t.snapshot?.meta.terminal||!I().terminal?w.announce(`${US}.`):w.agent(e)?D.open(e):w.announce(a(`O agente já saiu do escritório.`))}n.setOptions(OE(o)),Ae(),ke()}var mj=Jt({start:()=>hj});function hj(){NE(kE()),document.documentElement.lang=t(),document.querySelector(`meta[name="description"]`)?.setAttribute(`content`,a(`Escritório virtual em pixel art que mostra, em tempo real, o que seus agentes do Claude Code estão fazendo.`));let e=new URLSearchParams(location.search),n=new g({mock:e.has(`mock`)}),r=document.getElementById(`world`),i=document.getElementById(`ui`),o=__(r,n),s=gj({world:o,worldCanvas:r,uiRoot:i,mock:n.mock,params:e,version:()=>n.liveSnapshot?.meta.version??``});if(pj(i,n,o,s),n.mock)n.connect();else{rn().finally(()=>n.connect());let e=!1;n.on(`connection`,t=>{t===`open`?(e&&rn(),e=!0):t===`closed`&&e&&rn()})}Object.assign(window,{habblaud:{store:n,world:o,city:s}})}function gj(e){let t=null,n=null,r=!1,i=document.createElement(`canvas`);i.id=`city`,i.hidden=!0,e.worldCanvas.after(i);let a=()=>n??=Promise.all([o(()=>import(`./city-S-WD2HZe.js`),__vite__mapDeps([8,1,2,9,5,3,4,10])),o(()=>import(`./world-stream-FBFp8Oax.js`),__vite__mapDeps([11,2,1,9,5]))]).then(([n,r])=>{let a=Number(e.params.get(`perf`)),o=e.mock&&Number.isFinite(a)&&a>0?{buildings:a}:{},s={};return t=n.createCityScene({canvas:i,uiRoot:e.uiRoot,openStream:()=>r.createWorldStream({mock:e.mock,...o,memory:s}),options:()=>e.world.getOptions(),topInset:()=>e.uiRoot.querySelector(`.ui-topbar`)?.getBoundingClientRect().bottom??64,version:()=>e.version()}),t});return{get open(){return r},async show(){let t=await a();r=!0,e.world.setSuspended?.(!0),e.worldCanvas.hidden=!0,t.show()},hide(){r=!1,t?.hide(),e.worldCanvas.hidden=!1,e.world.setSuspended?.(!1)},zoomBy:e=>t?.zoomBy(e),recenter:()=>t?.recenter(),escape:()=>t?.escape()??!1,visitOwn:()=>t?.visitOwn(),scene:()=>t}}export{_p as A,ef as B,Fh as C,Dh as D,kh as E,Cf as F,Pd as G,$d as H,Jd as I,Ho as J,gu as K,Zd as L,Tf as M,wf as N,Fm as O,bf as P,Xd as R,Lh as S,Ih as T,nf as U,Yd as V,Fd as W,cs as Y,Q as _,eA as a,$h as b,$k as c,nA as d,Mk as f,zv as g,Bv as h,tA as i,Dp as j,qp as k,Qk as l,Kb as m,Wk as n,Xk as o,ax as p,yl as q,Gk as r,Yk as s,hj as start,mj as t,Zk as u,__ as v,Ph as w,jh as x,eg as y,tf as z};