@huynle/hub 0.7.2 → 0.7.4

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.
@@ -0,0 +1,20 @@
1
+ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var e={context:void 0,registry:void 0,effects:void 0,done:!1,getContextId(){return t(this.context.count)},getNextContextId(){return t(this.context.count++)}};function t(t){let n=String(t),r=n.length-1;return e.context.id+(r?String.fromCharCode(96+r):``)+n}function n(t){e.context=t}var r=(e,t)=>e===t,i=Symbol(`solid-proxy`),a=typeof Proxy==`function`,o=Symbol(`solid-track`),s={equals:r},c=null,l=xe,u=1,d=2,f={owned:null,cleanups:null,context:null,owner:null},p={},m=null,h=null,g=null,_=null,v=null,y=0;function b(e,t){let n=g,r=m,i=e.length===0,a=t===void 0?r:t,o=i?f:{owned:null,cleanups:null,context:a?a.context:null,owner:a},s=i?e:()=>e(()=>T(()=>Te(o)));m=o,g=null;try{return ye(s,!0)}finally{g=n,m=r}}function x(e,t){t=t?Object.assign({},s,t):s;let n={value:e,observers:null,observerSlots:null,comparator:t.equals||void 0};return[pe.bind(n),e=>(typeof e==`function`&&(e=h&&h.running&&h.sources.has(n)?e(n.tValue):e(n.value)),me(n,e))]}function ee(e,t,n){he(_e(e,t,!0,u))}function S(e,t,n){he(_e(e,t,!1,u))}function C(e,t,n){l=Se;let r=_e(e,t,!1,u),i=fe&&ue(fe);i&&(r.suspense=i),(!n||!n.render)&&(r.user=!0),v?v.push(r):he(r)}function w(e,t,n){n=n?Object.assign({},s,n):s;let r=_e(e,t,!0,0);return r.observers=null,r.observerSlots=null,r.comparator=n.equals||void 0,he(r),pe.bind(r)}function te(e){return e&&typeof e==`object`&&`then`in e}function ne(t,n,r){let i,a,o;typeof n==`function`?(i=t,a=n,o=r||{}):(i=!0,a=t,o=n||{});let s=null,c=p,l=null,u=!1,d=!1,f=`initialValue`in o,_=typeof i==`function`&&w(i),v=new Set,[y,b]=(o.storage||x)(o.initialValue),[S,C]=x(void 0),[ne,re]=x(void 0,{equals:!1}),[ie,E]=x(f?`ready`:`unresolved`);m&&D(()=>{for(let e of v.keys())e.decrement();v.clear(),h&&s&&h.promises.delete(s),s=null}),e.context&&(l=e.getNextContextId(),o.ssrLoadFrom===`initial`?c=o.initialValue:e.load&&e.has(l)&&(c=e.load(l)));function ae(e,t,n,r){return s===e&&(s=null,r!==void 0&&(f=!0),(e===c||t===c)&&o.onHydrated&&queueMicrotask(()=>o.onHydrated(r,{value:t})),c=p,h&&e&&u?(h.promises.delete(e),u=!1,ye(()=>{h.running=!0,oe(t,n)},!1)):oe(t,n)),t}function oe(e,t){ye(()=>{t===void 0&&b(()=>e),E(t===void 0?f?`ready`:`unresolved`:`errored`),C(t);for(let e of v.keys())e.decrement();v.clear()},!1)}function ce(){let e=fe&&ue(fe),t=y(),n=S();if(n!==void 0&&!s)throw n;return g&&!g.user&&e&&ee(()=>{ne(),s&&(e.resolved&&h&&u?h.promises.add(s):v.has(e)||(e.increment(),v.add(e)))}),t}function le(e=!0){if(e!==!1&&d)return;d=!1;let t=_?_():i;if(u=h&&h.running,t==null||t===!1){ae(s,T(y));return}h&&s&&h.promises.delete(s);let n,r=c===p?T(()=>{try{return a(t,{value:y(),refetching:e})}catch(e){n=e}}):c;if(n!==void 0)ae(s,void 0,De(n),t);else return te(r)?(s=r,`v`in r?(r.s===1?ae(s,r.v,void 0,t):ae(s,void 0,De(r.v),t),r):(d=!0,queueMicrotask(()=>d=!1),ye(()=>{E(f?`refreshing`:`pending`),re()},!1),r.then(e=>ae(r,e,void 0,t),e=>ae(r,void 0,De(e),t)))):(ae(s,r,void 0,t),r)}Object.defineProperties(ce,{state:{get:()=>ie()},error:{get:()=>S()},loading:{get(){let e=ie();return e===`pending`||e===`refreshing`}},latest:{get(){if(!f)return ce();let e=S();if(e&&!s)throw e;return y()}}});let de=m;return _?ee(()=>(de=m,le(!1))):le(!1),[ce,{refetch:e=>se(de,()=>le(e)),mutate:b}]}function re(e){return ye(e,!1)}function T(e){if(g===null)return e();let t=g;g=null;try{return e()}finally{g=t}}function ie(e,t,n){let r=Array.isArray(e),i,a=n&&n.defer;return n=>{let o;if(r){o=Array(e.length);for(let t=0;t<e.length;t++)o[t]=e[t]()}else o=e();if(a)return a=!1,n;let s=T(()=>t(o,i,n));return i=o,s}}function E(e){C(()=>T(e))}function D(e){return m===null||(m.cleanups===null?m.cleanups=[e]:m.cleanups.push(e)),e}function ae(){return g}function oe(){return m}function se(e,t){let n=m,r=g;m=e,g=null;try{return ye(t,!0)}catch(e){ke(e)}finally{m=n,g=r}}var[ce,le]=x(!1);function ue(e){let t;return m&&m.context&&(t=m.context[e.id])!==void 0?t:e.defaultValue}function de(e){let t=w(e),n=w(()=>Ae(t()));return n.toArray=()=>{let e=n();return Array.isArray(e)?e:e==null?[]:[e]},n}var fe;function pe(){let e=h&&h.running;if(this.sources&&(e?this.tState:this.state)){if((e?this.tState:this.state)===u)he(this);else{let e=_;_=null,ye(()=>Ce(this),!1),_=e}}if(g){let e=this.observers;if(!e||e[e.length-1]!==g){let t=e?e.length:0;g.sources?(g.sources.push(this),g.sourceSlots.push(t)):(g.sources=[this],g.sourceSlots=[t]),e?(e.push(g),this.observerSlots.push(g.sources.length-1)):(this.observers=[g],this.observerSlots=[g.sources.length-1])}}return e&&h.sources.has(this)?this.tValue:this.value}function me(e,t,n){let r=h&&h.running&&h.sources.has(e)?e.tValue:e.value;if(!e.comparator||!e.comparator(r,t)){if(h){let r=h.running;(r||!n&&h.sources.has(e))&&(h.sources.add(e),e.tValue=t),r||(e.value=t)}else e.value=t;e.observers&&e.observers.length&&ye(()=>{for(let t=0;t<e.observers.length;t+=1){let n=e.observers[t],r=h&&h.running;r&&h.disposed.has(n)||((r?!n.tState:!n.state)&&(n.pure?_.push(n):v.push(n),n.observers&&we(n)),r?n.tState=u:n.state=u)}if(_.length>1e6)throw _=[],Error()},!1)}return t}function he(e){if(!e.fn)return;Te(e);let t=y;ge(e,h&&h.running&&h.sources.has(e)?e.tValue:e.value,t),h&&!h.running&&h.sources.has(e)&&queueMicrotask(()=>{ye(()=>{h&&(h.running=!0),g=m=e,ge(e,e.tValue,t),g=m=null},!1)})}function ge(e,t,n){let r,i=m,a=g;g=m=e;try{r=e.fn(t)}catch(t){return e.pure&&(h&&h.running?(e.tState=u,e.tOwned&&e.tOwned.forEach(Te),e.tOwned=void 0):(e.state=u,e.owned&&e.owned.forEach(Te),e.owned=null)),e.updatedAt=n+1,ke(t)}finally{g=a,m=i}(!e.updatedAt||e.updatedAt<=n)&&(e.updatedAt!=null&&`observers`in e?me(e,r,!0):h&&h.running&&e.pure?(h.sources.has(e)||(e.value=r),h.sources.add(e),e.tValue=r):e.value=r,e.updatedAt=n)}function _e(e,t,n,r=u,i){let a={fn:e,state:r,updatedAt:null,owned:null,sources:null,sourceSlots:null,cleanups:null,value:t,owner:m,context:m?m.context:null,pure:n};return h&&h.running&&(a.state=0,a.tState=r),m===null||m!==f&&(h&&h.running&&m.pure?m.tOwned?m.tOwned.push(a):m.tOwned=[a]:m.owned?m.owned.push(a):m.owned=[a]),a}function ve(e){let t=h&&h.running;if((t?e.tState:e.state)===0)return;if((t?e.tState:e.state)===d)return Ce(e);if(e.suspense&&T(e.suspense.inFallback))return e.suspense.effects.push(e);let n=[e];for(;(e=e.owner)&&(!e.updatedAt||e.updatedAt<y);){if(t&&h.disposed.has(e))return;(t?e.tState:e.state)&&n.push(e)}for(let r=n.length-1;r>=0;r--){if(e=n[r],t){let t=e,i=n[r+1];for(;(t=t.owner)&&t!==i;)if(h.disposed.has(t))return}if((t?e.tState:e.state)===u)he(e);else if((t?e.tState:e.state)===d){let t=_;_=null,ye(()=>Ce(e,n[0]),!1),_=t}}}function ye(e,t){if(_)return e();let n=!1;t||(_=[]),v?n=!0:v=[],y++;try{let t=e();return be(n),t}catch(e){n||(v=null),_=null,ke(e)}}function be(e){if(_&&=(xe(_),null),e)return;let t;if(h){if(!h.promises.size&&!h.queue.size){let e=h.sources,n=h.disposed;v.push.apply(v,h.effects),t=h.resolve;for(let e of v)`tState`in e&&(e.state=e.tState),delete e.tState;h=null,ye(()=>{for(let e of n)Te(e);for(let t of e){if(t.value=t.tValue,t.owned)for(let e=0,n=t.owned.length;e<n;e++)Te(t.owned[e]);t.tOwned&&(t.owned=t.tOwned),delete t.tValue,delete t.tOwned,t.tState=0}le(!1)},!1)}else if(h.running){h.running=!1,h.effects.push.apply(h.effects,v),v=null,le(!0);return}}let n=v;v=null,n.length&&ye(()=>l(n),!1),t&&t()}function xe(e){for(let t=0;t<e.length;t++)ve(e[t])}function Se(t){let r,i=0;for(r=0;r<t.length;r++){let e=t[r];e.user?t[i++]=e:ve(e)}if(e.context){if(e.count){e.effects||=[],e.effects.push(...t.slice(0,i));return}n()}for(e.effects&&(e.done||!e.count)&&(t=[...e.effects,...t],i+=e.effects.length,delete e.effects),r=0;r<i;r++)ve(t[r])}function Ce(e,t){let n=h&&h.running;n?e.tState=0:e.state=0;for(let r=0;r<e.sources.length;r+=1){let i=e.sources[r];if(i.sources){let e=n?i.tState:i.state;e===u?i!==t&&(!i.updatedAt||i.updatedAt<y)&&ve(i):e===d&&Ce(i,t)}}}function we(e){let t=h&&h.running;for(let n=0;n<e.observers.length;n+=1){let r=e.observers[n];(t?!r.tState:!r.state)&&(t?r.tState=d:r.state=d,r.pure?_.push(r):v.push(r),r.observers&&we(r))}}function Te(e){let t;if(e.sources)for(;e.sources.length;){let t=e.sources.pop(),n=e.sourceSlots.pop(),r=t.observers;if(r&&r.length){let e=r.pop(),i=t.observerSlots.pop();n<r.length&&(e.sourceSlots[i]=n,r[n]=e,t.observerSlots[n]=i)}}if(e.tOwned){for(t=e.tOwned.length-1;t>=0;t--)Te(e.tOwned[t]);delete e.tOwned}if(h&&h.running&&e.pure)Ee(e,!0);else if(e.owned){for(t=e.owned.length-1;t>=0;t--)Te(e.owned[t]);e.owned=null}if(e.cleanups){for(t=e.cleanups.length-1;t>=0;t--)e.cleanups[t]();e.cleanups=null}h&&h.running?e.tState=0:e.state=0}function Ee(e,t){if(t||(e.tState=0,h.disposed.add(e)),e.owned)for(let t=0;t<e.owned.length;t++)Ee(e.owned[t])}function De(e){return e instanceof Error?e:Error(typeof e==`string`?e:`Unknown error`,{cause:e})}function Oe(e,t,n){try{for(let n of t)n(e)}catch(e){ke(e,n&&n.owner||null)}}function ke(e,t=m){let n=c&&t&&t.context&&t.context[c],r=De(e);if(!n)throw r;v?v.push({fn(){Oe(r,n,t)},state:u}):Oe(r,n,t)}function Ae(e){if(typeof e==`function`&&!e.length)return Ae(e());if(Array.isArray(e)){let t=[];for(let n=0;n<e.length;n++){let r=Ae(e[n]);if(Array.isArray(r)){if(r.length<32768)t.push.apply(t,r);else for(let e=0;e<r.length;e++)t.push(r[e])}else t.push(r)}return t}return e}var je=Symbol(`fallback`);function Me(e){for(let t=0;t<e.length;t++)e[t]()}function Ne(e,t,n={}){let r=[],i=[],a=[],s=0,c=t.length>1?[]:null;return D(()=>Me(a)),()=>{let l=e()||[],u=l.length,d,f;return l[o],T(()=>{let e,t,o,m,h,g,_,v,y;if(u===0)s!==0&&(Me(a),a=[],r=[],i=[],s=0,c&&=[]),n.fallback&&(r=[je],i[0]=b(e=>(a[0]=e,n.fallback())),s=1);else if(s===0){for(i=Array(u),f=0;f<u;f++)r[f]=l[f],i[f]=b(p);s=u}else{for(o=Array(u),m=Array(u),c&&(h=Array(u)),g=0,_=Math.min(s,u);g<_&&r[g]===l[g];g++);for(_=s-1,v=u-1;_>=g&&v>=g&&r[_]===l[v];_--,v--)o[v]=i[_],m[v]=a[_],c&&(h[v]=c[_]);for(e=new Map,t=Array(v+1),f=v;f>=g;f--)y=l[f],d=e.get(y),t[f]=d===void 0?-1:d,e.set(y,f);for(d=g;d<=_;d++)y=r[d],f=e.get(y),f!==void 0&&f!==-1?(o[f]=i[d],m[f]=a[d],c&&(h[f]=c[d]),f=t[f],e.set(y,f)):a[d]();for(f=g;f<u;f++)f in o?(i[f]=o[f],a[f]=m[f],c&&(c[f]=h[f],c[f](f))):i[f]=b(p);i=i.slice(0,s=u),r=l.slice(0)}return i});function p(e){if(a[f]=e,c){let[e,n]=x(f);return c[f]=n,t(l[f],e)}return t(l[f])}}}function Pe(e,t,n={}){let r=[],i=[],a=[],s=[],c=0,l;return D(()=>Me(a)),()=>{let u=e()||[],d=u.length;return u[o],T(()=>{if(d===0)return c!==0&&(Me(a),a=[],r=[],i=[],c=0,s=[]),n.fallback&&(r=[je],i[0]=b(e=>(a[0]=e,n.fallback())),c=1),i;for(r[0]===je&&(a[0](),a=[],r=[],i=[],c=0),l=0;l<d;l++)l<r.length&&r[l]!==u[l]?s[l](()=>u[l]):l>=r.length&&(i[l]=b(f));for(;l<r.length;l++)a[l]();return c=s.length=a.length=d,r=u.slice(0),i=i.slice(0,c)});function f(e){a[l]=e;let[n,r]=x(u[l]);return s[l]=r,t(n,l)}}}function O(e,t){return T(()=>e(t||{}))}function Fe(){return!0}var Ie={get(e,t,n){return t===i?n:e.get(t)},has(e,t){return t===i||e.has(t)},set:Fe,deleteProperty:Fe,getOwnPropertyDescriptor(e,t){return{configurable:!0,enumerable:!0,get(){return e.get(t)},set:Fe,deleteProperty:Fe}},ownKeys(e){return e.keys()}};function Le(e){return(e=typeof e==`function`?e():e)?e:{}}function Re(){for(let e=0,t=this.length;e<t;++e){let t=this[e]();if(t!==void 0)return t}}function ze(...e){let t=!1;for(let n=0;n<e.length;n++){let r=e[n];t||=!!r&&i in r,e[n]=typeof r==`function`?(t=!0,w(r)):r}if(a&&t)return new Proxy({get(t){for(let n=e.length-1;n>=0;n--){let r=Le(e[n])[t];if(r!==void 0)return r}},has(t){for(let n=e.length-1;n>=0;n--)if(t in Le(e[n]))return!0;return!1},keys(){let t=[];for(let n=0;n<e.length;n++)t.push(...Object.keys(Le(e[n])));return[...new Set(t)]}},Ie);let n={},r=Object.create(null);for(let t=e.length-1;t>=0;t--){let i=e[t];if(!i)continue;let a=Object.getOwnPropertyNames(i);for(let e=a.length-1;e>=0;e--){let t=a[e];if(t===`__proto__`||t===`constructor`)continue;let o=Object.getOwnPropertyDescriptor(i,t);if(!r[t])r[t]=o.get?{enumerable:!0,configurable:!0,get:Re.bind(n[t]=[o.get.bind(i)])}:o.value===void 0?void 0:o;else{let e=n[t];e&&(o.get?e.push(o.get.bind(i)):o.value!==void 0&&e.push(()=>o.value))}}}let o={},s=Object.keys(r);for(let e=s.length-1;e>=0;e--){let t=s[e],n=r[t];n&&n.get?Object.defineProperty(o,t,n):o[t]=n?n.value:void 0}return o}function Be(e,...t){let n=t.length;if(a&&i in e){let r=n>1?t.flat():t[0],i=new Set,a=t.map(t=>{let n=t.filter(e=>!i.has(e)&&(i.add(e),!0));return new Proxy({get(t){return n.includes(t)?e[t]:void 0},has(t){return n.includes(t)&&t in e},keys(){return n.filter(t=>t in e)}},Ie)});return a.push(new Proxy({get(t){return r.includes(t)?void 0:e[t]},has(t){return!r.includes(t)&&t in e},keys(){return Object.keys(e).filter(e=>!r.includes(e))}},Ie)),a}let r=[];for(let e=0;e<=n;e++)r[e]={};for(let i of Object.getOwnPropertyNames(e)){let a=n;for(let e=0;e<t.length;e++)if(t[e].includes(i)){a=e;break}let o=Object.getOwnPropertyDescriptor(e,i);!o.get&&!o.set&&o.enumerable&&o.writable&&o.configurable?r[a][i]=o.value:Object.defineProperty(r[a],i,o)}return r}var Ve=e=>`Stale read from <${e}>.`;function k(e){let t=`fallback`in e&&{fallback:()=>e.fallback};return w(Ne(()=>e.each,e.children,t||void 0))}function He(e){let t=`fallback`in e&&{fallback:()=>e.fallback};return w(Pe(()=>e.each,e.children,t||void 0))}function A(e){let t=e.keyed,n=w(()=>e.when,void 0,void 0),r=t?n:w(n,void 0,{equals:(e,t)=>!e==!t});return w(()=>{let i=r();if(i){let a=e.children;return typeof a==`function`&&a.length>0?T(()=>a(t?i:()=>{if(!T(r))throw Ve(`Show`);return n()})):a}return e.fallback},void 0,void 0)}function Ue(e){let t=de(()=>e.children),n=w(()=>{let e=t(),n=Array.isArray(e)?e:[e],r=()=>void 0;for(let e=0;e<n.length;e++){let t=e,i=n[e],a=r,o=w(()=>a()?void 0:i.when,void 0,void 0),s=i.keyed?o:w(o,void 0,{equals:(e,t)=>!e==!t});r=()=>a()||(s()?[t,o,i]:void 0)}return r});return w(()=>{let t=n()();if(!t)return e.fallback;let[r,i,a]=t,o=a.children;return typeof o==`function`&&o.length>0?T(()=>o(a.keyed?i():()=>{if(T(n)()?.[0]!==r)throw Ve(`Match`);return i()})):o},void 0,void 0)}function j(e){return e}var We=new Set([`className`,`value`,`readOnly`,`noValidate`,`formNoValidate`,`isMap`,`noModule`,`playsInline`,`adAuctionHeaders`,`allowFullscreen`,`browsingTopics`,`defaultChecked`,`defaultMuted`,`defaultSelected`,`disablePictureInPicture`,`disableRemotePlayback`,`preservesPitch`,`shadowRootClonable`,`shadowRootCustomElementRegistry`,`shadowRootDelegatesFocus`,`shadowRootSerializable`,`sharedStorageWritable`,...`allowfullscreen.async.alpha.autofocus.autoplay.checked.controls.default.disabled.formnovalidate.hidden.indeterminate.inert.ismap.loop.multiple.muted.nomodule.novalidate.open.playsinline.readonly.required.reversed.seamless.selected.adauctionheaders.browsingtopics.credentialless.defaultchecked.defaultmuted.defaultselected.defer.disablepictureinpicture.disableremoteplayback.preservespitch.shadowrootclonable.shadowrootcustomelementregistry.shadowrootdelegatesfocus.shadowrootserializable.sharedstoragewritable`.split(`.`)]),Ge=new Set([`innerHTML`,`textContent`,`innerText`,`children`]),Ke=Object.assign(Object.create(null),{className:`class`,htmlFor:`for`}),qe=Object.assign(Object.create(null),{class:`className`,novalidate:{$:`noValidate`,FORM:1},formnovalidate:{$:`formNoValidate`,BUTTON:1,INPUT:1},ismap:{$:`isMap`,IMG:1},nomodule:{$:`noModule`,SCRIPT:1},playsinline:{$:`playsInline`,VIDEO:1},readonly:{$:`readOnly`,INPUT:1,TEXTAREA:1},adauctionheaders:{$:`adAuctionHeaders`,IFRAME:1},allowfullscreen:{$:`allowFullscreen`,IFRAME:1},browsingtopics:{$:`browsingTopics`,IMG:1},defaultchecked:{$:`defaultChecked`,INPUT:1},defaultmuted:{$:`defaultMuted`,AUDIO:1,VIDEO:1},defaultselected:{$:`defaultSelected`,OPTION:1},disablepictureinpicture:{$:`disablePictureInPicture`,VIDEO:1},disableremoteplayback:{$:`disableRemotePlayback`,AUDIO:1,VIDEO:1},preservespitch:{$:`preservesPitch`,AUDIO:1,VIDEO:1},shadowrootclonable:{$:`shadowRootClonable`,TEMPLATE:1},shadowrootdelegatesfocus:{$:`shadowRootDelegatesFocus`,TEMPLATE:1},shadowrootserializable:{$:`shadowRootSerializable`,TEMPLATE:1},sharedstoragewritable:{$:`sharedStorageWritable`,IFRAME:1,IMG:1}});function Je(e,t){let n=qe[e];return typeof n==`object`?n[t]?n.$:void 0:n}var Ye=new Set([`beforeinput`,`click`,`dblclick`,`contextmenu`,`focusin`,`focusout`,`input`,`keydown`,`keyup`,`mousedown`,`mousemove`,`mouseout`,`mouseover`,`mouseup`,`pointerdown`,`pointermove`,`pointerout`,`pointerover`,`pointerup`,`touchend`,`touchmove`,`touchstart`]),Xe=new Set(`altGlyph.altGlyphDef.altGlyphItem.animate.animateColor.animateMotion.animateTransform.circle.clipPath.color-profile.cursor.defs.desc.ellipse.feBlend.feColorMatrix.feComponentTransfer.feComposite.feConvolveMatrix.feDiffuseLighting.feDisplacementMap.feDistantLight.feDropShadow.feFlood.feFuncA.feFuncB.feFuncG.feFuncR.feGaussianBlur.feImage.feMerge.feMergeNode.feMorphology.feOffset.fePointLight.feSpecularLighting.feSpotLight.feTile.feTurbulence.filter.font.font-face.font-face-format.font-face-name.font-face-src.font-face-uri.foreignObject.g.glyph.glyphRef.hkern.image.line.linearGradient.marker.mask.metadata.missing-glyph.mpath.path.pattern.polygon.polyline.radialGradient.rect.set.stop.svg.switch.symbol.text.textPath.tref.tspan.use.view.vkern`.split(`.`)),Ze={xlink:`http://www.w3.org/1999/xlink`,xml:`http://www.w3.org/XML/1998/namespace`},M=e=>w(()=>e());function Qe(e,t,n){let r=n.length,i=t.length,a=r,o=0,s=0,c=t[i-1].nextSibling,l=null;for(;o<i||s<a;)if(t[o]===n[s])o++,s++;else{for(;t[i-1]===n[a-1];)i--,a--;if(i===o){let t=a<r?s?n[s-1].nextSibling:n[a-s]:c;for(;s<a;)e.insertBefore(n[s++],t)}else if(a===s)for(;o<i;)(!l||!l.has(t[o]))&&t[o].remove(),o++;else if(t[o]===n[a-1]&&n[s]===t[i-1]){let r=t[--i].nextSibling;e.insertBefore(n[s++],t[o++].nextSibling),e.insertBefore(n[--a],r),t[i]=n[a]}else{if(!l){l=new Map;let e=s;for(;e<a;)l.set(n[e],e++)}let r=l.get(t[o]);if(r!=null){if(s<r&&r<a){let c=o,u=1,d;for(;++c<i&&c<a&&(d=l.get(t[c]))!=null&&d===r+u;)u++;if(u>r-s){let i=t[o];for(;s<r;)e.insertBefore(n[s++],i)}else e.replaceChild(n[s++],t[o++])}else o++}else t[o++].remove()}}}var $e=`_$DX_DELEGATE`;function et(e,t,n,r={}){let i;return b(r=>{i=r,t===document?e():R(t,e(),!n&&t.firstChild?null:void 0,n)},r.owner),()=>{i(),t.textContent=``}}function N(e,t,n,r){let i,a=()=>{let t=r?document.createElementNS(`http://www.w3.org/1998/Math/MathML`,`template`):document.createElement(`template`);return t.innerHTML=e,n?t.content.firstChild.firstChild:r?t.firstChild:t.content.firstChild},o=t?()=>T(()=>document.importNode(i||=a(),!0)):()=>(i||=a()).cloneNode(!0);return o.cloneNode=o,o}function P(e,t=window.document){let n=t[$e]||(t[$e]=new Set);for(let r=0,i=e.length;r<i;r++){let i=e[r];n.has(i)||(n.add(i),t.addEventListener(i,mt))}}function F(e,t,n){ut(e)||(n==null?e.removeAttribute(t):e.setAttribute(t,n))}function tt(e,t,n,r){ut(e)||(r==null?e.removeAttributeNS(t,n):e.setAttributeNS(t,n,r))}function nt(e,t,n){ut(e)||(n?e.setAttribute(t,``):e.removeAttribute(t))}function I(e,t){ut(e)||(t==null?e.removeAttribute(`class`):e.className=t)}function rt(e,t,n,r){if(r)Array.isArray(n)?(e[`$$${t}`]=n[0],e[`$$${t}Data`]=n[1]):e[`$$${t}`]=n;else if(Array.isArray(n)){let r=n[0];e.addEventListener(t,n[0]=t=>r.call(e,n[1],t))}else e.addEventListener(t,n,typeof n!=`function`&&n)}function it(e,t,n={}){let r=Object.keys(t||{}),i=Object.keys(n),a,o;for(a=0,o=i.length;a<o;a++){let r=i[a];r&&r!==`undefined`&&!t[r]&&(ft(e,r,!1),delete n[r])}for(a=0,o=r.length;a<o;a++){let i=r[a],o=!!t[i];i&&i!==`undefined`&&n[i]!==o&&o&&(ft(e,i,!0),n[i]=o)}return n}function at(e,t,n){if(!t)return n?F(e,`style`):t;let r=e.style;if(typeof t==`string`)return r.cssText=t;typeof n==`string`&&(r.cssText=n=void 0),n||={},t||={};let i,a;for(a in n)t[a]??r.removeProperty(a),delete n[a];for(a in t)i=t[a],i!==n[a]&&(r.setProperty(a,i),n[a]=i);return n}function ot(e,t,n){n==null?e.style.removeProperty(t):e.style.setProperty(t,n)}function st(e,t={},n,r){let i={};return r||S(()=>i.children=z(e,t.children,i.children)),S(()=>typeof t.ref==`function`&&L(t.ref,e)),S(()=>ct(e,t,n,!0,i,!0)),i}function L(e,t,n){return T(()=>e(t,n))}function R(e,t,n,r){if(n!==void 0&&!r&&(r=[]),typeof t!=`function`)return z(e,t,r,n);S(r=>z(e,t(),r,n),r)}function ct(e,t,n,r,i={},a=!1){t||={};for(let r in i)if(!(r in t)){if(r===`children`)continue;i[r]=pt(e,r,null,i[r],n,a,t)}for(let o in t){if(o===`children`){r||z(e,t.children);continue}let s=t[o];i[o]=pt(e,o,s,i[o],n,a,t)}}function lt(t){let n,r;return!ut()||!(n=e.registry.get(r=vt()))?t():(e.completed&&e.completed.add(n),e.registry.delete(r),n)}function ut(t){return!!e.context&&!e.done&&(!t||t.isConnected)}function dt(e){return e.toLowerCase().replace(/-([a-z])/g,(e,t)=>t.toUpperCase())}function ft(e,t,n){let r=t.trim().split(/\s+/);for(let t=0,i=r.length;t<i;t++)e.classList.toggle(r[t],n)}function pt(e,t,n,r,i,a,o){let s,c,l,u,d;if(t===`style`)return at(e,n,r);if(t===`classList`)return it(e,n,r);if(n===r)return r;if(t===`ref`)a||n(e);else if(t.slice(0,3)===`on:`){let i=t.slice(3);r&&e.removeEventListener(i,r,typeof r!=`function`&&r),n&&e.addEventListener(i,n,typeof n!=`function`&&n)}else if(t.slice(0,10)===`oncapture:`){let i=t.slice(10);r&&e.removeEventListener(i,r,!0),n&&e.addEventListener(i,n,!0)}else if(t.slice(0,2)===`on`){let i=t.slice(2).toLowerCase(),a=Ye.has(i);if(!a&&r){let t=Array.isArray(r)?r[0]:r;e.removeEventListener(i,t)}(a||n)&&(rt(e,i,n,a),a&&P([i]))}else if(t.slice(0,5)===`attr:`)F(e,t.slice(5),n);else if(t.slice(0,5)===`bool:`)nt(e,t.slice(5),n);else if((d=t.slice(0,5)===`prop:`)||(l=Ge.has(t))||!i&&((u=Je(t,e.tagName))||(c=We.has(t)))||(s=e.nodeName.includes(`-`)||`is`in o)){if(d)t=t.slice(5),c=!0;else if(ut(e))return n;t===`class`||t===`className`?I(e,n):s&&!c&&!l?e[dt(t)]=n:(t===`value`||t===`defaultValue`)&&(e.nodeName===`INPUT`||e.nodeName===`TEXTAREA`)?e[u||t]=n??``:e[u||t]=n}else{let r=i&&t.indexOf(`:`)>-1&&Ze[t.split(`:`)[0]];r?tt(e,r,t,n):F(e,Ke[t]||t,n)}return n}function mt(t){if(e.registry&&e.events&&e.events.find(([e,n])=>n===t))return;let n=t.target,r=`$$${t.type}`,i=t.target,a=t.currentTarget,o=e=>Object.defineProperty(t,"target",{configurable:!0,value:e}),s=()=>{let e=n[r];if(e&&!n.disabled){let i=n[`${r}Data`];if(i===void 0?e.call(n,t):e.call(n,i,t),t.cancelBubble)return}return n.host&&typeof n.host!=`string`&&!n.host._$host&&n.contains(t.target)&&o(n.host),!0},c=()=>{for(;s()&&(n=n._$host||n.parentNode||n.host););};Object.defineProperty(t,"currentTarget",{configurable:!0,get(){return n||document}}),e.registry&&!e.done&&(e.done=_$HY.done=!0);try{if(t.composedPath){let e=t.composedPath();o(e[0]);for(let t=0;t<e.length-2&&(n=e[t],s());t++){if(n._$host){n=n._$host,c();break}if(n.parentNode===a)break}}else c();o(i)}finally{t=n=null}}function z(e,t,n,r,i){let a=ut(e);if(a){!n&&(n=[...e.childNodes]);let t=[];for(let e=0;e<n.length;e++){let r=n[e];r.nodeType===8&&r.data.slice(0,2)===`!$`?r.remove():t.push(r)}n=t}for(;typeof n==`function`;)n=n();if(t===n)return n;let o=typeof t,s=r!==void 0;if(e=s&&n[0]&&n[0].parentNode||e,o===`string`||o===`number`){if(a||o===`number`&&(t=t.toString(),t===n))return n;if(s){let i=n[0];i&&i.nodeType===3?i.data!==t&&(i.data=t):i=document.createTextNode(t),n=_t(e,n,r,i)}else n=n!==``&&typeof n==`string`?e.firstChild.data=t:e.textContent=t}else if(t==null||o===`boolean`){if(a)return n;n=_t(e,n,r)}else if(o===`function`)return S(()=>{let i=t();for(;typeof i==`function`;)i=i();n=z(e,i,n,r)}),()=>n;else if(Array.isArray(t)){let o=[],c=n&&Array.isArray(n);if(ht(o,t,n,i))return S(()=>n=z(e,o,n,r,!0)),()=>n;if(a){if(!o.length)return n;if(r===void 0)return n=[...e.childNodes];let t=o[0];if(t.parentNode!==e)return n;let i=[t];for(;(t=t.nextSibling)!==r;)i.push(t);return n=i}if(o.length===0){if(n=_t(e,n,r),s)return n}else c?n.length===0?gt(e,o,r):Qe(e,n,o):(n&&_t(e),gt(e,o));n=o}else if(t.nodeType){if(a&&t.parentNode)return n=s?[t]:t;if(Array.isArray(n)){if(s)return n=_t(e,n,r,t);_t(e,n,null,t)}else n==null||n===``||!e.firstChild?e.appendChild(t):e.replaceChild(t,e.firstChild);n=t}return n}function ht(e,t,n,r){let i=!1;for(let a=0,o=t.length;a<o;a++){let o=t[a],s=n&&n[e.length],c;if(o!=null&&o!==!0&&o!==!1){if((c=typeof o)==`object`&&o.nodeType)e.push(o);else if(Array.isArray(o))i=ht(e,o,s)||i;else if(c===`function`){if(r){for(;typeof o==`function`;)o=o();i=ht(e,Array.isArray(o)?o:[o],Array.isArray(s)?s:[s])||i}else e.push(o),i=!0}else{let t=String(o);s&&s.nodeType===3&&s.data===t?e.push(s):e.push(document.createTextNode(t))}}}return i}function gt(e,t,n=null){for(let r=0,i=t.length;r<i;r++)e.insertBefore(t[r],n)}function _t(e,t,n,r){if(n===void 0)return e.textContent=``;let i=r||document.createTextNode(``);if(t.length){let r=!1;for(let a=t.length-1;a>=0;a--){let o=t[a];if(i!==o){let t=o.parentNode===e;!r&&!a?t?e.replaceChild(i,o):e.insertBefore(i,n):t&&o.remove()}else r=!0}}else e.insertBefore(i,n);return[i]}function vt(){return e.getNextContextId()}var yt=`http://www.w3.org/2000/svg`;function bt(e,t=!1,n=void 0){return t?document.createElementNS(yt,e):document.createElement(e,{is:n})}function xt(t){let{useShadow:n}=t,r=document.createTextNode(``),i=()=>t.mount||document.body,a=oe(),o,s=!!e.context;return C(()=>{s&&(oe().user=s=!1),o||=se(a,()=>w(()=>t.children));let e=i();if(e instanceof HTMLHeadElement){let[t,n]=x(!1);b(n=>R(e,()=>t()?n():o(),null)),D(()=>n(!0))}else{let i=bt(t.isSVG?`g`:`div`,t.isSVG),a=n&&i.attachShadow?i.attachShadow({mode:`open`}):i;Object.defineProperty(i,"_$host",{get(){return r.parentNode},configurable:!0}),R(a,o),e.appendChild(i),t.ref&&t.ref(i),D(()=>e.contains(i)&&e.removeChild(i))}},void 0,{render:!s}),r}function St(t,n){let r=w(t);return w(()=>{let t=r();switch(typeof t){case`function`:return T(()=>t(n));case`string`:let r=Xe.has(t),i=e.context?lt():bt(t,r,T(()=>n.is));return st(i,n,r),i}})}function Ct(e){let[,t]=Be(e,[`component`]);return St(()=>e.component,t)}var B=e=>e==null?``:String(e).trim(),wt=Object.freeze([[`role`,`Admins first`],[`email`,`Email`],[`lastSeen`,`Last seen`]]),Tt=Object.freeze([[`all`,`All`],[`admins`,`Admins`],[`active`,`Active`],[`disabled`,`Disabled`]]),Et=Object.freeze({signin:`Signed in`,"signin.denied":`Sign-in refused`,"device.pair":`Paired a device`,"device.revoke":`Revoked a device`,"machine.approve":`Approved a machine`,"machine.deny":`Denied a machine`,"machine.revoke":`Revoked a machine`,"user.role":`Changed a role`,"user.disable":`Disabled a user`,"user.enable":`Enabled a user`,"speech.default":`Changed the server speech default`,"migrate.local":`Moved the hub owner's machines and devices to the first admin`});function Dt(e){return e?.user?.role===`admin`}function Ot(e){let t=e?.user,n=e?.auth===`oidc`?`oidc`:`pairing`,r=Dt(e);if(n!==`oidc`)return{mode:n,admin:r,title:`This hub`,initial:`H`};let i=B(t?.name),a=B(t?.email),o=i||a||`Signed in`;return{mode:n,admin:r,title:o,...i&&a?{subtitle:a}:{},initial:(o.match(/[\p{L}\p{N}]/u)?.[0]??`?`).toUpperCase(),...r?{badge:`Admin`}:{}}}var kt=Object.freeze([[`users`,`Users`],[`machines`,`Machines`],[`approvals`,`Approvals`],[`audit`,`Audit log`]]);function At(e){return Dt(e)?kt.filter(([t])=>t!==`users`||e?.auth===`oidc`):[]}function jt(e,t){return Dt(e)&&t?.scope===`user`?[`user`,`default`]:[`user`]}function Mt(e){return e&&e.startsWith(`/`)&&!e.startsWith(`//`)&&!e.includes(`\\`)?e:`/`}function Nt(e,t){if(e?.mode===`oidc`&&typeof e.signIn==`string`&&e.signIn)return`${e.signIn}?next=${encodeURIComponent(Mt(t))}`}function Pt(e){let t=e?.auth===`oidc`?B(e?.user?.email):``;return t?`This machine will belong to you (${t}).`:`This machine will belong to you.`}var Ft={stt:[`provider`,`model`,`baseURL`,`language`],tts:[`provider`,`model`,`voice`,`baseURL`,`speed`]};function It(e){let t=e;if(t?.scope!==`user`)return;let n=t.default??{},r=t.user&&typeof t.user==`object`?t.user:void 0,i={own:{stt:0,tts:0}};for(let e of[`stt`,`tts`]){let a=t[e]??{},o=n[e]??{},s=r?.[e]??{},c={};for(let t of Ft[e]){let n=r?s[t]===void 0||s[t]===null:B(a[t])===B(o[t]),l=B(o[t]);c[t]=n?{inherited:n,note:l?`Using server default: ${l}`:`Server default: not set`}:{inherited:n},n||i.own[e]++}let l=r?!!s.apiKey?.set:a.apiKey?.source===`user`;c.apiKey=l?{inherited:!1}:{inherited:!0,note:o.apiKey?.set===!1?`Key: server default (none set)`:`Key: server default`},l&&i.own[e]++,i[e]=c}return i}function Lt(e){return{[e]:Object.fromEntries([...Ft[e],`apiKey`].map(e=>[e,null]))}}function Rt(e){let t=B(e);if(!t)return`Unknown action`;if(Et[t])return Et[t];let n=t.replace(/[._-]+/g,` `).trim().toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)}function zt(e,t=[]){let n=new Map(t.map(e=>[e.id,B(e.email)||B(e.name)||e.id])),r=e=>e===`system`?`System`:n.get(e)??e;return[...e??[]].sort((e,t)=>t.at-e.at).map(e=>({at:e.at,actor:r(e.actor),action:Rt(e.action),target:e.target===void 0?void 0:n.get(e.target)??e.target,detail:e.detail}))}var Bt=e=>(B(e.email)||B(e.name)||e.id).toLowerCase();function Vt(e,{query:t=``,filter:n=`all`,sort:r=`role`}={}){let i=B(t).toLowerCase(),a=e=>(!i||`${B(e.email)} ${B(e.name)}`.toLowerCase().includes(i))&&(n===`admins`?e.role===`admin`:n===`disabled`?!!e.disabled:n!==`active`||!e.disabled),o=(e,t)=>Bt(e).localeCompare(Bt(t)),s=r===`lastSeen`?(e,t)=>(t.lastSeen??0)-(e.lastSeen??0)||o(e,t):r===`email`?o:(e,t)=>Number(!!e.disabled)-Number(!!t.disabled)||Number(t.role===`admin`)-Number(e.role===`admin`)||o(e,t);return(e??[]).filter(a).sort(s)}function Ht(e,t,n){let r=B(e.email)||B(e.name)||e.id,i=e.id===n,a=(t??[]).filter(e=>e.role===`admin`&&!e.disabled).length,o=e.role===`admin`&&!e.disabled&&a<=1;return[e.role===`admin`?{label:`Remove admin`,change:{role:`user`},danger:!0,...o?{lastAdmin:!0}:{},confirm:i?`Remove your own admin role? You will lose access to the admin screens.`:`Remove admin from ${r}?`}:{label:`Make admin`,change:{role:`admin`},confirm:`Make ${r} an admin? Admins manage users, machines and the server speech default.`},e.disabled?{label:`Enable`,change:{disabled:!1},confirm:`Enable ${r}?`}:{label:`Disable`,change:{disabled:!0},danger:!0,...o?{lastAdmin:!0}:{},confirm:i?`Disable your own account? This device is signed out.`:`Disable ${r}? Their phones and machines are disconnected until you enable them again.`}]}function Ut(e){let t=B(e?.message);return t&&!/^HTTP \d+$/.test(t)?t:e?.status===403?`Only admins can do that.`:`The server refused the change (HTTP ${e?.status??`?`}).`}var Wt=e=>String(e??``).normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase(),Gt=e=>`${e.providerID}/${e.modelID}`,Kt=class{models;constructor(e=[]){this.models=Array.isArray(e)?e.filter(e=>e&&typeof e.providerID==`string`&&typeof e.modelID==`string`):[]}groups(e=``){let t=Wt(e.trim()),n=new Map,r=this.models.some(e=>e.enabled!==!1);for(let e of this.models){if(r&&e.enabled===!1||t&&!Wt([e.name,e.modelID,e.providerID].join(` `)).includes(t))continue;let i=n.get(e.providerID)??[];i.push({...e,variants:[...e.variants??[]]}),n.set(e.providerID,i)}return[...n].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({providerID:e,items:t.sort((e,t)=>(e.name||e.modelID).localeCompare(t.name||t.modelID))}))}selection(e){if(!e)return;let t=this.models.find(t=>t.providerID===e.providerID&&t.modelID===e.modelID);return t?{...t,variants:[...t.variants??[]],stale:t.enabled===!1}:{...e,name:Gt(e),variants:e.variant?[e.variant]:[],stale:!0}}},qt=e=>`${e}:reasoning`,Jt=(e,t)=>t===void 0?`${e}:text`:`${e}:text:${t}`,Yt=e=>`hubmsg:${e}`,Xt=1e3,Zt=(e,t)=>`activity:${e}:${t}`,Qt=(e,t)=>e.pos-t.pos||e.live-t.live,$t=class{items=new Map;subagents=new Map;details=new Map;places=new Map;top=0;bottom=0;liveSeq=0;seenSeq=0;loaded=!1;snapshots=0;history=new Set;load(e,t={}){let n=(e??[]).filter(e=>e&&typeof e.key==`string`),r=n.filter(e=>typeof e.pos!=`number`&&!this.places.has(e.key));r.forEach((e,n)=>{this.places.set(e.key,{pos:t.older?this.bottom-r.length+n:this.top+1+n,live:0})});for(let e of n){typeof e.pos==`number`&&Number.isFinite(e.pos)&&this.places.set(e.key,{pos:e.pos,live:0});let t=this.places.get(e.key).pos;this.top=Math.max(this.top,t),this.bottom=Math.min(this.bottom,t),this.history.add(e.key)}for(let e of n){let t=this.liveTwin(e);t?(this.items.delete(t.key),this.places.delete(t.key),t.kind===`reasoning`?this.put({...e,text:e.text||t.text||``}):t.kind===`tool`?this.put({...en(t,[`summary`,`error`]),...e}):this.put(e)):this.put(e)}if(!t.older){this.loaded=!0;for(let[e,t]of this.places)t.live>0&&t.pos<this.top&&this.places.set(e,{...t,pos:this.top});for(let e of this.subagents.values())e.place&&e.place.pos<this.top&&(e.place={...e.place,pos:this.top})}}liveTwin(e){if(this.history.has(e.key)&&this.items.has(e.key))return;let t=typeof e.messageID==`string`?e.messageID:void 0,n=[];e.kind===`reasoning`&&t&&n.push(qt(t)),e.kind===`assistant`&&t&&(typeof e.ordinal==`number`&&n.push(Jt(t,e.ordinal)),(e.ordinal===void 0||e.ordinal===0)&&n.push(Jt(t))),e.kind===`tool`&&typeof e.callID==`string`&&typeof e.sessionID==`string`&&n.push(Zt(e.sessionID,e.callID)),e.kind===`message`&&t&&n.push(Yt(t));for(let t of n){let n=t===e.key?void 0:this.items.get(t);if(n&&!this.history.has(t))return n}if(e.kind===`user`&&typeof e.text==`string`&&e.text){for(let t of this.items.values())if(t.kind===`user`&&!t.messageID&&!this.history.has(t.key)&&t.text===e.text)return t}}appendReasoning({sessionID:e,messageID:t,delta:n,at:r=Date.now()}){let i;for(let e of this.items.values())e.kind===`reasoning`&&e.messageID===t&&e.state===`running`&&(i=e);i??=this.items.get(qt(t));let a=i?.key??qt(t);this.upsert({key:a,kind:`reasoning`,messageID:t,...e?{sessionID:e}:{},text:`${i?.text??``}${n}`,state:`running`,at:i?.at??r})}appendText({sessionID:e,messageID:t,ordinal:n,delta:r,at:i=Date.now()}){let a=Jt(t,n),o=this.items.get(a);this.upsert({key:a,messageID:t,...e?{sessionID:e}:{},kind:`assistant`,text:`${o?.text??``}${r}`,live:!0,at:o?.at??i}),this.endReasoning(e)}liveTextKey(e){let t=Jt(e),n=-1;for(let r of this.items.values()){if(r.kind!==`assistant`||r.messageID!==e||this.history.has(r.key))continue;let i=r.key.startsWith(`${e}:text:`)?Number(r.key.slice(e.length+6)):NaN;Number.isInteger(i)&&i>n&&([t,n]=[r.key,i])}return t}activity(e,t){if(!t||typeof t.id!=`string`||t.kind===`thinking`)return;let n=Zt(e,t.id),r=this.items.get(n);this.upsert({key:n,sessionID:e,kind:`tool`,callID:t.id,...t.tool?{name:t.tool}:{},...t.summary?{summary:t.summary}:{},...t.error?{error:t.error}:{},...t.childSessionID?{childSessionID:t.childSessionID}:{},state:t.state,at:r?.at??t.at})}endReasoning(e,t=Date.now()){for(let n of this.items.values())n.kind===`reasoning`&&n.state===`running`&&(e===void 0||n.sessionID===e)&&this.upsert({key:n.key,kind:n.kind,state:`done`,completed:t})}upsert(e){e&&typeof e.key==`string`&&(this.places.has(e.key)||this.places.set(e.key,this.livePlace()),this.put(e))}livePlace(){return{pos:this.top,live:++this.liveSeq}}put(e){this.items.set(e.key,{...this.items.get(e.key)??{},...e})}hubMessage(e){if(e&&typeof e.key==`string`&&typeof e.messageID==`string`){for(let[t,n]of this.items)if(t!==e.key&&n.kind===`message`&&n.messageID===e.messageID&&this.history.has(t))return;if(!this.places.has(e.key)){if(typeof e.at==`number`&&Number.isFinite(e.at)){let t=e.at*Xt;this.places.set(e.key,{pos:t,live:0}),this.top=Math.max(this.top,t)}else this.places.set(e.key,this.livePlace())}this.put(e)}}fromHistory(e){return this.history.has(e)}forgetHistory(){for(let e of this.history)this.items.delete(e),this.places.delete(e);this.history.clear()}get(e){return this.items.get(e)}status(e,t){let n=new Set,r=new Set([t]);for(let t=!0;t;){t=!1;for(let n of e??[])typeof n?.id==`string`&&typeof n.parentID==`string`&&r.has(n.parentID)&&!r.has(n.id)&&(r.add(n.id),t=!0)}let i=(e??[]).every(e=>e?.id===t||typeof e?.parentID!=`string`),a=this.snapshots>0&&this.loaded;e?.length&&this.snapshots++;for(let o of e??[]){let s=o?.id;if(!o||typeof s!=`string`||!s||s===t||!r.has(s)&&!(i&&(e??[])[0]?.id===t))continue;n.add(s);let c=typeof o.since==`number`?o.since:void 0,l=o.state===`idle`?`done`:o.state,u=this.subagents.get(s)??{id:s,seen:++this.seenSeq,...a&&l===`working`?{place:this.livePlace()}:{}};this.subagents.set(s,{...u,title:typeof o.title==`string`?o.title:void 0,state:l,since:c})}for(let e of this.subagents.values())!n.has(e.id)&&e.state===`working`&&(e.state=`done`)}detail(e,t){this.details.set(e,t)}rows(){let e=[],t=new Map;for(let n of this.items.values()){let r={...n,depth:0,...this.details.has(n.key)?{detail:this.details.get(n.key)}:{}};if(n.sessionID&&this.subagents.has(n.sessionID)){let e=t.get(n.sessionID)??[];e.push({...r,depth:1}),t.set(n.sessionID,e)}else e.push(r)}let n=e=>this.places.get(e)??{pos:this.top,live:2**53-1},r=(e,t)=>Qt(n(e.key),n(t.key)),i=e=>[{key:`sub:${e.id}`,kind:`subagent`,label:e.title||e.id,state:e.state,sessionID:e.id,depth:0},...(t.get(e.id)??[]).sort(r)],a=[],o=new Set;for(let t of e.sort(r)){let e=typeof t.childSessionID==`string`&&!o.has(t.childSessionID)?this.subagents.get(t.childSessionID):void 0;e&&o.add(e.id),a.push({place:n(t.key),rows:e?i(e):[t]})}let s=[...this.subagents.values()].filter(e=>!o.has(e.id));s.filter(e=>!e.place).sort((e,t)=>(e.since??1/0)-(t.since??1/0)||e.seen-t.seen).forEach((e,t)=>a.push({place:{pos:-1/0,live:t},rows:i(e)}));for(let e of s)e.place&&a.push({place:e.place,rows:i(e)});return a.sort((e,t)=>Qt(e.place,t.place)).flatMap(e=>e.rows)}};function en(e,t){return Object.fromEntries(t.filter(t=>e[t]!==void 0).map(t=>[t,e[t]]))}function tn(e){let t=e&&typeof e==`object`?e:{},n=e=>typeof e==`string`&&e?e:void 0;return t.kind===`session`?n(t.name)?`@${t.name}`:String(t.sessionID??`?`):t.kind===`user`?`@me`:t.kind===`app`?`app ${n(t.label)??String(t.tokenID??`?`)}`:`?`}function nn(e,t){let n=t&&typeof t==`object`?t:void 0;if(!n||typeof n.id!=`string`||!n.id||typeof n.kind!=`string`||typeof n.to!=`string`)return;let r=t=>t?.kind===`session`&&t.sessionID===e,i=r(n.from)?`out`:r(n.recipient)?`in`:void 0;if(i)return{key:Yt(n.id),kind:`message`,messageID:n.id,sessionID:e,text:typeof n.text==`string`?n.text:``,...typeof n.at==`number`?{at:n.at}:{},direction:i,message:{kind:n.kind,from:tn(n.from),to:n.to,...typeof n.replyTo==`string`?{replyTo:n.replyTo}:{}},recipient:tn(n.recipient),...typeof n.state==`string`?{state:n.state}:{},...typeof n.delivery==`string`?{delivery:n.delivery}:{}}}var rn=new Set([`open`,`answered`,`expired`,`closed`]),an=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function on(e){if(!an(e))return;let{id:t,question:n,options:r,state:i,about:a,at:o,from:s}=e;if(typeof t!=`string`||!t.startsWith(`dec_`)||typeof n!=`string`||!Array.isArray(r)||!Array.isArray(a)||typeof i!=`string`||!rn.has(i)||typeof o!=`number`||!an(s))return;let c=r.filter(e=>an(e)&&typeof e.id==`string`&&typeof e.label==`string`);return{...e,options:c,about:a.filter(e=>typeof e==`string`)}}var sn=(e,t)=>t.at-e.at||(e.id<t.id?1:-1);function cn(e){return e.filter(e=>e.state===`open`).sort(sn)}function ln(e,t){return cn([...e.filter(e=>e.id!==t.id),t])}function un(e,t){return e.filter(e=>e.from.kind===`session`&&e.from.sessionID===t||e.about.includes(t))}var dn=e=>tn(e.from),fn=e=>e.tier===`tap`?`Answer here (tap): only a signed-in console can answer this one.`:``;function pn(e,t){let n=e-t;if(n<0)return``;let r=Math.floor(n/1e3),i=Math.floor(r/86400),a=Math.floor(r%86400/3600),o=Math.floor(r%3600/60);return i?`${i}d ${a}h`:a?`${a}h ${o}m`:o?`${o}m ${r%60}s`:`${r}s`}function mn(e,t){if(e.deadline===void 0)return``;let n=pn(e.deadline,t);if(!n)return`Past its deadline`;let r=e.onTimeout?e.options.find(t=>t.id===e.onTimeout)?.label:void 0;return`Deadline in ${n}${r?` · then ${r}`:``}`}function hn(e,t,n){let r=n.trim();return e.options.length?t===void 0||!e.options.some(e=>e.id===t)?{ok:!1,problem:`Pick one of the options`}:{ok:!0,body:{option:t,...r?{text:r}:{}}}:r?{ok:!0,body:{text:r}}:{ok:!1,problem:`Type an answer`}}var gn=[`approve`,`deny`,`answer`,`prompt`,`stop`,`roles`,`launch`],_n=new Set([`active`,`expired`,`revoked`]),vn=e=>!!e&&typeof e==`object`&&!Array.isArray(e),yn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),bn=[`sessions:read`,`sessions:manage`,`messages:send`,`messages:read`,`sessions:act`,`sessions:launch`,`events:subscribe`];function xn(e){if(vn(e)&&typeof e.id==`string`&&/^[0-9a-f]{16}$/.test(e.id)&&yn(e.scopes))return{id:e.id,...typeof e.label==`string`?{label:e.label}:{},scopes:e.scopes.filter(e=>bn.includes(e)),...typeof e.created==`number`?{created:e.created}:{}}}function Sn(e){return(vn(e)&&Array.isArray(e.tokens)?e.tokens:[]).map(xn).filter(e=>!!e)}function Cn(e,t){let n=e.trim();if(!n)return{ok:!1,error:`Give the token a label`};if(!t.length)return{ok:!1,error:`Pick at least one scope`};let r=t.find(e=>!bn.includes(e));return r?{ok:!1,error:`Unknown scope: ${r}`}:{ok:!0,body:{label:n,scopes:[...new Set(t)]}}}var wn={"sessions:read":`Read your sessions and their activity`,"sessions:manage":`Name sessions and claim roles`,"messages:send":`Send messages and asks, reply and decline`,"messages:read":`Read messages to it`,"sessions:act":`Approve, deny, answer, prompt and stop sessions (only under a grant)`,"sessions:launch":`Launch sessions (only under a grant with verb launch for the repo)`,"events:subscribe":`Subscribe webhooks to events`},Tn=e=>bn.includes(e);function En(e){let t=vn(e)?e.login:void 0;if(vn(t)&&typeof t.userCode==`string`&&typeof t.clientName==`string`&&yn(t.scopes)&&typeof t.created==`number`&&typeof t.expiresAt==`number`)return{userCode:t.userCode,clientName:t.clientName,scopes:t.scopes.filter(Tn),created:t.created,expiresAt:t.expiresAt}}function Dn(e){return bn.map(t=>{let n=e.scopes.includes(t);return{scope:t,label:wn[t],requested:n,checked:n}})}function On(e){if(!e.length)return{ok:!1,error:`Pick at least one scope`};let t=e.find(e=>!Tn(e));return t?{ok:!1,error:`Unknown scope: ${t}`}:{ok:!0,body:{scopes:[...new Set(e)]}}}function kn(e){if(!vn(e))return;let{id:t,holder:n,scope:r,allow:i,permissions:a,allowAlways:o,maxActionsPerHour:s,created:c,expiresAt:l,state:u}=e;if(typeof t==`string`&&typeof n==`string`&&typeof u==`string`&&_n.has(u)&&vn(r)&&yn(r.projects)&&yn(i)&&vn(a)&&yn(a.allow)&&yn(a.never)&&typeof o==`boolean`&&typeof s==`number`&&typeof c==`number`&&typeof l==`number`)return e}function An(e){return(vn(e)&&Array.isArray(e.grants)?e.grants:[]).map(kn).filter(e=>!!e)}function jn(e,t){return e.state===`revoked`||e.revokedAt!==void 0?`revoked`:e.state===`expired`||t>=e.expiresAt?`expired`:`active`}var Mn={active:`Active`,expired:`Expired`,revoked:`Revoked`};function Nn(e,t){let n=jn(e,t);return{id:e.id,holder:e.holderSessionID?`${e.holder} (${e.holderSessionID})`:e.holder,state:n,stateLabel:Mn[n],projects:e.scope.projects.join(`, `),verbs:e.allow.join(`, `),permit:e.permissions.allow.join(`, `),never:e.permissions.never.join(`, `),limits:[e.allowAlways?`may allow always`:``,`${e.maxActionsPerHour} actions an hour`].filter(Boolean).join(` · `),expiry:n===`active`?`Expires in ${pn(e.expiresAt,t)}`:Mn[n],editable:n===`active`}}function Pn(e){return{holder:e?.holder??``,projects:e?e.scope.projects.join(`
2
+ `):``,allow:e?[...e.allow]:[],permit:e?e.permissions.allow.join(`
3
+ `):``,never:e?e.permissions.never.join(`
4
+ `):``,expires:`8h`,maxActionsPerHour:String(e?.maxActionsPerHour??60),allowAlways:e?.allowAlways??!1}}var Fn=e=>e.split(`
5
+ `).map(e=>e.trim()).filter(Boolean),In=/^\d+(s|m|h|d)?$/,Ln=e=>/^([A-Za-z]:)?[\\/]/.test(e);function Rn(e){let t={},n=e.holder.trim();n||(t.holder=`Who holds it: @@orchestrator, @name, ses_… or app:<token id>`);let r=Fn(e.projects),i=r.find(e=>!Ln(e));r.length?i!==void 0&&(t.projects=`${i} is not an absolute directory`):t.projects=`At least one project directory`;let a=gn.filter(t=>e.allow.includes(t));a.length||(t.allow=`Pick at least one action`);let o=e.expires.trim();In.test(o)||(t.expires=`A duration: seconds, or 30m, 8h, 2d`);let s=e.maxActionsPerHour.trim(),c=/^\d+$/.test(s)?Number(s):NaN;return c>=1&&c<=1e3||(t.maxActionsPerHour=`A whole number from 1 to 1000`),Object.keys(t).length?{ok:!1,errors:t}:{ok:!0,body:{holder:n,scope:{projects:r},allow:a,permissions:{allow:Fn(e.permit),never:Fn(e.never)},expires:o,maxActionsPerHour:c,allowAlways:e.allowAlways}}}function zn(e){if(/^permissions\.never/.test(e))return`never`;if(/^permissions/.test(e))return`permit`;if(/^scope/.test(e))return`projects`;if(/^allow\b/.test(e))return`allow`;if(/^expires/.test(e))return`expires`;if(/^maxActionsPerHour/.test(e))return`maxActionsPerHour`;if(/^allowAlways/.test(e))return`allowAlways`;if(/holder|^No app token|^No session|^No such session/i.test(e))return`holder`}function Bn(e){if(!vn(e))return;let{seq:t,at:n,actor:r,verb:i,target:a,decision:o,outcome:s}=e;if(typeof t==`number`&&typeof n==`number`&&vn(r)&&typeof r.kind==`string`&&typeof i==`string`&&vn(a)&&typeof o==`string`&&typeof s==`string`)return e}function Vn(e){if(!vn(e))return{entries:[]};let t=(Array.isArray(e.entries)?e.entries:[]).map(Bn).filter(e=>!!e);return typeof e.next==`number`?{entries:t,next:e.next}:{entries:t}}var Hn={allow:`allowed`,needs_user:`needs you`,forbidden:`refused`,paused:`paused`,rate_limited:`rate limited`},Un={ok:`done`,failed:`failed`,gone:`already answered`,offline:`offline`,unsupported:`unsupported`,escalated:`sent to you`,refused:`refused`},Wn=new Set([`forbidden`,`paused`,`rate_limited`]),Gn=new Set([`failed`,`refused`,`offline`,`unsupported`]),Kn={"acting.pause":`turned agent actions off`,"acting.resume":`turned agent actions on`},qn=e=>e.kind===`user`?`you`:tn(e);function Jn(e){let t=e.target.requestID??e.target.formID,n=e.target.sessionID??``,r=Kn[e.verb]??[e.verb,t,t&&n?`in ${n}`:n].filter(Boolean).join(` `),i=Hn[e.decision]??e.decision,a=Un[e.outcome]??e.outcome,o=e.decision===`allow`&&e.outcome===`ok`;return{seq:e.seq,at:e.at,who:qn(e.actor),what:r,result:o?`done`:i===a?i:`${i} · ${a}`,tone:o?`ok`:Wn.has(e.decision)||Gn.has(e.outcome)?`err`:`warn`,grant:e.grant?`grant ${e.grant}`:``,reason:e.reason??``}}var Yn={approve:`Approved`,deny:`Denied`,answer:`Answered`},Xn=3;function Zn(e){let t=Yn[e.verb];if(t&&e.decision===`allow`&&e.outcome===`ok`)return`${t} by ${qn(e.actor)}${e.grant?` · grant ${e.grant}`:``}`}function Qn(e,t){return[t,...e.filter(e=>e.seq!==t.seq)].sort((e,t)=>t.seq-e.seq).slice(0,100)}function $n(e,t){for(let n of e){if(n.target.requestID!==t&&n.target.formID!==t)continue;let e=Zn(n);if(e)return e}}function er(e,t,n){let r=[];for(let i of[...e].sort((e,t)=>t.at-e.at||t.seq-e.seq)){if(r.length>=Xn)break;if(!i.target.sessionID||!t.has(i.target.sessionID)||n-i.at>6e5)continue;let e=Zn(i),a=i.target.requestID??i.target.formID??`seq-${i.seq}`;e&&!r.some(e=>e.key===a)&&r.push({key:a,text:e,at:i.at})}return r}function tr(e){let t=e.enabled!==!1,n=e.hubEnabled!==!1;return{on:t,hubOn:n,note:n?t?``:`Agents cannot act for you (approve, deny, answer, prompt, stop, launch). Reading and messaging still work.`:`An admin turned agent actions off for the whole hub: no agent can approve, deny, answer, prompt, stop or launch until it is on again.`}}var nr=/^(.*?) asks to approve( always(?: \(saves .*?\))?)? (.*?)\. Outside its grant: (.*)$/s,rr=`a permission request (details unknown)`;function ir(e){if(e.action?.kind!==`permission`)return;let t={requester:dn(e),always:e.action.always===!0,...e.action.requestID?{requestID:e.action.requestID}:{}},n=nr.exec(e.question);if(!n)return{...t,action:void 0,resources:[],reason:void 0};let r=n[3],i=r.indexOf(`: `),a=r!==rr;return{...t,always:t.always||!!n[2],action:a?i<0?r:r.slice(0,i):void 0,resources:a&&i>=0?r.slice(i+2).split(`, `).filter(Boolean):[],reason:n[4].trim()||void 0}}function ar(e){return!vn(e)||typeof e.by!=`string`||e.recommends!==`approve`?``:`${e.by} recommends Approve${typeof e.why==`string`&&e.why?`: ${e.why}`:``}`}var or=class extends Error{status;code;field;hint;constructor(e,t){super(t),this.status=e}},sr=class extends Error{cause;name=`NetworkError`;constructor(e){super(`Can't reach the hub: the connection dropped. Check your network and try again.`),this.cause=e}},cr;function lr(e){cr=e}async function V(e,{method:t=`GET`,json:n,body:r,headers:i={},signal:a,keepalive:o}={}){let s={method:t,credentials:`same-origin`,headers:{...i},signal:a,keepalive:o};n===void 0?r!==void 0&&(s.body=r):(s.headers[`content-type`]=`application/json`,s.body=JSON.stringify(n));let c;try{c=await fetch(e,s)}catch(e){throw e instanceof TypeError?new sr(e):e}if(!c.ok){let e=await c.json().catch(()=>({}));c.status===401&&cr?.();let t=e.error&&typeof e.error==`object`?e.error:e,n=typeof e.error==`string`?e.error:typeof t.message==`string`?t.message:``,r=new or(c.status,n||`HTTP ${c.status}`);throw typeof t.field==`string`&&(r.field=t.field),typeof t.code==`string`&&(r.code=t.code),typeof t.hint==`string`&&(r.hint=t.hint),r}return c}var H=async e=>(await V(e)).json(),U=encodeURIComponent,W=e=>`/api/sessions/${U(e)}`,G=e=>e instanceof Error?e.message:String(e),ur=Symbol(`store-raw`),dr=Symbol(`store-node`),fr=Symbol(`store-has`),pr=Symbol(`store-self`);function mr(e){let t=e[i];if(!t&&(Object.defineProperty(e,i,{value:t=new Proxy(e,Sr)}),!Array.isArray(e))){let n=Object.keys(e),r=Object.getOwnPropertyDescriptors(e),i=Object.getPrototypeOf(e),a=i!==null&&typeof e==`object`&&!!e&&!Array.isArray(e)&&i!==Object.prototype;if(a){let e=Object.getOwnPropertyDescriptors(i);n.push(...Object.keys(e)),Object.assign(r,e)}for(let i=0,o=n.length;i<o;i++){let o=n[i];a&&o===`constructor`||r[o].get&&Object.defineProperty(e,o,{configurable:!0,enumerable:r[o].enumerable,get:r[o].get.bind(t)})}}return t}function hr(e){let t;return typeof e==`object`&&!!e&&(e[i]||!(t=Object.getPrototypeOf(e))||t===Object.prototype||Array.isArray(e))}function gr(e,t=new Set){let n,r,i,a;if(n=e!=null&&e[ur])return n;if(!hr(e)||t.has(e))return e;if(Array.isArray(e)){Object.isFrozen(e)?e=e.slice(0):t.add(e);for(let n=0,a=e.length;n<a;n++)i=e[n],(r=gr(i,t))!==i&&(e[n]=r)}else{Object.isFrozen(e)?e=Object.assign({},e):t.add(e);let n=Object.keys(e),o=Object.getOwnPropertyDescriptors(e);for(let s=0,c=n.length;s<c;s++)a=n[s],!o[a].get&&(i=e[a],(r=gr(i,t))!==i&&(e[a]=r))}return e}function _r(e,t){let n=e[t];return n||Object.defineProperty(e,t,{value:n=Object.create(null)}),n}function vr(e,t,n){if(e[t])return e[t];let[r,i]=x(n,{equals:!1,internal:!0});return r.$=i,e[t]=r}function yr(e,t){let n=Reflect.getOwnPropertyDescriptor(e,t);return!n||n.get||!n.configurable||t===i||t===dr||(delete n.value,delete n.writable,n.get=()=>e[i][t]),n}function br(e){ae()&&vr(_r(e,dr),pr)()}function xr(e){return br(e),Reflect.ownKeys(e)}var Sr={get(e,t,n){if(t===ur)return e;if(t===i)return n;if(t===o)return br(e),n;let r=_r(e,dr),a=r[t],s=a?a():e[t];if(t===dr||t===fr||t===`__proto__`)return s;if(!a){let n=Object.getOwnPropertyDescriptor(e,t);ae()&&(typeof s!=`function`||Object.prototype.hasOwnProperty.call(e,t))&&!(n&&n.get)&&(s=vr(r,t,s)())}return hr(s)?mr(s):s},has(e,t){return t===ur||t===i||t===o||t===dr||t===fr||t===`__proto__`||(ae()&&vr(_r(e,fr),t)(),t in e)},set(){return!0},deleteProperty(){return!0},ownKeys:xr,getOwnPropertyDescriptor:yr};function Cr(e,t,n,r=!1){if(t===`__proto__`||!r&&e[t]===n)return;let i=e[t],a=e.length;n===void 0?(delete e[t],e[fr]&&e[fr][t]&&i!==void 0&&e[fr][t].$()):(e[t]=n,e[fr]&&e[fr][t]&&i===void 0&&e[fr][t].$());let o=_r(e,dr),s;if((s=vr(o,t,i))&&s.$(()=>n),Array.isArray(e)&&e.length!==a){for(let t=e.length;t<a;t++)(s=o[t])&&s.$();(s=vr(o,`length`,a))&&s.$(e.length)}(s=o[pr])&&s.$()}function wr(e,t){let n=Object.keys(t);for(let r=0;r<n.length;r+=1){let i=n[r];Tr(i)||Cr(e,i,t[i])}}function Tr(e){return e===`__proto__`||e===`constructor`||e===`prototype`}function Er(e,t){if(typeof t==`function`&&(t=t(e)),t=gr(t),Array.isArray(t)){if(e===t)return;let n=0,r=t.length;for(;n<r;n++){let r=t[n];e[n]!==r&&Cr(e,n,r)}Cr(e,`length`,r)}else wr(e,t)}function Dr(e,t,n=[]){let r,i=e;if(t.length>1){r=t.shift();let a=typeof r,o=Array.isArray(e);if(a===`string`&&(r===`__proto__`||t.length>1&&Tr(r)))return;if(Array.isArray(r)){for(let i=0;i<r.length;i++)Dr(e,[r[i]].concat(t),n);return}if(o&&a===`function`){for(let i=0;i<e.length;i++)r(e[i],i)&&Dr(e,[i].concat(t),n);return}if(o&&a===`object`){let{from:i=0,to:a=e.length-1,by:o=1}=r;for(let r=i;r<=a;r+=o)Dr(e,[r].concat(t),n);return}if(t.length>1){Dr(e[r],t,[r].concat(n));return}i=e[r],n=[r].concat(n)}let a=t[0];typeof a==`function`&&(a=a(i,n),a===i)||(r!==void 0||a!=null)&&(a=gr(a),r===void 0||hr(i)&&hr(a)&&!Array.isArray(a)?wr(i,a):Cr(e,r,a))}function Or(...[e,t]){let n=gr(e||{}),r=Array.isArray(n),i=mr(n);function a(...e){re(()=>{r&&e.length===1?Er(n,e[0]):Dr(n,e)})}return[i,a]}var kr=Symbol(`store-root`);function Ar(e){return e===`__proto__`||e===`constructor`||e===`prototype`}function jr(e,t,n,r,i){if(Ar(n))return;let a=t[n];if(e===a)return;let o=Array.isArray(e);if(n!==kr&&(!hr(e)||!hr(a)||o!==Array.isArray(a)||i&&e[i]!==a[i])){Cr(t,n,e);return}if(o){if(e.length&&a.length&&(!r||i&&e[0]&&e[0][i]!=null)){let t,n,o,s,c,l,u,d;for(o=0,s=Math.min(a.length,e.length);o<s&&(a[o]===e[o]||i&&a[o]&&e[o]&&a[o][i]&&a[o][i]===e[o][i]);o++)jr(e[o],a,o,r,i);let f=Array(e.length),p=new Map;for(s=a.length-1,c=e.length-1;s>=o&&c>=o&&(a[s]===e[c]||i&&a[s]&&e[c]&&a[s][i]&&a[s][i]===e[c][i]);s--,c--)f[c]=a[s];if(o>c||o>s){for(n=o;n<=c;n++)Cr(a,n,e[n]);for(;n<e.length;n++)Cr(a,n,f[n]),jr(e[n],a,n,r,i);a.length>e.length&&Cr(a,`length`,e.length);return}for(u=Array(c+1),n=c;n>=o;n--)l=e[n],d=i&&l?l[i]:l,t=p.get(d),u[n]=t===void 0?-1:t,p.set(d,n);for(t=o;t<=s;t++)l=a[t],d=i&&l?l[i]:l,n=p.get(d),n!==void 0&&n!==-1&&(f[n]=a[t],n=u[n],p.set(d,n));for(n=o;n<e.length;n++)n in f?(Cr(a,n,f[n]),jr(e[n],a,n,r,i)):Cr(a,n,e[n])}else for(let t=0,n=e.length;t<n;t++)jr(e[t],a,t,r,i);a.length>e.length&&Cr(a,`length`,e.length);return}let s=Object.keys(e);for(let t=0,n=s.length;t<n;t++)Ar(s[t])||jr(e[s[t]],a,s[t],r,i);let c=Object.keys(a);for(let t=0,n=c.length;t<n;t++)e[c[t]]===void 0&&Cr(a,c[t],void 0)}function Mr(e,t={}){let{merge:n,key:r=`id`}=t,i=gr(e);return e=>{if(!hr(e)||!hr(i))return i;let t=jr(i,{[kr]:e},kr,n,r);return t===void 0?e:t}}var Nr=new WeakMap,Pr={get(e,t){if(t===ur)return e;let n=e[t];if(t===i||t===o||t===dr||t===fr||t===`__proto__`)return n;let r;return hr(n)?Nr.get(n)||(Nr.set(n,r=new Proxy(n,Pr)),r):n},set(e,t,n){return Cr(e,t,gr(n)),!0},deleteProperty(e,t){return Cr(e,t,void 0,!0),!0}};function Fr(e){return t=>{if(hr(t)){let n;(n=Nr.get(t))||Nr.set(t,n=new Proxy(t,Pr)),e(n)}return t}}var Ir={blocked:0,working:1,error:2,idle:3},Lr=e=>Ir[e]??3,Rr=e=>String(e??``).replace(/(.)[\\/]+$/,`$1`);function zr(e){let t=Array.isArray(e?.status)?e.status:[];return t.length?t.some(e=>e.state===`blocked`)?`blocked`:t[0]?.state===`error`?`error`:t.some(e=>e.state===`working`)?`working`:`idle`:e?.blockers?.length?`blocked`:e?.state!==void 0&&e.state in Ir?e.state:`idle`}function Br(e){let t=Array.isArray(e?.status)?e.status:[];return(t.length?t:[{id:e?.id,title:e?.title,blockers:e?.blockers}]).flatMap(e=>(e.blockers??[]).map(t=>({...t,sessionID:e.id,sessionTitle:e.title})))}function Vr(e){let t=`idle`;for(let n of e)Lr(n)<Ir[t]&&(t=n);return t}function Hr(e){if(!e)return;if(e.kind===`thinking`)return`Thinking…`;let t=e.tool||`tool`;return e.summary?`${t} · ${e.summary}`:t}function Ur(e){return String(e??``).normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase()}var Wr=e=>Ur(e).split(/\s+/).filter(Boolean);function Gr(e,t){let n=Wr(t);if(!n.length)return!0;let r=[e.title||`Untitled`,e.projectName,e.project,e.directory].filter(Boolean).map(Ur);return n.every(e=>r.some(t=>t.includes(e)))}function Kr(e,t){let n=Rr(e),r=Rr(t);return n===r?``:n.startsWith(`${r}/`)?n.slice(r.length+1):n}var qr=e=>String(e??``).replace(/(.)[\\/]+$/,`$1`),Jr=e=>qr(e).split(/[\\/]/).pop()||String(e??``),Yr=[`hiddenSessions`,`hiddenWorkspaces`,`pinnedSessions`,`pinnedWorkspaces`],Xr=500,Zr=5e3,Qr=4096,$r=e=>e===`hiddenSessions`?Zr:Xr,ei=(e,t=Xr)=>{if(!Array.isArray(e))return[];let n=[...new Set(e.filter(e=>typeof e==`string`&&e.length>0&&e.length<=Qr))];return n.length>t?n.slice(n.length-t):n};function ti(e){let t=e,n=t&&typeof t==`object`&&t.prefs&&typeof t.prefs==`object`?t.prefs:e??{};return Object.fromEntries(Yr.map(e=>[e,ei(n[e],$r(e))]))}function ni(e){let t=e.trim();return t?t.length>200?{error:`Title is longer than 200 characters`}:{title:t}:{error:`Enter a title`}}function ri(e,t,n){let r;for(let i of e??[])for(let e of i.processes)for(let i of e.sessions)if(i.id===t){r??=i.title??``,i.title=n;for(let e of i.status??[])e.id===t&&(e.title=n)}return r}var ii=class{graceMs;pending=new Map;constructor(e=5e3){this.graceMs=e}set(e,t,n){this.pending.set(e,{title:t,at:n})}has(e){return this.pending.has(e)}drop(e,t){this.pending.get(e)?.title===t&&this.pending.delete(e)}apply(e,t){for(let[n,{title:r,at:i}]of[...this.pending]){let a=ai(e,n);a===r||t-i>this.graceMs?this.pending.delete(n):a!==void 0&&ri(e,n,r)}}},ai=(e,t)=>{for(let n of e??[])for(let e of n.processes)for(let n of e.sessions)if(n.id===t)return n.title??``};function oi(e,t,n,r){if(!Yr.includes(t))throw Error(`unknown prefs list: ${t}`);let i=e[t]??[],a=new Set(i),o=new Set(n.filter(e=>a.has(e)!==r));if(!o.size)return{prefs:e,patch:void 0};let s=r?ei([...i,...o],$r(t)):i.filter(e=>!o.has(e));return{prefs:{...e,[t]:s},patch:{[t]:s}}}var si=e=>{try{let t=JSON.parse(e??`null`);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}};function ci(e,t,n){let r=e!=null||t!=null,i={};for(let[r,a]of[[`pinnedSessions`,e],[`pinnedWorkspaces`,t]]){let e=n[r]??[],t=si(a).filter(t=>!e.includes(t));t.length&&(i[r]=ei([...e,...t]))}return{clear:r,patch:Object.keys(i).length?i:void 0}}var li={working:`working`,blocked:`blocked`};function ui(e){return Vr([zr(e),li[e?.terminal?.status??``]??`idle`])}var di=e=>!!e?.open&&e.terminal?.source===`herdr`&&!!e.terminal.workspaceID,fi=e=>qr(e?.project||e?.directory);function pi(e){return di(e)?`herdr:${e.terminal.workspaceID}`:fi(e)}var mi=(e,t)=>fi(e)===t||qr(e.directory)===t||di(e)&&pi(e)===t;function hi(e,t){if(t.sessions.has(e.id))return!0;for(let n of t.workspaces)if(mi(e,n))return!0;return!1}function gi(e,t){let n=(t.updated??0)>(e.updated??0)?t:e,r=e.open?e:t.open?t:void 0;return{...n,conversation:!!(e.conversation||t.conversation),busy:!!(e.busy||t.busy),...r?{open:!0,terminal:r.terminal}:{}}}function _i(e){let t=e?.processes??[],n=new Set(t.flatMap(e=>e.sessions.map(e=>e.id))),r=new Map;for(let e of t)for(let t of e.sessions){if(t.parentID&&n.has(t.parentID))continue;let e=r.get(t.id);r.set(t.id,e?gi(e,t):t)}return[...r.values()]}function vi(e){let t=yi(e);return e=>hi(e,t)}var yi=e=>({sessions:new Set(e?.hiddenSessions??[]),workspaces:new Set(e?.hiddenWorkspaces??[])}),bi=e=>e?.terminals?.herdr?.workspaces??[];function xi(e){let t=qr(e.project||e.directory),n=e.project?Kr(e.directory,t):``;return`${e.projectName||Jr(t)}${n?` › ${n}`:``}`}function Si(e,t,n){let r=xi(t),i=n?.trim()||void 0;return{machine:e,where:r,...i?{branch:i}:{},text:[e,r,i].filter(Boolean).join(` · `)}}function Ci(e,t,n){let r=di(e)?e.terminal.workspace||bi(t).find(t=>t.id===e.terminal.workspaceID)?.label||e.terminal.workspaceID:void 0;return{...e,title:e.title||e.terminal?.title||`Untitled`,updated:e.updated??0,state:ui(e),blockers:Br(e),exposed:e.exposed!==!1,pinned:n.has(e.id),nowText:Hr(e.now),where:xi(e),workspace:r??(e.projectName||Jr(fi(e))),machineID:t?.id}}var wi=50,Ti=200;function Ei(e){let t=bi(e).map(e=>({kind:`herdr`,key:`herdr:${e.id}`,workspaceID:e.id,label:e.label||e.id,directories:[...e.directories??[]]})),n=new Set(t.flatMap(e=>e.directories.map(qr))),r=_i(e),i=new Map,a=new Map;for(let e of r){let t=qr(e.directory);t&&(i.set(t,Math.max(i.get(t)??0,e.updated??0)),a.set(t,xi(e)))}for(let e of r){let t=qr(e.project);if(!t||a.has(t))continue;let n=Math.max(...r.filter(e=>qr(e.project)===t).map(e=>e.updated??0));i.set(t,n),a.set(t,e.projectName||Jr(t))}let o=[...i.entries()].filter(([e])=>!n.has(e)).sort((e,t)=>t[1]-e[1]).slice(0,wi).map(([e])=>({kind:`folder`,key:e,label:a.get(e)??Jr(e),directories:[e]}));return{herdr:!!e?.terminals?.herdr,targets:[...t,...o]}}function Di({target:e,directory:t,title:n,openInHerdr:r}){let i={directory:t},a=String(n??``).trim().slice(0,Ti);return a&&(i.title=a),r&&e?.kind===`herdr`&&e.workspaceID&&(i.herdrWorkspace=e.workspaceID),i}function Oi(e){if(typeof e==`string`&&e)return e.includes(`budget`)?`Quota exceeded`:ki[e]}var ki={"provider.quota":`Quota exceeded`,"provider.free-limit":`Quota exceeded`,"provider.auth":`Authentication failed`,"provider.rate-limit":`Rate limited`,"provider.internal":`Provider unavailable`,"provider.transport":`Provider unavailable`,"provider.timeout":`Provider unavailable`,"provider.content-filter":`Blocked by content filter`,"provider.no-route":`No route to model`,"provider.invalid-request":`Invalid request`,"provider.invalid-output":`Invalid model output`,"provider.unsupported-operation":`Unsupported operation`,"tool.execution":`Tool failed`,"permission.rejected":`Permission rejected`};function Ai(e){return typeof e==`number`&&Number.isInteger(e)&&e>=100&&e<=999?`HTTP ${e}`:void 0}function ji(e,t){if(typeof e!=`number`||!Number.isFinite(e)||e<=t)return;let n=Math.ceil((e-t)/1e3);if(n<60)return`${n}s`;let r=Math.floor(n/60);return r<60?`${r}m ${n%60}s`:`${Math.floor(r/60)}h ${r%60}m`}var Mi=e=>typeof e==`string`&&e.trim()?e.trim():void 0,Ni=(e,t)=>e.toLowerCase()===t.toLowerCase(),Pi=(e,t)=>e&&t&&!Ni(e,t)?t:void 0;function Fi(e){let t=Oi(e.errorType),n=Mi(e.message),r=Ai(e.errorStatus),i=Pi(t,n);return`${t??n??`Error`}${r?` (${r})`:``}${i?`: ${i}`:``}`}function Ii(e,t){let n=typeof e.attempt==`number`?` (attempt ${e.attempt})`:``,r=ji(e.next,t),i=Oi(e.errorType),a=Mi(e.message),o=Pi(i,a),s=i?o?`${i} — ${o}`:i:a;return`Retrying${n}${r?` · next in ${r}`:``}${s?`: ${s}`:``}`}var Li=e=>!!e&&typeof e==`object`&&typeof e.id==`string`;function Ri(e,t){let n=Array.isArray(e)?e.filter(Li):[],r=t?n.find(e=>e.id===t):n[0];if(!r)return;if(r.state===`error`)return zi(r);if(r.state===`working`||r.state===`blocked`)return;let i=new Set([r.id]);for(let e=!0;e;){e=!1;for(let t of n)t.parentID&&i.has(t.parentID)&&!i.has(t.id)&&(i.add(t.id),e=!0)}let a=n.find(e=>e.id!==r.id&&i.has(e.id)&&e.state===`error`);return a?zi(a):void 0}function zi(e){let t=Mi(e.detail),n=Ai(e.errorStatus),r=Mi(e.title);return{sessionID:e.id,...r?{title:r}:{},label:Oi(e.errorType)??t??`Error`,...t?{message:t}:{},...n?{status:n}:{},text:Fi({errorType:e.errorType,errorStatus:e.errorStatus,message:t})}}var Bi=e=>Array.isArray(e)?e:[];function Vi(e){return Bi(e).flatMap(e=>(Array.isArray(e.jobs)?e.jobs:[]).map(t=>({...t,sessionID:e.id,sessionTitle:e.title??``})))}function Hi(e){return Vi(e).filter(e=>e.status===`running`).length}function Ui(e,t){let n=Vi(e),r=n.filter(e=>e.status===`running`).sort((e,t)=>(e.started??0)-(t.started??0)),i=n.filter(e=>e.status!==`running`&&e.ended!==void 0&&t-e.ended<=6e4).sort((e,t)=>(t.ended??0)-(e.ended??0));return[...r,...i]}function Wi(e){let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${t}s`;let n=Math.floor(t/60);return n<60?`${n}m ${t%60}s`:`${Math.floor(n/60)}h ${n%60}m`}function Gi(e,t){if(e.status===`running`)return e.started===void 0?`running`:`running · ${Wi(t-e.started)}`;let n=e.status===`killed`?`killed`:e.status===`timeout`?`timed out`:void 0,r=e.exit===void 0?void 0:`exit ${e.exit}`,i=e.started!==void 0&&e.ended!==void 0?Wi(e.ended-e.started):void 0;return n?[n,r].filter(Boolean).join(` · `):[r??`ended`,i].filter(Boolean).join(` · `)}function Ki(e){return e<=0?``:`${e} job${e===1?``:`s`}`}function qi(e,t,n=Date.now()){let r=Bi(e),i=(t?r.find(e=>e.id===t&&e.retry):void 0)??r.find(e=>e.retry);return i?.retry?Ii(i.retry,n):void 0}function Ji(e,t,n){let r=new Set(t.pinnedSessions),i=new Set(t.hiddenSessions),a=vi(t),o=[];for(let t of e??[])for(let e of _i(t)){let s=Ci(e,t,r),c=s.open?s.terminal?.source===`herdr`?`herdr`:`tui`:`background`,l=n[s.id],u=s.state===`working`?qi(e.status,void 0,1/0):void 0,d=s.state===`error`?Ri(e.status,s.id)?.text??`Error`:void 0;o.push({...s,machineName:t.name,machineOnline:!!t.online,source:c,running:s.state===`working`||s.state===`blocked`,hidden:a(e),archived:i.has(s.id),unread:l!==void 0&&s.updated>l,group:pi(e),jobs:Hi(e.status),...u?{retry:u}:{},...d?{error:d}:{}})}return o.sort((e,t)=>t.updated-e.updated)}function Yi(e,t){if(!e?.length)return t;let n=new Map(e.map(e=>[e.id,e]));return t.map(e=>{let t=n.get(e.id);return t&&JSON.stringify(t)===JSON.stringify(e)?t:e})}var Xi=Object.freeze({query:``,filters:Object.freeze({status:`all`,source:`all`,machine:``,archived:!1}),sort:Object.freeze({key:`activity`,dir:`desc`})}),Zi=[`status`,`title`,`project`,`server`,`source`,`activity`],Qi=[`all`,`needs`,`running`,`idle`],$i=[`all`,`open`,`background`],ea=(e,t)=>e.localeCompare(t,void 0,{sensitivity:`base`}),ta=(e,t)=>t.updated-e.updated,na={status:(e,t)=>Ir[e.state]-Ir[t.state]||ta(e,t),title:(e,t)=>ea(e.title,t.title)||ta(e,t),project:(e,t)=>ea(e.workspace,t.workspace)||ta(e,t),server:(e,t)=>ea(e.machineName,t.machineName)||ta(e,t),source:(e,t)=>ea(e.source,t.source)||ta(e,t),activity:(e,t)=>e.updated-t.updated};function ra(e,t){let n=t.status===`needs`&&e.state===`blocked`;return!((t.archived?!e.hidden:e.hidden&&!n)||t.status===`needs`&&!la(e)||t.status===`running`&&!e.running||t.status===`idle`&&e.running||t.source===`open`&&e.source===`background`||t.source===`background`&&e.source!==`background`||t.machine&&e.machineID!==t.machine)}function ia(e,t){if(!t.trim()||Gr(e,t))return!0;let n=Ur(t).split(/\s+/).filter(Boolean),r=[e.title,e.workspace,e.where,e.directory,e.machineName].map(Ur);return n.every(e=>r.some(t=>t.includes(e)))}function aa(e,t){let n=na[t.sort.key],r=t.sort.key===`activity`?t.sort.dir===`desc`?-1:1:t.sort.dir===`asc`?1:-1;return e.filter(e=>ra(e,t.filters)&&ia(e,t.query)).sort((e,t)=>r*n(e,t))}var oa=(e,t,n)=>t.includes(e)?e:n;function sa(e){let t;try{if(t=JSON.parse(e??`null`)??{},typeof t!=`object`||Array.isArray(t))return Xi}catch{return Xi}let n=t.filters??{},r=t.sort??{},i=Xi,a=oa(r.key,Zi,i.sort.key),o=a===r.key?oa(r.dir,[`asc`,`desc`],i.sort.dir):i.sort.dir,s=a===i.sort.key&&o===i.sort.dir?i.sort:{key:a,dir:o},c={status:oa(n.status,Qi,i.filters.status),source:oa(n.source,$i,i.filters.source),machine:typeof n.machine==`string`&&n.machine.length<=200?n.machine:``,archived:n.archived===!0||n.hidden===!0},l=Object.keys(c).every(e=>c[e]===i.filters[e]);return l&&s===i.sort?Xi:{query:``,filters:l?i.filters:c,sort:s}}function ca(e){return JSON.stringify({filters:e.filters,sort:e.sort})}var la=e=>e.state===`blocked`||e.state===`error`&&!e.hidden;function ua(e,{query:t,groupBy:n,sortBy:r,recentLimit:i=20}){let a=e.filter(e=>!e.hidden),o=e.filter(la),s=r===`title`?(e,t)=>ea(e.title,t.title)||ta(e,t):ta;if(t.trim())return[{id:`results`,title:`Results`,kind:`results`,rows:a.filter(e=>ia(e,t)).sort(ta)}];let c=new Set,l=e=>{for(let t of e)c.add(t.id);return e},u=[],d=e=>e.rows.length&&u.push(e);d({id:`needs`,title:`Needs you`,kind:`needs`,rows:l(o.sort(ta))}),d({id:`running`,title:`Running`,kind:`running`,rows:l(a.filter(e=>!c.has(e.id)&&e.running).sort(ta))}),d({id:`pinned`,title:`Pinned`,kind:`pinned`,rows:l(a.filter(e=>!c.has(e.id)&&e.pinned).sort(s))});let f=new Map;for(let e of a){if(c.has(e.id)||!e.open)continue;let t=n===`machine`?e.machineID:`${e.machineID}\u0000${e.group}`,r=f.get(t);r||(r={title:n===`machine`?e.machineName:e.workspace,key:n===`machine`?e.machineID:e.group,machineID:e.machineID,directory:e.directory,rows:[]},f.set(t,r)),r.rows.push(e)}let p=e=>Math.max(...e.map(e=>e.updated)),m=[...f.values()].sort((e,t)=>r===`title`&&ea(e.title,t.title)||p(t.rows)-p(e.rows));for(let e of m){e.rows.sort(s),l(e.rows);let t=[...e.rows].sort(ta);d({id:`group:${e.machineID}:${e.key}`,title:e.title,kind:`group`,key:e.key,machineID:e.machineID,directory:t[0].directory,rows:e.rows})}return d({id:`recents`,title:`Recents`,kind:`recents`,rows:a.filter(e=>!c.has(e.id)).sort(ta).slice(0,i)}),u}var da=864e5;function fa(e,t,n){if(!Number.isInteger(t)||t<1)return[];let r=n-t*da;return e.filter(e=>!e.hidden&&!e.running&&!e.pinned&&!e.open&&e.updated<r)}function pa(e,t){return t.phase!==`off`&&t.sessionID===e.id||e.conversation===!0}var ma=.75,ha=.05;function ga(e){let t=typeof e==`string`?e.trim()?Number(e):NaN:Number(e??NaN);if(!Number.isFinite(t))return 1;let n=Math.round(t/ha)/Math.round(1/ha);return Math.min(2,Math.max(ma,Number(n.toFixed(2))))}function _a(e){let t=ga(e);return`${Number.isInteger(t)?t.toFixed(1):String(t)}×`}var va={working:`working`,blocked:`blocked`,error:`failed`,idle:`done`},ya=160,ba=class{rootID;max;maxSubagents;maxText;items=[];subagents=new Map;seq=0;rootState;rootSince;busyAt;writing;lastAt;constructor(e,{max:t=30,maxSubagents:n=10,maxText:r=4e3}={}){this.rootID=e,this.max=t,this.maxSubagents=n,this.maxText=r}touch(e){e!==void 0&&Number.isFinite(e)&&!((this.lastAt??-1/0)>=e)&&(this.lastAt=e)}reasoning(e,t,n,r=Date.now()){let i=`thinking:${t}`;this.items.some(e=>e.id===i)||this.activity(e,{id:i,kind:`thinking`,state:`running`,at:r});let a=this.items.find(e=>e.id===i);a&&(a.text=`${a.text??``}${n??``}`.slice(-this.maxText)),this.touch(r)}text(e,t,n,r=Date.now()){for(let t of this.items)t.sessionID===e&&t.kind===`thinking`&&t.state===`running`&&(t.state=`done`);if(this.touch(r),e===this.rootID){this.writing={messageID:t,at:r};return}let i=this.subagents.get(e);i||(i={id:e,state:`working`,at:r},this.subagents.set(e,i),this.trim()),i.msg!==t&&(i.out=``),i.msg=t,i.out=`${i.out??``}${n??``}`.slice(-600);let a=i.out.split(`
6
+ `).map(e=>e.trim()).filter(Boolean).at(-1);a&&(i.line=a.length>ya?`…${a.slice(-159)}`:a)}activity(e,t){if(!t||typeof t.id!=`string`)return;let n=t.sessionID??e??this.rootID,r=this.items.find(e=>e.id===t.id);if(r){r.state=t.state??r.state,t.error!==void 0&&(r.error=t.error),t.summary&&(r.summary=t.summary),t.tool&&(r.tool=t.tool),this.touch(t.at);return}let i=Number.isFinite(t.at)?t.at:Date.now();this.touch(i);for(let e of this.items)e.sessionID===n&&e.kind===`thinking`&&e.state===`running`&&e.at<=i&&(e.state=`done`);let a={id:t.id,sessionID:n,kind:t.kind===`thinking`?`thinking`:`tool`,tool:t.tool,summary:t.summary,state:t.state??`running`,error:t.error,at:i,seq:++this.seq},o=this.items.length;for(;o>0&&this.items[o-1].at>i;)o--;this.items.splice(o,0,a),n!==this.rootID&&!this.subagents.has(n)&&this.subagents.set(n,{id:n,state:`working`,at:i}),this.trim()}load(e){for(let t of[...e??[]].sort((e,t)=>(e.at??0)-(t.at??0)))this.activity(t.sessionID??this.rootID,t)}status(e,t=Date.now()){let n=new Set,r=this.stateKey(),i;for(let r of e??[]){if(r.id===this.rootID){i=r;continue}n.add(r.id);let e=va[r.state]??`working`,a=this.subagents.get(r.id);a?(a.state=e,r.title&&(a.title=r.title),a.since=r.since):e!==`done`&&this.subagents.set(r.id,{id:r.id,title:r.title,state:e,at:t,since:r.since})}for(let e of this.subagents.values())!n.has(e.id)&&(e.state===`working`||e.state===`blocked`)&&(e.state=`done`);let a=i?.state===`working`||i?.state===`blocked`||[...this.subagents.values()].some(e=>e.state===`working`||e.state===`blocked`);if(i&&!a)for(let e of this.items)e.state===`running`&&(e.state=`done`);i&&(this.rootState=i.state,this.rootSince=i.since,i.state!==`working`&&(this.writing=void 0)),this.rootState===`working`||[...this.subagents.values()].some(e=>e.state===`working`)?this.busyAt===void 0&&(this.busyAt=t):this.busyAt=void 0,r!==void 0&&r!==this.stateKey()&&this.touch(t),this.trim()}stateKey(){if(this.rootState!==void 0)return[this.rootState,...[...this.subagents.values()].map(e=>`${e.id}=${e.state}`)].join(` `)}trim(){for(;this.items.length>this.max;){let e=this.items.findIndex(e=>e.state!==`running`);this.items.splice(e===-1?0:e,1)}if(this.subagents.size>this.maxSubagents){let e=[...this.subagents.values()].filter(e=>e.state===`done`||e.state===`failed`).sort((e,t)=>e.at-t.at);for(let t of e.slice(0,this.subagents.size-this.maxSubagents))this.subagents.delete(t.id)}}rows(){let e=e=>!(e.kind===`thinking`&&e.state!==`running`&&!e.text),t=(e,t)=>({key:e.id,depth:t,kind:e.kind,label:e.kind===`thinking`&&e.state!==`running`?`Thought`:Sa(e),state:e.state,error:e.error,sessionID:e.sessionID,...e.text?{text:e.text}:{}}),n=[];for(let r of this.items)r.sessionID===this.rootID&&e(r)&&n.push({at:r.at,seq:r.seq,rows:[t(r,0)]});for(let r of this.subagents.values())n.push({at:r.at,seq:0,rows:[{key:`sub:${r.id}`,depth:0,kind:`subagent`,label:r.title||r.id,state:r.state,sessionID:r.id,...r.line?{line:r.line}:{}},...this.items.filter(t=>t.sessionID===r.id&&e(t)).map(e=>t(e,1))]});return n.sort((e,t)=>e.at-t.at||e.seq-t.seq).flatMap(e=>e.rows)}now(){for(let e=this.items.length-1;e>=0;e--)if(this.items[e].state===`running`)return Sa(this.items[e]);let e=[...this.subagents.values()].reverse().find(e=>e.state===`working`);return e?`Subagent: ${e.title||e.id}`:void 0}pulse(){let e=[...this.subagents.values()].filter(e=>e.state===`working`),t=this.rootState===`working`,n=t||e.length>0,r=!n&&(this.rootState===`blocked`||[...this.subagents.values()].some(e=>e.state===`blocked`)),i=r?`Needs you`:`Idle`,a;if(n){let n=this.items.filter(e=>e.sessionID===this.rootID),r=[...n].reverse().find(e=>e.state===`running`),o=r?r.kind===`thinking`?`Thinking`:`Running ${Sa(r)}`:void 0,s=this.writing;s&&!n.some(e=>e.at>s.at)&&(o=`Writing reply`);let c=e.length,l=c===0?``:o||c>1?`${c} subagent${c===1?``:`s`} working`:`Subagent “${e[0].title||e[0].id}” working`;i=o&&l?`${o} · ${l}`:o||l||`Working`;let u=[t?this.rootSince:void 0,...e.map(e=>e.since)].filter(e=>typeof e==`number`&&Number.isFinite(e));a=u.length?Math.min(...u):this.busyAt}return{busy:n,blocked:r,label:i,since:a,lastAt:this.lastAt}}};function xa(e){let t=Math.max(0,Math.floor((Number(e)||0)/1e3)),n=e=>String(e).padStart(2,`0`);return t<60?`${t}s`:t<3600?`${Math.floor(t/60)}m ${n(t%60)}s`:`${Math.floor(t/3600)}h ${n(Math.floor(t%3600/60))}m`}function Sa(e){if(e.kind===`thinking`)return`Thinking…`;let t=e.tool||`tool`;return e.summary?`${t} · ${e.summary}`:t}var Ca=Object.freeze({working:Object.freeze([`On it.`,`Give me a sec.`,`One moment.`,`Let me check.`,`Okay, looking into it.`,`Sure, one sec.`,`Hang on.`,`Let me see.`,`Checking now.`,`Bear with me.`]),subagent:Object.freeze([`I'll hand that off.`,`Starting that in the background.`,`Sending that off now.`,`Getting a helper on it.`,`Passing that along.`]),still:Object.freeze([`Still on it.`,`Almost there.`,`Still working through it.`,`Bear with me, still going.`,`Taking a bit longer.`])});function wa(){let e=Object.values(Ca),t=[];for(let n=0;n<Math.max(...e.map(e=>e.length));n++)for(let r of e)n<r.length&&t.push(r[n]);return t}var Ta=class{rng;ready;bags=new Map;last=new Map;used=new Map;count=0;constructor({rng:e=Math.random,ready:t=()=>!0}={}){this.rng=e,this.ready=t}pick(e){let t=Ca[e],n=this.last.get(e),r=this.bags.get(e);r?.length||(r=this.shuffle(t),r.length>1&&r[0]===n&&r.push(r.shift()),this.bags.set(e,r));let i=e=>e!==n||t.length<2,a=r.findIndex(e=>i(e)&&this.ready(e)),o;if(a>=0)o=r.splice(a,1)[0];else{let e=t.filter(e=>i(e)&&this.ready(e)).sort((e,t)=>(this.used.get(e)??0)-(this.used.get(t)??0))[0];e?o=e:(a=r.findIndex(i),o=a>=0?r.splice(a,1)[0]:t.find(i))}return o??=t[0],this.last.set(e,o),this.used.set(o,++this.count),o}shuffle(e){let t=[...e];for(let e=t.length-1;e>0;e--){let n=Math.floor(this.rng()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}},Ea=class{ackMs;quietMs;stillMs;enabled=!0;busy=!1;awaiting;pendingSubagent=!1;lastSay=-1/0;lastSpoke=-1/0;user=!1;agent=!1;cue=!1;pick;constructor({ackMs:e=2500,quietMs:t=3e3,stillMs:n=4e4,pick:r}={}){if(!r){let e=new Ta;r=t=>e.pick(t)}this.pick=r,this.ackMs=e,this.quietMs=t,this.stillMs=n}get gated(){return this.user||this.agent||this.cue}heard(e,{tone:t=!0}={}){return this.awaiting=Math.min(this.awaiting??e,e),t&&this.enabled&&!this.user?[{type:`earcon`,name:`heard`}]:[]}awaitReply(e){this.awaiting=e}speechEnded(e){return this.userTalking(!1,e),this.enabled?[{type:`earcon`,name:`heard`}]:[]}working(e,t){e&&!this.busy&&(this.lastSpoke=Math.max(this.lastSpoke,t)),e||(this.awaiting=void 0,this.pendingSubagent=!1),this.busy=e}agentSaid(e){this.lastSay=e,this.spoke(e)}agentSpeaking(e,t){this.agent=e,this.spoke(t)}userTalking(e,t){this.user=e,e||(this.lastSpoke=Math.max(this.lastSpoke,t))}cueSpeaking(e,t){this.cue=e,e||(this.lastSpoke=Math.max(this.lastSpoke,t))}subagentStarted(e){e-this.lastSay>=this.quietMs&&(this.pendingSubagent=!0)}subagentFinished(e){return this.enabled&&!this.user?[{type:`earcon`,name:`done`}]:[]}nextDue(e){if(this.enabled&&!this.gated){if(this.pendingSubagent)return e;if(this.busy)return Math.min(this.awaiting===void 0?1/0:this.awaiting+this.ackMs,this.lastSpoke+this.stillMs)}}tick(e){return!this.enabled||this.gated?[]:this.pendingSubagent?this.say(`subagent`,e):this.awaiting!==void 0&&this.busy&&e-this.awaiting>=this.ackMs?this.say(`working`,e):this.busy&&e-this.lastSpoke>=this.stillMs?this.say(`still`,e):[]}spoke(e){this.awaiting=void 0,this.pendingSubagent=!1,this.lastSpoke=Math.max(this.lastSpoke,e)}say(e,t){return this.spoke(t),[{type:`speak`,cue:e,text:this.pick(e)}]}},Da=class{scheduler;playFn;ready;now;setTimer;clearTimer;timer;constructor({scheduler:e,play:t,ready:n=()=>!0,now:r=()=>Date.now(),setTimer:i=(e,t)=>setTimeout(e,t),clearTimer:a=e=>clearTimeout(e)}){this.scheduler=e,this.playFn=t,this.ready=n,this.now=r,this.setTimer=i,this.clearTimer=a}poke(){if(this.stop(),this.ready())for(let e=0;e<3;e++){let e=this.now(),t=this.scheduler.nextDue(e);if(t===void 0||!Number.isFinite(t))return;if(t>e){this.timer=this.setTimer(()=>{this.timer=void 0,this.poke()},t-e);return}let n=this.scheduler.tick(e);n.length&&this.playFn(n)}}stop(){this.timer!==void 0&&this.clearTimer(this.timer),this.timer=void 0}},Oa=new Set([`working`,`blocked`]);function ka(e,t,n){let r=new Map((e??[]).filter(e=>e.id!==n).map(e=>[e.id,e.state])),i=[],a=[];for(let e of t??[]){if(e.id===n)continue;let t=r.get(e.id);r.delete(e.id),e.state===`working`&&!Oa.has(t??``)?i.push(e.id):Oa.has(t??``)&&!Oa.has(e.state)&&a.push(e.id)}for(let[e,t]of r)Oa.has(t)&&a.push(e);return{started:i,finished:a}}function Aa(e){return(e??[]).some(e=>e.state===`working`)}var ja=Object.freeze([`openrouter`,`openai-compatible`]),Ma={stt:[`provider`,`model`,`baseURL`,`language`],tts:[`provider`,`model`,`voice`,`baseURL`,`speed`]},Na=e=>e==null?``:String(e).trim();function Pa(e){let t={};for(let n of[`stt`,`tts`]){let r=e?.[n]??{};t[n]=Object.fromEntries(Ma[n].map(e=>[e,Na(r[e])])),t[n].apiKey={action:`keep`,value:``}}return t}function Fa(e,t){let n={};for(let r of[`stt`,`tts`]){let i=e?.[r]??{},a=t[r],o={};for(let e of Ma[r]){if(e===`baseURL`&&Na(a.provider)!==`openai-compatible`)continue;let t=Na(a[e]);t!==Na(i[e])&&(o[e]=t===``?null:e===`speed`?Number(t):t)}a.apiKey?.action===`set`?o.apiKey=Na(a.apiKey.value):a.apiKey?.action===`clear`&&(o.apiKey=null),Object.keys(o).length&&(n[r]=o)}return n}function Ia(e){let t={};for(let n of[`stt`,`tts`]){let r=e[n],i=(e,r)=>t[`${n}.${e}`]=r;if(ja.includes(Na(r.provider))||i(`provider`,`Choose a provider.`),Na(r.model)||i(`model`,`Enter a model.`),Na(r.provider)===`openai-compatible`){let e=Na(r.baseURL);e?/^https?:\/\/[^\s/]+/i.test(e)||i(`baseURL`,`Enter an http:// or https:// URL.`):i(`baseURL`,`Enter the server's base URL.`)}if(n===`tts`){Na(r.voice)||i(`voice`,`Enter a voice.`);let e=Na(r.speed);e&&!(Number(e)>=.25&&Number(e)<=4)&&i(`speed`,`Use a number from 0.25 to 4.`)}r.apiKey?.action===`set`&&!Na(r.apiKey.value)&&i(`apiKey`,`Paste the new key, or cancel.`)}return t}function La(e,t){let n;for(let r of Object.keys(e??{}))String(t??``).startsWith(r)&&(n===void 0||r.length>n.length)&&(n=r);return n===void 0?[]:[...e[n]??[]]}var Ra=/^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i;function za(e,t){if(!e||e.stt&&e.tts)return;let n=!1;try{n=Ra.test(new URL(t??``).hostname)}catch{n=!1}return{reason:e.reason||`Choose a speech provider and add its API key in Settings → Speech.`,micBlocked:!e.stt,...n?{storage:`Keys are stored on this computer in ~/.local/state/hub`}:{}}}var Ba=()=>({machines:void 0,reads:{},prefs:ti({}),prefsSource:`unknown`,prefsPending:0,prefsStale:!1,connection:`connecting`,enrollmentRev:0}),Va=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Ha(e,t,n){for(let r of e??[])for(let e of r.processes)for(let r of e.sessions)r.id===t&&n(r)}function Ua(e,t){if(!Va(t)||typeof t.type!=`string`)return!1;switch(t.type){case`catalog`:return Array.isArray(t.machines)?(e.machines=t.machines,!0):!1;case`status`:{if(typeof t.sessionID!=`string`||!Array.isArray(t.sessions))return!1;let n=!1;return Ha(e.machines,t.sessionID,e=>{e.status=t.sessions,n=!0}),n}case`conversation`:{if(typeof t.sessionID!=`string`||typeof t.on!=`boolean`)return!1;let n=!1;return Ha(e.machines,t.sessionID,e=>{e.conversation=t.on,n=!0}),n}case`reads`:return Va(t.reads)?(e.reads=Object.fromEntries(Object.entries(t.reads).filter(e=>typeof e[1]==`number`)),!0):!1;case`prefs`:return e.prefsSource===`hub`?e.prefsPending?(e.prefsStale=!0,!0):(e.prefs=ti(t.prefs),!0):!1;case`enrollment`:return e.enrollmentRev++,!0;case`handoff`:return typeof t.sessionID==`string`&&(e.notice={kind:`handoff`,sessionID:t.sessionID,at:Date.now()},!0);default:return!1}}function Wa(e,t){let n;for(let r of e??[])for(let e of r.processes){let i=e.sessions.find(e=>e.id===t);i&&(!n||(i.updated??0)>(n.session.updated??0))&&(n={session:i,machine:r,process:e})}return n??Ga(e,t)}function Ga(e,t){for(let n of e??[])for(let e of n.processes)for(let r of e.sessions){let i=Array.isArray(r.status)?r.status:[],a=i.find(e=>e.id===t);if(!a||r.id===t)continue;let o=Ka(i,t),s=i.filter(e=>e.id&&o.has(e.id)),c=s.some(e=>e.state===`blocked`)?`blocked`:a.state===`error`?`error`:s.some(e=>e.state===`working`)?`working`:`idle`;return{session:{...r,id:t,title:a.title??``,...a.parentID?{parentID:a.parentID}:{},rootID:r.id,state:c,blockers:a.blockers??[],busy:!1,conversation:!1},machine:n,process:e}}}function Ka(e,t){let n=new Set([t]);for(let t=!0;t;){t=!1;for(let r of e??[])r.id&&r.parentID&&n.has(r.parentID)&&!n.has(r.id)&&(n.add(r.id),t=!0)}return n}function qa(e){return(e??[]).some(e=>e.state===`working`||e.state===`blocked`)}var Ja=class{max;feeds=new Map;constructor(e=50){this.max=e}has(e){return this.feeds.has(e)}feed(e,t){let n=this.feeds.get(e);if(!n)for(n=new ba(e),t&&n.status(t),this.feeds.set(e,n);this.feeds.size>this.max;)this.feeds.delete(this.feeds.keys().next().value);return n}apply(e){if(!Va(e))return;let t=typeof e.sessionID==`string`?e.sessionID:void 0;if(!t)return;let n=typeof e.rootID==`string`?e.rootID:t,r=typeof e.messageID==`string`?e.messageID:void 0;switch(e.type){case`activity`:return Va(e.item)?(this.feed(n).activity(t,e.item),n):void 0;case`delta`:return typeof e.text!=`string`||!e.text?void 0:(this.feed(n).text(t,r,e.text),n);case`reasoning`:return typeof e.delta!=`string`||!e.delta?void 0:(this.feed(n).reasoning(t,r??`unknown`,e.delta),n);case`status`:return Array.isArray(e.sessions)?(this.feed(t).status(e.sessions),t):void 0;default:return}}};function Ya(e,t){let n=new URLSearchParams;e.lite&&n.set(`lite`,`1`),e.session&&n.set(`session`,e.session),t&&n.set(`last`,t);let r=n.toString().replace(/\+/g,`%20`);return r?`/api/events?${r}`:`/api/events`}var Xa=class{deps;state=`stopped`;lastID;scope={lite:!1};hideTimer;staleTimer;constructor(e){this.deps=e}start(e){this.scope=e,this.reopen(`start`)}received(e){e&&(this.lastID=e),this.state===`open`&&this.watch()}setScope(e){let t=e.lite===this.scope.lite&&e.session===this.scope.session;this.scope=e,!t&&this.state===`open`&&this.reopen(`scope`)}hidden(){this.state===`open`&&this.hideTimer===void 0&&(this.hideTimer=this.deps.setTimer(()=>{this.hideTimer=void 0,!(this.state!==`open`||this.deps.keepOpen())&&(this.clear(),this.state=`paused`,this.deps.close())},this.deps.hiddenMs??3e4))}visible(){this.hideTimer!==void 0&&(this.deps.clearTimer(this.hideTimer),this.hideTimer=void 0),this.state===`paused`&&this.reopen(`resume`)}reopen(e=`reconnect`){this.state===`open`&&this.deps.close(),this.clear(),this.state=`open`,this.deps.open(Ya(this.scope,this.lastID),e),this.watch()}stop(){if(this.state===`stopped`)return;this.clear();let e=this.state===`open`;this.state=`stopped`,e&&this.deps.close()}watch(){this.staleTimer!==void 0&&this.deps.clearTimer(this.staleTimer),this.staleTimer=this.deps.setTimer(()=>{this.staleTimer=void 0,this.state===`open`&&this.reopen(`stale`)},this.deps.staleMs??45e3)}clear(){for(let e of[this.hideTimer,this.staleTimer])e!==void 0&&this.deps.clearTimer(e);this.hideTimer=this.staleTimer=void 0}};function Za(e,t){return t===`scope`&&e===`live`?{connection:`live`,reconnecting:!1}:{connection:`connecting`,reconnecting:e!==`connecting`}}var Qa=e=>e&&e.startsWith(`/`)&&!e.startsWith(`//`)&&!e.includes(`\\`)?e:`/`;function $a(e){let t=e.pathname,n=e.searchParams;if(t===`/pair`)return{name:`pair`,next:Qa(n.get(`next`)),error:n.get(`error`)??``};if(t===`/approve`)return{name:`approve`,code:n.get(`code`)??``};if(t===`/new`)return{name:`new`,machine:n.get(`machine`)??void 0,dir:n.get(`dir`)??void 0,key:n.get(`key`)??void 0};if(t===`/settings`)return{name:`settings`,section:e.hash.slice(1)||void 0};let r=/^\/s\/([^/]+)$/.exec(t);if(r)try{return{name:`session`,id:decodeURIComponent(r[1])}}catch{return{name:`home`}}return{name:`home`}}var[eo,to]=x(new URL(location.href)),no=eo,K=()=>$a(eo()),ro=0;function io(e,{replace:t=!1}={}){let n=new URL(e,location.origin);n.pathname+n.search+n.hash!==location.pathname+location.search+location.hash&&(history[t?`replaceState`:`pushState`]({},``,n.pathname+n.search+n.hash),t||ro++),to(new URL(location.href))}window.addEventListener(`popstate`,()=>{ro=Math.max(0,ro-1),to(new URL(location.href))}),document.addEventListener(`click`,e=>{let t=e.target?.closest?.(`a[href]`);if(!t||t.target||t.hasAttribute(`download`)||e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let n=t.getAttribute(`href`)??``;!n.startsWith(`/`)||n.startsWith(`//`)||n.startsWith(`/auth/`)||n.startsWith(`/api/`)||(e.preventDefault(),io(n))});var ao=e=>`/s/${encodeURIComponent(e)}`,[oo,so]=x(),co=oo,lo=0,uo;function q(e,t=``,n){let r=++lo;so({id:r,text:e,kind:t,action:n}),clearTimeout(uo),uo=setTimeout(()=>oo()?.id===r&&so(void 0),n||t?8e3:4e3)}var fo=()=>so(void 0),[J,Y]=Or(Ba()),po=new Ja,[mo,ho]=x(0),go=mo,[X,_o]=x(),[vo,yo]=x(),[bo,xo]=x(),[So,Co]=x([]),[wo,To]=x([]),[Eo,Do]=x([]),Oo=new Set;function ko(e){return Oo.add(e),()=>Oo.delete(e)}var Ao=b(()=>w(e=>Yi(e,Ji(J.machines,J.prefs,J.reads)))),jo=e=>Wa(J.machines,e),Mo=new ii;lr(()=>{K().name!==`pair`&&($o(),_o(void 0),No())});function No(){let e=location.pathname+location.search;io(`/pair${e===`/`||e.startsWith(`/pair`)?``:`?next=${U(e)}`}`,{replace:!0})}async function Po(){if(X())return!0;let e=await fetch(`/api/me`,{credentials:`same-origin`});if(e.status===401)return No(),!1;if(!e.ok)throw Error(`HTTP ${e.status}`);return _o(await e.json()),!0}async function Fo(){if(vo()!==void 0)return vo()??null;try{let e=await fetch(`/api/auth`,{credentials:`same-origin`}),t=e.ok?await e.json():null;return yo(t),t}catch{return null}}var Io,Lo,Ro=1e3,zo=()=>!1,[Bo,Vo]=x(``),Ho,Uo=!1,Wo=new Xa({setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e),open:(e,t)=>Zo(e,t),close:()=>Xo(),keepOpen:()=>zo()});function Go(e){zo=e}function Ko(e){Wo.setScope(e)}var qo=!1;function Jo(){qo||(qo=!0,document.addEventListener(`visibilitychange`,()=>document.visibilityState===`hidden`?Wo.hidden():Wo.visible()),window.addEventListener(`pageshow`,e=>{e.persisted&&Wo.state!==`stopped`&&Wo.reopen()}),window.addEventListener(`online`,()=>Wo.state===`open`&&J.connection===`down`&&Wo.reopen()))}function Yo(e={lite:!1}){Wo.state===`stopped`&&(Jo(),Wo.start(e),document.visibilityState===`hidden`&&Wo.hidden())}function Xo(){clearTimeout(Lo),Io?.close(),Io=void 0,Wo.state===`paused`&&Y(`connection`,`paused`)}function Zo(e,t){clearTimeout(Lo),Io?.close();let n=Za(J.connection,t);Uo=n.reconnecting,n.reconnecting&&Qo(`reconnecting`),Y(`connection`,n.connection);let r=new EventSource(e,{withCredentials:!0});Io=r,r.onopen=()=>{Ro=1e3,Y(`connection`,`live`),Uo&&Qo(`updated`,2e3),Uo=!1,ds(),ts(),os(),rs()},r.onerror=async()=>{Io===r&&(Y(`connection`,`down`),(await fetch(`/api/me`,{credentials:`same-origin`}).catch(()=>void 0))?.status===401?($o(),_o(void 0),No()):r.readyState===EventSource.CLOSED&&Io===r&&(Io=void 0,Lo=setTimeout(()=>Wo.state===`open`&&Wo.reopen(),Ro),Ro=Math.min(3e4,Ro*2)))},r.addEventListener(`ping`,()=>Wo.received()),r.onmessage=e=>{Wo.received(e.lastEventId||void 0);let t;try{t=JSON.parse(e.data)}catch{return}es(t)}}function Qo(e,t){clearTimeout(Ho),Vo(e),t&&(Ho=setTimeout(()=>Vo(``),t))}function $o(){Wo.stop(),Io?.close(),Io=void 0,clearTimeout(Lo)}function es(e){re(()=>{if(e.type===`prefs`?(Y(Fr(t=>Ua(t,e))),J.prefsStale&&!J.prefsPending&&fs()):e.type===`catalog`?Y(Fr(t=>{Ua(t,e),Mo.apply(t.machines,Date.now())})):Y(Fr(t=>Ua(t,e))),e.type===`status`){let t=jo(e.sessionID);!po.has(e.sessionID)&&t&&po.feed(e.sessionID)}if(po.apply(e)!==void 0&&ho(e=>e+1),e.type===`enrollment`&&os(),e.type===`decision`){let t=on(e.decision);t&&To(e=>ln(e,t))}if(e.type===`agent`){let t=Bn(e.entry);t&&Do(e=>Qn(e,t))}e.type===`resync`&&(ts(),fs(),os(),rs()),e.type===`handoff`&&(K().name!==`session`||K().id!==e.sessionID)&&q(`Handed off: ${jo(e.sessionID)?.session.title||e.sessionID}`,``,{label:`Open`,run:()=>io(`/s/${U(e.sessionID)}`)})});for(let t of Oo)t(e)}async function ts(){try{let{reads:e}=await H(`/api/reads`);Y(`reads`,e??{})}catch{}}async function ns(e){try{let{reads:t}=await(await V(`${W(e)}/read`,{method:`POST`,json:{}})).json();t&&typeof t==`object`&&Y(`reads`,t)}catch{}}async function rs(){try{let{decisions:e}=await H(`/api/decisions?state=open`);To(cn((e??[]).map(on).filter(e=>!!e)))}catch(e){e instanceof or&&e.status===404&&To([])}}function is(e){To(t=>ln(t,e))}function as(e){To(t=>t.filter(t=>t.id!==e)),rs()}async function os(){if(!Dt(X()))Co([]);else try{Co((await H(`/api/enrollments`)).enrollments??[])}catch{Co([])}}async function ss(){try{xo((await H(`/api/settings/speech`)).ready??null)}catch{xo(null)}}var cs=`voice.viewPrefs`,ls=!1,us=()=>J.prefsSource===`hub`||J.prefsSource===`local`;async function ds(){if(!(us()||ls)){ls=!0;try{Y({prefs:ti(await H(`/api/prefs/view`)),prefsSource:`hub`})}catch(e){if(e instanceof or&&e.status===404){let e;try{e=JSON.parse(localStorage.getItem(cs)??`null`)}catch{}Y({prefs:ti(e),prefsSource:`local`})}else Y(`prefsSource`,`error`)}finally{ls=!1}us()&&await ps()}}async function fs(){Y({prefsStale:!1,prefsSource:`unknown`}),await ds()}async function ps(){let{clear:e,patch:t}=ci(localStorage.getItem(`voice.pins`),localStorage.getItem(`voice.pinnedWorkspaces`),J.prefs);e&&(t&&(Y(`prefs`,e=>({...e,...t})),!(await ms(t)).ok)||(localStorage.removeItem(`voice.pins`),localStorage.removeItem(`voice.pinnedWorkspaces`)))}async function ms(e){if(J.prefsSource===`local`)return localStorage.setItem(cs,JSON.stringify(J.prefs)),{ok:!0};Y(`prefsPending`,e=>e+1);try{let t=await(await V(`/api/prefs/view`,{method:`PUT`,json:e})).json().catch(()=>void 0);return J.prefsPending===1&&t&&!J.prefsStale&&Y(`prefs`,ti(t)),{ok:!0}}catch(e){return{ok:!1,error:e}}finally{Y(`prefsPending`,e=>e-1),!J.prefsPending&&J.prefsStale&&fs()}}function hs(e,t,n,r={}){gs(e,[t],n,r)}function gs(e,t,n,{message:r,undo:i=!1}={}){if(!us()){q(`Your view settings are still loading. Try again in a moment.`,`err`),ds();return}let a=new Set(J.prefs[e]),o=t.filter(e=>a.has(e)!==n),{prefs:s,patch:c}=oi(J.prefs,e,o,n);c&&(Y(`prefs`,s),r&&q(r,``,i?{label:`Undo`,run:()=>gs(e,o,!n)}:void 0),ms(c).then(({ok:t,error:r})=>{t||(Y(`prefs`,oi(J.prefs,e,o,!n).prefs),q(`Could not save that change: ${G(r)}`,`err`))}))}async function _s(e,t){try{return await V(`${W(e)}/expose`,{method:`POST`,json:{on:t}}),q(t?`Voice enabled`:`Voice disabled`),!0}catch(e){return q(`Could not ${t?`enable`:`disable`} Voice: ${G(e)}`,`err`),!1}}async function vs(e,t){let n=ni(t);if(`error`in n)return q(n.error,`err`),!1;let{title:r}=n,i=jo(e)?.session.title;if(i===r)return!1;Mo.set(e,r,Date.now()),Y(Fr(t=>void ri(t.machines,e,r)));try{let t=await(await V(`${W(e)}/rename`,{method:`POST`,json:{title:r}})).json().catch(()=>void 0),n=typeof t?.title==`string`&&t.title?t.title:r;return n!==r&&jo(e)?.session.title===r&&(Mo.drop(e,r),Mo.set(e,n,Date.now()),Y(Fr(t=>void ri(t.machines,e,n)))),!0}catch(t){return Mo.drop(e,r),i!==void 0&&jo(e)?.session.title===r&&Y(Fr(t=>void ri(t.machines,e,i))),q(`Could not rename: ${G(t)}`,`err`),!1}}var[ys,bs]=x(new Set),xs=e=>ys().has(e),Ss=(e,t)=>bs(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r}),Cs=6e4;async function ws(e){if(xs(e))return;let t=jo(e)?.session.title;Ss(e,!0);let n=!1;try{let r=await(await V(`${W(e)}/rename`,{method:`POST`,json:{auto:!0}})).json().catch(()=>void 0);if(r?.pending){n=!0,q(`OpenCode is still naming it; the title changes when it's ready`);let r=Date.now()+Cs,i=()=>{let n=jo(e)?.session.title;n!==void 0&&n!==t?(Ss(e,!1),q(`Renamed to “${n}”`)):Date.now()>=r?Ss(e,!1):setTimeout(i,500)};setTimeout(i,500);return}let i=typeof r?.title==`string`?r.title:void 0;if(r?.unchanged||!i||i===t){q(`OpenCode kept the title`);return}Mo.set(e,i,Date.now()),Y(Fr(t=>void ri(t.machines,e,i))),q(`Renamed to “${i}”`)}catch(e){q(`Could not auto-name: ${G(e)}`,`err`)}finally{n||Ss(e,!1)}}async function Ts(e){try{let{stopped:t}=await(await V(`${W(e)}/stop`,{method:`POST`,json:{}})).json(),n=Array.isArray(t)?t.length:0;q(n?`Stopped ${n} session${n===1?``:`s`}`:`Nothing was running`)}catch(e){q(`Could not stop: ${G(e)}`,`err`)}}var Es=N(`<svg viewBox="72 51 368 368"aria-hidden=true><g transform="translate(0 20.7)"><g stroke=currentColor stroke-width=22 stroke-linecap=round><line x1=256 y1=256 x2=256 y2=90></line><line x1=256 y1=256 x2=399.8 y2=339></line><line x1=256 y1=256 x2=112.2 y2=339></line></g><g fill=currentColor><circle cx=256 cy=90 r=40></circle><circle cx=399.8 cy=339 r=40></circle><circle cx=112.2 cy=339 r=40></circle></g><circle class=hub-mark-gap cx=256 cy=256 r=71></circle><circle class=hub-mark-hub cx=256 cy=256 r=60>`);function Ds(e){let t=()=>e.size??18;return(()=>{var n=Es();return S(r=>{var i=`hub-mark${e.class?` ${e.class}`:``}`,a=t(),o=t();return i!==r.e&&F(n,`class`,r.e=i),a!==r.t&&F(n,`width`,r.t=a),o!==r.a&&F(n,`height`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})()}var Os=N(`<svg viewBox="0 0 24 24"aria-hidden=true>`),ks=N(`<svg><path></svg>`,!1,!0,!1),As=N(`<span class=voice-dot role=img aria-label="Voice mode on"title="Voice mode on">`),js=N(`<span class=spinner>`),Ms=N(`<span role=img>`),Ns=N(`<span class=status-dot>`),Ps=N(`<button type=button>`),Fs=N(`<button type=button aria-haspopup=menu>`),Is=N(`<div class=menu role=menu>`),Ls=N(`<div class=menu-sep role=separator>`),Rs=N(`<div class=menu-section>`),zs=N(`<span class=menu-hint>`),Bs=N(`<kbd class=menu-key>`),Vs=N(`<button type=button><span class=menu-check></span><span class=menu-label>`),Hs=N(`<div class=dialog-head><h2>`),Us=N(`<div class=dialog-body>`),Ws=N(`<dialog>`),Gs=N(`<span class=error-badge role=img>!`),Ks={menu:[`M4 6h16`,`M4 12h16`,`M4 18h16`],sidebar:[`M4 5h16v14H4z`,`M9 5v14`],rail:[`M4 5h16v14H4z`,`M15 5v14`],plus:[`M12 5v14`,`M5 12h14`],file:[`M6 3h8l4 4v14H6z`,`M14 3v4h4`],more:[`M5 12h.01`,`M12 12h.01`,`M19 12h.01`],search:[`M11 4a7 7 0 1 0 0 14a7 7 0 0 0 0-14z`,`M20 20l-4-4`],mic:[`M12 3a3 3 0 0 1 3 3v6a3 3 0 0 1-6 0V6a3 3 0 0 1 3-3z`,`M5 11a7 7 0 0 0 14 0`,`M12 18v3`],wave:[`M3 12h2`,`M7 8v8`,`M11 5v14`,`M15 8v8`,`M19 11v2`],stop:[`M7 7h10v10H7z`],send:[`M12 19V5`,`M5 12l7-7 7 7`],chevron:[`M9 6l6 6-6 6`],down:[`M6 9l6 6 6-6`],close:[`M6 6l12 12`,`M18 6L6 18`],back:[`M15 5l-7 7 7 7`],settings:[`M4 7h10M18 7h2M4 17h4M12 17h8`,`M16 5v4`,`M10 15v4`],branch:[`M6 3v12`,`M18 9a3 3 0 1 0 0-6a3 3 0 0 0 0 6z`,`M6 21a3 3 0 1 0 0-6a3 3 0 0 0 0 6z`,`M18 9a9 9 0 0 1-9 9`],server:[`M4 5h16v6H4z`,`M4 13h16v6H4z`,`M8 8h.01`,`M8 16h.01`],diff:[`M12 3v6`,`M9 6h6`,`M9 18h6`,`M5 3h14v18H5z`],pin:[`M12 17v5`,`M8 3h8l-1 6 3 3H6l3-3z`],muted:[`M12 3a3 3 0 0 1 3 3v6a3 3 0 0 1-6 0V6a3 3 0 0 1 3-3z`,`M5 11a7 7 0 0 0 14 0`,`M4 4l16 16`],home:[`M4 11l8-7 8 7`,`M6 10v10h12V10`],cloud:[`M7 18h10a4 4 0 0 0 .5-7.97A6 6 0 0 0 6.1 9.1A4.5 4.5 0 0 0 7 18z`],folder:[`M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`],bell:[`M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9`,`M10.3 21a1.94 1.94 0 0 0 3.4 0`]};function Z(e){return(()=>{var t=Os();return R(t,O(k,{get each(){return[...Ks[e.name]]},children:e=>(()=>{var t=ks();return F(t,`d`,e),t})()})),S(()=>F(t,`class`,`icon ${e.class??``}`)),t})()}var qs={idle:`Idle`,working:`Running`,blocked:`Needs you`,error:`Error`};function Js(){return As()}function Ys(e){return(()=>{var t=Ms();return R(t,O(A,{get when(){return e.state===`working`},get fallback(){return Ns()},get children(){return js()}})),S(n=>{var r=`status ${e.state} ${e.class??``}`,i=qs[e.state],a=qs[e.state];return r!==n.e&&I(t,n.e=r),i!==n.t&&F(t,`aria-label`,n.t=i),a!==n.a&&F(t,`title`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}function Xs(e){let[t,n]=Be(e,[`icon`,`label`,`class`]);return(()=>{var e=Ps();return st(e,ze({get class(){return`icon-btn ${t.class??``}`},get"aria-label"(){return t.label},get title(){return t.label}},n),!1,!0),R(e,O(Z,{get name(){return t.icon}})),e})()}function Zs(e){let[t,n]=x(!1),r,i,[a,o]=x({top:0,left:0,right:0,bottom:0}),s=()=>{let e=r.getBoundingClientRect();o({top:e.bottom+4,left:e.left,right:window.innerWidth-e.right,bottom:window.innerHeight-e.top+4})},c=()=>n(!1),l=e=>{if(!t())return;let n=e.target;!r.contains(n)&&!i?.contains(n)&&c()},u=n=>{if(t()){if(n.key===`Escape`)c(),r.focus();else if(/^[1-9]$/.test(n.key)&&!(n.target instanceof HTMLInputElement||n.target instanceof HTMLTextAreaElement)){let t=e.items().filter(e=>typeof e==`object`&&`run`in e&&!e.disabled)[Number(n.key)-1];t&&(n.preventDefault(),c(),t.run())}}};E(()=>{document.addEventListener(`mousedown`,l),document.addEventListener(`keydown`,u)}),D(()=>{document.removeEventListener(`mousedown`,l),document.removeEventListener(`keydown`,u)});let d=()=>{let t=0;return e.items().map(e=>({item:e,index:typeof e==`object`&&`run`in e&&!e.disabled?++t:0}))};return[(()=>{var i=Fs();i.$$click=e=>{e.stopPropagation(),e.preventDefault(),s(),n(!t())};var a=r;return typeof a==`function`?L(a,i):r=i,R(i,()=>e.text??O(Z,{get name(){return e.icon??`more`}})),S(n=>{var r=e.class??`icon-btn`,a=e.label,o=e.label,s=t();return r!==n.e&&I(i,n.e=r),a!==n.t&&F(i,`aria-label`,n.t=a),o!==n.a&&F(i,`title`,n.a=o),s!==n.o&&F(i,`aria-expanded`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),i})(),O(A,{get when(){return t()},get children(){return O(xt,{get children(){var t=Is(),n=i;return typeof n==`function`?L(n,t):i=t,R(t,O(k,{get each(){return d()},children:({item:e,index:t})=>e===`sep`?Ls():`section`in e?(()=>{var t=Rs();return R(t,()=>e.section),t})():(()=>{var n=Vs(),r=n.firstChild,i=r.nextSibling;return n.$$click=t=>{t.stopPropagation(),c(),e.run()},R(r,()=>e.checked?`✓`:``),R(i,()=>e.label),R(n,O(A,{get when(){return e.hint},get children(){var t=zs();return R(t,()=>e.hint),t}}),null),R(n,O(A,{when:t>0&&t<10,get children(){var e=Bs();return R(e,t),e}}),null),S(t=>{var r=e.checked===void 0?`menuitem`:`menuitemradio`,i=e.checked,a=`menu-item${e.danger?` danger`:``}`,o=e.disabled;return r!==t.e&&F(n,`role`,t.e=r),i!==t.t&&F(n,`aria-checked`,t.t=i),a!==t.a&&I(n,t.a=a),o!==t.o&&(n.disabled=t.o=o),t},{e:void 0,t:void 0,a:void 0,o:void 0}),n})()})),S(n=>at(t,{...e.up?{bottom:`${a().bottom}px`}:{top:`${a().top}px`},...e.align===`left`?{left:`${a().left}px`}:{right:`${a().right}px`}},n)),t}})}})]}function Qs(e){let t;return C(()=>{let n=e.open;t&&(n&&!t.open?t.showModal():!n&&t.open&&t.close())}),(()=>{var n=Ws();n.$$click=n=>n.target===t&&e.onClose(),n.addEventListener(`close`,()=>e.onClose());var r=t;return typeof r==`function`?L(r,n):t=n,R(n,O(A,{get when(){return e.open},get children(){return[(()=>{var t=Hs(),n=t.firstChild;return R(n,()=>e.title),R(t,O(Xs,{icon:`close`,label:`Close`,onClick:()=>e.onClose()}),null),t})(),(()=>{var t=Us();return R(t,()=>e.children),t})()]}})),S(t=>{var r=`dialog${e.wide?` wide`:``} ${e.class??``}`,i=e.title;return r!==t.e&&I(n,t.e=r),i!==t.t&&F(n,`aria-label`,t.t=i),t},{e:void 0,t:void 0}),n})()}var[$s,ec]=x(Date.now());setInterval(()=>ec(Date.now()),3e4);var tc=$s,[nc,rc]=x(Date.now());setInterval(()=>rc(Date.now()),1e3);var ic=nc;function ac(e){return(()=>{var t=Gs();return S(n=>{var r=`Error: ${e.text}`,i=e.text;return r!==n.e&&F(t,`aria-label`,n.e=r),i!==n.t&&F(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}function oc(e,t=$s()){if(!e)return``;let n=Math.max(0,Math.round((t-e)/1e3));return n<45?`just now`:n<3600?`${Math.round(n/60)}m ago`:n<86400?`${Math.round(n/3600)}h ago`:`${Math.round(n/86400)}d ago`}var sc=e=>String(e??``).replace(/[\\/]+$/,``).split(/[\\/]/).pop()||e||``,cc=(e,t)=>`${e} ${t}${e===1?``:`s`}`,lc={herdr:`Herdr`,tui:`TUI`,background:`Background`};P([`click`]);var uc=N(`<p class=error role=alert>`),dc=N(`<form class="card stack"novalidate><div class=field><label for=pair-code>Pairing code</label><input id=pair-code class=pair-code type=text inputmode=numeric autocomplete=one-time-code maxlength=6></div><p class="small muted">In OpenCode run /hub → Pair a phone on a computer connected to this hub to get a 6-digit code. For the very first device, use the code printed in the hub's log.</p><div class=field><label for=pair-name>Device name</label><input id=pair-name type=text maxlength=64></div><button type=submit class="btn primary">Pair`),fc=N(`<p class=muted>Sign in to see and control your own OpenCode sessions.`),pc=N(`<a class="btn primary signin">Sign in with Google`),mc=N(`<details class=card><summary>Have a pairing code?`),hc=N(`<main class=entry><h1 class="display brand-big"> Hub`),gc=N(`<p class=muted>Loading…`),_c=N(`<p class=muted>Pair this browser with your hub to see and control your OpenCode sessions.`),vc=N(`<p>A terminal on <strong></strong> asks to act as you through the hub CLI.`),yc=N(`<p class="small muted">Code <!> · requested <!>. Approve only if you ran <span class=mono>hub login</span> yourself and this code matches the one in your terminal.`),bc=N(`<fieldset class=stack><legend class=small>What it may do`),xc=N(`<p class=small>Launch is ticked: the terminal can start sessions in a repository once you also create a grant with verb launch for it.`),Sc=N(`<div class=row><button type=button class="btn primary">Approve</button><button type=button class="btn danger">Deny`),Cc=N(`<p role=status>`),wc=N(`<main class=entry><h1 class=display>CLI login for </h1><div class="card stack"><a class=btn href=/>Back to sessions`),Tc=N(`<label class=check><input type=checkbox><span><span class=mono></span> `),Ec=N(`<main class=entry><p class=muted>Loading…`),Dc=N(`<strong>`),Oc=N(`<p>`),kc=N(`<p class="small muted">Approve only if this code matches the one shown in OpenCode.`),Ac=N(`<p class=small>`),jc=N(`<main class=entry><h1 class=display>Approve machine</h1><div class="card stack"><a class=btn href=/>Back to sessions`),Mc=N(`<p>No code given.`),Nc=N(`<strong class=mono>`);function Pc(){let e=navigator.userAgent,t=/Pixel[^;)]*/.exec(e)?.[0]||(/iPhone/.test(e)?`iPhone`:/iPad/.test(e)?`iPad`:/Android/.test(e)?`Android`:/Mac OS X/.test(e)?`Mac`:/Windows/.test(e)?`Windows`:`Browser`),n=/Edg\//.test(e)?`Edge`:/Firefox\//.test(e)?`Firefox`:/Chrome\//.test(e)?`Chrome`:/Safari\//.test(e)?`Safari`:``;return`${t.trim()}${n?` · ${n}`:``}`.slice(0,64)}function Fc(e){let[t,n]=x(),[r,i]=x(!1),[a,o]=x(``),[s,c]=x(Pc()),[l,u]=x(e.error?`Sign-in did not work: ${e.error}`:``),[d,f]=x(!1);E(async()=>{let[t,r]=await Promise.all([fetch(`/api/me`,{credentials:`same-origin`}).catch(()=>void 0),Fo()]);if(t?.ok)return _o(await t.json()),io(e.next,{replace:!0});n(Nt(r??void 0,e.next)),i(!0)});let p=async t=>{t.preventDefault();let n=a().replace(/\D/g,``);if(n.length!==6)return u(`Enter the 6-digit code.`);f(!0),u(``);try{await V(`/api/pair`,{method:`POST`,json:{code:n,deviceName:s().trim()||Pc()}}),_o(void 0),io(e.next,{replace:!0})}catch(e){u(e instanceof or&&e.status===401?`That code is wrong or expired. Get a fresh one and try again.`:G(e)),f(!1)}},m=()=>(()=>{var e=dc(),t=e.firstChild,n=t.firstChild.nextSibling,r=t.nextSibling.nextSibling,i=r.firstChild.nextSibling,u=r.nextSibling;return e.addEventListener(`submit`,p),n.$$input=e=>o(e.currentTarget.value),i.$$input=e=>c(e.currentTarget.value),R(e,O(A,{get when(){return l()},get children(){var e=uc();return R(e,l),e}}),u),S(()=>u.disabled=d()),S(()=>n.value=a()),S(()=>i.value=s()),e})();return(()=>{var n=hc(),i=n.firstChild,a=i.firstChild;return R(i,O(Ds,{class:`brand-mark`,size:30}),a),R(n,O(A,{get when(){return r()},get fallback(){return gc()},get children(){return O(A,{get when(){return t()},get fallback(){return[_c(),M(m)]},get children(){return[fc(),(()=>{var e=pc();return S(()=>F(e,`href`,t())),e})(),(()=>{var t=mc();return t.firstChild,R(t,m,null),S(()=>t.open=!!e.error),t})()]}})}}),null),n})()}function Ic(e){let t=Dn(e.login),[n,r]=x(t.filter(e=>e.checked).map(e=>e.scope)),[i,a]=x(``),[o,s]=x(``),[c,l]=x(!1),u=()=>e.login.userCode,d=async t=>{let r=t===`approve`?On(n()):{ok:!0,body:{}};if(!r.ok)return a(r.error);l(!0);try{await V(`/api/cli-logins/${U(u())}/${t}`,{method:`POST`,json:r.body}),s(t===`approve`?`The terminal on ${e.login.clientName} is logged in as you, with ${n().join(`, `)}.${n().includes(`sessions:launch`)?` To launch, it also needs a grant with verb launch (Settings → Agents).`:``} You can revoke it in Settings → Agents.`:`Denied the CLI login for ${e.login.clientName}.`)}catch(e){a(e instanceof or&&e.status===404?`No pending request with code ${u()}. It may have expired or been answered already.`:G(e)),l(!1)}};return(()=>{var a=wc(),s=a.firstChild;s.firstChild;var l=s.nextSibling,f=l.firstChild;return R(s,()=>e.login.clientName,null),R(l,O(A,{get when(){return!o()},get fallback(){return(()=>{var e=Cc();return R(e,o),e})()},get children(){return[(()=>{var t=vc(),n=t.firstChild.nextSibling;return R(n,()=>e.login.clientName),t})(),(()=>{var t=yc(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,R(t,u,n),R(t,()=>oc(e.login.created),r),t})(),(()=>{var e=bc();return e.firstChild,R(e,O(k,{each:t,children:e=>(()=>{var t=Tc(),i=t.firstChild,a=i.nextSibling,o=a.firstChild;return o.nextSibling,i.addEventListener(`change`,t=>r(t.currentTarget.checked?[...n(),e.scope]:n().filter(t=>t!==e.scope))),R(o,()=>e.scope),R(a,()=>e.label,null),R(a,()=>e.requested?` (requested)`:``,null),S(()=>i.disabled=c()),S(()=>i.checked=e.checked),t})()}),null),e})(),O(A,{get when(){return n().includes(`sessions:launch`)},get children(){return xc()}}),(()=>{var e=Sc(),t=e.firstChild,n=t.nextSibling;return t.$$click=()=>void d(`approve`),n.$$click=()=>void d(`deny`),S(e=>{var r=c(),i=c();return r!==e.e&&(t.disabled=e.e=r),i!==e.t&&(n.disabled=e.t=i),e},{e:void 0,t:void 0}),e})(),O(A,{get when(){return i()},get children(){var e=Cc();return R(e,i),e}})]}}),f),a})()}function Lc(e){let[t,n]=x(),[r,i]=x(!e.code);return E(async()=>{if(e.code){try{n(En(await(await V(`/api/cli-logins/${U(e.code.toUpperCase())}`)).json()))}catch{}i(!0)}}),O(A,{get when(){return r()},get fallback(){return Ec()},get children(){return O(A,{get when(){return t()},get fallback(){return O(Rc,{get code(){return e.code}})},children:e=>O(Ic,{get login(){return e()}})})}})}function Rc(e){let t=()=>e.code.toUpperCase(),[n,r]=x(``),[i,a]=x(``),[o,s]=x(!1),[c,l]=x(!Dt(X()));E(async()=>{await os(),l(!0)});let u=()=>So().find(e=>e.userCode===t()),d=()=>`No pending request with code ${t()}. It may have expired or been answered already.`,f=async e=>{s(!0);let n=u()?.machineName;try{await V(`/api/enrollments/${U(t())}/${e}`,{method:`POST`,json:{}}),a(e===`approve`?`${n??`The machine`} is approved and belongs to you. It will connect in a few seconds.`:`Denied ${n??`the request with code ${t()}`}.`)}catch(e){r(e instanceof or&&e.status===404?d():G(e)),s(!1)}};return(()=>{var e=jc(),r=e.firstChild.nextSibling,a=r.firstChild;return R(r,O(A,{get when(){return!i()},get fallback(){return(()=>{var e=Cc();return R(e,i),e})()},get children(){return O(A,{get when(){return t()},get fallback(){return Mc()},get children(){return O(A,{get when(){return c()},get fallback(){return gc()},get children(){return O(A,{get when(){return!Dt(X())||u()},get fallback(){return(()=>{var e=Oc();return R(e,d),e})()},get children(){return[(()=>{var e=Oc();return R(e,O(A,{get when(){return u()},get fallback(){return[`A machine showing code `,(()=>{var e=Nc();return R(e,t),e})(),` wants to connect to this hub.`]},get children(){return[(()=>{var e=Dc();return R(e,()=>u().machineName),e})(),` wants to connect to this hub.`]}})),e})(),(()=>{var e=kc(),t=e.firstChild;return R(e,(()=>{var e=M(()=>!!u());return()=>e()?`Code ${u().userCode} · requested ${oc(u().created)}. `:``})(),t),e})(),(()=>{var e=Ac();return R(e,()=>Pt(X())),e})(),(()=>{var e=Sc(),t=e.firstChild,n=t.nextSibling;return t.$$click=()=>void f(`approve`),n.$$click=()=>void f(`deny`),S(e=>{var r=o(),i=o();return r!==e.e&&(t.disabled=e.e=r),i!==e.t&&(n.disabled=e.t=i),e},{e:void 0,t:void 0}),e})(),O(A,{get when(){return n()},get children(){var e=Cc();return R(e,n),e}})]}})}})}})}}),a),e})()}P([`input`,`click`]);function zc(e){return e.supported?e.permission===`denied`?{state:`blocked`,message:`Notifications are blocked for this site. Allow them in the browser's site settings, then reload.`,action:`none`,warn:!0}:e.permission==="default"?{state:`off`,message:`Notifications are off on this device.`,action:`enable`,warn:!0}:!e.worker||!e.endpoint||!e.hubSubscribed?{state:`repair`,message:`Allowed, but this device is not subscribed on this hub, so nothing will arrive (this happens after the hub moves to a new address). Enable again to fix it.`,action:`enable`,warn:!0}:{state:`on`,message:`On for this device.`,action:`disable`,warn:!1}:{state:`unsupported`,message:`This browser can't get notifications here. On iPhone, add the app to the Home Screen first (iOS 16.4+); everywhere else the hub must be on https.`,action:`none`,warn:!0}}var Bc=e=>e.supported&&e.permission===`granted`&&(!e.endpoint||!e.hubSubscribed);function Vc(e){if(e.subscriptions===0)return{ok:!1,text:`This device is not subscribed; enable notifications first`};if(e.sent>0)return{ok:!0,text:e.sent===1?`Test notification sent to this device`:`Test notification sent (${e.sent} subscriptions)`};let t=e.failed[0];return t?{ok:!1,text:`Test failed: ${t.host} ${t.status===void 0?`did not answer`:`answered ${t.status}`}`}:{ok:!1,text:`Test failed`}}var Hc=[1,2,5,10,15,30,60],Uc=[{title:`Needs you`,kinds:[{key:`question`,label:`Question`,description:`A session or subagent asks you something.`},{key:`permission`,label:`Needs permission`,description:`A tool call waits for your OK (answer from the notification).`},{key:`decision`,label:`Decision`,description:`A session asks you to decide (hub ask @me), with options and a recommendation.`},{key:`message`,label:`Message`,description:`Agent messaging needs you: a message to you, an unanswered ask, or sessions looping.`}]},{title:`Session`,kinds:[{key:`done`,label:`All done`,description:`The session and all its subagents and scripts finished; nothing waits on you. Once per run.`},{key:`failed`,label:`Failed`,description:`The session's run failed (provider or tool error), with the reason.`},{key:`providerError`,label:`Model provider error`,description:`Quota, budget, auth or model-routing errors of the session or a subagent; once per run.`},{key:`turn`,label:`Turn finished`,description:`Every reply of the main session, also the short ones between subagents. Noisy.`},{key:`stopped`,label:`Stopped`,description:`A run stopped without you asking (OpenCode shut down, inactivity).`},{key:`retry`,label:`Retrying`,description:`The provider failed and OpenCode is retrying the request.`}]},{title:`Subagents`,kinds:[{key:`subagentDone`,label:`Subagent finished`,description:`Each subagent that finishes, by name.`},{key:`subagentFailed`,label:`Subagent failed`,description:`Each subagent that fails, with the reason.`}]},{title:`Scripts and tools`,kinds:[{key:`jobDone`,label:`Script finished`,description:`A background shell or terminal exited 0.`},{key:`jobFailed`,label:`Script failed`,description:`A background shell or terminal exited non-zero, was killed or timed out.`},{key:`longTool`,label:`Long tool finished`,description:`A tool call that ran 30 seconds or more ended.`}]},{title:`Voice`,kinds:[{key:`say`,label:`Spoken reply`,description:`Voice mode replies while no device shows the session.`},{key:`handoff`,label:`Hand-off`,description:`A session sent to this device from the terminal (ignores quiet hours).`}]},{title:`Activity digest`,kinds:[{key:`activity`,label:`Activity`,description:`One quiet, self-replacing summary per session: subagents, long tools, scripts, idle.`}]}],Wc=Uc.flatMap(e=>e.kinds);function Gc(e){let t=Wc.filter(t=>e[t.key]).map(e=>e.label);return t.length?`You'll get: ${t.join(`, `)}.`:`You'll get no notifications on this device.`}function Kc(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`}catch{return`UTC`}}var qc=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window&&window.isSecureContext;function Jc(e){let t=`=`.repeat((4-e.length%4)%4),n=atob((e+t).replace(/-/g,`+`).replace(/_/g,`/`));return Uint8Array.from(n,e=>e.charCodeAt(0))}var Yc=(e,t)=>!e||e.byteLength!==t.byteLength?!1:new Uint8Array(e).every((e,n)=>e===t[n]),[Xc,Zc]=x(0),[Qc,$c]=x(new Set),el=()=>`Notification`in window?Notification.permission:`default`;async function tl(){if(`serviceWorker`in navigator)return await navigator.serviceWorker.getRegistration(`/`).catch(()=>void 0)??void 0}async function nl(){if(qc())return await(await tl())?.pushManager.getSubscription()??void 0}async function rl(e){let t=await H(`/api/push/prefs${e?`?endpoint=${encodeURIComponent(e)}`:``}`);return $c(new Set(t.muted??[])),t}async function il(){let e=qc(),t=e?await tl():void 0,n=await t?.pushManager.getSubscription().catch(()=>null)??void 0,r=await rl(n?.endpoint).catch(()=>void 0);return{env:{supported:e,permission:el(),worker:!!t,...n?{endpoint:n.endpoint}:{},hubSubscribed:!!r?.subscribed,hubSubscriptions:r?.subscriptions??0},view:r}}async function al(){let{publicKey:e}=await H(`/api/push/key`),t=Jc(e);await tl()||await navigator.serviceWorker.register(`/sw.js`,{scope:`/`});let n=await navigator.serviceWorker.ready,r=await n.pushManager.getSubscription();return r&&!Yc(r.options?.applicationServerKey,t)&&(await r.unsubscribe(),r=null),r??=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),await V(`/api/push/subscribe`,{method:`POST`,json:{subscription:r.toJSON()}}),r}async function ol(){if(!qc())throw Error(`This browser does not support push notifications here. On iPhone, add the app to the Home Screen first (iOS 16.4+).`);if(await Notification.requestPermission()!==`granted`)throw Error(`Notifications are blocked. Allow them in the browser's site settings.`);await al()}async function sl(){let e=await nl();e&&(await V(`/api/push/unsubscribe`,{method:`POST`,json:{endpoint:e.endpoint}}).catch(()=>{}),await e.unsubscribe().catch(()=>{}))}async function cl(e){return(await V(`/api/push/test`,{method:`POST`,json:e?{kind:e}:{}})).json()}async function ll(e,t){let n=Qc(),r=new Set(n);t?r.add(e):r.delete(e),$c(r);try{let n=await(await V(`/api/push/mute`,{method:`PUT`,json:{sessionID:e,muted:t}})).json();$c(new Set(n.muted)),q(t?`Notifications muted for this session`:`Notifications on for this session`)}catch(e){$c(n),q(e instanceof Error?e.message:String(e),`err`)}}async function ul(){let{env:e}=await il().catch(()=>({env:void 0}));e&&Bc(e)&&await al().then(()=>Zc(e=>e+1),e=>console.warn(`push re-subscribe:`,e?.message??e))}function dl(){`serviceWorker`in navigator&&(navigator.serviceWorker.register(`/sw.js`,{scope:`/`}).catch(e=>console.warn(`service worker:`,e.message)),navigator.serviceWorker.addEventListener(`message`,e=>{let t=e.data;if(t?.type===`navigate`&&typeof t.url==`string`){let e=new URL(t.url,location.origin);e.origin===location.origin&&io(e.pathname+e.search)}for(let e of fl)e(t)}))}var fl=new Set;function pl(e){return fl.add(e),()=>fl.delete(e)}var[ml,hl]=x(),gl=(e,t)=>ml()?.id===e&&ml()?.place===t;function _l(e,t){if(!e.length)return;let n=t?`Archived`:`Unarchived`,r=e.length===1?`${n} “${e[0].title}”`:`${n} ${e.length} sessions`;gs(`hiddenSessions`,e.map(e=>e.id),t,{message:r,undo:!0})}function vl(e,{open:t=!0,place:n}={}){return[...t?[{label:`Open`,run:()=>io(ao(e.id))}]:[],...n?[{label:`Rename…`,run:()=>hl({id:e.id,place:n})}]:[],{label:xs(e.id)?`Naming…`:`Auto-name`,run:()=>void ws(e.id),disabled:xs(e.id)},{label:e.pinned?`Unpin`:`Pin`,run:()=>hs(`pinnedSessions`,e.id,!e.pinned)},{label:e.archived?`Unarchive`:`Archive`,run:()=>_l([e],!e.archived)},...e.running?[{label:`Stop`,run:()=>void Ts(e.id),danger:!0}]:[],`sep`,{label:e.exposed?`Disallow Voice`:`Allow Voice`,run:()=>void _s(e.id,!e.exposed)},Qc().has(e.id)?{label:`Unmute notifications`,run:()=>void ll(e.id,!1)}:{label:`Mute notifications`,run:()=>void ll(e.id,!0)}]}var yl=N(`<span class="badge-pill agent-request"title="An agent asked to act outside its grant">Agent request`),bl=N(`<span>`),xl=N(`<p role=timer>`),Sl=N(`<div role=radiogroup aria-label=Options class=choice-group>`),Cl=N(`<p class="muted small decision-why">Why: `),wl=N(`<input type=text class=decision-note aria-label="Note (optional)"placeholder="Note (optional)">`),Tl=N(`<p class="muted small decision-tier">`),El=N(`<div role=group><p class="blocker-head decision-head"><strong>Decision</strong> <span class=muted>from </span></p><p class="blocker-text decision-question"></p><form class=form-card novalidate><fieldset><div class=row><button type=submit class="btn small primary">Answer`),Dl=N(`<a>`),Ol=N(`<dt>Action`),kl=N(`<dd class=mono>`),Al=N(`<dt>`),jl=N(`<dd>`),Ml=N(`<dt>Outside its grant`),Nl=N(`<dl class="escalation-details small"data-escalation><dt>Requested by</dt><dd>`),Pl=N(`<code class=escalation-resource>`),Fl=N(`<label class=text-field><span class=field-title>Your answer</span><textarea rows=2 aria-label="Your answer">`),Il=N(`<span class="badge-pill safe"title="A timeout may pick this option">safe`),Ll=N(`<span class="badge-pill recommended">Recommended`),Rl=N(`<label><input type=radio><span>`),zl={low:`Low urgency`,normal:``,high:`Urgent`};function Bl(e){let t=()=>e.decision,[n,r]=x(),[i,a]=x(``),[o,s]=x(!1),[c,l]=x(Date.now()),u=setInterval(()=>t().deadline!==void 0&&l(Date.now()),1e3);D(()=>clearInterval(u));let d=()=>no().searchParams.get(`decision`)===t().id,f;E(()=>{d()&&f?.scrollIntoView({block:`center`})});let p=()=>t().sessionID?jo(t().sessionID):void 0,m=async e=>{e.preventDefault();let r=hn(t(),n(),i());if(!r.ok)q(r.problem,`err`);else{s(!0);try{let{decision:e}=await(await V(`/api/decisions/${U(t().id)}/answer`,{method:`POST`,json:r.body})).json();q(`Answer sent`),e?is(e):as(t().id)}catch(e){if(e instanceof or&&e.status===409&&e.code===`gone`){q(`Already answered or expired`),as(t().id);return}q(G(e),`err`),s(!1)}}},h=e=>t().recommendation?.option===e;return(()=>{var s=El(),l=s.firstChild,u=l.firstChild.nextSibling.nextSibling;u.firstChild;var g=l.nextSibling,_=g.nextSibling,v=_.firstChild,y=v.firstChild,b=f;return typeof b==`function`?L(b,s):f=s,R(u,()=>dn(t()),null),R(l,O(A,{get when(){return ir(t())},get children(){return yl()}}),null),R(l,O(A,{get when(){return zl[t().urgency]},get children(){var e=bl();return R(e,()=>zl[t().urgency]),S(()=>I(e,`badge-pill urgency ${t().urgency}`)),e}}),null),R(l,O(A,{get when(){return M(()=>!!e.showSession)()&&p()},children:e=>[` · `,(()=>{var t=Dl();return R(t,()=>e().session.title||e().session.id),S(()=>F(t,`href`,ao(e().session.id))),t})()]}),null),R(g,()=>t().question),R(s,O(A,{get when(){return ir(t())},children:e=>(()=>{var t=Nl(),n=t.firstChild.nextSibling;return R(n,()=>e().requester),R(t,O(A,{get when(){return e().action},get children(){return[Ol(),(()=>{var t=kl();return R(t,()=>e().action,null),R(t,()=>e().always?` (always)`:``,null),t})()]}}),null),R(t,O(A,{get when(){return e().resources.length},get children(){return[(()=>{var t=Al();return R(t,()=>e().resources.length===1?`Resource`:`Resources`),t})(),(()=>{var t=jl();return R(t,O(k,{get each(){return e().resources},children:e=>(()=>{var t=Pl();return R(t,e),t})()})),t})()]}}),null),R(t,O(A,{get when(){return e().reason},get children(){return[Ml(),(()=>{var t=jl();return R(t,()=>e().reason),t})()]}}),null),t})()}),_),R(s,O(A,{get when(){return mn(t(),c())},get children(){var e=xl();return R(e,()=>mn(t(),c())),S(()=>I(e,`decision-deadline small${t().escalatedAt!==void 0||t().deadline<=c()?` overdue`:``}`)),e}}),_),_.addEventListener(`submit`,e=>void m(e)),R(v,O(A,{get when(){return t().options.length},get fallback(){return(()=>{var e=Fl(),t=e.firstChild.nextSibling;return t.$$input=e=>a(e.currentTarget.value),S(()=>t.value=i()),e})()},get children(){return[(()=>{var e=Sl();return R(e,O(k,{get each(){return t().options},children:e=>(()=>{var i=Rl(),a=i.firstChild,o=a.nextSibling;return a.addEventListener(`change`,()=>r(e.id)),R(o,()=>e.label),R(i,O(A,{get when(){return e.safe},get children(){return Il()}}),null),R(i,O(A,{get when(){return h(e.id)},get children(){return Ll()}}),null),S(n=>{var r=`choice${h(e.id)?` recommended`:``}`,o=`d-${t().id}`;return r!==n.e&&I(i,n.e=r),o!==n.t&&F(a,`name`,n.t=o),n},{e:void 0,t:void 0}),S(()=>a.value=e.id),S(()=>a.checked=n()===e.id),i})()})),e})(),O(A,{get when(){return t().recommendation?.why},get children(){var e=Cl();return e.firstChild,R(e,()=>t().recommendation.why,null),e}}),(()=>{var e=wl();return e.$$input=e=>a(e.currentTarget.value),S(()=>e.value=i()),e})()]}}),y),R(v,O(A,{get when(){return fn(t())},get children(){var e=Tl();return R(e,()=>fn(t())),e}}),y),S(e=>{var n=`card decision urgency-${t().urgency}${d()?` targeted`:``}`,r=`Decision: ${t().question}`,i=t().id,a=o();return n!==e.e&&I(s,e.e=n),r!==e.t&&F(s,`aria-label`,e.t=r),i!==e.a&&F(s,`data-decision`,e.a=i),a!==e.o&&(v.disabled=e.o=a),e},{e:void 0,t:void 0,a:void 0,o:void 0}),s})()}function Vl(e){let t=w(()=>new Map(e.decisions.map(e=>[e.id,e]))),n=w((e=[])=>{let n=[...t().keys()];return n.length===e.length&&n.every((t,n)=>t===e[n])?e:n});return O(k,{get each(){return n()},children:n=>O(A,{get when(){return t().get(n)},children:t=>O(Bl,{get decision(){return t()},get showSession(){return e.showSession}})})})}P([`input`]);var Hl={side:{min:180,max:480,default:235},rail:{min:220,max:640,default:260}},Ul=`hub.panels`,Wl=(e,{min:t,max:n})=>Math.min(n,Math.max(t,e));function Gl(e,t,n){let{min:r,max:i}=Hl[e];return{min:r,max:Math.max(r,Math.min(i,Math.floor(t-420-n)))}}function Kl(e,t,n){let r=Wl(e.side,Gl(`side`,t,n.rail?Hl.rail.min:0));return{side:r,rail:Wl(e.rail,Gl(`rail`,t,n.side?r:0))}}function ql(e,t,n,r,i){let a=r?64:16,o=e===`side`?`ArrowRight`:`ArrowLeft`,s=e===`side`?`ArrowLeft`:`ArrowRight`;if(n===o)return Wl(t+a,i);if(n===s)return Wl(t-a,i);if(n===`Home`)return i.min;if(n===`End`)return i.max}function Jl(e,t,n,r){let i=e===`side`?t+n:t-n;return e===`side`&&i<r.min-48?{collapse:!0}:{width:Wl(Math.round(i),r)}}var Yl=(e,t)=>{let{min:n,max:r,default:i}=Hl[e];return typeof t==`number`&&Number.isFinite(t)?Wl(Math.round(t),{min:n,max:r}):i};function Xl(e){let t;try{t=JSON.parse(e.getItem(`hub.panels`)??`null`)}catch{t=null}let n=t&&typeof t==`object`&&!Array.isArray(t)?t:{};return{side:Yl(`side`,n.side),rail:Yl(`rail`,n.rail)}}function Zl(e,t,n){try{e.setItem(Ul,JSON.stringify({...Xl(e),[t]:Yl(t,n)}))}catch{}}var Ql=window.matchMedia(`(max-width: 760px)`),[$l,eu]=x(Ql.matches);Ql.addEventListener(`change`,()=>{eu(Ql.matches),cu(!Ql.matches&&localStorage.getItem(nu)!==`0`)});var Q=$l,tu=`hub.sidebar.collapsed`,nu=`hub.rail.open`,[ru,iu]=x(localStorage.getItem(tu)===`1`),[au,ou]=x(!1),[su,cu]=x(!Ql.matches&&localStorage.getItem(nu)!==`0`);function lu(e){iu(e),localStorage.setItem(tu,e?`1`:`0`)}function uu(e){cu(e),$l()||localStorage.setItem(nu,e?`1`:`0`)}function du(){$l()?ou(!au()):lu(!ru())}var[fu,pu]=x(window.innerWidth);window.addEventListener(`resize`,()=>pu(window.innerWidth));var[mu,hu]=x(Xl(localStorage)),[gu,_u]=x(!1),[vu,yu]=x(),bu=()=>Kl(mu(),fu(),{side:!ru()&&!$l(),rail:gu()});function xu(e){let t=bu(),n=e===`side`?gu()?t.rail:0:!ru()&&!$l()?t.side:0;return Gl(e,fu(),n)}function Su(e,t,n=!0){hu(n=>({...n,[e]:t})),n&&Zl(localStorage,e,t)}var Cu=N(`<span class="naming muted small"role=status><span class="spinner small"aria-hidden=true></span>Naming…`),wu=N(`<span class=rename-wrap><input type=text aria-label="Session title"><button type=button class="icon-btn small auto-name-btn"aria-label=Auto-name title="Let OpenCode name this session">✨`),Tu,Eu=0;function Du(e){return O(A,{get when(){return gl(e.id,e.place)},get fallback(){return e.children},get children(){return O(ku,{get id(){return e.id},get title(){return e.title},get place(){return e.place},get class(){return e.class}})}})}function Ou(e){return O(A,{get when(){return xs(e.id)},get children(){return Cu()}})}function ku(e){let t,n=!1,r=Tu&&Tu.id===e.id&&Tu.place===e.place?Tu.value:void 0,i=()=>{n||(n=!0,Tu=void 0,hl(void 0),ws(e.id))},a=r=>{if(n)return;n=!0;let i=t.value;Tu=void 0,hl(void 0),r&&i.trim()&&i.trim()!==e.title&&vs(e.id,i)};return E(()=>{Eu++,t.focus(),r===void 0&&t.select()}),D(()=>{if(Eu--,setTimeout(()=>{Eu>0||(Tu=void 0,ml()?.id===e.id&&ml()?.place===e.place&&hl(void 0))},0),n)return;n=!0;let r=ml();r?.id===e.id&&r.place===e.place&&(Tu={id:e.id,place:e.place,value:t.value})}),(()=>{var n=wu(),o=n.firstChild,s=o.nextSibling;o.addEventListener(`blur`,()=>a(!0)),o.$$keydown=e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),a(!0)):e.key===`Escape`&&(e.preventDefault(),a(!1))},o.$$mousedown=e=>e.stopPropagation(),o.$$click=e=>e.stopPropagation();var c=t;return typeof c==`function`?L(c,o):t=o,F(o,`maxlength`,200),s.$$click=e=>{e.preventDefault(),e.stopPropagation(),i()},s.$$mousedown=e=>{e.preventDefault(),e.stopPropagation()},S(()=>I(o,`rename-field${e.class?` ${e.class}`:``}`)),S(()=>o.value=r??e.title),n})()}P([`click`,`mousedown`,`keydown`]);var Au=class{deps;state={phase:`idle`};recording;release;run=0;listeners=new Set;constructor(e){this.deps=e}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}forSession(e){let t=this.state.sessionID===e;return{recording:t&&(this.state.phase===`recording`||this.state.phase===`starting`)?this.state.secondsLeft??60:!1,transcribing:t&&this.state.phase===`transcribing`}}async toggle(e){let{phase:t}=this.state;if(t===`idle`)return this.start(e);if(t===`recording`&&this.state.sessionID===e)return this.finish()}viewing(e){let{phase:t}=this.state;(t===`recording`||t===`starting`)&&this.state.sessionID!==e&&this.cancel(`Dictation cancelled: you left the session it was for.`)}cancel(e){this.state.phase!==`idle`&&(this.run++,this.recording?.cancel(),this.recording=void 0,this.unhold(),this.set({phase:`idle`}),e&&this.deps.notify(e,`warn`))}async start(e){let t=++this.run;this.set({phase:`starting`,sessionID:e,secondsLeft:60}),this.release=this.deps.hold?.();let n;try{n=await this.deps.record(e=>{t===this.run&&this.state.phase===`recording`&&this.set({...this.state,secondsLeft:e})})}catch(e){return t===this.run?(this.unhold(),this.set({phase:`idle`}),this.deps.notify(e instanceof Error?e.message:String(e),`err`)):void 0}if(t!==this.run)return n.cancel();this.recording=n,this.set({phase:`recording`,sessionID:e,secondsLeft:60})}async finish(){let e=this.recording,t=this.state.sessionID;if(!e||!t)return;let n=this.run;this.recording=void 0,this.set({phase:`transcribing`,sessionID:t});try{let r=(await e.finish()).trim();if(n!==this.run)return;r?this.deps.deliver(t,r):this.deps.notify(`Didn't catch that. Try again.`,`warn`)}catch(e){n===this.run&&this.deps.notify(e instanceof Error?e.message:String(e),`err`)}finally{n===this.run&&(this.unhold(),this.set({phase:`idle`}))}}unhold(){let e=this.release;this.release=void 0,e?.()}set(e){this.state=e;for(let e of[...this.listeners])e()}},ju={phase:`off`,voice:`off`,level:0,held:``,paused:!1},Mu=class{deps;state=ju;conversation;run=0;sinks=new Map;listeners=new Set;bubbles=0;constructor(e){this.deps=e}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}isOn(e){return this.state.phase!==`off`&&this.state.sessionID===e}errorFor(e){return this.state.error?.sessionID===e?this.state.error.message:void 0}needsTap(e){return this.state.error?.sessionID===e&&this.state.error.gesture===!0}toggle(e){return this.isOn(e)?this.stop():this.start(e)}end(){return this.stop()}async start(e){if(this.isOn(e))return;this.state.phase!==`off`&&await this.stop();let t=++this.run,n=``,r=!1;this.set({...ju,phase:`starting`,sessionID:e,voice:`starting`});let i=await this.deps.expose(e);if(t!==this.run)return;if(!i)return this.set({...ju,error:{sessionID:e,message:`Could not turn Voice on for this session.`}});let a=this.deps.create(e,{state:e=>t===this.run&&this.set({...this.state,voice:e,paused:e===`paused`}),level:e=>t===this.run&&this.set({...this.state,level:e}),held:e=>t===this.run&&this.set({...this.state,held:e}),ignored:e=>t===this.run&&this.set({...this.state,ignored:e}),timing:e=>t===this.run&&this.set({...this.state,timing:e}),detector:e=>t===this.run&&this.set({...this.state,detector:e}),user:t=>this.sinks.get(e)?.user(t)??`voice:${++this.bubbles}`,tick:(t,n)=>this.sinks.get(e)?.tick(t,n),agent:t=>this.sinks.get(e)?.agent(t),note:(i,a)=>{if((a===`err`||a===`gesture`)&&t===this.run&&this.state.phase===`starting`){n=i,r=a===`gesture`;return}if(a===`gesture`&&t===this.run&&this.state.phase===`on`){let t=this.stop(),n=this.run;t.then(()=>n===this.run&&this.set({...ju,error:{sessionID:e,message:i,gesture:!0}}));return}let o=this.sinks.get(e);o?o.note(i,a):this.deps.notify(i,a)},ended:()=>{t===this.run&&this.conversation===a&&this.state.phase!==`starting`&&(this.run++,this.conversation=void 0,this.set(ju))}});this.conversation=a;let o=await a.start();if(t===this.run){if(!o)return this.run++,this.conversation=void 0,this.set({...ju,error:{sessionID:e,message:n||`Could not start Voice mode.`,...r?{gesture:r}:{}}});this.set({...this.state,phase:`on`,agent:a.agent})}}async stop(e={}){this.run++;let t=this.conversation;this.conversation=void 0,this.state.phase!==`off`&&this.set(ju),this.deps.stopPlayback(),await t?.stop(e.keepalive?{keepalive:!0}:void 0)}mute(){let e=this.conversation;e&&(e.paused?e.resume():e.pause(),this.set({...this.state,paused:e.paused}))}hold(){let e=this.conversation;return!e||e.paused?()=>{}:(e.pause(),this.set({...this.state,paused:!0}),()=>{this.conversation===e&&e.paused&&(e.resume(),this.set({...this.state,paused:!1}))})}async sendTyped(e,t){let n=this.conversation;return!n||n.sessionID!==e||this.state.phase!==`on`?!1:(await n.sendTyped(t),!0)}onEvent(e){this.conversation&&e.sessionID===this.conversation.sessionID&&this.conversation.onEvent(e)}onStatus(e,t){this.conversation?.sessionID===e&&this.conversation.onStatus(t)}attach(e,t){return this.sinks.set(e,t),()=>{this.sinks.get(e)===t&&this.sinks.delete(e)}}set(e){this.state=e;for(let e of[...this.listeners])e()}},Nu=3e3,Pu=`Voice mode on`,Fu=`Voice mode paused · unlock to talk`,Iu={starting:`starting`,listening:`listening`,hearing:`listening`,transcribing:`thinking`,sent:`thinking`,speaking:`speaking`,paused:`muted`,suspended:`paused`,off:`off`},Lu=(e,t,n)=>({sessionID:e,title:n===`suspended`?Fu:Pu,body:`${t} · ${Iu[n]??n}`}),Ru=class{controller;surface;options;shown;shownAt=0;timer;mediaFor;now;setTimer;clearTimer;unsubscribe;constructor(e,t,n){this.controller=e,this.surface=t,this.options=n,this.now=n.now??Date.now,this.setTimer=n.setTimer??((e,t)=>setTimeout(e,t)),this.clearTimer=n.clearTimer??(e=>clearTimeout(e)),this.unsubscribe=e.subscribe(()=>this.refresh())}needsPermission(){return this.controller.state.phase===`on`&&!this.surface.allowed()}async endFromNotification(e){this.controller.state.phase!==`off`&&this.controller.state.sessionID===e&&await this.controller.end()}refresh(){let e=this.controller.state;if(e.phase!==`on`||!e.sessionID)return this.clear();let t=e.sessionID,n=this.options.title(t);if(this.mediaFor!==t&&(this.mediaFor=t,this.surface.media({title:Pu,artist:n},()=>void this.controller.end())),!this.surface.allowed())return;let r=Lu(t,n,e.voice);if(this.shown&&this.shown.sessionID===r.sessionID&&this.shown.body===r.body)return this.cancel();let i=r.title!==this.shown?.title,a=this.shown?.sessionID===t&&!i?this.shownAt+Nu-this.now():0;if(a<=0)return this.show(r);this.timer===void 0&&(this.timer=this.setTimer(()=>{this.timer=void 0,this.refresh()},a))}dispose(){this.unsubscribe(),this.cancel(),this.surface.close(),this.mediaFor&&this.surface.media(null),this.shown=this.mediaFor=void 0}show(e){this.cancel(),this.surface.show(e),this.shown=e,this.shownAt=this.now()}clear(){this.cancel(),this.shown&&this.surface.close(),this.mediaFor&&this.surface.media(null),this.shown=this.mediaFor=void 0}cancel(){this.timer!==void 0&&(this.clearTimer(this.timer),this.timer=void 0)}},zu=[`image/png`,`image/jpeg`,`image/webp`,`image/gif`],Bu={maxImages:4,maxSide:1600,perImageBase64:18e4,totalBase64:7e5},Vu=[.85,.72,.6,.48,.36],Hu=[1,.75,.55,.4,.28,.2],Uu=class extends Error{constructor(e=`This image is too large to attach, even after shrinking it`){super(e),this.name=`ImageTooLargeError`}},Wu=e=>4*Math.ceil(e/3),Gu=e=>zu.includes(e);function Ku(e,t,n=Bu){if(e>=n.maxImages)return`Attach at most ${n.maxImages} images to a message`;if(!Gu(t))return`Only PNG, JPEG, WebP or GIF images can be attached`}function qu(e,t=Bu){return Math.max(0,Math.min(t.perImageBase64,t.totalBase64-e))}function Ju(e,t,n){let r=Math.min(1,n/Math.max(e,t));return{width:Math.max(1,Math.round(e*r)),height:Math.max(1,Math.round(t*r))}}function Yu(e,t){let n=t===`image/png`?`png`:t===`image/gif`?`gif`:t===`image/webp`?`webp`:`jpg`;return`${e.replace(/\.[A-Za-z0-9]{1,5}$/,``)||`image`}.${n}`}async function Xu(e,t,n,r=Bu){if(t<=0)throw new Uu(`No room for another image in this message`);let i=Ju(e.width,e.height,r.maxSide);for(let r of Hu){let a=Math.max(1,Math.round(i.width*r)),o=Math.max(1,Math.round(i.height*r)),s=[...e.keepPng?[{type:`image/png`,width:a,height:o}]:[],...Vu.map(e=>({type:`image/jpeg`,quality:e,width:a,height:o}))];for(let e of s){let r=await n(e);if(Wu(r.size)<=t)return{blob:r,request:e}}}throw new Uu}var Zu=()=>({draft:``,images:[],pending:[],stopping:!1});function Qu(e,t){switch(t.type){case`input`:return{...e,draft:t.text,error:void 0};case`attach`:return e.images.length>=Bu.maxImages?e:{...e,images:[...e.images,t.image],error:void 0};case`detach`:return{...e,images:e.images.filter(e=>e.id!==t.id),error:void 0};case`attachError`:return{...e,error:t.message};case`submit`:{let n=e.draft.trim();if(!n&&!e.images.length)return e;let r={id:t.id,text:n,...e.images.length?{images:e.images}:{}};return{...e,draft:``,images:[],pending:[...e.pending,r],error:void 0}}case`accepted`:return e.pending.some(e=>e.id===t.id)?{...e,pending:e.pending.filter(e=>e.id!==t.id)}:e;case`rejected`:{let n=e.pending.find(e=>e.id===t.id);return n?{...e,draft:e.draft&&n.text?`${n.text}\n${e.draft}`:n.text||e.draft,images:[...n.images??[],...e.images].slice(0,Bu.maxImages),pending:e.pending.filter(e=>e.id!==t.id),error:t.message}:e}case`stop`:return{...e,stopping:!0};case`stopped`:return{...e,stopping:!1}}}function $u(e,{running:t,offline:n}){let r=e.draft.trim().length>0||e.images.length>0,i=e.pending.length>0&&!t;return{primary:t?`steer`:`send`,canSubmit:r&&!n&&!i,showStop:t,canStop:t&&!n&&!e.stopping,...n?{hint:`The machine running this session is disconnected; it is read-only until it reconnects.`}:{}}}function ed(e,t){return e===202?t.mode===`turn`?`accepted`:`steered`:`result`}function td(e){if(e.outcome&&e.outcome!==`succeeded`)return e.outcome===`timeout`?{text:`The agent is still working; the reply may be partial.`,kind:`sys`}:{text:`Turn ${e.outcome}${e.message?`: ${e.message}`:``}`,kind:`err`}}async function nd(e,{timeoutMs:t=4e3,pollMs:n=100}={}){let r=Date.now()+t;for(;;){if(e())return!0;if(Date.now()>=r)return!1;await new Promise(e=>setTimeout(e,Math.min(n,Math.max(0,r-Date.now()))))}}var rd=class{drafts=new Map;listeners=new Set;get(e){return this.drafts.get(e)??``}set(e,t){if(this.get(e)!==t){t?this.drafts.set(e,t):this.drafts.delete(e);for(let t of[...this.listeners])t(e)}}append(e,t){let n=this.get(e).replace(/\s+$/,``),r=n?`${n} ${t}`:t;return this.set(e,r),r}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}},id=-19.5,ad=-50,od=20,sd=9,cd=2,ld=60,ud=.4,dd=.1,fd=-70,pd=-10,md=e=>e>0?20*Math.log10(e):-1/0,hd=e=>e>0?-.691+10*Math.log10(e):-1/0;function gd(e){let t=1681.974450955533,n=.7071752369554196,r=Math.tan(Math.PI*t/e),i=10**(3.999843853973347/20),a=i**.4996667741545416,o=1+r/n+r*r,s={b0:(i+a*r/n+r*r)/o,b1:2*(r*r-i)/o,b2:(i-a*r/n+r*r)/o,a1:2*(r*r-1)/o,a2:(1-r/n+r*r)/o};return t=38.13547087602444,n=.5003270373238773,r=Math.tan(Math.PI*t/e),o=1+r/n+r*r,[s,{b0:1,b1:-2,b2:1,a1:2*(r*r-1)/o,a2:(1-r/n+r*r)/o}]}function _d(e,t){let n=new Float64Array(e.length),r=0,i=0,a=0,o=0;for(let s=0;s<e.length;s++){let c=e[s],l=t.b0*c+t.b1*r+t.b2*i-t.a1*a-t.a2*o;i=r,r=c,o=a,a=l,n[s]=l}return n}function vd(e,t){if(!e.length)return-1/0;let[n,r]=gd(t),i=_d(_d(e,n),r),a=new Float64Array(i.length+1);for(let e=0;e<i.length;e++)a[e+1]=a[e]+i[e]*i[e];let o=Math.round(ud*t),s=Math.round(dd*t);if(i.length<o){let e=hd(a[i.length]/i.length);return e>fd?e:-1/0}let c=[];for(let e=0;e+o<=i.length;e+=s){let t=(a[e+o]-a[e])/o;hd(t)>fd&&c.push(t)}if(!c.length)return-1/0;let l=e=>e.reduce((e,t)=>e+t,0)/e.length,u=hd(l(c))+pd,d=c.filter(e=>hd(e)>u);return hd(l(d.length?d:c))}function yd(e){let t=0;for(let n=0;n<e.length;n++)t=Math.max(t,Math.abs(e[n]));return md(t)}function bd(e,t){let n=10**(ad/20),r=0;for(;r<e.length&&Math.abs(e[r])<=n;)r++;if(r===e.length)return e;let i=e.length-1;for(;i>r&&Math.abs(e[i])<=n;)i--;let a=Math.round(80/1e3*t),o=Math.max(0,r-a),s=Math.min(e.length,i+1+a);return o===0&&s===e.length?e:e.slice(o,s)}function xd(e,t,n,r){let i=e.length,a=new Float32Array(i),o=!1;for(let t=0;t<i;t++){let i=Math.abs(e[t]*n);a[t]=i>r?r/i:1,i>r&&(o=!0)}let s=new Float32Array(i);if(o){let e=Math.exp(-1/Math.max(1,cd/1e3*t)),n=Math.exp(-1/Math.max(1,ld/1e3*t)),r=1;for(let t=i-1;t>=0;t--)a[t]=r=Math.min(a[t],1-(1-r)*e);r=1;for(let e=0;e<i;e++)a[e]=r=Math.min(a[e],1-(1-r)*n)}for(let t=0;t<i;t++)s[t]=e[t]*n*a[t];return s}function Sd(e,t,n){let r=bd(e,t),i=vd(r,t);if(!Number.isFinite(i))return{samples:r,gainDb:0,loudness:i};let a=10**(-1/20),o=Math.min(od,-1-yd(r)+sd),s=Math.min(n-i,o),c=xd(r,t,10**(s/20),a);for(let e=0;e<3;e++){let e=n-vd(c,t);if(e<.1||s>=o)break;s=Math.min(s+e,o),c=xd(r,t,10**(s/20),a)}return{samples:c,gainDb:s,loudness:i}}function Cd(e,t){let n=new Uint8Array(44+e.length*2),r=new DataView(n.buffer),i=(e,t)=>{for(let r=0;r<t.length;r++)n[e+r]=t.charCodeAt(r)};i(0,`RIFF`),r.setUint32(4,n.length-8,!0),i(8,`WAVE`),i(12,`fmt `),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,`data`),r.setUint32(40,e.length*2,!0);for(let t=0;t<e.length;t++){let n=Math.max(-1,Math.min(1,e[t]));r.setInt16(44+t*2,Math.round(n<0?n*32768:n*32767),!0)}return n}var wd=`voice.replyLoudness`,Td=8;function Ed(e){try{let t=JSON.parse(e.getItem(wd)??`{}`);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}function Dd(e,t){let n=Ed(e)[t];return Array.isArray(n)?n.filter(e=>typeof e==`number`&&Number.isFinite(e)):[]}function Od(e,t,n){if(!(!Number.isFinite(n)||n<-50||n>0))try{let r=Ed(e),i=[...Dd(e,t),Math.round(n*10)/10].slice(-21);delete r[t],r[t]=i;let a=Object.keys(r);for(let e of a.slice(0,Math.max(0,a.length-Td)))delete r[e];e.setItem(wd,JSON.stringify(r))}catch{}}var kd=e=>{let t=[...e].sort((e,t)=>e-t),n=t.length>>1;return t.length%2?t[n]:(t[n-1]+t[n])/2};function Ad(e,t){let n=[];try{t!==void 0&&(n=Dd(e,t))}catch{n=[]}return n.length?Math.min(-14,Math.max(-26,kd(n))):id}var jd={heard:[{freq:880,ms:80}],done:[{freq:660,ms:70},{gap:50},{freq:990,ms:70}],pending:[{freq:587,ms:110}],paused:[{freq:784,ms:90},{gap:40},{freq:523,ms:160}],resumed:[{freq:523,ms:90},{gap:40},{freq:784,ms:120}]},Md=`hub-cues-v2`,Nd=[`hub-cues-v1`],Pd=`x-hub-cue-target`,Fd=1,Id=`https://hub-cues.invalid`,Ld=e=>`${Id}/${encodeURIComponent(e)}/`,Rd=(e,t)=>`${Ld(e)}${encodeURIComponent(t)}`;async function zd(){try{let e=globalThis.caches;return e?await e.open(Md):void 0}catch{return}}function Bd(e,t){e.defaultPlaybackRate=t,e.playbackRate=t,e.preservesPitch=!0,e.webkitPreservesPitch=!0}var Vd=class{api;speed;onSpeaking;normalize;target;phrases=new Map;urls=new Map;key=Promise.resolve(void 0);audio;ctx;loading=new AbortController;speaking=!1;constructor({api:e,speed:t,onSpeaking:n,audio:r,normalize:i,target:a}){this.api=e,this.speed=t,this.onSpeaking=n,this.normalize=i,this.target=a,this.audio=r??new Audio}unlock(){let e=globalThis,t=e.AudioContext||e.webkitAudioContext;t&&((!this.ctx||this.ctx.state===`closed`)&&(this.ctx=new t),this.ctx.resume?.().catch(()=>{}))}play(e){for(let t of e??[])t.type===`earcon`?this.earcon(t.name):t.type===`speak`&&this.say(t.text)}earcon(e){let t=this.ctx,n=jd[e];if(!t||!n||t.state===`closed`)return;let r=t.currentTime+.01;for(let e of n){if(e.gap){r+=e.gap/1e3;continue}let n=t.createOscillator(),i=t.createGain(),a=r+(e.ms??0)/1e3;n.type=`sine`,n.frequency.value=e.freq??440,i.gain.setValueAtTime(1e-4,r),i.gain.exponentialRampToValueAtTime(.12,r+.012),i.gain.exponentialRampToValueAtTime(1e-4,a),n.connect(i).connect(t.destination),n.start(r),n.stop(a+.02),r=a}}async prefetch(e,t){this.key=Promise.resolve(t).catch(()=>void 0);let n=[...e],{signal:r}=this.loading;await Promise.all([this.prune(),...Array.from({length:Math.min(2,n.length)},async()=>{for(let e=n.shift();e!==void 0&&!r.aborted;e=n.shift())await this.phrase(e).catch(()=>void 0)})])}ready(e){return this.urls.has(e)}phrase(e){let t=this.phrases.get(e);return t||(t=this.load(e),this.phrases.set(e,t),t.catch(()=>this.phrases.delete(e))),t}async load(e){let{signal:t}=this.loading,n=await this.key,r=n?await zd():void 0,i=n?Rd(n,e):``,a=this.target?.(n)??-19.5,o=r?await r.match(i).catch(()=>void 0):void 0,s=await o?.blob().catch(()=>void 0),c=!this.normalize||Math.abs(Number(o?.headers.get(Pd)??NaN)-a)<=Fd;if(!s||!c){let n=s??await(await this.api(`/api/speak`,{method:`POST`,json:{text:e},signal:t})).blob();s=n;let o={};if(this.normalize)try{s=await this.normalize(n,a),o[Pd]=String(a)}catch{}o[`content-type`]=s.type||`audio/mpeg`,await r?.put(i,new Response(s,{headers:o})).catch(()=>{})}let l=URL.createObjectURL(s);return this.urls.set(e,l),l}async prune(){let e=await this.key,t=e?await zd():void 0;if(!t||!e)return;let n=globalThis.caches;for(let e of Nd)await n?.delete(e).catch(()=>!1);try{for(let n of await t.keys())n.url.startsWith(Ld(e))||await t.delete(n)}catch{}}say(e){let t=this.urls.get(e);return t?this.playURL(t):(this.earcon(`pending`),this.phrase(e).catch(()=>{}),Promise.resolve())}async playURL(e){let t=this.audio;this.setSpeaking(!0),t.src=e,t.volume=1,Bd(t,this.speed?.()??1);let n=new Promise(e=>{t.onended=t.onpause=t.onerror=()=>e()});await t.play().then(()=>!0,()=>!1)&&await n,t.onended=t.onpause=t.onerror=null,this.setSpeaking(!1)}stop(){this.audio.paused||this.audio.pause(),this.setSpeaking(!1)}setSpeaking(e){e!==this.speaking&&(this.speaking=e,this.onSpeaking?.(e))}close(){this.stop(),this.loading.abort(),this.loading=new AbortController,this.ctx?.close?.().catch(()=>{}),this.ctx=void 0}},Hd=new Set([`um`,`umm`,`uh`,`uhh`,`uhm`,`erm`,`er`,`eh`,`ah`,`hmm`,`hm`,`mm`,`mmm`,`mhm`,`mm-hmm`,`uh-huh`]),Ud=new Set([...Hd,`and`,`but`,`so`,`or`,`because`,`cause`,`then`,`with`,`to`,`the`,`a`,`an`,`of`,`for`,`if`,`that`,`like`,`maybe`]),Wd=new Map([[`stop`,`interrupt`],[`cancel`,`interrupt`],[`never mind`,`interrupt`],[`nevermind`,`interrupt`],[`stop that`,`interrupt`],[`hold on`,`interrupt`],[`pause listening`,`pause`]]);function Gd(e){return String(e??``).toLowerCase().replace(/[^\p{L}\p{N}'\s-]+/gu,` `).split(/\s+/).map(e=>e.replace(/^[-']+|[-']+$/g,``)).filter(Boolean)}function Kd(e){return Wd.get(Gd(e).join(` `))}function qd(e){return Gd(e).every(e=>Hd.has(e))}function Jd(e){let t=String(e??``).trim(),n=Gd(t);return!n.length||Ud.has(n[n.length-1])||/(\.\.\.|…|[,;:\-–—])["'”’)\]]*$/.test(t)?!1:/[.?!]["'”’)\]]*$/.test(t)?!0:n.length>=3}var Yd=new Set([`e.g.`,`i.e.`,`mr.`,`mrs.`,`ms.`,`dr.`,`st.`,`vs.`,`cf.`,`prof.`,`jr.`,`sr.`,`approx.`,`no.`,`fig.`]),Xd=/[.?!…]+["'”’)\]]*(?=\s|$)/g;function Zd(e,{minChars:t=4,maxChars:n=300}={}){let r=String(e??``).replace(/```[\s\S]*?(?:```|$)/g,`
7
+ (code omitted)
8
+ `).split(/\r?\n/).map(e=>e.replace(/\s+/g,` `).trim()).filter(Boolean).flatMap(Qd),i=[],a=``;for(let e of r){let n=a?`${a} ${e}`:e;n.length<t?a=n:(i.push(n),a=``)}return a&&(i.length?i[i.length-1]+=` ${a}`:i.push(a)),i.flatMap(e=>$d(e,n))}function Qd(e){let t=[],n=0;for(let r of e.matchAll(Xd)){let i=r.index+r[0].length;if(i>=e.length)break;let a=e.slice(i).trimStart()[0]??``;if(!/[?!]/.test(r[0])){let t=e.lastIndexOf(` `,r.index)+1,n=e.slice(t,i).toLowerCase(),o=t===0&&/^\d+[.)]$/.test(n);if(Yd.has(n.replace(/["'”’)\]]+$/,``))||o||/\p{Ll}/u.test(a))continue}t.push(e.slice(n,i).trim()),n=i}let r=e.slice(n).trim();return r&&t.push(r),t.filter(Boolean)}function $d(e,t){let n=[],r=e;for(;r.length>t;){let e=r.slice(0,t),i=Math.max(e.lastIndexOf(`, `),e.lastIndexOf(`; `));i=i>t/2?i+1:e.lastIndexOf(` `),i<=0&&(i=t),n.push(r.slice(0,i).trim()),r=r.slice(i).trim()}return r&&n.push(r),n}var ef=16e3;function tf(e,t,n){if(t===n)return Float32Array.from(e);let r=Math.floor(e.length*n/t),i=new Float32Array(r),a=t/n;if(a>1)for(let t=0;t<r;t++){let n=Math.floor(t*a),r=Math.min(e.length,Math.max(n+1,Math.floor((t+1)*a))),o=0;for(let t=n;t<r;t++)o+=e[t];i[t]=o/(r-n)}else for(let t=0;t<r;t++){let n=t*a,r=Math.floor(n),o=e[Math.min(r+1,e.length-1)];i[t]=e[r]+(o-e[r])*(n-r)}return i}function nf(e,t){return Cd(tf(e,t,ef),ef)}function rf(e){return{audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,...e?{deviceId:{exact:e}}:{}}}}var af=Object.freeze({minSpeechMs:300,endSilenceMs:350,trailingKeepMs:200,preRollMs:300,holdMs:800}),of=af.trailingKeepMs,sf=120,cf=4,lf=e=>e.reduce((e,t)=>e+t.ms,0);function uf(e,t){for(;e.length>1&&lf(e)-e[0].ms>=t;)e.shift()}var df=class{sampleRate;minSpeechMs;endSilenceMs;preRollMs;maxSegmentMs;onsetGapMs;minVoicedRatio;state=`silence`;preroll=[];frames=[];segmentMs=0;onsetMs=0;voicedMs=0;gapMs=0;silenceMs=0;constructor({sampleRate:e,minSpeechMs:t=af.minSpeechMs,endSilenceMs:n=af.endSilenceMs,preRollMs:r=af.preRollMs,maxSegmentMs:i=6e4,onsetGapMs:a=sf,minVoicedRatio:o=0}){this.sampleRate=e,this.minSpeechMs=t,this.endSilenceMs=n,this.preRollMs=r,this.maxSegmentMs=i,this.onsetGapMs=a,this.minVoicedRatio=o,this.reset()}get active(){return this.state===`speech`}reset(){this.state=`silence`,this.preroll=[],this.frames=[],this.segmentMs=0,this.onsetMs=0,this.voicedMs=0,this.gapMs=0,this.silenceMs=0}process(e,t){let n={samples:Float32Array.from(e),ms:e.length/this.sampleRate*1e3},r=[];if(this.state===`silence`)t?(this.state=`onset`,this.frames=[...this.preroll,n],this.segmentMs=lf(this.frames),this.preroll=[],this.onsetMs=this.voicedMs=n.ms,this.gapMs=0):(this.preroll.push(n),uf(this.preroll,this.preRollMs));else if(this.state===`onset`)this.frames.push(n),this.segmentMs+=n.ms,this.onsetMs+=n.ms,t?(this.voicedMs+=n.ms,this.gapMs=0):((this.gapMs+=n.ms)>this.onsetGapMs||this.voicedMs<this.minVoicedRatio*this.onsetMs)&&(this.preroll=this.frames,uf(this.preroll,this.preRollMs),this.frames=[],this.state=`silence`),this.state===`onset`&&this.voicedMs>=this.minSpeechMs&&(this.state=`speech`,this.silenceMs=0,r.push({type:`start`}));else if(this.frames.push(n),this.segmentMs+=n.ms,t&&(this.voicedMs+=n.ms),this.silenceMs=t?0:this.silenceMs+n.ms,this.silenceMs>=this.endSilenceMs){let e=this.silenceMs-of;for(;this.frames.length&&this.frames[this.frames.length-1].ms<=e;)e-=this.frames.pop().ms;r.push(this.finish(!1))}else this.segmentMs>=this.maxSegmentMs&&r.push(this.finish(!0));return r}finish(e){let t=new Float32Array(this.frames.reduce((e,t)=>e+t.samples.length,0)),n=0;for(let e of this.frames)t.set(e.samples,n),n+=e.samples.length;let r=this.voicedMs;return this.reset(),{type:`end`,samples:t,durationMs:t.length/this.sampleRate*1e3,forced:e,speechMs:r}}},ff=class{marginDb;minDb;speakingBoostDb;speaking=!1;floor=void 0;constructor({marginDb:e=10,minDb:t=-50,speakingBoostDb:n=8}={}){this.marginDb=e,this.minDb=t,this.speakingBoostDb=n}measure(e,t,n){let r=0;for(let t=0;t<e.length;t++)r+=e[t]*e[t];let i=20*Math.log10(Math.max(Math.sqrt(r/Math.max(1,e.length)),1e-7)),a=this.floor??=i,o=Math.max(a+this.marginDb,this.minDb)+(this.speaking?this.speakingBoostDb:0),s=i>=(n?o-cf:o),c=Math.max(0,Math.min(1,(i-a)/36)),l=t/(n?15e3:4e3);return this.floor+=(i-a)*(i<a?.2:Math.min(1,l)),{db:i,floor:a,level:c,voiced:s}}},pf=class{sendFn;holdMs;maxUtteranceMs;onHeld;setTimer;clearTimer;nextID=1;pending=[];text=``;ms=0;speaking=!1;timer;constructor({send:e,holdMs:t=af.holdMs,maxUtteranceMs:n=6e4,onHeld:r,setTimer:i=(e,t)=>setTimeout(e,t),clearTimer:a=e=>clearTimeout(e)}){this.sendFn=e,this.holdMs=t,this.maxUtteranceMs=n,this.onHeld=r,this.setTimer=i,this.clearTimer=a,this.reset()}get held(){return this.text}reset(){this.cancelHold(),this.pending=[],this.text=``,this.ms=0,this.speaking=!1,this.onHeld?.(``)}speechStarted(){this.speaking=!0,this.cancelHold()}segmentEnded(e){this.speaking=!1;let t=this.nextID++;return this.pending.push({id:t,ms:e}),t}transcribed(e,t){let n=this.pending.find(t=>t.id===e);if(n){for(n.text=String(t??``).replace(/\s+/g,` `).trim();this.pending[0]?.text!==void 0;)this.apply(this.pending.shift());this.evaluate()}}apply({text:e,ms:t}){Kd(e)?(this.cancelHold(),this.text=``,this.ms=0,this.sendFn(e)):qd(e)||(this.text=this.text?`${this.text} ${e}`:e,this.ms+=t,(Jd(this.text)||this.ms>=this.maxUtteranceMs)&&this.flush())}evaluate(){this.onHeld?.(this.text),!(!this.text||this.speaking||this.pending.length)&&(this.cancelHold(),this.timer=this.setTimer(()=>{this.timer=void 0,this.flush()},this.holdMs))}flush(){this.cancelHold();let e=this.text;this.text=``,this.ms=0,e&&this.sendFn(e),this.onHeld?.(``)}cancelHold(){this.timer!==void 0&&this.clearTimer(this.timer),this.timer=void 0}},mf=2,hf=class{synth;play;stop;onState;onError;items=[];generation=0;controller=new AbortController;speaking=!1;playing=!1;constructor({synth:e,play:t,stop:n,onState:r,onError:i}){this.synth=e,this.play=t,this.stop=n,this.onState=r,this.onError=i}enqueue(e){for(let t of e)String(t??``).trim()&&this.items.push({text:String(t).trim()});this.items.length&&(this.speaking?this.prefetch():this.run(this.generation))}prefetch(){for(let e of this.items.slice(0,this.playing?mf:3))this.fetch(e)}clear(){this.generation++,this.controller.abort(),this.controller=new AbortController,this.items=[],this.playing=!1,this.stop(),this.setSpeaking(!1)}fetch(e){e&&!e.audio&&(e.audio=this.synth(e.text,this.controller.signal),e.audio.catch(()=>{}))}async run(e){for(this.setSpeaking(!0);e===this.generation&&this.items.length;){let t=this.items[0];this.prefetch();let n;try{n=await t.audio}catch(n){if(e!==this.generation)return;this.items.shift(),this.onError?.(n,t.text);continue}if(e!==this.generation)return;this.items.shift(),this.playing=!0,this.prefetch();try{await this.play(n)}catch(n){e===this.generation&&this.onError?.(n,t.text)}finally{e===this.generation&&(this.playing=!1)}}e===this.generation&&this.setSpeaking(!1)}setSpeaking(e){e!==this.speaking&&(this.speaking=e,this.onState?.(e))}},gf=class{parts=new Map;limit;constructor({limit:e=50}={}){this.limit=e}get size(){return this.parts.size}accept(e){let t=String(e.text??``);if(typeof e.seq!=`number`)return{sentences:Zd(t),text:t};let n=`${e.messageID??``} ${e.ordinal??0}`,r=this.parts.get(n);if(r||(r={next:0,held:new Map,texts:[],muted:!1},this.parts.set(n,r),this.parts.size>this.limit&&this.parts.delete(this.parts.keys().next().value)),e.seq<r.next||r.held.has(e.seq))return;r.held.set(e.seq,t);let i=[];for(;r.held.has(r.next);)i.push(r.held.get(r.next)),r.held.delete(r.next++);if(i.length)return r.texts.push(...i),{sentences:r.muted?[]:i.flatMap(e=>Zd(e)),text:r.texts.join(` `)}}mute(){for(let e of this.parts.values())e.muted=!0}},_f=class{pending={};turn;last;mark(e,t){switch(e){case`speechEnd`:return this.pending={speechEnd:t},!0;case`transcript`:return this.pending.speechEnd!==void 0&&(this.pending.transcript=t,!0);case`accepted`:return this.turn={...this.pending,accepted:t},this.pending={},!0;case`firstSay`:return!this.turn||this.turn.firstSay!==void 0?!1:(this.turn.firstSay=t,!0);case`firstByte`:return this.turn?.firstSay===void 0||this.turn.firstByte!==void 0?!1:(this.turn.firstByte=t,!0);case`firstAudio`:return this.turn?.firstSay!==void 0&&(this.last={...this.turn,firstAudio:t},this.turn=void 0,!0)}}},vf=e=>`${(e/1e3).toFixed(1)} s`;function yf(e){let t=e?.speechEnd??e?.accepted;if(!e||t===void 0||e.firstAudio===void 0)return;let n=[[`transcript`,`transcript`],[`accepted`,`accepted`],[`firstSay`,`first reply`],[`firstByte`,`first byte`],[`firstAudio`,`audio`]],r=[],i=t;for(let[t,a]of n){let n=e[t];n===void 0||t===`accepted`&&e.speechEnd===void 0||(r.push(`${a} ${vf(n-i)}`),i=n)}return{summary:`last turn: ${vf(e.firstAudio-t)} to first audio`,detail:r.join(` · `)}}var bf=12,xf=e=>String(e??``).replace(/\s+/g,` `).trim();function Sf(e,t){let n=xf(e),r=xf(t);if(!n)return{mode:`new`,text:t};if(n.includes(r))return{mode:`keep`,text:e};if(r.startsWith(n))return{mode:`update`,text:t};for(let e=Math.min(n.length,r.length-1);e>=bf;e--)if(n.endsWith(r.slice(0,e)))return{mode:`update`,text:n+r.slice(e)};return{mode:`new`,text:t}}function Cf(e,t,n){let r=new Map((e??[]).map(e=>[e.id,e])),i=[],a=e=>`Subagent “${e.title||e.id}”`;for(let e of t){if(e.id===n)continue;let t=r.get(e.id)?.state;r.delete(e.id),e.state!==t&&(e.state===`working`?i.push(`${a(e)} is working`):e.state===`error`?i.push(`${a(e)} failed${e.detail?`: ${e.detail}`:``}`):e.state===`blocked`?i.push(`${a(e)} needs you`):(t===`working`||t===`blocked`)&&i.push(`${a(e)} finished`))}for(let e of r.values())e.id!==n&&(e.state===`working`||e.state===`blocked`)&&i.push(`${a(e)} finished`);return i}var wf=16e3,Tf=512/wf*1e3,Ef=Object.freeze({startProb:.6,endProb:.35,speakingStartProb:.85,minSpeechMs:250,endSilenceMs:af.endSilenceMs,maxSegmentMs:6e4,gateDb:3,energyMarginDb:10,energyMinSpeechMs:af.minSpeechMs}),Df=Object.freeze([`low`,`normal`,`high`]);function Of(e){return Df.includes(e)?e:`normal`}var kf=Object.freeze({low:Object.freeze({...Ef,startProb:.75,endProb:.45,speakingStartProb:.92,minSpeechMs:350,gateDb:6,energyMarginDb:13,energyMinSpeechMs:400}),normal:Ef,high:Object.freeze({...Ef,startProb:.45,endProb:.25,speakingStartProb:.75,minSpeechMs:180,gateDb:0,energyMarginDb:7,energyMinSpeechMs:250})});function Af(e){return kf[Of(e)]}var jf=.75,Mf=class{speaking=!1;segmenter;current;constructor(e,t=wf){this.current=e,this.segmenter=new df({sampleRate:t,endSilenceMs:e.endSilenceMs,maxSegmentMs:e.maxSegmentMs})}get params(){return this.current}set params(e){this.current=e,this.segmenter.endSilenceMs=e.endSilenceMs,this.segmenter.maxSegmentMs=e.maxSegmentMs}get state(){return this.segmenter.state}get active(){return this.segmenter.active}reset(){this.segmenter.reset()}process(e,t){let n=this.current;this.segmenter.minSpeechMs=n.minSpeechMs,this.segmenter.minVoicedRatio=jf;let r=this.segmenter.state===`speech`?n.endProb:this.speaking?n.speakingStartProb:n.startProb;return this.segmenter.process(e,t>=r)}processEnergy(e,t){return this.segmenter.minSpeechMs=this.current.energyMinSpeechMs,this.segmenter.minVoicedRatio=0,this.segmenter.process(e,t)}},Nf=class{from;ratio;input=new Float32Array;pos=0;out=new Float32Array(512);filled=0;constructor(e){this.from=e,this.ratio=e/wf}push(e){let t=new Float32Array(this.input.length+e.length);t.set(this.input),t.set(e,this.input.length);let n=[],r=e=>{this.out[this.filled++]=e,this.filled===512&&(n.push(this.out),this.out=new Float32Array(512),this.filled=0)},i=this.ratio;if(i>=1)for(;;){let e=Math.floor(this.pos+1e-9),n=Math.max(e+1,Math.floor(this.pos+i+1e-9));if(n>t.length)break;let a=0;for(let r=e;r<n;r++)a+=t[r];r(a/(n-e)),this.pos+=i}else for(;;){let e=Math.floor(this.pos);if(e+1>=t.length)break;r(t[e]+(t[e+1]-t[e])*(this.pos-e)),this.pos+=i}let a=Math.min(t.length,Math.floor(this.pos+1e-9));return this.input=t.slice(a),this.pos-=a,n}},Pf=64,Ff=class{sampleRate=wf;stats={frames:0,avgMs:0,maxMs:0,skipped:0};resampler;meter;vad;onEvents;onLevel;warn;now;model;queue=[];inFlight=0;generation=0;warned=new Set;speakingOn=!1;tail=0;constructor({sampleRate:e,params:t=Ef,onEvents:n,onLevel:r,warn:i=e=>console.warn(e),now:a=()=>performance.now()}){this.resampler=new Nf(e),this.meter=new ff({marginDb:t.energyMarginDb}),this.vad=new Mf(t),this.onEvents=n,this.onLevel=r,this.warn=i,this.now=a}get classifier(){return this.model}set classifier(e){this.model=e}get mode(){return this.model?`silero`:`energy`}get params(){return this.vad.params}set params(e){this.vad.params=e,this.meter.marginDb=e.energyMarginDb}get speaking(){return this.speakingOn}set speaking(e){this.speakingOn&&!e&&(this.tail=Math.ceil(400/Tf)),this.speakingOn=e}get active(){return this.vad.active}reset(){this.generation++,this.queue=[],this.inFlight=0,this.vad.reset()}push(e){for(let t of this.resampler.push(e))this.chunk(t)}chunk(e){let t=this.speakingOn||this.tail>0;!this.speakingOn&&this.tail>0&&this.tail--,this.meter.speaking=t;let n=this.vad.state===`speech`,{db:r,floor:i,level:a,voiced:o}=this.meter.measure(e,Tf,n);this.onLevel?.(a);let s={chunk:e,energyVoiced:o,guarded:t};this.queue.push(s),this.model&&this.inFlight>=Pf&&this.drop(`stalled`);let c=this.model;if(!c)s.energy=!0;else if(!n&&r<i+this.vad.params.gateDb+(t?this.meter.speakingBoostDb:0))s.prob=0,this.stats.skipped++;else{let t=this.generation,n=this.now();this.inFlight++,c(e).then(e=>{t===this.generation&&(this.inFlight--,this.record(this.now()-n),s.prob=e,this.drain())},e=>{t===this.generation&&(this.inFlight--,s.energy=!0,this.model===c&&this.drop(e?.message??String(e)),this.drain())})}this.drain()}drop(e){this.model=void 0,this.generation++,this.inFlight=0;for(let e of this.queue)e.prob===void 0&&(e.energy=!0);this.warnOnce(`failed`,`Voice: on-device speech detection stopped (${e}); using the energy detector`)}record(e){let t=this.stats;t.frames++,t.avgMs+=(e-t.avgMs)/t.frames,t.maxMs=Math.max(t.maxMs,e)}drain(){let e=[];for(;this.queue.length&&(this.queue[0].energy||this.queue[0].prob!==void 0);){let t=this.queue.shift();this.vad.speaking=t.guarded,e.push(...t.energy?this.vad.processEnergy(t.chunk,t.energyVoiced):this.vad.process(t.chunk,t.prob))}e.length&&this.onEvents(e)}warnOnce(e,t){this.warned.has(e)||(this.warned.add(e),this.warn(t))}};function If(e){let t=new URL(e),n=t.searchParams.get(`voice`)===`1`;return t.searchParams.delete(`voice`),{voice:n,path:`${t.pathname}${t.search}${t.hash}`}}function Lf(e){return e.audioState===`suspended`||e.error===`NotAllowedError`&&!e.activated&&e.micPermission!==`denied`}var Rf=new Set(`yes.yeah.yep.yup.no.nope.nah.ok.okay.sure.right.correct.stop.cancel.wait.pause.hold.go.continue.next.done.again.undo.never.nevermind.do.please.thanks`.split(`.`)),zf=new Set([`you`,`bye`,`bye bye`,`thank you`,`thank you very much`,`thank you so much`,`thanks for watching`,`thank you for watching`,`thanks for watching and see you next time`,`thank you for watching and see you next time`,`thanks for listening`,`thank you for listening`,`see you next time`,`see you in the next video`,`please subscribe`,`please subscribe to my channel`,`like and subscribe`,`the end`,`ご視聴ありがとうございました`,`продолжение следует`,`字幕由amara org社区提供`,`untertitel im auftrag des zdf für funk 2017`]),Bf=[/^(?:subtitles?|captions?|subtitled|captioned|transcribed|transcription|translated|translation)\b.*\bby\b/,/\bamara\s*\.?\s*org\b/,/^sous-titr/,/^untertitel\b/],Vf=/^(?:\[[^\]]*\]|\([^)]*\)|\*[^*]*\*|♪[^♪]*♪|\s)+$/u;function Hf(e){return e.toLowerCase().replace(/[^\p{L}\p{N}'\s]+/gu,` `).replace(/\s+/g,` `).trim()}function Uf(e,{speechMs:t}={}){let n=String(e??``).trim();if(!n)return`empty`;if(!/[\p{L}\p{N}]/u.test(n))return`no words`;if(Vf.test(n))return`sound`;let r=Hf(n);if(r.replace(/\s/g,``).length<2)return`too short`;if(zf.has(r)||zf.has(r.replace(/ /g,``))||Bf.some(e=>e.test(r)||e.test(n.toLowerCase())))return`noise`;let i=r.split(` `),a=i.some(e=>Rf.has(e));if(i.length>1&&i.every(e=>e===i[0])&&!a)return`repeated`;if(t!==void 0&&t<400&&i.length<=2&&!a)return`short`}var Wf=3e4,Gf;function Kf(){return Gf??=qf().catch(e=>{throw Gf=void 0,e}),Gf}function qf(){return new Promise((e,t)=>{let n;try{n=new Worker(new URL(`/assets/silero-worker-C8-8vLVS.js`,``+import.meta.url),{type:`module`,name:`silero-vad`})}catch(e){return t(e)}let r=new Map,i=1,a=!1,o=e=>{for(let t of r.values())t.reject(e);r.clear(),n.terminate(),Gf=void 0,a||t(e)},s=setTimeout(()=>o(Error(`the speech model took too long to load`)),Wf);n.onerror=e=>{e.preventDefault(),clearTimeout(s),o(Error(e.message||`the speech detection worker failed`))},n.onmessage=t=>{let c=t.data;if(c.type===`ready`)clearTimeout(s),a=!0,e({classify(e){return new Promise((t,a)=>{let o=i++;r.set(o,{resolve:t,reject:a}),n.postMessage({type:`chunk`,id:o,samples:e})})},reset(){n.postMessage({type:`reset`})}});else if(c.type===`error`)clearTimeout(s),o(Error(c.message||`the speech model could not load`));else if(c.type===`prob`||c.type===`fail`){let e=r.get(c.id);r.delete(c.id),c.type===`prob`?e?.resolve(c.p):e?.reject(Error(c.message||`speech detection failed`))}}})}var Jf=()=>Object.assign(Error(`The download was aborted`),{name:`AbortError`}),Yf=class{chunks=[];firstByte;done=!1;error;resolveFirst;rejectFirst;waiters=[];constructor(){this.firstByte=new Promise((e,t)=>{this.resolveFirst=e,this.rejectFirst=t}),this.firstByte.catch(()=>{})}push(e){!this.done&&this.error===void 0&&e.byteLength&&(this.chunks.push(e),this.chunks.length===1&&this.resolveFirst(),this.wake())}end(){this.done||this.error!==void 0||(this.done=!0,this.resolveFirst(),this.wake())}fail(e){this.done||this.error!==void 0||(this.error=e??Error(`The download failed`),this.rejectFirst(this.error),this.wake())}async*read(e){let t=0;for(;;){if(e?.aborted)throw Jf();if(t<this.chunks.length)yield this.chunks[t++];else{if(this.error!==void 0)throw this.error;if(this.done)return;await new Promise(t=>{this.waiters.push(t),e?.addEventListener(`abort`,()=>t(),{once:!0})})}}}async whole(){for await(let e of this.read());return this.chunks}wake(){let e=this.waiters;this.waiters=[];for(let t of e)t()}};function Xf(e,t){let n=new Yf;if(!e)return n.end(),n;let r=e.getReader(),i=()=>{n.fail(Jf()),r.cancel().catch(()=>{})};return t?.aborted?i():t?.addEventListener(`abort`,i,{once:!0}),(async()=>{try{for(;;){let{done:e,value:t}=await r.read();if(e)break;t&&n.push(t)}n.end()}catch(e){n.fail(t?.aborted?Jf():e)}finally{t?.removeEventListener(`abort`,i)}})(),n}async function Zf(e,t,n){try{for await(let r of e.read(n))if(await t.append(r),n?.aborted)return!1}catch{return!1}return!n?.aborted&&(t.end(),!0)}function Qf(e){try{return e.MediaSource?.isTypeSupported?.(`audio/mpeg`)===!0}catch{return!1}}var $f=24e3,ep=1,tp=2;async function np(e){let t=globalThis,n=t.OfflineAudioContext||t.webkitOfflineAudioContext;if(!n)throw Error(`No OfflineAudioContext here`);let r=new n(1,1,$f),i=await new Promise((t,n)=>{r.decodeAudioData(e,t,n)?.then(t,n)}),a=Array.from({length:i.numberOfChannels},(e,t)=>i.getChannelData(t));if(a.length===1)return{samples:a[0],rate:i.sampleRate};let o=new Float32Array(i.length);for(let e of a)for(let t=0;t<o.length;t++)o[t]+=e[t]/a.length;return{samples:o,rate:i.sampleRate}}async function rp(e,t){let{samples:n,rate:r}=await np(await e.arrayBuffer()),i=Sd(n,r,t);return new Blob([Cd(i.samples,r)],{type:`audio/wav`})}function ip(e){try{return Ad(localStorage,e)}catch{return Ad({getItem:()=>null,setItem:()=>{}},e)}}var ap=0,op=e=>{let t=globalThis;t.requestIdleCallback?t.requestIdleCallback(e,{timeout:5e3}):setTimeout(e,500)};function sp(e,t){!t||!e.length||ap>=tp||(ap++,op(()=>{(async()=>{try{let n=new Uint8Array(e.reduce((e,t)=>e+t.byteLength,0)),r=0;for(let t of e)n.set(t,r),r+=t.byteLength;let{samples:i,rate:a}=await np(n.buffer);if(i.length<a*ep)return;Od(localStorage,t,vd(i,a))}catch{}finally{ap--}})()}))}var cp=500,lp=8e3,up=e=>Math.min(lp,cp*2**Math.max(0,e)),dp=class{options;live=!0;lastFrame=0;isMuted=!1;isEnded=!1;suspended=!1;visible=!0;gapMs;constructor(e={}){this.options=e,this.gapMs=e.gapMs??1500}get needsMic(){return this.isEnded}get wantsRecovery(){return!this.live&&this.visible}get reason(){if(!this.live)return this.isEnded?`ended`:this.isMuted?`muted`:this.suspended?`suspended`:`frames`}start(e){this.live=!0,this.isMuted=this.isEnded=this.suspended=!1,this.lastFrame=e}frame(e){this.lastFrame=e,!this.live&&!this.blocked()&&this.set(!0)}tick(e){this.live&&e-this.lastFrame>this.gapMs&&this.set(!1)}muted(e,t){this.isMuted=e,e&&this.lose()}ended(e){this.isEnded=!0,this.lose()}replaced(e){this.isEnded=this.isMuted=!1}audio(e,t){this.suspended=e!==`running`,this.suspended&&this.lose()}visibility(e,t){this.visible=e}blocked(){return this.isEnded||this.isMuted||this.suspended}lose(){this.live&&this.set(!1)}set(e){this.live=e,this.options.onChange?.(e,this.reason)}},fp=2500,pp=3e3,mp=!1,hp=2,gp=`Tap to start Voice mode`,_p=`GestureRequired`,vp=500,yp=500,bp=3e3,xp=()=>navigator.userActivation?.hasBeenActive??!0;async function Sp(){try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return`unknown`}}var Cp={speechEnd:`hub-voice:speech-end`,transcript:`hub-voice:transcript`,accepted:`hub-voice:accepted`,firstSay:`hub-voice:first-say`,firstByte:`hub-voice:first-byte`,firstAudio:`hub-voice:first-audio`},wp=class{sessionID;api;player;ui;opts;active=!1;paused=!1;agent;inflight=0;sent=new Map;typed=new Set;typing=0;heardAt=0;lastStatus;cuePicker=new Ta({ready:e=>this.cuePlayer?.ready(e)??!1});scheduler=new Ea({pick:e=>this.cuePicker.pick(e)});cuePlayer;voiceKey;onVisibility;liveness=new dp({onChange:(e,t)=>this.livenessChanged(e,t)});micTimer;recoverTimer;recoverAttempt=0;recovering=!1;lastResumeTry=0;track;stream;ctx;source;sink;tap;vad;endpointer;queue;streaming=Qf(window);says=new gf;turns=new _f;cueClock;speechEndedAt;silence;silenceURL;wakeLock;warnedAutoplay=!1;state;ignoredTimer;sensitivity=`normal`;cueSpeaking=!1;attempt=0;constructor({sessionID:e,api:t,player:n,ui:r,options:i={}}){this.sessionID=e,this.api=t,this.player=n,this.ui=r,this.opts={cues:!0,background:!1,speed:()=>1,title:()=>`OpenCode session`,sensitivity:()=>`normal`,...i},this.lastStatus=i.status,this.scheduler.enabled=this.opts.cues!==!1,this.scheduler.working(Aa(i.status),Date.now()),this.cuePlayer=new Vd({api:this.api,speed:this.opts.speed,normalize:rp,target:ip,onSpeaking:e=>{this.cueSpeaking=e,this.guardEcho(),this.scheduler.cueSpeaking(e,Date.now()),this.cueClock.poke()}}),this.cueClock=new Da({scheduler:this.scheduler,play:e=>this.cuePlayer.play(e),ready:()=>this.active&&!this.paused}),this.onVisibility=()=>{let e=document.visibilityState===`visible`;this.liveness.visibility(e,Date.now()),this.active&&(e?(this.opts.background||this.lockScreen(),this.recover()):this.opts.background&&!this.paused&&this.silence?.play().catch(()=>{}))}}onWake=()=>{this.active&&document.visibilityState===`visible`&&this.recover()};onTrackMute=()=>this.liveness.muted(!0,Date.now());onTrackUnmute=()=>{this.liveness.muted(!1,Date.now()),this.recover()};onTrackEnded=()=>this.liveness.ended(Date.now());get path(){return`/api/sessions/${encodeURIComponent(this.sessionID)}`}async start(){if(this.active)return!0;let e=++this.attempt,t=()=>e!==this.attempt;this.ui.state(`starting`),this.cuePlayer.unlock(),this.opts.background&&this.startSilence();let n=window;if(!navigator.mediaDevices?.getUserMedia||!(n.AudioContext||n.webkitAudioContext))return this.ui.note(`This browser cannot listen here (the microphone needs HTTPS).`,`err`),this.ui.state(`off`),!1;let r;try{r=await navigator.mediaDevices.getUserMedia(rf(this.opts.deviceId))}catch(e){if(t())return!1;let n=e;return Lf({error:n.name,micPermission:await Sp(),activated:xp()})?this.ui.note(gp,`gesture`):this.ui.note(n.name===`NotAllowedError`?`Microphone permission was denied. Allow it in the browser's site settings.`:`Microphone: ${n.message}`,`err`),this.ui.state(`off`),this.stopSilence(),!1}if(t())return r.getTracks().forEach(e=>e.stop()),!1;this.stream=r;try{let{agent:e}=await(await this.api(`${this.path}/conversation`,{method:`POST`,json:{on:!0}})).json();this.agent=e}catch(e){return this.release(),this.stopSilence(),t()||(this.ui.note(`Could not start Voice mode: ${e.message}`,`err`),this.ui.state(`off`)),!1}if(t())return this.release(),await this.api(`${this.path}/conversation`,{method:`POST`,json:{on:!1}}).catch(()=>{}),!1;this.active=!0,this.prefetchCues();try{await this.listen()}catch(e){return t()||(e.name===_p?this.ui.note(gp,`gesture`):this.ui.note(`Could not start listening: ${e.message}`,`err`),await this.stop()),!1}return!t()&&(this.opts.background?this.mediaSession():this.lockScreen(),this.liveness.visibility(document.visibilityState!==`hidden`,Date.now()),document.addEventListener(`visibilitychange`,this.onVisibility),window.addEventListener?.(`pageshow`,this.onWake),window.addEventListener?.(`focus`,this.onWake),this.micTimer=setInterval(()=>this.checkMic(),yp),this.cueClock.poke(),this.refresh(),!0)}prefetchCues(){this.opts.cues!==!1&&this.scheduler.enabled&&this.cuePlayer.prefetch(wa(),this.voiceKey=this.cueKey())}async cueKey(){try{let{tts:e}=await(await this.api(`/api/settings/speech`)).json();return e?.voice?[e.provider,e.model,e.voice,e.speed??``,e.baseURL??``].join(`|`):void 0}catch{return}}async listen(){let e=window,t=e.AudioContext||e.webkitAudioContext,n=this.ctx=new t;if(await Promise.race([n.resume().catch(()=>{}),new Promise(e=>setTimeout(e,vp))]),Lf({audioState:n.state,activated:xp()}))throw Object.assign(Error(gp),{name:_p});if(this.liveness.start(Date.now()),n.onstatechange=()=>this.liveness.audio(n.state,Date.now()),this.watchTrack(this.stream),this.source=n.createMediaStreamSource(this.stream),this.sink=n.createGain(),this.sink.gain.value=0,this.sink.connect(n.destination),n.audioWorklet&&`AudioWorkletNode`in window){await n.audioWorklet.addModule(`/vad-worklet.js`);let e=new AudioWorkletNode(n,`vad-tap`,{numberOfInputs:1,numberOfOutputs:1,channelCount:1});e.port.onmessage=e=>this.frame(e.data),this.tap=e}else{let e=n.createScriptProcessor(1024,1,1);e.onaudioprocess=e=>this.frame(Float32Array.from(e.inputBuffer.getChannelData(0))),this.tap=e}this.source.connect(this.tap),this.tap.connect(this.sink),this.sensitivity=this.opts.sensitivity();let r=this.vad=new Ff({sampleRate:n.sampleRate,params:Af(this.sensitivity),onEvents:e=>this.vadEvents(e),onLevel:e=>this.ui.level(e)});this.ui.detector?.({mode:`energy`}),Kf().then(e=>{this.vad===r&&(e.reset(),r.classifier=t=>e.classify(t),this.ui.detector?.({mode:`silero`}))},e=>{mp||console.warn(`Voice: on-device speech detection unavailable (${e?.message??e}); using the energy detector`),mp=!0}),this.endpointer=new pf({send:e=>void this.deliver(e),onHeld:e=>this.ui.held?.(e)}),this.queue=new hf({synth:(e,t)=>this.synth(e,t),play:e=>this.play(e),stop:()=>{this.player.paused||this.player.pause()},onState:e=>{this.guardEcho(),this.scheduler.agentSpeaking(e,Date.now()),e&&this.cuePlayer.stop(),this.cueClock.poke(),this.refresh()},onError:e=>{e?.name!==`AbortError`&&this.ui.note(`Could not read the reply aloud: ${e?.message}`,`err`)}})}guardEcho(){this.vad&&(this.vad.speaking=!!this.queue?.speaking||this.cueSpeaking)}frame(e){if(!this.active||(this.liveness.frame(Date.now()),!this.vad||this.paused||!this.liveness.live))return;let t=this.opts.sensitivity();t!==this.sensitivity&&(this.sensitivity=t,this.vad.params=Af(t)),this.vad.push(e)}vadEvents(e){let t=this.vad;if(this.active&&t&&!this.paused&&this.liveness.live)for(let n of e){if(n.type===`start`)this.endpointer.speechStarted(),this.scheduler.userTalking(!0,Date.now()),this.cuePlayer.stop(),this.queue.speaking?this.hushReplies():this.says.mute();else{this.speechEndedAt=Date.now(),this.markTurn(`speechEnd`),this.cuePlayer.play(this.scheduler.speechEnded(this.speechEndedAt));let e=this.endpointer.segmentEnded(n.durationMs);this.transcribe(e,nf(n.samples,t.sampleRate),n.speechMs),this.ui.detector?.({mode:t.mode,...t.mode===`silero`?{avgMs:t.stats.avgMs}:{}})}this.cueClock.poke(),this.refresh()}}async transcribe(e,t,n){this.inflight++,this.refresh();let r=``;try{r=(await(await this.api(`/api/transcribe`,{method:`POST`,body:t,headers:{"content-type":`audio/wav`}})).json()).text??``}catch(e){this.active&&this.ui.note(`Transcription failed: ${e.message}`,`err`)}finally{this.inflight--}this.active&&(Uf(r,{speechMs:n})&&(r.trim()&&this.showIgnored(r.trim()),r=``),r.trim()&&this.markTurn(`transcript`),this.endpointer?.transcribed(e,r),this.refresh())}showIgnored(e){clearTimeout(this.ignoredTimer),this.ui.ignored?.(e),this.ignoredTimer=setTimeout(()=>this.ui.ignored?.(``),pp)}async deliver(e,t=!1){let n=Kd(e);if(n===`pause`)return this.ui.note(`Paused listening.`),this.stop();if(n===`interrupt`){this.hushReplies(),this.ui.note(`“${e}” — interrupting.`);try{await this.api(`${this.path}/interrupt`,{method:`POST`,json:{}})}catch(e){this.ui.note(`Could not interrupt: ${e.message}`,`err`)}return}let r=this.ui.user(e);t&&this.typing++,this.scheduler.awaitReply(t?Date.now():this.speechEndedAt??Date.now()),this.cueClock.poke();try{let{inboxID:n}=await(await this.api(`${this.path}/utterance`,{method:`POST`,json:{text:e}})).json();this.markTurn(`accepted`),this.sent.get(n)===`heard`?this.ui.tick(r,`heard`):(this.ui.tick(r,`sent`),t&&this.typed.add(n)),this.sent.set(n,r)}catch(e){let t=e;this.ui.tick(r,`failed`),this.ui.note(t.status===409?t.message:`Could not send: ${t.message}`,`err`)}finally{t&&this.typing--}}sendTyped(e){return this.hushReplies(),this.deliver(e,!0)}hushReplies(){this.queue?.clear(),this.says.mute()}onEvent(e){if(e.sessionID===this.sessionID){if(e.type===`heard`){let t=this.sent.get(e.inboxID);t!==void 0&&t!==`heard`?this.ui.tick(t,`heard`):this.sent.set(e.inboxID,`heard`),this.heardAt=Date.now();let n=this.typed.delete(e.inboxID)||t===void 0&&this.typing>0;this.active&&!this.paused&&this.cuePlayer.play(this.scheduler.heard(this.heardAt,{tone:n})),this.cueClock.poke(),this.refresh(),setTimeout(()=>this.refresh(),2550)}else if(e.type===`say`){if(!this.active)return;let t=this.says.accept(e);if(!t)return;this.scheduler.agentSaid(Date.now()),this.cuePlayer.stop(),this.cueClock.poke(),this.ui.agent({messageID:e.messageID,text:t.text}),t.sentences.length&&this.markTurn(`firstSay`),this.queue?.enqueue(t.sentences)}else e.type===`conversation`&&!e.on&&this.active&&(this.ui.note(`Voice mode was turned off.`),this.stop({post:!1}))}}onStatus(e){let t=Date.now(),{started:n,finished:r}=ka(this.lastStatus,e,this.sessionID);if(this.lastStatus=e,this.scheduler.working(Aa(e),t),this.active){for(let e=0;e<n.length;e++)this.scheduler.subagentStarted(t);r.length&&!this.paused&&this.cuePlayer.play(this.scheduler.subagentFinished(t)),this.cueClock.poke()}}setCues(e){this.scheduler.enabled=e,e?this.active&&this.prefetchCues():this.cuePlayer.stop(),this.cueClock.poke()}setBackground(e){this.opts.background=e,this.active&&(e?(this.wakeLock?.release().catch(()=>{}),this.wakeLock=void 0,this.startSilence(),this.mediaSession()):(this.stopSilence(),this.clearMediaSession(),this.lockScreen()))}pause(){this.active&&!this.paused&&(this.paused=!0,this.cueClock.stop(),this.hushReplies(),this.cuePlayer.stop(),this.endpointer?.reset(),this.vad?.reset(),this.stream?.getAudioTracks().forEach(e=>e.enabled=!1),this.silence?.pause(),navigator.mediaSession&&(navigator.mediaSession.playbackState=`paused`),this.ui.level(0),this.refresh())}resume(){this.active&&this.paused&&(this.paused=!1,this.stream?.getAudioTracks().forEach(e=>e.enabled=!0),this.ctx?.resume().catch(()=>{}),this.opts.background&&(this.silence?.play().catch(()=>{}),navigator.mediaSession&&(navigator.mediaSession.playbackState=`playing`)),this.cueClock.poke(),this.refresh())}mediaSession(){navigator.mediaSession&&(navigator.mediaSession.playbackState=this.paused||!this.liveness.live?`paused`:`playing`)}watchTrack(e){this.unwatchTrack();let t=e.getAudioTracks?.()[0];t?.addEventListener&&(this.track=t,t.addEventListener(`mute`,this.onTrackMute),t.addEventListener(`unmute`,this.onTrackUnmute),t.addEventListener(`ended`,this.onTrackEnded),t.muted&&this.liveness.muted(!0,Date.now()),t.readyState===`ended`&&this.liveness.ended(Date.now()))}unwatchTrack(){let e=this.track;this.track=void 0,e?.removeEventListener&&(e.removeEventListener(`mute`,this.onTrackMute),e.removeEventListener(`unmute`,this.onTrackUnmute),e.removeEventListener(`ended`,this.onTrackEnded))}checkMic(){if(!this.active)return;let e=Date.now();this.liveness.tick(e),!(this.liveness.live||document.visibilityState===`visible`||e-this.lastResumeTry<bp)&&(this.lastResumeTry=e,this.ctx&&this.ctx.state!==`running`&&this.ctx.resume().catch(()=>{}),this.opts.background&&!this.paused&&this.silence?.play().catch(()=>{}))}livenessChanged(e,t){this.active&&(e?(clearTimeout(this.recoverTimer),this.recoverTimer=void 0,this.recoverAttempt=0,this.cuePlayer.earcon(`resumed`),this.cueClock.poke()):(this.vad?.reset(),this.ui.level(0),this.cuePlayer.earcon(`paused`),this.lastResumeTry=Date.now(),this.liveness.wantsRecovery&&this.scheduleRecover()),this.opts.background&&this.mediaSession(),this.refresh())}scheduleRecover(){this.recoverTimer===void 0&&this.active&&(this.recoverTimer=setTimeout(()=>{this.recoverTimer=void 0,this.recover()},up(this.recoverAttempt++)))}recover(){!this.active||this.liveness.live||this.recovering||(clearTimeout(this.recoverTimer),this.recoverTimer=void 0,this.recovering=!0,this.tryRecover().finally(()=>{this.recovering=!1,this.active&&this.liveness.wantsRecovery&&this.scheduleRecover()}))}async tryRecover(){this.cuePlayer.unlock();let e=this.ctx,t=e&&e.state!==`running`?e.resume().catch(()=>{}):void 0;this.opts.background&&!this.paused&&this.silence?.play().catch(()=>{}),this.liveness.needsMic||this.track?.readyState===`ended`?await this.reacquire():t&&await Promise.race([t,new Promise(e=>setTimeout(e,vp))])}async reacquire(){let e;try{e=await navigator.mediaDevices.getUserMedia(rf(this.opts.deviceId))}catch(e){if(!this.active)return;Lf({error:e.name,micPermission:await Sp(),activated:xp()})&&this.ui.note(gp,`gesture`);return}if(!this.active||!this.ctx||!this.tap)e.getTracks().forEach(e=>e.stop());else{this.release(),this.stream=e,this.paused&&e.getAudioTracks().forEach(e=>e.enabled=!1);try{this.source?.disconnect()}catch{}this.source=this.ctx.createMediaStreamSource(e),this.source.connect(this.tap),this.liveness.replaced(Date.now()),this.watchTrack(e)}}clearMediaSession(){navigator.mediaSession&&(navigator.mediaSession.playbackState=`none`)}startSilence(){if(!this.silence){let e=URL.createObjectURL(new Blob([nf(new Float32Array(16e3*hp),16e3)],{type:`audio/wav`})),t=new Audio(e);t.loop=!0,t.setAttribute(`aria-hidden`,`true`),this.silence=t,this.silenceURL=e}this.silence.play().catch(()=>{})}stopSilence(){this.silence&&=(this.silence.pause(),this.silence.removeAttribute(`src`),this.silence.load(),this.silenceURL&&URL.revokeObjectURL(this.silenceURL),this.silenceURL=void 0)}hush(){if(this.paused)return this.resume();this.hushReplies(),this.cuePlayer.stop()}async synth(e,t){let n=Xf((await this.api(`/api/speak`,{method:`POST`,json:{text:e},signal:t})).body,t);return n.firstByte.then(()=>this.markTurn(`firstByte`),()=>{}),n.whole().then(async e=>sp(e,await(this.voiceKey??=this.cueKey()))).catch(()=>{}),n}async play(e){let t=this.player,n=new AbortController,r;try{if(this.streaming){if(await e.firstByte,e.done&&!e.chunks.length)return;let i=new MediaSource;r=URL.createObjectURL(i),t.src=r,this.feedSource(i,e,n.signal)}else{let n=await e.whole();if(!n.length)return;r=URL.createObjectURL(new Blob(n,{type:`audio/mpeg`})),t.src=r}let i=new Promise(e=>{t.onended=t.onpause=t.onerror=()=>e()});if(!await t.play().then(()=>!0,()=>!1)){this.warnedAutoplay||this.ui.note(`The browser blocked audio playback. Tap the mic to allow it.`),this.warnedAutoplay=!0;return}this.markTurn(`firstAudio`),await i}finally{n.abort(),t.onended=t.onpause=t.onerror=null,r&&URL.revokeObjectURL(r)}}async feedSource(e,t,n){try{if(e.readyState!==`open`&&await new Promise(t=>e.addEventListener(`sourceopen`,t,{once:!0})),n.aborted)return;let r=e.addSourceBuffer(`audio/mpeg`);!await Zf(t,{append:e=>new Promise((t,n)=>{r.addEventListener(`updateend`,()=>t(),{once:!0}),r.addEventListener(`error`,()=>n(Error(`Could not decode the reply audio`)),{once:!0}),r.appendBuffer(e)}),end:()=>{e.readyState===`open`&&!r.updating&&e.endOfStream()}},n)&&!n.aborted&&e.readyState===`open`&&!r.updating&&e.endOfStream()}catch{}}markTurn(e){if(!this.turns.mark(e,Date.now()))return;try{performance.mark(Cp[e])}catch{}let t=e===`firstAudio`?yf(this.turns.last):void 0;t&&this.ui.timing?.(t)}refresh(){if(!this.active)return;let e=this.paused?`paused`:this.liveness.live?this.queue?.speaking?`speaking`:this.vad?.active?`hearing`:this.inflight>0||this.endpointer?.held?`transcribing`:Date.now()-this.heardAt<fp?`sent`:`listening`:`suspended`;e!==this.state&&(this.state=e,this.ui.state(e))}async lockScreen(){if(`wakeLock`in navigator&&document.visibilityState===`visible`&&(!this.wakeLock||this.wakeLock.released))try{this.wakeLock=await navigator.wakeLock.request(`screen`)}catch{}}release(){this.unwatchTrack(),this.stream?.getTracks().forEach(e=>e.stop()),this.stream=void 0}async stop({post:e=!0,keepalive:t=!1}={}){this.attempt++;let n=this.active;this.active=!1,this.paused=!1,this.state=void 0,document.removeEventListener(`visibilitychange`,this.onVisibility),window.removeEventListener?.(`pageshow`,this.onWake),window.removeEventListener?.(`focus`,this.onWake),clearInterval(this.micTimer),clearTimeout(this.recoverTimer),this.micTimer=this.recoverTimer=void 0,this.recoverAttempt=0,this.ctx&&(this.ctx.onstatechange=null),this.cueClock.stop(),this.cuePlayer.close(),this.stopSilence(),this.opts.background&&this.clearMediaSession(),this.queue?.clear(),this.endpointer?.reset(),this.vad?.reset();try{this.source?.disconnect(),this.tap?.disconnect(),this.tap&&`port`in this.tap&&(this.tap.port.onmessage=null),this.sink?.disconnect()}catch{}this.ctx?.close().catch(()=>{}),this.ctx=this.source=this.tap=this.sink=this.vad=void 0,this.release(),this.wakeLock?.release().catch(()=>{}),this.wakeLock=void 0,this.ui.level(0),this.ui.held?.(``),clearTimeout(this.ignoredTimer),this.ui.ignored?.(``),this.ui.state(`off`),this.ui.ended(),e&&n&&await this.api(`${this.path}/conversation`,{method:`POST`,json:{on:!1},keepalive:t}).catch(()=>{})}},Tp=`voice.speed`,Ep=`voice.cues`,Dp=`voice.background`,Op=`voice.micDevice`,kp=`voice.sensitivity`,Ap=Of(localStorage.getItem(kp)),jp={get speed(){return ga(localStorage.getItem(Tp))},set speed(e){localStorage.setItem(Tp,String(ga(e))),Bd($,ga(e))},get cues(){return localStorage.getItem(Ep)!==`0`},set cues(e){localStorage.setItem(Ep,e?`1`:`0`)},get background(){return localStorage.getItem(Dp)===`1`},set background(e){localStorage.setItem(Dp,e?`1`:`0`)},get sensitivity(){return Ap},set sensitivity(e){Ap=Of(e),localStorage.setItem(kp,Ap)}},$=new Audio;$.preload=`none`,$.volume=1,Bd($,jp.speed);function Mp(){$.paused&&($.muted=!0,$.play().catch(()=>{}).finally(()=>{$.pause(),$.muted=!1}))}var[Np,Pp]=x(localStorage.getItem(Op)??``);function Fp(e){Pp(e),localStorage.setItem(Op,e)}async function Ip(){if(!navigator.mediaDevices?.enumerateDevices)return[];let e=(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`);if(e.length&&e.every(e=>!e.label))try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(e=>e.stop()),e=(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===`audioinput`)}catch{}return e}async function Lp(e,t){let n=await navigator.mediaDevices.getUserMedia(rf(e||void 0)),r=new AudioContext,i=r.createMediaStreamSource(n),a=r.createAnalyser();a.fftSize=512,i.connect(a);let o=new Float32Array(a.fftSize),s=0,c=()=>{a.getFloatTimeDomainData(o);let e=0;for(let t of o)e+=t*t;let n=20*Math.log10(Math.max(Math.sqrt(e/o.length),1e-7));t(Math.max(0,Math.min(1,(n+60)/50))),s=requestAnimationFrame(c)};return c(),()=>{cancelAnimationFrame(s),n.getTracks().forEach(e=>e.stop()),r.close()}}var Rp=6e4;function zp(){for(let e of[`audio/webm;codecs=opus`,`audio/webm`,`audio/mp4`,`audio/ogg;codecs=opus`])if(window.MediaRecorder?.isTypeSupported?.(e))return e;return``}async function Bp(e){if(!navigator.mediaDevices?.getUserMedia||!window.MediaRecorder)throw Error(`This browser cannot record here (the microphone needs HTTPS).`);let t;try{t=await navigator.mediaDevices.getUserMedia(rf(Np()||void 0))}catch(e){let t=e;throw Error(t.name===`NotAllowedError`?`Microphone permission was denied. Allow it in the browser's site settings.`:`Microphone: ${t.message}`)}let n=zp(),r=new MediaRecorder(t,n?{mimeType:n}:void 0),i=[],a=Date.now();r.ondataavailable=e=>e.data.size&&i.push(e.data);let o=!1,s=new Promise((e,a)=>{r.onstop=async()=>{if(clearInterval(c),clearTimeout(l),t.getTracks().forEach(e=>e.stop()),o)return e(``);let s=new Blob(i,{type:(r.mimeType||n||`audio/webm`).split(`;`)[0]});if(!s.size)return e(``);try{let{text:t}=await(await V(`/api/transcribe`,{method:`POST`,body:s,headers:{"content-type":s.type}})).json();e(String(t??``).trim())}catch(e){let t=e;a(Error(t.status===413?`That recording was too long.`:`Transcription failed: ${t.message}`))}}});r.start();let c=setInterval(()=>e?.(Math.max(0,Math.ceil((Rp-(Date.now()-a))/1e3))),1e3),l=setTimeout(()=>r.state===`recording`&&r.stop(),Rp);return{finish(){return r.state===`recording`&&r.stop(),s},cancel(){o=!0,r.state===`recording`&&r.stop()}}}var Vp=new Mu({async expose(e){let t=()=>jo(e)?.session.exposed!==!1;if(t())return!0;if(!await _s(e,!0))return!1;for(let e=0;e<25&&!t();e++)await new Promise(e=>setTimeout(e,200));return!0},create:(e,t)=>new wp({sessionID:e,api:V,player:$,ui:t,options:{cues:jp.cues,background:jp.background,speed:()=>jp.speed,sensitivity:()=>jp.sensitivity,title:()=>jo(e)?.session.title||`OpenCode session`,status:jo(e)?.session.status,deviceId:Np()||void 0}}),stopPlayback:()=>{$.paused||$.pause()},notify:(e,t)=>q(e,t===`err`?`err`:``)}),[Hp,Up]=x(0);Vp.subscribe(()=>Up(e=>e+1));var Wp=`voice-mode`,Gp=Promise.resolve(),Kp=e=>{Gp=Gp.then(async()=>{let t=`serviceWorker`in navigator?await navigator.serviceWorker.getRegistration(`/`):void 0;t&&await e(t)}).catch(()=>{})},qp={allowed:()=>`Notification`in window&&Notification.permission===`granted`&&`serviceWorker`in navigator,show:e=>Kp(t=>t.showNotification(e.title,{body:e.body,tag:Wp,silent:!0,requireInteraction:!0,icon:`/icon-192.png`,badge:`/icon-192.png`,data:{kind:`voice`,sessionID:e.sessionID,url:`/s/${encodeURIComponent(e.sessionID)}`},renotify:!1,actions:[{action:`end`,title:`End`},{action:`open`,title:`Open`}]})),close:()=>Kp(async e=>(await e.getNotifications({tag:Wp})).forEach(e=>e.close())),media:(e,t)=>{let n=navigator.mediaSession;if(n)try{n.metadata=e&&`MediaMetadata`in window?new MediaMetadata({title:e.title,artist:e.artist,artwork:[{src:`/icon-192.png`,sizes:`192x192`,type:`image/png`},{src:`/icon-512.png`,sizes:`512x512`,type:`image/png`}]}):null;let r=e&&t?()=>t():null;n.setActionHandler(`pause`,r);for(let e of[`stop`,`play`])try{n.setActionHandler(e,e===`stop`?r:null)}catch{}}catch{}}},Jp=new Ru(Vp,qp,{title:e=>jo(e)?.session.title||`OpenCode session`});pl(e=>{e?.type===`voice-end`&&typeof e.sessionID==`string`&&Jp.endFromNotification(e.sessionID)});function Yp(){return Hp(),Jp.needsPermission()}async function Xp(){try{await ol()}catch(e){q(e instanceof Error?e.message:String(e),`err`)}Jp.refresh(),Up(e=>e+1)}function Zp(){return Hp(),Vp.state}var Qp=()=>{let e=Zp().sessionID;return e?jo(e)?.session.title||`Session`:``};ko(e=>{e.type===`say`||e.type===`heard`||e.type===`conversation`?Vp.onEvent(e):e.type===`status`&&typeof e.sessionID==`string`&&Array.isArray(e.sessions)&&Vp.onStatus(e.sessionID,e.sessions)}),window.addEventListener(`pagehide`,()=>{Vp.stop({keepalive:!0}),qp.close()});var $p=new rd,em=new Au({record:e=>Bp(e),deliver:(e,t)=>void $p.append(e,t),notify:(e,t)=>q(e,t),hold:()=>Vp.hold()}),[tm,nm]=x(0);em.subscribe(()=>nm(e=>e+1));function rm(e){return tm(),em.forSession(e)}var im=N(`<div class=banner><span></span><a class="btn small"href=/settings#machines>Review`),am=N(`<div class=banner><span><strong>Set up speech</strong> · </span><a class="btn small"href=/settings#speech>Set up`),om=N(`<section class=decisions aria-label=Decisions><h2 class=section-title>`),sm=N(`<select aria-label=Server><option value>All servers`),cm=N(`<div class=bulk-bar role=region aria-label="Selected sessions"><span> selected</span><button type=button class="btn small"></button><button type=button class="btn small">Clear selection`),lm=N(`<div class=empty><p class=display>No machines yet</p><p class=muted>In OpenCode run /hub → Connect to a hub…, then approve it here.`),um=N(`<ul class=home-list>`),dm=N(`<div class=home><header class=home-head><h1 class=display>All sessions</h1><a class="btn primary"href=/new> New session</a></header><div class=home-tools><label class=search><input type=search placeholder="Search title, project, folder or server"aria-label="Search sessions"></label><button type=button class="btn small">Archive inactive…</button></div><div class=chips role=group aria-label=Filters></div><p class="count muted"role=status>`),fm=N(`<option>`),pm=N(`<button type=button class=chip>`),mm=N(`<p class="muted small offline-line"><strong></strong> · offline · seen `),hm=N(`<form class=archive-inactive><label class=field><span>Inactive for more than (days)</span><input type=number min=1 step=1 inputmode=numeric></label><p class="muted small"> without activity for more than <!> (not running, pinned or open in a terminal). Archived sessions leave your lists on every device; nothing is deleted and you can unarchive them under Archived.</p><div class=dialog-actions><button type=button class=btn>Cancel</button><button type=submit class="btn primary">`),gm=N(`<table class=sessions-table><thead><tr><th class=col-pick><input type=checkbox aria-label="Select all shown sessions"></th><th class=col-now>Now</th><th class=col-actions><span class=sr-only>Actions</span></th></tr></thead><tbody>`),_m=N(`<th><button type=button class=th-btn><span class=sort-mark aria-hidden=true>`),vm=N(`<tr><td colspan=9 class="muted empty-cell">No sessions match.`),ym=N(`<span class=jobs-badge>`),bm=N(`<a>`),xm=N(`<span class=unread-dot role=img aria-label=Unread>`),Sm=N(`<tr><td class=col-pick><input type=checkbox></td><td class=col-status><span class=sr-only></span></td><td class=col-title></td><td class=col-project></td><td class=col-server><span></span></td><td class=col-source></td><td class=col-activity></td><td></td><td class=col-actions>`),Cm=N(`<a class=home-item-link><span class=home-item-text><span class=home-item-title></span><span>`),wm=N(`<li>`),Tm=N(`<span class=home-item-link>`),Em=`hub.table`;function Dm(e){go();let t=e.blockers[0];if(e.state===`blocked`&&t)return`${t.kind===`permission`?`Permission`:`Question`}: ${t.summary}`;if(e.state===`error`)return e.error??`Error`;if(e.state!==`working`)return``;if(e.retry)return e.retry;let n=po.has(e.id)?po.feed(e.id):void 0,r=n?.pulse(),i=e.jobs?` · ${Ki(e.jobs)}`:``;if(r?.busy&&r.label!==`Working`)return r.label+i;let a=n?.now()??e.nowText;return a?a+i:e.jobs?`Background: ${Ki(e.jobs)}`:`Working`}var Om=[[`status`,`Status`],[`title`,`Title`],[`project`,`Project`],[`server`,`Server`],[`source`,`Open in`],[`activity`,`Last activity`]],km=[[`needs`,`Needs you`,{status:`needs`}],[`running`,`Running`,{status:`running`}],[`idle`,`Idle`,{status:`idle`}],[`open`,`Open in terminal`,{source:`open`}],[`background`,`Background`,{source:`background`}],[`archived`,`Archived`,{archived:!0}]];function Am(){let[e,t]=x(sa(localStorage.getItem(Em))),[n,r]=x(``),i=e=>{t(e),localStorage.setItem(Em,ca(e))},a=w(()=>aa(Ao(),{...e(),query:n()})),[o,s]=x(new Set),c=w(()=>a().filter(e=>o().has(e.id))),l=(e,t)=>{let n=new Set(o());t?n.add(e):n.delete(e),s(n)},u=e=>s(e?new Set(a().map(e=>e.id)):new Set),d=()=>{_l(c(),!e().filters.archived),s(new Set)},[f,p]=x(!1),m=()=>J.machines??[],h=t=>Object.keys(t).every(n=>e().filters[n]===t[n]),g=t=>{let n=e().filters,r=Object.fromEntries(Object.keys(t).map(e=>[e,Xi.filters[e]]));i({...e(),filters:h(t)?{...n,...r}:{...n,...t}})},_=t=>{let n=e().sort;i({...e(),sort:{key:t,dir:n.key===t?n.dir===`asc`?`desc`:`asc`:t===`activity`?`desc`:`asc`}})},v=()=>za(bo()??void 0,X()?.publicURL);return(()=>{var t=dm(),s=t.firstChild,y=s.firstChild.nextSibling,b=y.firstChild,x=s.nextSibling,ee=x.firstChild,C=ee.firstChild,w=ee.nextSibling,te=x.nextSibling,ne=te.nextSibling;return R(y,O(Z,{name:`plus`}),b),R(t,O(A,{get when(){return So().length},get children(){var e=im(),t=e.firstChild;return R(t,(()=>{var e=M(()=>So().length===1);return()=>e()?`${So()[0].machineName} wants to connect.`:`${So().length} machines want to connect.`})()),e}}),x),R(t,O(A,{get when(){return v()},get children(){var e=am(),t=e.firstChild;return t.firstChild.nextSibling,R(t,()=>v().reason,null),e}}),x),R(t,O(A,{get when(){return wo().length},get children(){var e=om(),t=e.firstChild;return R(t,(()=>{var e=M(()=>wo().length===1);return()=>e()?`A decision waits for you`:`${wo().length} decisions wait for you`})()),R(e,O(Vl,{get decisions(){return wo()},showSession:!0}),null),e}}),x),R(ee,O(Z,{name:`search`}),C),C.$$input=e=>r(e.currentTarget.value),w.$$click=()=>p(!0),R(x,O(A,{get when(){return m().length>1},get children(){var t=sm();return t.firstChild,t.addEventListener(`change`,t=>i({...e(),filters:{...e().filters,machine:t.currentTarget.value}})),R(t,O(k,{get each(){return m()},children:e=>(()=>{var t=fm();return R(t,()=>e.name),S(()=>t.value=e.id),t})()}),null),S(()=>t.value=e().filters.machine),t}}),null),R(te,O(k,{each:km,children:([e,t,n])=>(()=>{var r=pm();return r.$$click=()=>g(n),F(r,`data-chip`,e),R(r,t),S(()=>F(r,`aria-pressed`,h(n))),r})()})),R(t,O(A,{get when(){return c().length},get children(){var t=cm(),n=t.firstChild,r=n.firstChild,i=n.nextSibling,a=i.nextSibling;return R(n,()=>c().length,r),i.$$click=d,R(i,()=>e().filters.archived?`Unarchive`:`Archive`),a.$$click=()=>u(!1),t}}),ne),R(ne,(()=>{var e=M(()=>J.machines===void 0);return()=>e()?`Loading…`:`${a().length} of ${Ao().filter(e=>!e.hidden).length} sessions`})()),R(t,O(A,{get when(){return M(()=>!!J.machines)()&&J.machines.length===0},get children(){return lm()}}),null),R(t,O(A,{get when(){return Q()},get fallback(){return O(Nm,{get rows(){return a()},get table(){return e()},sortBy:_,get picked(){return o()},pick:l,pickAll:u})},get children(){var e=um();return R(e,O(k,{get each(){return a()},children:e=>O(Pm,{row:e})})),e}}),null),R(t,O(k,{get each(){return m().filter(e=>!e.online)},children:e=>(()=>{var t=mm(),n=t.firstChild;return n.nextSibling,R(n,()=>e.name),R(t,()=>oc(e.lastSeen,tc()),null),t})()}),null),R(t,O(Mm,{get open(){return f()},get rows(){return Ao()},onClose:()=>p(!1)}),null),S(()=>C.value=n()),t})()}var jm=30;function Mm(e){let[t,n]=x(String(jm)),r=w(()=>e.open?fa(e.rows,Number(t()),tc()):[]),i=()=>r().length,a=()=>{_l(r(),!0),e.onClose()};return O(Qs,{get open(){return e.open},title:`Archive inactive sessions`,get onClose(){return e.onClose},get children(){var r=hm(),o=r.firstChild,s=o.firstChild.nextSibling,c=o.nextSibling,l=c.firstChild,u=l.nextSibling;u.nextSibling;var d=c.nextSibling.firstChild,f=d.nextSibling;return r.addEventListener(`submit`,e=>{e.preventDefault(),i()&&a()}),s.$$input=e=>n(e.currentTarget.value),R(c,(()=>{var e=M(()=>i()===1);return()=>e()?`1 session`:`${i()} sessions`})(),l),R(c,(()=>{var e=M(()=>Number(t())===1);return()=>e()?`1 day`:`${t()||`?`} days`})(),u),rt(d,`click`,e.onClose,!0),R(f,(()=>{var e=M(()=>i()===1);return()=>e()?`Archive 1 session`:`Archive ${i()} sessions`})()),S(()=>f.disabled=!i()),S(()=>s.value=t()),r}})}function Nm(e){let t=()=>e.rows.length>0&&e.rows.every(t=>e.picked.has(t.id)),n=t=>e.table.sort.key===t?e.table.sort.dir===`asc`?`ascending`:`descending`:`none`;return(()=>{var r=gm(),i=r.firstChild,a=i.firstChild,o=a.firstChild,s=o.firstChild,c=o.nextSibling,l=i.nextSibling;return s.addEventListener(`change`,t=>e.pickAll(t.currentTarget.checked)),R(a,O(k,{each:Om,children:([t,r])=>(()=>{var i=_m(),a=i.firstChild,o=a.firstChild;return I(i,`col-${t}`),a.$$click=()=>e.sortBy(t),R(a,r,o),R(o,(()=>{var n=M(()=>e.table.sort.key===t);return()=>n()?e.table.sort.dir===`asc`?`↑`:`↓`:``})()),S(()=>F(i,`aria-sort`,n(t))),i})()}),c),R(l,O(k,{get each(){return e.rows},get fallback(){return vm()},children:t=>(()=>{var n=Sm(),r=n.firstChild,i=r.firstChild,a=r.nextSibling,o=a.firstChild,s=a.nextSibling,c=s.nextSibling,l=c.nextSibling,u=l.firstChild,d=l.nextSibling,f=d.nextSibling,p=f.nextSibling,m=p.nextSibling;return n.$$click=e=>!e.target.closest(`button,a,select,input`)&&io(ao(t.id)),i.addEventListener(`change`,n=>e.pick(t.id,n.currentTarget.checked)),R(a,O(Ys,{get state(){return t.state}}),o),R(o,()=>qs[t.state]),R(a,O(A,{get when(){return t.error},children:e=>O(ac,{get text(){return e()}})}),null),R(a,O(A,{get when(){return t.jobs},get children(){var e=ym();return R(e,()=>t.jobs),S(n=>{var r=Ki(t.jobs),i=Ki(t.jobs);return r!==n.e&&F(e,`title`,n.e=r),i!==n.t&&F(e,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),e}}),null),R(s,O(A,{get when(){return pa(t,Zp())},get children(){return O(Js,{})}}),null),R(s,O(Du,{get id(){return t.id},get title(){return t.title},place:`table`,get children(){var e=bm();return R(e,()=>t.title),S(()=>F(e,`href`,ao(t.id))),e}}),null),R(s,O(Ou,{get id(){return t.id}}),null),R(s,O(A,{get when(){return t.unread},get children(){return xm()}}),null),R(c,()=>t.where),R(u,()=>t.machineName),R(d,()=>lc[t.source]),R(f,()=>oc(t.updated,tc())),R(p,()=>Dm(t)),R(m,O(Zs,{get label(){return`More actions for ${t.title}`},class:`icon-btn small`,items:()=>vl(t,{place:`table`})})),S(e=>{var r=`${t.unread?`unread`:``}`,a=`Select ${t.title}`,o=t.directory,s=t.machineOnline?``:`muted`,l=`col-now ${t.error?`error`:`muted`}`,d=t.error;return r!==e.e&&I(n,e.e=r),a!==e.t&&F(i,`aria-label`,e.t=a),o!==e.a&&F(c,`title`,e.a=o),s!==e.o&&I(u,e.o=s),l!==e.i&&I(p,e.i=l),d!==e.n&&F(p,`title`,e.n=d),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),S(()=>i.checked=e.picked.has(t.id)),n})()})),S(()=>s.checked=t()),r})()}function Pm(e){let t=()=>e.row;return(()=>{var e=wm();return R(e,O(A,{get when(){return!gl(t().id,`phone`)},get fallback(){return(()=>{var e=Tm();return R(e,O(Ys,{get state(){return t().state}}),null),R(e,O(Du,{get id(){return t().id},get title(){return t().title},place:`phone`,children:null}),null),e})()},get children(){var e=Cm(),n=e.firstChild,r=n.firstChild,i=r.nextSibling;return R(e,O(Ys,{get state(){return t().state}}),n),R(e,O(A,{get when(){return t().error},children:e=>O(ac,{get text(){return e()}})}),n),R(r,O(A,{get when(){return pa(t(),Zp())},get children(){return O(Js,{})}}),null),R(r,()=>t().title,null),R(r,O(Ou,{get id(){return t().id}}),null),R(r,O(A,{get when(){return t().unread},get children(){return xm()}}),null),R(i,()=>Dm(t())||`${t().where} · ${t().machineName} · ${oc(t().updated,tc())}`),S(n=>{var r=ao(t().id),a=`home-item-meta ${t().error?`error`:`muted`}`;return r!==n.e&&F(e,`href`,n.e=r),a!==n.t&&I(i,n.t=a),n},{e:void 0,t:void 0}),e}}),null),R(e,O(Zs,{get label(){return`More actions for ${t().title}`},class:`icon-btn small`,items:()=>vl(t(),{place:`phone`})}),null),S(()=>I(e,`home-item${t().unread?` unread`:``}`)),e})()}P([`input`,`click`]);var Fm=N(`<div role=separator aria-orientation=vertical tabindex=0>`);function Im(e){let t=0,n=0,r=0,i,a=()=>bu()[e.panel],o=()=>xu(e.panel),s=()=>{r=0,i!==void 0&&Su(e.panel,i,!1)},c=()=>{r&&cancelAnimationFrame(r),r=0,i=void 0,yu(void 0),document.documentElement.classList.remove(`resizing`)},l=(t,n,r)=>{t.hasPointerCapture(n)&&t.releasePointerCapture(n),c(),Su(e.panel,r)};return E(()=>e.panel===`rail`&&_u(!0)),D(()=>{e.panel===`rail`&&_u(!1),vu()===e.panel&&c()}),(()=>{var c=Fm();return c.$$keydown=t=>{let n=ql(e.panel,a(),t.key,t.shiftKey,o());n!==void 0&&(t.preventDefault(),Su(e.panel,n))},c.$$dblclick=()=>Su(e.panel,Hl[e.panel].default),c.addEventListener(`pointercancel`,t=>vu()===e.panel&&l(t.currentTarget,t.pointerId,i??a())),c.$$pointerup=t=>vu()===e.panel&&l(t.currentTarget,t.pointerId,i??a()),c.$$pointermove=a=>{if(vu()!==e.panel)return;let c=Jl(e.panel,t,a.clientX-n,o());`collapse`in c?(l(a.currentTarget,a.pointerId,t),lu(!0)):(i=c.width,r||=requestAnimationFrame(s))},c.$$pointerdown=r=>{r.button===0&&(r.preventDefault(),r.currentTarget.setPointerCapture(r.pointerId),t=a(),n=r.clientX,yu(e.panel),document.documentElement.classList.add(`resizing`))},S(t=>{var n=`panel-handle${vu()===e.panel?` dragging`:``}`,r=e.panel,i=e.label,s=a(),l=o().min,u=o().max;return n!==t.e&&I(c,t.e=n),r!==t.t&&F(c,`data-panel`,t.t=r),i!==t.a&&F(c,`aria-label`,t.a=i),s!==t.o&&F(c,`aria-valuenow`,t.o=s),l!==t.i&&F(c,`aria-valuemin`,t.i=l),u!==t.n&&F(c,`aria-valuemax`,t.n=u),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),c})()}P([`pointerdown`,`pointermove`,`pointerup`,`dblclick`,`keydown`]);var Lm={service:`background service`,standalone:`standalone`};function Rm(e){return(e??[]).map(e=>{let t=!!e.online,n=e.processes.find(e=>e.kind===`service`)??e.processes[0],r=t?n?[Lm[n.kind]??n.kind,n.opencodeVersion?`OpenCode ${n.opencodeVersion}`:``].filter(Boolean).join(` · `):`online`:`offline`;return{id:e.id,name:e.name,online:t,disabled:!t,detail:r,herdr:t&&!!e.terminals?.herdr,canCreate:t&&e.processes.some(e=>e.kind===`service`)}}).sort((e,t)=>Number(t.online)-Number(e.online)||e.name.localeCompare(t.name))}function zm(e,t,n){let r=t=>t?e.find(e=>e.id===t&&e.online):void 0;return(r(t)??r(n)??e.find(e=>e.canCreate)??e.find(e=>e.online))?.id}function Bm(e,t,n){let r=(t,n)=>{let r=t?e.find(e=>e.key===t):void 0;if(r)return{key:r.key,dir:n&&r.directories.includes(n)?n:r.directories[0]??n??``}},i=e[0];return r(t.key,t.dir)??r(n?.key,n?.dir)??(i?{key:i.key,dir:i.directories[0]??``}:void 0)}function Vm(e,t){let n=Ur(t).split(/\s+/).filter(Boolean);return n.length?e.filter(e=>{let t=[e.label,...e.directories].map(Ur);return n.every(e=>t.some(t=>t.includes(e)))}):[...e]}var Hm=`hub.newSession`;function Um(e){try{let t=JSON.parse(e.getItem(`hub.newSession`)??`null`);if(t&&typeof t.machine==`string`&&typeof t.key==`string`&&typeof t.dir==`string`)return{machine:t.machine,key:t.key,dir:t.dir}}catch{}}function Wm(e,t){try{e.setItem(Hm,JSON.stringify({machine:t.machine,key:t.key,dir:t.dir}))}catch{}}var Gm=`hub.railCollapsed`;function Km(e){try{let t=JSON.parse(e.getItem(`hub.railCollapsed`)??`[]`);return new Set(Array.isArray(t)?t.filter(e=>typeof e==`string`):[])}catch{return new Set}}function qm(e,t){let n=Km(e);n.has(t)?n.delete(t):n.add(t);try{e.setItem(Gm,JSON.stringify([...n]))}catch{}return n}var Jm=0,Ym=e=>e.reduce((e,t)=>e+t.data.length,0);async function Xm(e,t){let n=Ku(t.length,e.type);if(n)throw Error(n);let r=await Zm(e);try{let n=e.type!==`image/jpeg`&&$m(r),{blob:i,request:a}=await Xu({width:r.width,height:r.height,keepPng:n},qu(Ym(t)),e=>eh(r,e)),o=await th(i);return{id:`img${++Jm}`,mime:a.type,data:o.slice(o.indexOf(`,`)+1),name:Yu(e.name||`image`,a.type),preview:URL.createObjectURL(i)}}finally{`close`in r&&r.close()}}async function Zm(e){try{return await createImageBitmap(e)}catch{let t=URL.createObjectURL(e);try{let e=new Image;return e.src=t,await e.decode(),e}catch{throw Error(`Could not read ${e.name||`this image`}`)}finally{URL.revokeObjectURL(t)}}}function Qm(e,t){let n=document.createElement(`canvas`);n.width=e,n.height=t;let r=n.getContext(`2d`);if(!r)throw Error(`This browser cannot process images`);return[n,r]}function $m(e){let t=Math.max(1,Math.min(64,e.width)),n=Math.max(1,Math.min(64,e.height)),[,r]=Qm(t,n);r.drawImage(e,0,0,t,n);let i=r.getImageData(0,0,t,n).data;for(let e=3;e<i.length;e+=4)if(i[e]<255)return!0;return!1}function eh(e,t){let[n,r]=Qm(t.width,t.height);return t.type===`image/jpeg`&&(r.fillStyle=`#fff`,r.fillRect(0,0,t.width,t.height)),r.imageSmoothingQuality=`high`,r.drawImage(e,0,0,t.width,t.height),new Promise((e,r)=>n.toBlob(t=>t?e(t):r(Error(`Could not encode the image`)),t.type,t.quality))}function th(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(Error(`Could not read the encoded image`)),r.readAsDataURL(e)})}function nh(e){if(!e)return[];let t=[...e.files].filter(e=>e.type.startsWith(`image/`));return t.length?t:[...e.items].flatMap(e=>e.kind===`file`&&e.type.startsWith(`image/`)?[e.getAsFile()].filter(e=>!!e):[])}var rh=new Map;function ih(e,t){rh.set(e,t)}function ah(e){let t=rh.get(e);return rh.delete(e),t}var oh=N(`<li class="attachment busy"aria-label="Preparing image"><span class="spinner small">`),sh=N(`<ul class=attachments aria-label="Attached images">`),ch=N(`<span class="spinner small">`),lh=N(`<form class="composer new-composer"><div class=composer-box><textarea rows=3 aria-label="Describe a task or ask a question"placeholder="Describe a task or ask a question"></textarea><input type=file class=sr-only tabindex=-1 aria-hidden=true data-testid=new-attach-input multiple><div class=composer-actions><button type=button class=icon-btn aria-label="Attach images"></button><span class=grow></span><button type=submit class="send icon-send"aria-label="Start session"title="Start session">`),uh=N(`<span class="meta-chip readonly"title="Branch of this folder"><span class="chip-text mono">`),dh=N(`<label class="meta-chip toggle-chip"><input type=checkbox><span class=chip-text>Open in Herdr tab`),fh=N(`<div class=env-meta role=group aria-label="Where the session runs">`),ph=N('<p class="small warn"> has no background service connected; start `opencode serve --service` there to create sessions.'),mh=N(`<p class=error role=alert>`),hh=N(`<div class=new-session><header class=topbar><h1 class=title>New session</h1></header><div class="column narrow new-column"><p class="display greeting">What should we work on?`),gh=N(`<p class=muted>No machine is connected to this hub yet.`),_h=N(`<li class=attachment><img><button type=button class=attachment-remove>`),vh=N(`<span aria-hidden=true>`),yh=N(`<span class=chip-text>`),bh=N(`<button type=button class="meta-chip folder-chip"aria-haspopup=dialog aria-label="Choose project folder"><span class=chip-text>`),xh=N(`<div class="menu folder-menu"role=dialog aria-label="Choose project folder"><input class=folder-search type=search placeholder="Search folders"aria-label="Search folders"><div class=folder-list role=listbox aria-label=Folders>`),Sh=N(`<p class="muted small pad">No folder matches.`),Ch=N(`<div class=menu-section> · Herdr`),wh=N(`<button type=button role=option class=menu-item><span class=menu-check></span><span class=menu-label></span><span class=menu-hint>`),Th=N(`<button type=button role=option class=menu-item><span class=menu-check></span><span class=menu-label></span><span class="menu-hint mono">`);function Eh(e){let t=Um(localStorage),n=()=>J.machines??[],r=w(()=>Rm(n())),[i,a]=x(),o=()=>{let n=i();return n&&r().some(e=>e.id===n&&e.online)?n:zm(r(),e.machine,t?.machine)},s=()=>r().find(e=>e.id===o()),c=()=>n().find(e=>e.id===o()),l=w(()=>{let t=c();if(!t)return[];let n=Ei(t).targets;return e.key&&e.dir&&t.id===e.machine&&!n.some(t=>t.key===e.key)&&n.push({kind:`folder`,key:e.key,label:sc(e.dir),directories:[e.dir]}),n}),[u,d]=x(),f=()=>{let n=u();if(n&&n.machine===o()&&l().some(e=>e.key===n.key))return{key:n.key,dir:n.dir};let r=o()===e.machine?{key:e.key,dir:e.dir}:{};return Bm(l(),r,t?.machine===o()?t:void 0)},p=()=>l().find(e=>e.key===f()?.key),m=e=>e.directories.length?e.directories:l().filter(e=>e.kind===`folder`).flatMap(e=>e.directories),h=()=>{let e=f(),t=p();return!e||!t?``:e.dir&&m(t).includes(e.dir)?e.dir:m(t)[0]??``},g=(e,t)=>e?.processes.flatMap(e=>e.sessions).filter(e=>!e.parentID&&e.directory===t).sort((e,t)=>(t.updated??0)-(e.updated??0))[0],[_]=ne(()=>{let e=g(c(),h());return e?e.id:void 0},async e=>(await H(`${W(e)}/summary`).catch(()=>({}))).branch),[v,y]=x(!0),b=()=>!!s()?.herdr&&p()?.kind===`herdr`&&v(),[ee,C]=x(``),[te,re]=x([]),[T,ie]=x(!1),[D,ae]=x(``),[oe,se]=x(!1),ce=Promise.resolve(),le=e=>{ce=ce.then(async()=>{ie(!0);try{for(let t of e)try{let e=await Xm(t,te());re(t=>[...t,e])}catch(e){ae(G(e))}}finally{ie(!1)}})},ue=()=>!oe()&&!T()&&!!s()?.canCreate&&!!h()&&(!!ee().trim()||te().length>0),de=async()=>{let e=s(),t=p(),n=h();if(ue()&&e&&t){se(!0),ae(``);try{let r=Di({target:t,directory:n,openInHerdr:b()}),i=await(await V(`/api/machines/${U(e.id)}/sessions`,{method:`POST`,json:r})).json();Wm(localStorage,{machine:e.id,key:t.key,dir:n}),ih(i.sessionID,{text:ee().trim(),images:te()}),io(ao(i.sessionID),{replace:!0}),i.warning?q(`Session created, but Herdr didn't open it: ${i.warning}`,`warn`):i.openedIn===`herdr`&&q(`Opened in Herdr · ${t.label}`)}catch(t){ae(t instanceof or&&t.status===409?`The background service on ${e.name} isn't connected. Start it, then try again.`:`Could not create the session: ${G(t)}`),se(!1)}}},fe=()=>[{section:`Choose environment`},...r().map(e=>({label:e.name,hint:e.online?e.canCreate?e.detail:`${e.detail} · no background service`:`offline`,checked:e.id===o(),disabled:e.disabled,run:()=>a(e.id)}))],pe,me;E(()=>pe?.focus());let he=()=>{pe.style.height=`auto`,pe.style.height=`${Math.min(pe.scrollHeight,320)}px`};return(()=>{var e=hh(),t=e.firstChild,n=t.firstChild,i=t.nextSibling;return i.firstChild,R(t,O(A,{get when(){return Q()},get children(){return O(Xs,{icon:`menu`,label:`Open sidebar`,onClick:du})}}),n),R(i,O(A,{get when(){return r().length},get fallback(){return gh()},get children(){return[(()=>{var e=lh(),t=e.firstChild,n=t.firstChild,r=n.nextSibling,i=r.nextSibling.firstChild,a=i.nextSibling.nextSibling;e.addEventListener(`drop`,e=>{let t=nh(e.dataTransfer);t.length&&(e.preventDefault(),le(t))}),e.addEventListener(`dragover`,e=>[...e.dataTransfer?.types??[]].includes(`Files`)&&e.preventDefault()),e.addEventListener(`submit`,e=>{e.preventDefault(),de()}),R(t,O(A,{get when(){return te().length||T()},get children(){var e=sh();return R(e,O(k,{get each(){return te()},children:e=>(()=>{var t=_h(),n=t.firstChild,r=n.nextSibling;return r.$$click=()=>re(t=>t.filter(t=>t.id!==e.id)),R(r,O(Z,{name:`close`})),S(t=>{var i=e.preview,a=e.name,o=e.name,s=`Remove ${e.name}`;return i!==t.e&&F(n,`src`,t.e=i),a!==t.t&&F(n,`alt`,t.t=a),o!==t.a&&F(n,`title`,t.a=o),s!==t.o&&F(r,`aria-label`,t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),null),R(e,O(A,{get when(){return T()},get children(){return oh()}}),null),e}}),n),n.$$keydown=e=>{e.key===`Enter`&&!e.shiftKey&&!e.isComposing&&!(matchMedia(`(max-width: 760px)`).matches&&`ontouchstart`in window)&&(e.preventDefault(),de())},n.addEventListener(`paste`,e=>{let t=nh(e.clipboardData);t.length&&(e.preventDefault(),le(t))}),n.$$input=e=>{C(e.currentTarget.value),he()};var o=pe;typeof o==`function`?L(o,n):pe=n,r.addEventListener(`change`,e=>{let t=[...e.currentTarget.files??[]];e.currentTarget.value=``,t.length&&le(t)});var s=me;return typeof s==`function`?L(s,r):me=r,i.$$click=()=>me.click(),R(i,O(Z,{name:`plus`})),R(a,O(A,{get when(){return oe()},get fallback(){return O(Z,{name:`send`})},get children(){return ch()}})),S(e=>{var t=zu.join(`,`),n=te().length>=Bu.maxImages||T(),o=!ue();return t!==e.e&&F(r,`accept`,e.e=t),n!==e.t&&(i.disabled=e.t=n),o!==e.a&&(a.disabled=e.a=o),e},{e:void 0,t:void 0,a:void 0}),S(()=>n.value=ee()),e})(),(()=>{var e=fh();return R(e,O(Zs,{label:`Choose environment`,class:`meta-chip env-chip`,align:`left`,items:fe,get text(){return[O(Z,{name:`cloud`}),(()=>{var e=vh();return S(()=>I(e,`online-dot${s()?.online?` on`:``}`)),e})(),(()=>{var e=yh();return R(e,()=>s()?.name??`No environment`),e})(),O(Z,{name:`down`,class:`chip-caret`})]}}),null),R(e,O(Dh,{get targets(){return l()},get current(){return f()},get dir(){return h()},get disabled(){return!s()},foldersOf:m,onPick:(e,t)=>d({machine:o(),key:e,dir:t})}),null),R(e,O(A,{get when(){return _()},get children(){var e=uh(),t=e.firstChild;return R(e,O(Z,{name:`branch`}),t),R(t,_),e}}),null),R(e,O(A,{get when(){return M(()=>!!s()?.herdr)()&&p()?.kind===`herdr`},get children(){var e=dh(),t=e.firstChild;return t.addEventListener(`change`,e=>y(e.currentTarget.checked)),S(()=>F(e,`title`,`Open the new session in a new tab of the Herdr workspace ${p().label}`)),S(()=>t.checked=v()),e}}),null),e})(),O(A,{get when(){return M(()=>!!s())()&&!s().canCreate},get children(){var e=ph(),t=e.firstChild;return R(e,()=>s().name,t),e}}),O(A,{get when(){return D()},get children(){var e=mh();return R(e,D),e}})]}}),null),e})()}function Dh(e){let[t,n]=x(!1),[r,i]=x(``),[a,o]=x({top:0,left:0}),s,c,l,u=()=>Vm(e.targets,r()),d=()=>{let t=e.targets.find(t=>t.key===e.current?.key);return t?t.kind===`herdr`&&e.dir?`${t.label} · ${sc(e.dir)}`:t.label:`No folder`},f=()=>{let e=s.getBoundingClientRect();o({top:e.bottom+4,left:e.left}),i(``),n(!t()),t()&&queueMicrotask(()=>l?.focus())},p=e=>{t()&&!s.contains(e.target)&&!c?.contains(e.target)&&n(!1)},m=e=>{t()&&e.key===`Escape`&&(n(!1),s.focus())};E(()=>{document.addEventListener(`mousedown`,p),document.addEventListener(`keydown`,m)}),D(()=>{document.removeEventListener(`mousedown`,p),document.removeEventListener(`keydown`,m)});let h=(t,r)=>{e.onPick(t,r),n(!1)};return[(()=>{var n=bh(),r=n.firstChild;n.$$click=f;var i=s;return typeof i==`function`?L(i,n):s=n,R(n,O(Z,{name:`folder`}),r),R(r,d),R(n,O(Z,{name:`down`,class:`chip-caret`}),null),S(r=>{var i=t(),a=e.dir||`Choose a folder`,o=e.disabled;return i!==r.e&&F(n,`aria-expanded`,r.e=i),a!==r.t&&F(n,`title`,r.t=a),o!==r.a&&(n.disabled=r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})(),O(A,{get when(){return t()},get children(){return O(xt,{get children(){var t=xh(),n=t.firstChild,o=n.nextSibling,s=c;typeof s==`function`?L(s,t):c=t,n.$$keydown=t=>{let n=u()[0];t.key===`Enter`&&n&&(t.preventDefault(),h(n.key,e.foldersOf(n)[0]??``))},n.$$input=e=>i(e.currentTarget.value);var d=l;return typeof d==`function`?L(d,n):l=n,R(o,O(A,{get when(){return u().length},get fallback(){return Sh()},get children(){return O(k,{get each(){return u()},children:t=>O(A,{get when(){return M(()=>t.kind===`herdr`)()&&e.foldersOf(t).length>1},get fallback(){return(()=>{var n=wh(),r=n.firstChild,i=r.nextSibling,a=i.nextSibling;return n.$$click=()=>h(t.key,e.foldersOf(t)[0]??``),R(r,()=>e.current?.key===t.key?`✓`:``),R(i,()=>t.label),R(a,(()=>{var n=M(()=>t.kind===`herdr`);return()=>n()?`Herdr`:sc(e.foldersOf(t)[0]??``)})()),S(r=>{var i=e.current?.key===t.key,a=e.foldersOf(t)[0];return i!==r.e&&F(n,`aria-selected`,r.e=i),a!==r.t&&F(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()},get children(){return[(()=>{var e=Ch(),n=e.firstChild;return R(e,()=>t.label,n),e})(),O(k,{get each(){return e.foldersOf(t)},children:n=>(()=>{var r=Th(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling;return r.$$click=()=>h(t.key,n),F(r,`title`,n),R(i,()=>e.current?.key===t.key&&e.dir===n?`✓`:``),R(a,()=>sc(n)),R(o,n),S(()=>F(r,`aria-selected`,e.current?.key===t.key&&e.dir===n)),r})()})]}})})}})),S(e=>{var n=`${a().top}px`,r=`${a().left}px`;return n!==e.e&&ot(t,`top`,e.e=n),r!==e.t&&ot(t,`left`,e.t=r),e},{e:void 0,t:void 0}),S(()=>n.value=r()),t}})}})]}P([`input`,`keydown`,`click`]);function Oh(e,t,n){let r=n?`/s/${encodeURIComponent(n)}`:`/`,i=r===t?`/`:r,a=e.state;(a?.hubSessionPath!==t||a?.hubSessionBack!==i)&&(e.replaceState({hubSessionPath:`/`},``,`/`),i!==`/`&&e.pushState({hubSessionPath:i,hubSessionBack:`/`},``,i),e.pushState({hubSessionPath:t,hubSessionBack:i},``,t))}var kh=200,Ah=10,jh=e=>e instanceof Error?e.message:String(e),Mh=e=>e&&typeof e==`object`&&typeof e.status==`number`?e.status:void 0,Nh=class{timeline;fetch;options;state=`idle`;error;cursor;invalid=!1;generation=0;loading;constructor(e,t,n={}){this.timeline=e,this.fetch=t,this.options=n}get hasOlder(){return this.cursor!==void 0}get limit(){return this.options.limit??80}changed(){this.options.onChange?.()}async first(){let e=this.begin(),t=await this.fetch({limit:this.limit,order:`desc`});e===this.generation&&await this.show(t,e)}async resync(){let e=this.begin(),t=await this.fetch({limit:this.limit,order:`desc`});if(e!==this.generation)return;let n=t.items??[],r=t.older===void 0||n.some(e=>this.timeline.fromHistory(e?.key));t.cursor===void 0&&r?(this.timeline.load(n),this.state===`loading`&&(this.state=this.cursor===void 0?`done`:`idle`),this.changed()):(this.timeline.forgetHistory(),await this.show(t,e))}older(){if(this.loading)return this.loading;if(this.state!==`idle`||this.cursor===void 0)return Promise.resolve();let e=this.generation,t=this.cursor;this.state=`loading`,this.changed();let n=(async()=>{try{let n=await this.fetch({limit:this.limit,before:t});if(e!==this.generation)return;this.timeline.load(n.items,{older:!0}),this.cursor=n.older,this.state=n.older===void 0?`done`:`idle`,this.error=void 0}catch(t){if(e!==this.generation)return;this.state=`error`,this.error=jh(t),this.invalid=Mh(t)===400}finally{e===this.generation&&(this.loading=void 0,this.changed())}})();return this.loading=n,n}async retry(){if(this.state===`error`){if(this.invalid){let e=this.begin();this.timeline.forgetHistory();try{let t=await this.fetch({limit:this.limit,order:`desc`});e===this.generation&&await this.show(t,e)}catch(t){if(e!==this.generation)return;this.state=`error`,this.error=jh(t),this.invalid=!0,this.changed()}}else return this.state=`idle`,this.error=void 0,this.older()}}begin(){return this.loading=void 0,++this.generation}async show(e,t){if(this.timeline.load(e.items),this.error=void 0,this.invalid=!1,e.cursor!==void 0&&e.older===void 0){let n=e.cursor;for(let e=1;n!==void 0&&e<Ah;e++){let e=await this.fetch({limit:kh,cursor:n});if(t!==this.generation)return;this.timeline.load(e.items),n=e.cursor}this.cursor=void 0,this.state=`done`}else this.cursor=e.older,this.state=e.older===void 0?`done`:`idle`;this.changed()}},Ph=[`native`,`hooks`,`rpc`,`screen`],Fh={opencode:`OpenCode`,"claude-code":`Claude Code`,codex:`Codex`},Ih=e=>Fh[e]??e;function Lh(e){let t=e?.harness||`opencode`;if(t===`opencode`)return{native:!0,harness:t,harnessName:`OpenCode`,evidence:`native`,turn:!0,steer:!0,interrupt:!0,stop:!0,permission:!0,form:!0,models:!0,timeline:!0,summary:!0,voice:!0,queued:!1};let n=Ph.includes(e?.evidence??``)?e.evidence:`unknown`,r=e?.features?new Set(e.features):void 0,i=e=>!r||r.has(e);return{native:!1,harness:t,harnessName:Ih(t),evidence:n,turn:i(`turn`),steer:i(`steer`),interrupt:i(`interrupt`),stop:i(`stop`),permission:i(`permission`),form:i(`form`),models:i(`models`),timeline:i(`timeline`),summary:i(`summary`),voice:i(`conversation`)&&i(`steer`),queued:n===`hooks`||n===`screen`||n===`unknown`}}var Rh={native:{label:`Native`,detail:e=>`The hub sees ${e}'s own events: status and turns are confirmed by the harness.`},hooks:{label:`Hooks`,detail:e=>`The hub follows ${e} through its lifecycle hooks: status updates at hook points, and prompts are queued until its next hook.`},rpc:{label:`RPC`,detail:e=>`The hub drives ${e} through its RPC API: prompts and turns are confirmed by the harness.`},screen:{label:`Screen`,detail:e=>`The hub reads ${e}'s terminal screen: status is a guess that never counts as idle, and prompts are pasted in (at most queued).`},unknown:{label:`Unknown`,detail:e=>`The ${e} spoke declared no evidence level: the session never counts as idle and prompts are at most queued.`}};function zh(e){if(e.native)return;let t=Rh[e.evidence];return{level:e.evidence,label:t.label,detail:t.detail(e.harnessName)}}function Bh(e,t){return e.turn&&e.steer?{show:!0,allowed:!0}:!e.turn&&!e.steer?{show:!1,allowed:!1,hint:`This ${e.harnessName} session takes no prompts from the hub; type in its terminal.`}:t&&!e.steer?{show:!0,allowed:!1,hint:`${e.harnessName} can't take input while it runs here; send once the session is idle.`}:!t&&!e.turn?{show:!0,allowed:!1,hint:`${e.harnessName} takes input here only while the session runs.`}:{show:!0,allowed:!0}}function Vh(e,t){return t===`result`?{tick:`heard`}:e.queued?t===`steered`?{tick:`queued`,toast:`Queued: ${e.harnessName} picks it up at its next step`}:{tick:`queued`}:t===`steered`?{tick:`sent`,toast:`Steered the running session`}:{tick:`sent`}}var Hh={queued:`queued`,retained:`held`,pending:`pending`};function Uh(e){return typeof e==`string`?Hh[e]:void 0}function Wh(e){let t=e;if(!t||t.status!==409||t.code!==`unsupported`)return;let n=typeof t.message==`string`?t.message.trim().replace(/\.$/,``):``;return n?`Not available for this session: ${n[0].toLowerCase()}${n.slice(1)}. Use its terminal.`:`Not available for this session. Use its terminal.`}var Gh=(e,t,n)=>`/api/sessions/${encodeURIComponent(e)}/timeline/messages/${encodeURIComponent(t)}/files/${n}`;function Kh(e){let t=[];if(Array.isArray(e.images))e.images.forEach((n,r)=>{n&&typeof n.mime==`string`&&t.push({key:`${e.key}:${r}`,name:String(n.name||`image`),mime:n.mime,...typeof n.preview==`string`?{src:n.preview}:{}})});else if(Array.isArray(e.files))for(let n of e.files){if(!n||typeof n.mime!=`string`||!Number.isInteger(n.index))continue;let r=Gu(n.mime)&&typeof e.sessionID==`string`&&typeof e.messageID==`string`;t.push({key:`${e.key}:${n.index}`,name:typeof n.name==`string`&&n.name?n.name:n.mime.startsWith(`image/`)?`image`:`file`,mime:n.mime,...r?{src:Gh(e.sessionID,e.messageID,n.index)}:{}})}return t}function qh(e){let t=[];for(let n of e)if(!((n.depth??0)>0))switch(n.kind){case`user`:{let e=Kh(n);(n.text||e.length)&&t.push({type:`user`,key:n.key,text:n.text??``,...e.length?{images:e}:{}});break}case`assistant`:n.text&&t.push({type:`assistant`,key:n.key,text:n.text,live:n.live===!0});break;case`reasoning`:{let e=n.state===`running`,r=!e&&typeof n.at==`number`&&typeof n.completed==`number`?Math.max(0,Math.round((n.completed-n.at)/1e3)):void 0;t.push({type:`thought`,key:n.key,text:n.text??``,running:e,...r===void 0?{}:{seconds:r}});break}case`tool`:{let e=t[t.length-1],r=e?.type===`tools`?e:void 0,i=r??{type:`tools`,key:`tools:${n.key}`,items:[],failed:0,running:0};i.items.push(n),n.state===`failed`&&i.failed++,n.state===`running`&&i.running++,r||t.push(i);break}case`message`:t.push(Zh(n));break;case`error`:t.push(Yh(n));break;case`retry`:t.push({type:`retry`,key:n.key,...Jh(`attempt`,n.attempt),...Jh(`next`,n.next),...typeof n.errorType==`string`?{errorType:n.errorType}:{},...Jh(`errorStatus`,n.errorStatus),...typeof n.text==`string`&&n.text?{message:n.text}:{}});break;case`subagent`:n.sessionID&&t.push({type:`subagent`,key:n.key,sessionID:n.sessionID,label:n.label??n.sessionID,state:n.state??`working`})}return t}var Jh=(e,t)=>typeof t==`number`&&Number.isFinite(t)?{[e]:t}:{};function Yh(e){let t=typeof e.text==`string`&&e.text.trim()?e.text.trim():void 0,n=Oi(e.errorType),r=Ai(e.errorStatus);return{type:`error`,key:e.key,label:n??t??`Error`,...n&&t?{message:t}:{},...r?{status:r}:{}}}function Xh(e,t){return{text:Ii(e,t),waiting:ji(e.next,t)!==void 0}}function Zh(e){let t=e.message&&typeof e.message==`object`?e.message:{},n=typeof t.kind==`string`?t.kind:`msg`,r=e.direction===`out`?`out`:`in`,i=String(t.to??``),a=typeof e.recipient==`string`?e.recipient:void 0,o=Uh(e.delivery),s=n===`primer`?`Hub identity note`:r===`out`?`to ${i}${a&&a!==i?` (→ ${a})`:``}`:`from ${String(t.from??`?`)}`;return{type:`message`,key:e.key,direction:r,kind:n,label:s,text:e.text??``,primer:n===`primer`,...typeof e.state==`string`?{state:e.state}:{},...o?{delivery:o}:{}}}var Qh=`The model didn't share its reasoning text (only an encrypted summary).`;function $h(e){let t=e.running?`Thinking…`:e.seconds===void 0?`Thought`:`Thought for ${e.seconds}s`;return e.text?{label:t,body:e.text,muted:!1}:{label:t,body:e.running?`Waiting for the model's reasoning…`:Qh,muted:!0}}var eg=N(`<p class=composer-error role=alert>`),tg=N(`<p class="composer-hint muted small">`),ng=N(`<li class="attachment busy"aria-label="Preparing image"><span class="spinner small">`),rg=N(`<ul class=attachments aria-label="Attached images">`),ig=N(`<div><button type=button class=split-main>`),ag=N(`<button type=button class="btn stop"aria-label="Stop the session and its subagents"> Stop`),og=N(`<span class=sr-only>`),sg=N(`<button type=button class=model-chip title="Voice model (the orchestrator you talk to)">Voice: `),cg=N(`<button type=button class=model-chip title="Worker model (subagents that do the work)">Worker: `),lg=N(`<form><div class=composer-box><textarea rows=1 aria-label=Message></textarea><input type=file class=sr-only tabindex=-1 aria-hidden=true data-testid=attach-input multiple><div class=composer-actions><button type=button class=icon-btn aria-label="Attach images"></button><span class=grow></span><button type=button></button><button type=submit></button></div></div><div class=composer-meta><span class="muted small"></span><span class=grow>`),ug=N(`<li class=attachment><img><button type=button class=attachment-remove title=Remove>`),dg=N(`<span class="spinner small">`),fg=N(`<button type=button class=split-chev aria-label="Choose microphone"aria-haspopup=dialog>`),pg=N(`<p class="error small pad">`),mg=N(`<div class="menu mic-picker"role=dialog aria-label=Microphone><div class=menu-section>Microphone</div><div class=level aria-label="Input level"role=meter aria-valuemin=0 aria-valuemax=100><span>`),hg=N(`<button type=button class=menu-item role=menuitemradio><span class=menu-check></span><span class=menu-label>`),gg=N(`<span class=muted> · “<!>…”`),_g=N(`<span class=voice-ignored title="Heard as background noise, not sent"> · ignored: “<!>”`),vg=N(`<p class="voice-hint small">Allow notifications to keep a “Voice mode on” notification with an End button while the screen is off. <button type=button class=link>Allow notifications`),yg=N(`<div role=region aria-label="Voice mode"><div class=wave aria-hidden=true></div><span class=voice-state role=status aria-live=polite></span><span class=grow></span><button type=button class=model-chip title="Voice model"></button><button type=button></button><button type=button class="btn small end">End`),bg=N(`<span>`);function xg(e){let t,n,[r,i]=x(!1),a=()=>e.images.length>=Bu.maxImages,o=()=>{t.style.height=`auto`,t.style.height=`${Math.min(t.scrollHeight,280)}px`};C(()=>{e.draft,queueMicrotask(o)});let s=()=>e.view.primary===`steer`?`Steer`:`Send`;return(()=>{var o=lg(),c=o.firstChild,l=c.firstChild,u=l.nextSibling,d=u.nextSibling,f=d.firstChild,p=f.nextSibling.nextSibling,m=p.nextSibling,h=c.nextSibling,g=h.firstChild;g.nextSibling,o.addEventListener(`drop`,t=>{let n=nh(t.dataTransfer);i(!1),n.length&&(t.preventDefault(),e.onAttach(n))}),o.addEventListener(`dragleave`,e=>{e.currentTarget.contains(e.relatedTarget)||i(!1)}),o.addEventListener(`dragover`,e=>{[...e.dataTransfer?.types??[]].includes(`Files`)&&(e.preventDefault(),i(!0))}),o.addEventListener(`submit`,t=>{t.preventDefault(),e.view.canSubmit&&!e.attaching&&e.onSubmit()}),R(o,O(A,{get when(){return e.error},get children(){var t=eg();return R(t,()=>e.error),t}}),c),R(o,O(A,{get when(){return e.view.hint},get children(){var t=tg();return R(t,()=>e.view.hint),t}}),c),R(c,O(A,{get when(){return e.images.length||e.attaching},get children(){var t=rg();return R(t,O(k,{get each(){return e.images},children:t=>(()=>{var n=ug(),r=n.firstChild,i=r.nextSibling;return i.$$click=()=>e.onDetach(t.id),R(i,O(Z,{name:`close`})),S(e=>{var n=t.preview,a=t.name,o=t.name,s=`Remove ${t.name}`;return n!==e.e&&F(r,`src`,e.e=n),a!==e.t&&F(r,`alt`,e.t=a),o!==e.a&&F(r,`title`,e.a=o),s!==e.o&&F(i,`aria-label`,e.o=s),e},{e:void 0,t:void 0,a:void 0,o:void 0}),n})()}),null),R(t,O(A,{get when(){return e.attaching},get children(){return ng()}}),null),t}}),l),l.$$keydown=t=>{t.key===`Enter`&&!t.shiftKey&&!t.isComposing&&!(matchMedia(`(max-width: 760px)`).matches&&`ontouchstart`in window)&&(t.preventDefault(),e.view.canSubmit&&!e.attaching&&e.onSubmit())},l.addEventListener(`paste`,t=>{let n=nh(t.clipboardData);n.length&&(t.preventDefault(),e.onAttach(n))}),l.$$input=t=>e.onInput(t.currentTarget.value);var _=t;typeof _==`function`?L(_,l):t=l,u.addEventListener(`change`,t=>{let n=[...t.currentTarget.files??[]];t.currentTarget.value=``,n.length&&e.onAttach(n)});var v=n;return typeof v==`function`?L(v,u):n=u,f.$$click=()=>n.click(),R(f,O(Z,{name:`plus`})),rt(p,`click`,e.onDictate,!0),R(p,O(A,{get when(){return!e.transcribing},get fallback(){return dg()},get children(){return O(Z,{get name(){return e.dictating===!1?`mic`:`stop`}})}})),R(d,O(A,{get when(){return e.showVoice!==!1},get children(){var t=ig(),n=t.firstChild;return rt(n,`click`,e.onVoice,!0),R(n,O(Z,{name:`wave`})),R(t,O(Sg,{}),null),S(r=>{var i=`split${e.voiceOn?` on`:``}`,a=e.voiceOn,o=e.voiceOn?`End Voice mode`:`Start Voice mode`,s=e.voiceBlocked??(e.voiceOn?`End Voice mode`:`Voice mode: talk hands-free`),c=!!e.voiceBlocked&&!e.voiceOn;return i!==r.e&&I(t,r.e=i),a!==r.t&&F(n,`aria-pressed`,r.t=a),o!==r.a&&F(n,`aria-label`,r.a=o),s!==r.o&&F(n,`title`,r.o=s),c!==r.i&&(n.disabled=r.i=c),r},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t}}),m),R(d,O(A,{get when(){return e.view.showStop},get children(){var t=ag(),n=t.firstChild;return rt(t,`click`,e.onStop,!0),R(t,O(Z,{name:`stop`}),n),S(()=>t.disabled=!e.view.canStop),t}}),m),R(m,O(A,{get when(){return e.view.primary===`send`},get fallback(){return s()},get children(){return[O(Z,{name:`send`}),(()=>{var e=og();return R(e,s),e})()]}})),R(g,()=>e.metaLeft),R(h,O(A,{get when(){return e.showModels!==!1},get children(){return[(()=>{var t=sg();return t.firstChild,t.$$click=()=>e.onModel(`voice`),R(t,()=>e.voiceModel,null),t})(),(()=>{var t=cg();return t.firstChild,t.$$click=()=>e.onModel(`worker`),R(t,()=>e.workerModel,null),t})()]}}),null),S(t=>{var n=`composer${r()?` dragging`:``}`,i=e.voiceOn?`Voice mode is on — talk, or type here`:e.view.primary===`steer`?`Steer the running session…`:`Reply…`,s=zu.join(`,`),c=a()?`At most ${Bu.maxImages} images per message`:`Attach images (or paste / drop them here)`,d=a()||e.attaching,h=`icon-btn${e.dictating===!1?``:` recording`}`,g=e.dictating===!1?`Dictate`:`Stop dictation`,_=e.voiceBlocked??(e.dictating===!1?`Dictate`:`Stop dictation (${e.dictating}s left)`),v=!!e.voiceBlocked||e.transcribing||e.voiceOn,y=`btn primary send ${e.view.primary}`,b=!e.view.canSubmit||e.attaching;return n!==t.e&&I(o,t.e=n),i!==t.t&&F(l,`placeholder`,t.t=i),s!==t.a&&F(u,`accept`,t.a=s),c!==t.o&&F(f,`title`,t.o=c),d!==t.i&&(f.disabled=t.i=d),h!==t.n&&I(p,t.n=h),g!==t.s&&F(p,`aria-label`,t.s=g),_!==t.h&&F(p,`title`,t.h=_),v!==t.r&&(p.disabled=t.r=v),y!==t.d&&I(m,t.d=y),b!==t.l&&(m.disabled=t.l=b),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0}),S(()=>l.value=e.draft),o})()}function Sg(){let[e,t]=x(!1),[n,r]=x([]),[i,a]=x(0),[o,s]=x(``),c,l,u,[d,f]=x({right:0,bottom:0}),p=async()=>{u?.(),u=void 0;try{u=await Lp(Np(),a),s(``)}catch(e){s(e.name===`NotAllowedError`?`Microphone permission was denied.`:`Microphone: ${e.message}`)}},m=async()=>{let e=c.getBoundingClientRect();if(f({right:window.innerWidth-e.right,bottom:window.innerHeight-e.top+6}),t(!0),!navigator.mediaDevices)return s(`This browser cannot use the microphone here (it needs HTTPS).`);r(await Ip().catch(()=>[])),p()},h=()=>{t(!1),u?.(),u=void 0,a(0)},g=t=>e()&&!c.contains(t.target)&&!l?.contains(t.target)&&h(),_=t=>e()&&t.key===`Escape`&&h();return document.addEventListener(`mousedown`,g),document.addEventListener(`keydown`,_),D(()=>{document.removeEventListener(`mousedown`,g),document.removeEventListener(`keydown`,_),h()}),[(()=>{var t=fg();t.$$click=()=>e()?h():void m();var n=c;return typeof n==`function`?L(n,t):c=t,R(t,O(Z,{name:`down`})),S(()=>F(t,`aria-expanded`,e())),t})(),O(A,{get when(){return e()},get children(){return O(xt,{get children(){var e=mg(),t=e.firstChild.nextSibling,r=t.firstChild,a=l;return typeof a==`function`?L(a,e):l=e,R(e,O(k,{get each(){return[{deviceId:``,label:`System default`},...n().filter(e=>e.deviceId&&e.deviceId!=="default")]},children:(e,t)=>(()=>{var n=hg(),r=n.firstChild,i=r.nextSibling;return n.$$click=()=>{Fp(e.deviceId),p()},R(r,()=>Np()===e.deviceId?`✓`:``),R(i,()=>e.label||`Microphone ${t()}`),S(()=>F(n,`aria-checked`,Np()===e.deviceId)),n})()}),t),R(e,O(A,{get when(){return o()},get children(){var e=pg();return R(e,o),e}}),null),S(n=>{var a=`${d().right}px`,o=`${d().bottom}px`,s=Math.round(i()*100),c=`${Math.round(i()*100)}%`;return a!==n.e&&ot(e,`right`,n.e=a),o!==n.t&&ot(e,`bottom`,n.t=o),s!==n.a&&F(t,`aria-valuenow`,n.a=s),c!==n.o&&ot(r,`width`,n.o=c),n},{e:void 0,t:void 0,a:void 0,o:void 0}),e}})}})]}var Cg={starting:`Starting…`,listening:`Listening`,hearing:`Listening`,transcribing:`Thinking`,sent:`Thinking`,speaking:`Speaking`,paused:`Muted`,suspended:`Paused — mic stopped by the phone (screen off). Unlock to resume.`,off:`Off`};function wg(e,t){let n=e?[e.summary,e.detail]:[];return t&&n.push(t.mode===`silero`?`speech detection: on-device model${t.avgMs?` (${t.avgMs.toFixed(1)} ms per 32 ms of audio)`:``}`:`speech detection: loudness (the on-device model is loading or unavailable)`),n.length?n.join(`
9
+ `):void 0}function Tg(e){let t=()=>e.state===`listening`&&e.working?`Thinking`:Cg[e.state],n=[.5,.8,1,.7,.45];return(()=>{var r=yg(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling.nextSibling,s=o.nextSibling,c=s.nextSibling;return R(i,O(k,{each:n,children:t=>(()=>{var n=bg();return S(r=>ot(n,`transform`,`scaleY(${Math.max(.15,Math.min(1,(e.state===`speaking`?.6:e.level)*t*1.6))})`)),n})()})),R(a,t,null),R(a,O(A,{get when(){return e.held},get children(){var t=gg(),n=t.firstChild.nextSibling;return n.nextSibling,R(t,()=>e.held,n),t}}),null),R(a,O(A,{get when(){return e.ignored},get children(){var t=_g(),n=t.firstChild.nextSibling;return n.nextSibling,R(t,()=>e.ignored,n),t}}),null),rt(o,`click`,e.onModel,!0),R(o,()=>e.model),rt(s,`click`,e.onMute,!0),R(s,O(Z,{get name(){return e.state===`paused`?`muted`:`mic`}})),rt(c,`click`,e.onEnd,!0),R(r,O(A,{get when(){return e.notifyHint},get children(){var t=vg(),n=t.firstChild.nextSibling;return n.$$click=()=>e.onAllowNotifications?.(),t}}),null),S(t=>{var n=`voice-bar ${e.state}`,i=e.detector?.mode,o=wg(e.timing,e.detector),c=`icon-btn${e.state===`paused`?` on`:``}`,l=e.state===`paused`,u=e.state===`paused`?`Unmute`:`Mute`,d=e.state===`paused`?`Unmute`:`Mute`;return n!==t.e&&I(r,t.e=n),i!==t.t&&F(r,`data-vad`,t.t=i),o!==t.a&&F(a,`title`,t.a=o),c!==t.o&&I(s,t.o=c),l!==t.i&&F(s,`aria-pressed`,t.i=l),u!==t.n&&F(s,`aria-label`,t.n=u),d!==t.s&&F(s,`title`,t.s=d),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),r})()}P([`input`,`keydown`,`click`]);var Eg=e=>String(e??``).normalize(`NFD`).replace(/[\u0300-\u036f]/g,``).toLowerCase();function Dg(e){let t=e,n=Array.isArray(e)?e:Array.isArray(t?.models)?t.models:[],r=new Set,i=[];for(let e of n){let t=e,n=typeof e==`string`?e.trim():typeof t?.id==`string`?t.id.trim():``;if(!n||r.has(n))continue;r.add(n);let a=typeof t?.name==`string`?t.name.trim():``;i.push(a&&a!==n?{id:n,name:a}:{id:n})}return i}function Og(e){let t=e?.note;return!Array.isArray(e)&&typeof t==`string`&&t.trim()?t.trim():void 0}var kg=e=>e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;function Ag(e,t,{current:n=``,limit:r=200,grouped:i=!1}={}){let a=String(t??``).trim(),o=Eg(a),s=o.split(/\s+/).filter(Boolean),c=[...e??[]],l=String(n??``).trim();l&&!c.some(e=>e.id===l)&&c.unshift({id:l,custom:!0});let u=[];if(c.forEach((e,t)=>{let n=Eg(e.id),r=`${n} ${Eg(e.name)}`;if(!s.every(e=>r.includes(e)))return;let i=o?n===o?0:n.startsWith(o)?1:2:e.id===l?0:1;u.push({option:e,rank:i,index:t})}),u.sort((e,t)=>e.rank-t.rank||e.index-t.index),i){let e=new Map;for(let t of u)e.has(kg(t.option.id))||e.set(kg(t.option.id),e.size);u.sort((t,n)=>e.get(kg(t.option.id))-e.get(kg(n.option.id)))}let d=u.slice(0,r).map(({option:e})=>({id:e.id,...e.name?{name:e.name}:{},...l&&e.id===l?{current:!0}:{},...e.custom?{custom:!0}:{}})),f=c.some(e=>e.id===a);return{items:d,total:u.length,more:Math.max(0,u.length-r),...a&&!f?{custom:a}:{}}}function jg(e,t,n){return n?t===`home`?0:t===`end`?n-1:e<0?t>0?0:n-1:((e+t)%n+n)%n:-1}var Mg=()=>({query:``,active:0}),Ng=e=>[void 0,...(e.variants??[]).filter(e=>e!=="default")];function Pg(e,t,n=100){if(t.chosen)return{mode:`variants`,model:t.chosen,rows:Ng(t.chosen)};let r=e.groups(t.query).flatMap(e=>e.items.map(t=>({...t,group:e.providerID})));return{mode:`models`,rows:r.slice(0,n),total:r.length,more:Math.max(0,r.length-n)}}var Fg=(e,t)=>({...e,query:t,active:0}),Ig=(e,t)=>({providerID:e.providerID,modelID:e.modelID,...t?{variant:t}:{}});function Lg(e,t,n){let r=Pg(e,t);if(r.mode===`variants`)return n<0||n>=r.rows.length?{state:t}:{state:t,pick:Ig(r.model,r.rows[n])};let i=r.rows[n];return i?Ng(i).length>1?{state:{...t,chosen:i,active:0}}:{state:t,pick:Ig(i)}:{state:t}}function Rg(e,t,n,{inSearch:r}){let i=Pg(e,t).rows.length;if(n===`ArrowDown`||n===`ArrowUp`)return{state:{...t,active:Math.max(0,jg(t.active,n===`ArrowDown`?1:-1,i))},handled:!0};if(n===`Enter`)return{...Lg(e,t,t.active),handled:!0};if(n===`Backspace`&&t.chosen&&!r)return{state:{...t,chosen:void 0,active:0},handled:!0};if(/^[1-9]$/.test(n)&&!r){let r=Number(n)-1;return r>=i?{state:t,handled:!1}:{...Lg(e,t,r),handled:!0}}return{state:t,handled:!1}}var zg=(e,t)=>({[e]:t}),Bg=N(`<div>`),Vg=N(`<p class="error small"role=alert>Couldn't load models: `),Hg=N(`<p class="muted small">Loading models…`),Ug=N(`<input type=search class=picker-search placeholder="Search models"aria-label="Search models"autofocus>`),Wg=N(`<p class="muted small"role=status>`),Gg=N(`<ul class=picker-list role=listbox aria-label=Models>`),Kg=N(`<li class="muted small">No models match.`),qg=N(`<div class="picker-group muted small">`),Jg=N(`<span class="po-id muted">variants ›`),Yg=N(`<span class=po-mark>✓`),Xg=N(`<kbd>`),Zg=N(`<li><button type=button role=option><span class=po-name></span><span class="po-id muted">`),Qg=N(`<div class=stack><div class=row><button type=button class="btn small"aria-label="Back to models">‹ Back</button><p class="muted small">Variant of </p></div><ul class=picker-list role=listbox aria-label=Variants>`),$g=N(`<li><button type=button role=option><span class=po-name></span><kbd>`);function e_(e,t){let n=e?.prefs[t]??e?.defaults[t];return n?`${n.modelID}${n.variant?` · ${n.variant}`:``}`:`default`}function t_(e){let[t,n]=x(),[r,i]=x(``),[a,o]=x();return{prefs:t,error:r,load:async()=>{try{n(await H(`${W(e())}/model-prefs`)),i(``)}catch(e){i(G(e))}},loadCatalog:async()=>{if(a())return a();let{models:t}=await H(`${W(e())}/models`),n=new Kt(t);return o(n),n},save:async(t,r)=>{try{n(await(await V(`${W(e())}/model-prefs`,{method:`PUT`,json:zg(t,r)})).json()),q(`${t===`voice`?`Voice`:`Worker`} model applies to the next ${t===`voice`?`turn`:`task`}.`)}catch(e){q(`Couldn't set the ${t===`voice`?`Voice`:`Worker`} model: ${G(e)}`,`err`)}}}}function n_(e){let[t,n]=x(Mg()),[r,i]=x(),[a,o]=x(``),s=()=>e.kind!==void 0,c=()=>e.kind?e.models.prefs()?.prefs[e.kind]??e.models.prefs()?.defaults[e.kind]:void 0,l=e=>c()?.providerID===e.providerID&&c()?.modelID===e.modelID,u=()=>{n(Mg()),o(``),e.models.loadCatalog().then(i,e=>o(G(e)))},d=w(()=>r()?Pg(r(),t()):void 0),f=t=>{if(n(t.state),!t.pick||!e.kind)return;let r=e.kind;e.onClose(),e.models.save(r,t.pick)},p=e=>r()&&f(Lg(r(),t(),e)),m=e=>{if(!r()||e.altKey||e.ctrlKey||e.metaKey)return;let n=Rg(r(),t(),e.key,{inSearch:e.target instanceof HTMLInputElement});if(!n.handled)return;e.preventDefault(),f(n);let i=e.currentTarget;queueMicrotask(()=>i.querySelector(`.picker-opt.active`)?.scrollIntoView({block:`nearest`}))};return C(ie(s,e=>e&&u())),O(Qs,{get open(){return s()},get title(){return`${e.kind===`voice`?`Voice`:`Worker`} model`},get onClose(){return e.onClose},class:`picker`,get children(){var e=Bg();return e.$$keydown=m,R(e,O(A,{get when(){return!a()},get fallback(){return(()=>{var e=Vg();return e.firstChild,R(e,a,null),e})()},get children(){return O(A,{get when(){return d()},get fallback(){return Hg()},children:e=>O(A,{get when(){return M(()=>e().mode===`models`)()&&e()},get fallback(){return O(r_,{get view(){return e()},get active(){return t().active},get current(){return c()},onPick:p,onBack:()=>n(e=>({...e,chosen:void 0,active:0}))})},children:e=>[(()=>{var e=Ug();return e.$$input=e=>n(t=>Fg(t,e.currentTarget.value)),S(()=>e.value=t().query),e})(),(()=>{var t=Wg();return R(t,(()=>{var t=M(()=>e().total===1);return()=>t()?`1 model`:`${e().total} models`})(),null),R(t,(()=>{var t=M(()=>!!e().more);return()=>t()?` · showing ${e().rows.length}, search to narrow`:``})(),null),t})(),(()=>{var n=Gg();return R(n,O(k,{get each(){return e().rows},get fallback(){return Kg()},children:(n,r)=>(()=>{var i=Zg(),a=i.firstChild,o=a.firstChild,s=o.nextSibling;return R(i,O(A,{get when(){return r()===0||e().rows[r()-1].group!==n.group},get children(){var e=qg();return R(e,()=>n.group),e}}),a),a.$$click=()=>p(r()),R(o,()=>n.name||n.modelID),R(s,()=>n.modelID),R(a,O(A,{get when(){return(n.variants??[]).some(e=>e!=="default")},get children(){return Jg()}}),null),R(a,O(A,{get when(){return l(n)},get children(){return Yg()}}),null),R(a,O(A,{get when(){return r()<9},get children(){var e=Xg();return R(e,()=>r()+1),e}}),null),S(e=>{var i=`picker-opt${t().active===r()?` active`:``}`,o=l(n);return i!==e.e&&I(a,e.e=i),o!==e.t&&F(a,`aria-selected`,e.t=o),e},{e:void 0,t:void 0}),i})()})),n})()]})})}})),e}})}function r_(e){let t;E(()=>t?.focus());let n=()=>e.current?.providerID===e.view.model.providerID&&e.current?.modelID===e.view.model.modelID;return(()=>{var r=Qg(),i=r.firstChild,a=i.firstChild,o=a.nextSibling;o.firstChild;var s=i.nextSibling;return rt(a,`click`,e.onBack,!0),R(o,()=>e.view.model.name||e.view.model.modelID,null),R(s,O(k,{get each(){return e.view.rows},children:(r,i)=>(()=>{var a=$g(),o=a.firstChild,s=o.firstChild,c=s.nextSibling;return o.$$click=()=>e.onPick(i()),L(e=>i()===0&&(t=e),o),R(s,r??`Default`),R(o,O(A,{get when(){return M(()=>!!n())()&&e.current?.variant===r},get children(){return Yg()}}),c),R(c,()=>i()+1),S(t=>{var a=`picker-opt${e.active===i()?` active`:``}`,s=n()&&e.current?.variant===r;return a!==t.e&&I(o,t.e=a),s!==t.t&&F(o,`aria-selected`,t.t=s),t},{e:void 0,t:void 0}),a})()})),r})()}P([`keydown`,`input`,`click`]);var i_=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;function a_(e){let t=[],n=0,r=0,i=!1;for(let a of String(e??``).replace(/\r\n?/g,`
10
+ `).split(`
11
+ `)){let e=i_.exec(a);if(e)n=Number(e[1]),r=Number(e[2]),i=!0,t.push({type:`hunk`,text:a});else if(!i||a.startsWith(`\\`))a&&t.push({type:`meta`,text:a});else if(a.startsWith(`+`))t.push({type:`add`,text:a.slice(1),newNo:r++});else if(a.startsWith(`-`))t.push({type:`del`,text:a.slice(1),oldNo:n++});else if(a.startsWith(` `)||a===``){if(a===``&&t.length&&t[t.length-1].type!==`context`)continue;t.push({type:`context`,text:a.slice(1),oldNo:n++,newNo:r++})}else i=!1,t.push({type:`meta`,text:a})}return t}var o_=N(`<section><h3><button type=button class=card-toggle><span>`),s_=N(`<ul class=job-list>`),c_=N(`<ul class=mcp-list>`),l_=N(`<aside class=rail aria-label="Session details"><div class=rail-head><span class=rail-title>Details`),u_=N(`<p class="rail-error small"><strong>`),d_=N(`<p class="muted small">`),f_=N(`<dl class=kv><dt>Machine</dt><dd><span aria-hidden=true></span> <span class=muted>· </span></dd><dt>Project</dt><dd class=mono></dd><dt>Branch</dt><dd class=mono></dd><dt>Open in</dt><dd>`),p_=N(`<span class=muted>`),m_=N(`<p class="small retry-note">`),h_=N(`<li><span aria-hidden=true></span><span class="job-command mono"></span><span class="muted small">`),g_=N(`<div class=meter role=meter aria-valuemin=0 aria-valuemax=100 aria-label="Context used"><span>`),__=N(`<p class=small><strong></strong><span class=muted> `),v_=N(`<li><span aria-hidden=true></span><span class=mcp-name></span><span class="muted small">`),y_=N(`<span class=diffstat><span class=add>+</span> <span class=del>−`),b_=N(`<ul class=file-list>`),x_=N(`<p class="muted small">No changes.`),S_=N(`<li><button type=button class=file><span></span><span class=file-name></span><span class="diffstat small"><span class=add>+</span> <span class=del>−`),C_=N(`<p class="muted small more-files">+<!> more <!> (only the most-changed files are listed)`),w_=N(`<table class=diff><tbody>`),T_=N(`<p class="muted small pad">The diff is too large to show completely (512 KB).`),E_=N(`<section class=diff-panel><header class=diff-head><select aria-label="Changed file"></select><label class="small muted wrap-toggle"><input type=checkbox> Wrap</label></header><div>`),D_=N(`<option>`),O_=N(`<p class="muted small pad">Loading diff…`),k_=N(`<p class="muted small pad">`),A_=N(`<p class="muted small pad">No textual changes (binary file, or a rename).`),j_=N(`<tr><td class=ln></td><td class=ln></td><td class=code-line><span class=sign>`),M_=e=>e.truncated&&e.totalFiles?Math.max(0,e.totalFiles-e.files.length):0,[N_,P_]=x(Km(localStorage));function F_(e){let t=()=>!N_().has(e.id);return(()=>{var n=o_(),r=n.firstChild,i=r.firstChild,a=i.firstChild;return i.$$click=()=>P_(qm(localStorage,e.id)),R(i,O(Z,{name:`chevron`,class:`card-chevron`}),a),R(a,()=>e.title),R(r,()=>e.extra,null),R(n,O(A,{get when(){return t()},get children(){return e.children}}),null),S(r=>{var a=`rail-card${t()?``:` collapsed`}`,o=e.label??e.title,s=e.domID,c=e.id,l=t();return a!==r.e&&I(n,r.e=a),o!==r.t&&F(n,`aria-label`,r.t=o),s!==r.a&&F(n,`id`,r.a=s),c!==r.o&&F(n,`data-card`,r.o=c),l!==r.i&&F(i,`aria-expanded`,r.i=l),r},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),n})()}var I_=e=>e>=1e3?`${(e/1e3).toFixed(e>=1e5?0:1)}k`:String(e);function L_(e){let t=()=>e.found?.session,n=()=>t()?.open?t()?.terminal?.source===`herdr`?`herdr`:`tui`:`background`,r=()=>Ui(t()?.status,tc()),i=()=>r().filter(e=>e.status===`running`).length,a=()=>t()?.state===`working`||t()?.status?.some(e=>e.state===`working`)?qi(t()?.status,t()?.id,ic()):void 0,o=()=>Ri(t()?.status,t()?.id),s=()=>{let t=e.summary?.mcp;return t?.length?`Connectors · ${t.filter(e=>e.status===`connected`).length} connected`:`Connectors`};return(()=>{var c=l_(),l=c.firstChild;return l.firstChild,R(l,O(Xs,{icon:`close`,label:`Close details`,get onClick(){return e.onClose}}),null),R(c,O(A,{get when(){return o()},children:e=>(()=>{var n=u_(),r=n.firstChild;return R(r,()=>e().label),R(n,(()=>{var t=M(()=>!!e().status);return()=>t()?` · ${e().status}`:``})(),null),R(n,(()=>{var n=M(()=>!!(e().title&&e().sessionID!==t()?.id));return()=>n()?` · ${e().title}`:``})(),null),S(()=>F(n,`title`,e().text)),n})()}),null),R(c,O(F_,{id:`environment`,title:`Environment`,get children(){return O(A,{get when(){return e.found},get fallback(){return(()=>{var e=d_();return R(e,()=>J.machines?`Not reported by any connected machine.`:`Loading…`),e})()},children:r=>(()=>{var i=f_(),a=i.firstChild.nextSibling,o=a.firstChild,s=o.nextSibling,c=s.nextSibling;c.firstChild;var l=a.nextSibling.nextSibling,u=l.nextSibling.nextSibling,d=u.nextSibling.nextSibling;return R(a,()=>r().machine.name,s),R(c,(()=>{var e=M(()=>J.connection!==`live`);return()=>e()?`Connecting`:r().machine.online?`online`:`offline`})(),null),R(l,()=>sc(e.summary?.directory??r().session.directory)),R(u,()=>e.summary?.branch??(()=>{var t=p_();return R(t,()=>e.loading?`…`:`—`),t})()),R(d,()=>lc[n()],null),R(d,(()=>{var e=M(()=>!!t()?.terminal?.workspace);return()=>e()?` · ${t().terminal.workspace}`:``})(),null),S(t=>{var n=`online-dot${r().machine.online&&J.connection===`live`?` on`:``}`,i=e.summary?.directory??r().session.directory;return n!==t.e&&I(o,t.e=n),i!==t.t&&F(l,`title`,t.t=i),t},{e:void 0,t:void 0}),i})()})}}),null),R(c,O(A,{get when(){return r().length||a()},get children(){return O(F_,{id:`jobs`,get title(){return`Jobs${i()?` · ${i()} running`:``}`},label:`Background jobs`,get children(){return[O(A,{get when(){return a()},children:e=>(()=>{var t=m_();return R(t,e),t})()}),(()=>{var e=s_();return R(e,O(k,{get each(){return r()},children:e=>(()=>{var n=h_(),r=n.firstChild,i=r.nextSibling,a=i.nextSibling;return R(i,()=>e.command??e.id),R(a,()=>Gi(e,tc()),null),R(a,(()=>{var n=M(()=>!!(e.sessionID!==t()?.id&&e.sessionTitle));return()=>n()?` · ${e.sessionTitle}`:``})(),null),S(t=>{var i=`job ${e.status}`,a=e.command??e.id,o=`job-dot ${e.status===`running`?`on`:e.exit?`bad`:``}`;return i!==t.e&&I(n,t.e=i),a!==t.t&&F(n,`title`,t.t=a),o!==t.a&&I(r,t.a=o),t},{e:void 0,t:void 0,a:void 0}),n})()})),e})()]}})}}),null),R(c,O(F_,{id:`context`,title:`Context`,get children(){return O(A,{get when(){return e.summary?.context},get fallback(){return(()=>{var t=d_();return R(t,()=>e.loading?`Loading…`:`No usage reported yet.`),t})()},children:e=>[(()=>{var t=g_(),n=t.firstChild;return S(r=>{var i=e().percent??0,a=`${e().percent??0}%`,o=(e().percent??0)>80?`hot`:``;return i!==r.e&&F(t,`aria-valuenow`,r.e=i),a!==r.t&&ot(n,`width`,r.t=a),o!==r.a&&I(n,r.a=o),r},{e:void 0,t:void 0,a:void 0}),t})(),(()=>{var t=__(),n=t.firstChild,r=n.nextSibling;return r.firstChild,R(n,(()=>{var t=M(()=>e().percent!==void 0);return()=>t()?`${e().percent}%`:I_(e().used)})()),R(r,(()=>{var t=M(()=>!!e().limit);return()=>t()?`${I_(e().used)} / ${I_(e().limit)} tokens`:`tokens`})(),null),R(r,(()=>{var t=M(()=>!!e().model);return()=>t()?` · ${e().model}`:``})(),null),t})()]})}}),null),R(c,O(F_,{id:`mcp`,get title(){return s()},label:`MCP servers`,get children(){return O(A,{get when(){return e.summary?.mcp?.length},get fallback(){return(()=>{var t=d_();return R(t,()=>e.loading?`Loading…`:`No MCP servers.`),t})()},get children(){var t=c_();return R(t,O(k,{get each(){return e.summary.mcp},children:e=>(()=>{var t=v_(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling;return R(r,()=>e.name),R(i,()=>e.status.replace(`_`,` `)),S(r=>{var i=e.error??e.status,a=`mcp-dot ${e.status}`;return i!==r.e&&F(t,`title`,r.e=i),a!==r.t&&I(n,r.t=a),r},{e:void 0,t:void 0}),t})()})),t}})}}),null),R(c,O(F_,{id:`changes`,title:`Changes`,domID:`rail-changes`,get extra(){return O(A,{get when(){return e.summary?.changes},children:e=>(()=>{var t=y_(),n=t.firstChild;n.firstChild;var r=n.nextSibling.nextSibling;return r.firstChild,R(n,()=>e().additions,null),R(r,()=>e().deletions,null),t})()})},get children(){return O(A,{get when(){return e.summary?.changes},get fallback(){return(()=>{var t=d_();return R(t,(()=>{var t=M(()=>!!e.loading);return()=>t()?`Loading…`:e.summaryError||`No working-tree changes reported (not a git repository, or OpenCode is still warming up).`})()),t})()},children:t=>O(A,{get when(){return t().files.length},get fallback(){return x_()},get children(){return[(()=>{var n=b_();return R(n,O(k,{get each(){return t().files},children:t=>(()=>{var n=S_(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.nextSibling.firstChild;o.firstChild;var s=o.nextSibling.nextSibling;return s.firstChild,r.$$click=()=>e.onFile(t.file),R(i,()=>t.status[0].toUpperCase()),R(a,()=>t.file),R(o,()=>t.additions,null),R(s,()=>t.deletions,null),S(e=>{var n=t.file,a=`file-status ${t.status}`;return n!==e.e&&F(r,`title`,e.e=n),a!==e.t&&I(i,e.t=a),e},{e:void 0,t:void 0}),n})()})),n})(),O(A,{get when(){return M_(t())},children:e=>(()=>{var t=C_(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,R(t,e,n),R(t,()=>e()===1?`file`:`files`,r),t})()})]}})})}}),null),c})()}function R_(e){let[t]=ne(()=>e.file,async t=>H(`${W(e.sessionID)}/diff?file=${U(t)}`)),[n,r]=x(!1);return(()=>{var i=E_(),a=i.firstChild,o=a.firstChild,s=o.nextSibling,c=s.firstChild,l=a.nextSibling;return R(a,O(Z,{name:`diff`}),o),o.addEventListener(`change`,t=>e.onFile(t.currentTarget.value)),R(o,O(k,{get each(){return e.files},children:e=>(()=>{var t=D_();return t.value=e,R(t,e),t})()})),R(a,O(A,{get when(){return t()},children:e=>(()=>{var t=y_(),n=t.firstChild;n.firstChild;var r=n.nextSibling.nextSibling;return r.firstChild,R(n,()=>e().additions,null),R(r,()=>e().deletions,null),t})()}),s),c.addEventListener(`change`,e=>r(e.currentTarget.checked)),R(a,O(Xs,{icon:`close`,label:`Close diff`,get onClick(){return e.onClose}}),null),R(l,O(A,{get when(){return!t.loading},get fallback(){return O_()},get children(){return O(A,{get when(){return!t.error},get fallback(){return(()=>{var e=k_();return R(e,(()=>{var e=M(()=>t.error?.message===`No changes for that file`);return()=>e()?`This file has no changes any more.`:`Could not load the diff: ${t.error?.message}`})()),e})()},get children(){return O(A,{get when(){return t()?.patch},get fallback(){return A_()},get children(){return[(()=>{var e=w_(),n=e.firstChild;return R(n,O(k,{get each(){return a_(t().patch).filter(e=>e.type!==`meta`)},children:e=>(()=>{var t=j_(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.firstChild;return R(n,()=>e.oldNo??``),R(r,()=>e.newNo??``),R(a,(()=>{var t=M(()=>e.type===`add`);return()=>t()?`+`:e.type===`del`?`−`:` `})()),R(i,()=>e.text,null),S(()=>I(t,e.type)),t})()})),e})(),O(A,{get when(){return t().truncated},get children(){return T_()}})]}})}})}})),S(t=>{var r=`Changes in ${e.file}`,a=`diff-body${n()?` wrap`:``}`;return r!==t.e&&F(i,`aria-label`,t.e=r),a!==t.t&&I(l,t.t=a),t},{e:void 0,t:void 0}),S(()=>o.value=e.file),S(()=>c.checked=n()),i})()}P([`click`]);var z_=N(`<div role=status><a class=voice-pill-link title="Go to the session in Voice mode">Voice: <strong></strong></a><button type=button class="btn small end"aria-label="End Voice mode">End`);function B_(){let e=()=>Zp().sessionID??``;return(()=>{var t=z_(),n=t.firstChild,r=n.firstChild.nextSibling,i=n.nextSibling;return R(t,O(Z,{name:`wave`}),n),R(r,Qp),i.$$click=()=>void Vp.end(),S(r=>{var i=`voice-pill ${Zp().voice}`,a=`Voice mode is on in ${Qp()}`,o=ao(e());return i!==r.e&&I(t,r.e=i),a!==r.t&&F(t,`aria-label`,r.t=a),o!==r.a&&F(n,`href`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),t})()}P([`click`]);function V_(e){let t={};for(let n of e)n.type!==`external`&&(n.type===`boolean`?t[n.key]=n.default===!0:n.type===`multiselect`?t[n.key]=Array.isArray(n.default)?[...n.default]:[]:t[n.key]=n.default===void 0||Array.isArray(n.default)?``:String(n.default));return t}function H_(e,t){return e&&(e.type===`number`||e.type===`integer`)&&typeof t==`string`&&t.trim()?Number(t):typeof t==`string`?t.trim():t}function U_(e,t){let n=new Map(e.map(e=>[e.key,e]));return e.filter(e=>(e.when??[]).every(e=>{let r=H_(n.get(e.key),t[e.key])===e.value;return e.op===`eq`?r:!r}))}var W_=e=>typeof e==`string`?e.trim():``;function G_(e,t){let n={};for(let r of U_(e,t)){let e=K_(r,t[r.key]);e&&(n[r.key]=e)}return n}function K_(e,t){switch(e.type){case`external`:return;case`boolean`:return;case`multiselect`:{let n=Array.isArray(t)?t:[];return e.minItems!==void 0&&n.length<e.minItems?`Choose at least ${e.minItems}`:e.required&&!n.length?`Required`:e.maxItems!==void 0&&n.length>e.maxItems?`Choose at most ${e.maxItems}`:void 0}case`number`:case`integer`:{let n=W_(t);if(!n)return e.required?`Required`:void 0;let r=Number(n);return Number.isFinite(r)?e.type===`integer`&&!Number.isInteger(r)?`Enter a whole number`:e.minimum!==void 0&&r<e.minimum?`At least ${e.minimum}`:e.maximum!==void 0&&r>e.maximum?`At most ${e.maximum}`:void 0:`Enter a number`}case`string`:{let n=W_(t);if(!n)return e.required?`Required`:void 0;if(e.options?.length&&!e.custom&&!e.options.some(e=>e.value===n))return`Choose one of the options`;if(e.minLength!==void 0&&n.length<e.minLength)return`At least ${e.minLength} characters`;if(e.maxLength!==void 0&&n.length>e.maxLength)return`At most ${e.maxLength} characters`;if(e.pattern)try{if(!new RegExp(e.pattern).test(n))return`Doesn't match the expected format`}catch{}return}}}function q_(e,t){let n={};for(let r of U_(e,t)){let e=t[r.key];if(r.type!==`external`){if(r.type===`boolean`)n[r.key]=e===!0;else if(r.type===`multiselect`)n[r.key]=Array.isArray(e)?[...e]:[];else{let t=W_(e);if(!t)continue;n[r.key]=r.type===`number`||r.type===`integer`?Number(t):t}}}return n}var J_=N(`<p>`),Y_=N(`<p class="muted small"data-answer-unavailable> can't take this answer from the hub; answer it in the terminal.`),X_=N(`<p class="blocker-text mono">`),Z_=N(`<p class="blocker-recommendation small"data-recommendation>`),Q_=N(`<p class=blocker-text>`),$_=N(`<p class="answered-by small muted"data-answered-by>`),ev=N(`<div role=group><p class=blocker-head><strong>`),tv=N(`<p class="muted small">This question has nothing to fill in here; answer it in the terminal.`),nv=N(`<div class=row><button type=button class="btn small primary">Allow once</button><button type=button class="btn small">Always allow</button><button type=button class="btn small danger">Deny`),rv=N(`<form class=form-card novalidate><fieldset><div class=row><button type=submit class="btn small primary"></button><button type=button class="btn small">Dismiss`),iv=N(`<p class="field-error small"role=alert>`),av=N(`<div>`),ov=N(`<span class=field-title>`),sv=N(`<span class="field-desc muted small">`),cv=N(`<a class="btn small"target=_blank rel="noopener noreferrer">Open link`),lv=N(`<label class=check><input type=checkbox>`),uv=N(`<input type=text placeholder="Other (comma separated)">`),dv=N(`<div role=group class=choice-group>`),fv=N(`<input type=text placeholder="Type your own answer">`),pv=N(`<div role=radiogroup class=choice-group>`),mv=N(`<label class=text-field>`),hv=N(`<input type=text>`),gv=N(`<span class="muted small"> — `),_v=N(`<label class=choice><input type=checkbox><span>`),vv=N(`<label class=choice><input type=radio><span>`);function yv(e,t){return!(e instanceof or)||e.status!==409||e.code!==`gone`?!1:(q(`Already answered or expired`),t(),!0)}function bv(e){let[t,n]=x(!1),r=()=>e.blocker,i=()=>r().sessionID&&r().sessionID!==e.rootID?` (${r().sessionTitle||`subagent`})`:``,a=()=>r().kind===`permission`?`Permission request`:`Question`;return O(A,{get when(){return!t()},get children(){var t=ev(),o=t.firstChild,s=o.firstChild;return R(s,(()=>{var e=M(()=>r().kind===`permission`);return()=>e()?`Permission`:r().question?`Question`:`Form`})()),R(o,i,null),R(t,O(Ue,{get fallback(){return tv()},get children(){return[O(j,{get when(){return e.canAnswer===!1},get children(){return[(()=>{var e=J_();return R(e,()=>r().summary),S(()=>I(e,`blocker-text${r().kind===`permission`?` mono`:``}`)),e})(),(()=>{var t=Y_(),n=t.firstChild;return R(t,()=>e.harnessName??`This harness`,n),t})()]}}),O(j,{get when(){return r().kind===`permission`},get children(){return[(()=>{var e=X_();return R(e,()=>r().summary),e})(),O(A,{get when(){return ar(r().recommendation)},get children(){var e=Z_();return R(e,()=>ar(r().recommendation)),e}}),O(xv,{get sessionID(){return e.sessionID},get blocker(){return r()},onGone:()=>n(!0)})]}}),O(j,{get when(){return M(()=>r().kind===`form`)()&&r().fields?.length},get children(){return[O(A,{get when(){return!r().question||r().summary!==`Questions`},get children(){var e=Q_();return R(e,()=>r().summary),e}}),O(Sv,{get sessionID(){return e.sessionID},get blocker(){return r()},get fields(){return r().fields},onGone:()=>n(!0)})]}})]}}),null),R(t,O(A,{get when(){return $n(Eo(),r().id)},get children(){var e=$_();return R(e,()=>$n(Eo(),r().id)),e}}),null),S(e=>{var n=`card blocker ${r().kind}`,i=`${a()}: ${r().summary}`;return n!==e.e&&I(t,e.e=n),i!==e.t&&F(t,`aria-label`,e.t=i),e},{e:void 0,t:void 0}),t}})}function xv(e){let[t,n]=x(!1),r=async t=>{n(!0);try{await V(`${W(e.sessionID)}/permission`,{method:`POST`,json:{requestID:e.blocker.id,decision:t}}),q(t===`reject`?`Denied`:`Allowed`)}catch(t){yv(t,e.onGone)||q(Wh(t)??G(t),`err`),n(!1)}};return(()=>{var e=nv(),n=e.firstChild,i=n.nextSibling,a=i.nextSibling;return n.$$click=()=>void r(`once`),i.$$click=()=>void r(`always`),a.$$click=()=>void r(`reject`),S(e=>{var r=t(),o=t(),s=t();return r!==e.e&&(n.disabled=e.e=r),o!==e.t&&(i.disabled=e.t=o),s!==e.a&&(a.disabled=e.a=s),e},{e:void 0,t:void 0,a:void 0}),e})()}function Sv(e){let[t,n]=x(V_(e.fields)),[r,i]=x({}),[a,o]=x(!1),[s,c]=x(!1),l=w((n=[])=>{let r=U_(e.fields,t()).map(e=>e.key);return r.length===n.length&&r.every((e,t)=>e===n[t])?n:r}),u=t=>e.fields.find(e=>e.key===t),d=(e,t)=>{n(n=>({...n,[e]:t})),r()[e]&&i(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e)))},f=async(t,n)=>{o(!0);try{await V(`${W(e.sessionID)}/form`,{method:`POST`,json:{formID:e.blocker.id,...t}}),c(!0),q(n)}catch(t){yv(t,e.onGone)||q(Wh(t)??G(t),`err`),o(!1)}},p=n=>{n.preventDefault();let r=G_(e.fields,t());if(i(r),Object.keys(r).length)return;let a=q_(e.fields,t());e.blocker.question&&!Object.values(a).some(e=>Array.isArray(e)?e.length>0:e!==``&&e!==!1)?q(`Pick or type an answer first (Dismiss skips the questions)`,`err`):f({answer:a},`Answer sent`)},m=()=>a()||s();return(()=>{var n=rv(),i=n.firstChild,a=i.firstChild,o=a.firstChild,c=o.nextSibling;return n.addEventListener(`submit`,p),R(i,O(k,{get each(){return l()},children:n=>O(A,{get when(){return u(n)},children:i=>(()=>{var a=av();return F(a,`data-key`,n),R(a,O(Cv,{get field(){return i()},get value(){return t()[n]},onChange:e=>d(n,e),get formID(){return e.blocker.id}}),null),R(a,O(A,{get when(){return r()[n]},get children(){var e=iv();return R(e,()=>r()[n]),e}}),null),S(()=>I(a,`form-field ${i().type}`)),a})()})}),a),R(o,()=>s()?`Sent`:`Submit`),c.$$click=()=>void f({cancel:!0},`Dismissed`),S(()=>i.disabled=m()),n})()}function Cv(e){let t=()=>e.field,n=()=>`f-${e.formID}-${t().key}`,r=()=>t().title||t().key,i=()=>typeof e.value==`string`?e.value:``,a=()=>Array.isArray(e.value)?e.value:[],o=()=>new Set((t().options??[]).map(e=>e.value)),s=()=>[(()=>{var e=ov();return R(e,r,null),R(e,()=>t().required?` *`:``,null),e})(),O(A,{get when(){return t().description},get children(){var e=sv();return R(e,()=>t().description),e}})];return O(Ue,{get children(){return[O(j,{get when(){return t().type===`external`},get children(){return[O(s,{}),(()=>{var e=cv();return S(()=>F(e,`href`,t().url)),e})()]}}),O(j,{get when(){return t().type===`boolean`},get children(){var t=lv(),n=t.firstChild;return n.addEventListener(`change`,t=>e.onChange(t.currentTarget.checked)),R(t,O(s,{}),null),S(()=>n.checked=e.value===!0),t}}),O(j,{get when(){return t().type===`multiselect`},get children(){var n=dv();return R(n,O(s,{}),null),R(n,O(k,{get each(){return t().options??[]},children:t=>(()=>{var n=_v(),r=n.firstChild,i=r.nextSibling;return r.addEventListener(`change`,n=>e.onChange(n.currentTarget.checked?[...a(),t.value]:a().filter(e=>e!==t.value))),R(i,()=>t.label),R(n,O(A,{get when(){return t.description},get children(){var e=gv();return e.firstChild,R(e,()=>t.description,null),e}}),null),S(()=>r.checked=a().includes(t.value)),n})()}),null),R(n,O(A,{get when(){return t().custom},get children(){var t=uv();return t.addEventListener(`change`,t=>e.onChange([...a().filter(e=>o().has(e)),...t.currentTarget.value.split(`,`).map(e=>e.trim()).filter(Boolean)])),S(()=>F(t,`aria-label`,`${r()}: other`)),S(()=>t.value=a().filter(e=>!o().has(e)).join(`, `)),t}}),null),S(()=>F(n,`aria-label`,r())),n}}),O(j,{get when(){return M(()=>t().type===`string`)()&&t().options?.length},get children(){var a=pv();return R(a,O(s,{}),null),R(a,O(k,{get each(){return t().options??[]},children:t=>(()=>{var r=vv(),a=r.firstChild,o=a.nextSibling;return a.addEventListener(`change`,()=>e.onChange(t.value)),R(o,()=>t.label),R(r,O(A,{get when(){return t.description},get children(){var e=gv();return e.firstChild,R(e,()=>t.description,null),e}}),null),S(()=>F(a,`name`,n())),S(()=>a.checked=i()===t.value),r})()}),null),R(a,O(A,{get when(){return t().custom},get children(){var t=fv();return t.$$input=t=>e.onChange(t.currentTarget.value),S(()=>F(t,`aria-label`,`${r()}: your own answer`)),S(()=>t.value=o().has(i())?``:i()),t}}),null),S(()=>F(a,`aria-label`,r())),a}}),O(j,{when:!0,get children(){return[(()=>{var e=mv();return R(e,O(s,{})),S(()=>F(e,`for`,n())),e})(),(()=>{var r=hv();return r.$$input=t=>e.onChange(t.currentTarget.value),S(e=>{var i=n(),a=t().type===`number`||t().type===`integer`?`decimal`:void 0,o=t().placeholder??``;return i!==e.e&&F(r,`id`,e.e=i),a!==e.t&&F(r,`inputmode`,e.t=a),o!==e.a&&F(r,`placeholder`,e.a=o),e},{e:void 0,t:void 0,a:void 0}),S(()=>r.value=i()),r})()]}})]}})}P([`click`,`input`]);var wv=/^(\s{0,3})(`{3,}|~{3,})\s*([^\s`]*)/,Tv=/^\s{0,3}(#{1,6})(?:\s+(.*))?$/,Ev=/^\s{0,3}(={2,}|-{3,})\s*$/,Dv=/^\s{0,3}([-*_])(\s*\1){2,}\s*$/,Ov=/^\s{0,3}>\s?(.*)$/,kv=/^(\s*)([-*+]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/,Av=/^\[([ xX])\](?:\s+(.*))?$/,jv=/^:?-+:?$/,Mv=e=>e.length-e.trimStart().length,Nv=(e,t)=>e.slice(Math.min(t,Mv(e))),Pv=e=>wv.test(e),Fv=e=>Pv(e)||Tv.test(e)||Dv.test(e)||Ov.test(e)||kv.test(e);function Iv(e,t={}){let n=String(e??``).replace(/\r\n?/g,`
12
+ `).split(`
13
+ `).map(e=>e.replace(/^[ \t]+/,e=>e.replace(/\t/g,` `))),r=!!t.streaming,i=Lv(n,{streaming:r},!0).blocks;return Wv(i,r?Uv(i):void 0)}function Lv(e,t,n){let r=[],i=[],a=!1,o=!1,s=!1,c=()=>{a&&o&&(s=!0),a=!1,o=!0},l=()=>{i.length&&r.push({type:`paragraph`,text:i.join(`
14
+ `)}),i=[]};for(let o=0;o<e.length;o++){let s=e[o];if(!s.trim()){l(),a=!0;continue}let u=wv.exec(s);if(u){l(),c();let[,t,n]=u,i=[];for(o++;o<e.length;o++){let r=/^\s*(`{3,}|~{3,})\s*$/.exec(e[o]);if(r&&r[1][0]===n[0]&&r[1].length>=n.length)break;i.push(Nv(e[o],t.length))}r.push({type:`code`,lang:u[3]??``,text:i.join(`
15
+ `)});continue}if(i.length){let e=Ev.exec(s);if(e){r.push({type:`heading`,level:e[1][0]===`=`?1:2,text:i.join(`
16
+ `)}),i=[];continue}}let d=Tv.exec(s);if(d){l(),c(),r.push({type:`heading`,level:d[1].length,text:(d[2]??``).replace(/(^|\s+)#+\s*$/,``).trim()});continue}if(Dv.test(s)){l(),c(),r.push({type:`rule`});continue}let f=Hv(e,o,t.streaming&&n);if(f){l(),c(),r.push(f.block),o=f.end-1;continue}if(Ov.test(s)){l(),c();let i=[],a=o;for(;a<e.length;a++){let t=Ov.exec(e[a]);if(t)i.push(t[1]);else if(e[a].trim()&&i.at(-1)?.trim()&&!Fv(e[a]))i.push(e[a]);else break}r.push({type:`quote`,blocks:Lv(i,t,n&&a===e.length).blocks}),o=a-1;continue}let p=kv.exec(s);if(p&&(!i.length||Rv(p[2]))){l(),c();let i=zv(e,o,t,n);r.push(i.block),o=i.end-1,i.trailingBlank&&(a=!0)}else i.length||c(),i.push(s.trim())}return l(),{blocks:r,loose:s,trailingBlank:a}}var Rv=e=>!/\d/.test(e)||/^0*1[.)]$/.test(e);function zv(e,t,n,r){let i=kv.exec(e[t]),a=/\d/.test(i[2]),o=i[2].slice(-1),s=[],c=!1,l=!1,u=t;for(;u<e.length;){let t=kv.exec(e[u]);if(!t||/\d/.test(t[2])!==a||t[2].slice(-1)!==o)break;s.length&&l&&(c=!0);let i=t[1].length,d=t[3]?.replace(/\t/g,` `).length??0,f=i+t[2].length+(d>=1&&d<=4?d:1),p=[d>4?`${` `.repeat(d-1)}${t[4]??``}`.trim():t[4]??``],m,h=e=>{if(m){let t=/^\s*(`{3,}|~{3,})\s*$/.exec(e);t&&t[1][0]===m[0]&&t[1].length>=m.length&&(m=void 0)}else{let t=wv.exec(e);t&&(m=t[2])}};h(p[0]);let g=u+1,_=0;for(;g<e.length;g++){let t=e[g];if(!t.trim()){_++;continue}let n=Mv(t),r;if(r=m?!0:_?n>=Math.min(f,i+2):n>=f?!0:kv.test(t)?n>=i+2:n>i||!Fv(t)&&!Pv(p.at(-1)),!r)break;for(;_;_--)p.push(``);let a=Nv(t,f);p.push(a),h(a)}l=_>0;let v=Av.exec(p[0]),y=Lv(v?[v[2]??``,...p.slice(1)]:p,n,r&&g===e.length);y.loose&&(c=!0),s.push({...v?{checked:v[1]!==` `}:{},blocks:y.blocks}),u=g}let d=a?Number(i[2].slice(0,-1)):void 0;return{block:{type:`list`,ordered:a,...a?{start:d}:{},loose:c,items:s},end:u,trailingBlank:l}}function Bv(e){let t=e.trim();t.startsWith(`|`)&&(t=t.slice(1)),t.endsWith(`|`)&&!t.endsWith(`\\|`)&&(t=t.slice(0,-1));let n=[],r=``;for(let e=0;e<t.length;e++)t[e]===`\\`&&t[e+1]===`|`?(r+=`|`,e++):t[e]===`|`?(n.push(r.trim()),r=``):r+=t[e];return n.push(r.trim()),n}var Vv=e=>{let t=e.trim(),n=t.startsWith(`:`),r=t.length>1&&t.endsWith(`:`);return n&&r?`center`:r?`right`:n?`left`:null};function Hv(e,t,n){let r=e[t];if(!r.includes(`|`))return;let i=Bv(r),a=e[t+1],o;if(a!==void 0){let r=Bv(a),s=t+1===e.length-1;r.length===i.length&&r.every(e=>jv.test(e))?o=r.map(Vv):s&&/^[\s|:-]*$/.test(a)&&(a.includes(`-`)||n)&&a.includes(`|`)&&r.length<=i.length&&(o=i.map((e,t)=>r[t]&&jv.test(r[t])?Vv(r[t]):null))}else n&&r.trimStart().startsWith(`|`)&&(r.match(/\|/g)?.length??0)>=2&&(o=i.map(()=>null));if(!o)return;let s=[],c=t+2;for(;c<e.length;c++){let t=e[c];if(!t.trim()||!t.includes(`|`)||Pv(t)||Ov.test(t)||Tv.test(t))break;s.push(Bv(t).slice(0,i.length))}return{block:{type:`table`,align:o,head:i,rows:s},end:Math.min(c,e.length)}}function Uv(e){let t=e.at(-1);if(t){if(t.type===`paragraph`||t.type===`heading`)return{node:t};if(t.type===`quote`)return Uv(t.blocks);if(t.type===`list`)return Uv(t.items.at(-1)?.blocks??[]);if(t.type===`table`){let e=t.rows.length-1;return{node:t,cell:e>=0?[e,t.rows[e].length-1]:[-1,t.head.length-1]}}}}function Wv(e,t){let n=e=>t?.node===e;return e.map(e=>{switch(e.type){case`paragraph`:return{type:`paragraph`,children:iy(e.text,{streaming:n(e)})};case`heading`:return{type:`heading`,level:e.level,children:iy(e.text,{streaming:n(e)})};case`quote`:return{type:`quote`,blocks:Wv(e.blocks,t)};case`list`:return{...e,items:e.items.map(e=>({...e.checked===void 0?{}:{checked:e.checked},blocks:Wv(e.blocks,t)}))};case`table`:{let r=(r,i,a)=>iy(r,{streaming:n(e)&&t.cell[0]===i&&t.cell[1]===a}),i=e.head.length;return{type:`table`,align:e.align,head:e.head.map((e,t)=>r(e,-1,t)),rows:e.rows.map((e,t)=>Array.from({length:i},(n,i)=>r(e[i]??``,t,i)))}}default:return e}})}function Gv(e){let t=e.trim();if(!/[\\\s\u0000-\u001f\u007f-\u009f]/.test(t)&&(/^(https?:|mailto:)/i.test(t)||t.startsWith(`/`)&&!t.startsWith(`//`)))return t}var Kv=/[!-/:-@[-`{-~]/,qv=/\s/,Jv=/[\p{L}\p{N}_]/u,Yv={"**":`strong`,__:`strong`,"~~":`del`,"==":`mark`},Xv=(e,t,n)=>{let r=0;for(;e[t+r]===n;)r++;return r};function Zv(e,t,n){for(let r=t;r<e.length;r++){if(e[r]!=="`")continue;let t=Xv(e,r,"`");if(t===n)return r;r+=t-1}return-1}function Qv(e,t,n,r){for(let i=t;i<=e.length-n.length;i++){let t=e[i];if(t===`\\`)i++;else if(t==="`"&&n!=="`"){let t=Xv(e,i,"`"),n=Zv(e,i+t,t);i=(n>=0?n:i)+t-1}else if(e.startsWith(n,i)&&r(i))return i}return-1}function $v(e,t){let n=0;for(let r=t+1;r<e.length;r++){let t=e[r];if(t===`\\`)r++;else if(t==="`"){let t=Xv(e,r,"`"),n=Zv(e,r+t,t);r=(n>=0?n:r)+t-1}else if(t===`[`)n++;else if(t===`]`){if(n===0)return r;n--}}return-1}function ey(e,t){let n=0;for(let r=t;r<e.length;r++)if(e[r]===`(`)n++;else if(e[r]===`)`){if(n===0)return r;n--}else if(e[r]===`
17
+ `)return-1;return-1}function ty(e){let t=e.trim();return t.startsWith(`<`)?t.slice(1,t.indexOf(`>`)>0?t.indexOf(`>`):void 0):t.split(/\s+/)[0]??``}var ny=e=>e.map(e=>e.type===`text`||e.type===`code`?e.text:e.type===`image`?e.alt:e.type===`br`?` `:ny(e.children)).join(``);function ry(e,t){let n=/^https?:\/\/[^\s<>]+/i.exec(e.slice(t,t+2048));if(!n)return;let r=n[0];for(;;){let e=r.at(-1);if(/[.,:;!?'"*_~]/.test(e))r=r.slice(0,-1);else if(e===`)`&&(r.match(/\(/g)?.length??0)<(r.match(/\)/g)?.length??0))r=r.slice(0,-1);else if(e===`]`&&(r.match(/\[/g)?.length??0)<(r.match(/\]/g)?.length??0))r=r.slice(0,-1);else break}return/^https?:\/\/[^/]/i.test(r)?r:void 0}function iy(e,t={}){let n=String(e??``),r=!!t.streaming,i=[],a=``,o=(...e)=>{a&&i.push({type:`text`,text:a}),a=``,i.push(...e)},s=0;for(;s<n.length;){let e=n[s],i=n[s+1];if(e===`\\`){if(i===`
18
+ `){o({type:`br`}),s+=2;continue}if(i!==void 0&&Kv.test(i)){a+=i,s+=2;continue}}if(e===`
19
+ `){a=a.replace(/ +$/,``),o({type:`br`}),s++;continue}if(e==="`"){let e=Xv(n,s,"`"),t=Zv(n,s+e,e);if(t>=0||r){let r=n.slice(s+e,t>=0?t:void 0);r.length>2&&r.startsWith(` `)&&r.endsWith(` `)&&r.trim()&&(r=r.slice(1,-1)),o({type:`code`,text:r}),s=t>=0?t+e:n.length;continue}a+=n.slice(s,s+e),s+=e;continue}let c=n.slice(s,s+2),l=Yv[c];if(l&&i!==void 0&&n[s+2]!==void 0&&!qv.test(n[s+2])&&n[s+2]!==e&&(e!==`_`||s===0||!Jv.test(n[s-1]))){let i=Qv(n,s+3,c,t=>!qv.test(n[t-1])&&(e!==`_`||!Jv.test(n[t+2]??``)));if(i>0||r){o({type:l,children:iy(n.slice(s+2,i>0?i:void 0),{inLink:t.inLink,streaming:i<0})}),s=i>0?i+2:n.length;continue}}if((e===`*`||e===`_`)&&i!==void 0&&i!==e&&!qv.test(i)&&(e===`*`||s===0||!Jv.test(n[s-1]))){let i=Qv(n,s+1,e,t=>n[t+1]===e||n[t-1]===e?!1:!qv.test(n[t-1])&&(e!==`_`||!Jv.test(n[t+1]??``)));if(i>s+1||r){o({type:`em`,children:iy(n.slice(s+1,i>s?i:void 0),{inLink:t.inLink,streaming:i<0})}),s=i>s?i+1:n.length;continue}}let u=e===`!`&&i===`[`;if(e===`[`||u){let e=u?s+1:s,i=$v(n,e);if(i>0&&n[i+1]===`(`){let a=ey(n,i+2),c=iy(n.slice(e+1,i),{inLink:!0});if(a>0){let e=Gv(ty(n.slice(i+2,a)));u?o({type:`image`,alt:ny(c),...e?{href:e}:{}}):e&&!t.inLink?o({type:`link`,href:e,children:c}):o(...c),s=a+1;continue}if(r&&!n.slice(i).includes(`
20
+ `)){o(...u?[{type:`text`,text:ny(c)}]:c),s=n.length;continue}}}if(e===`<`&&!t.inLink){let e=/^<([a-zA-Z][a-zA-Z0-9+.-]{1,31}:[^\s<>]*)>/.exec(n.slice(s,s+2048)),t=/^<([^\s<>@\\]+@[^\s<>@\\]+\.[^\s<>@\\]+)>/.exec(n.slice(s,s+512)),r=e??t;if(r){let t=Gv(e?r[1]:`mailto:${r[1]}`);t?o({type:`link`,href:t,children:[{type:`text`,text:r[1]}]}):a+=r[0],s+=r[0].length;continue}}if((e===`h`||e===`H`)&&!t.inLink&&(s===0||!/[\p{L}\p{N}_/]/u.test(n[s-1]))&&n.slice(s-2,s)!==`](`){let e=ry(n,s),t=e&&Gv(e);if(e&&t){o({type:`link`,href:t,children:[{type:`text`,text:e}]}),s+=e.length;continue}}a+=e,s++}return a&&i.push({type:`text`,text:a}),i}var ay=`modulepreload`,oy=function(e){return`/`+e},sy={},cy=function(e){return e.pathname.endsWith(`.css`)},ly=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},uy=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=oy(t,n);let r=s(t),i=cy(r);return ly(sy,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:ay,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},dy=N(`<br>`),fy=N(`<code class=inline-code>`),py=N(`<a rel="noopener noreferrer">`),my=N(`<a class=md-image target=_blank rel="noopener noreferrer"title="Image (opens in a new tab)">`),hy=N(`<span class=md-image>`),gy=N(`<div><div class=code-head><span class=code-lang></span><button type=button class=code-btn></button><button type=button class=code-btn></button></div><pre class=code><code>`),_y=N(`<span>`),vy=N(`<hr>`),yy=N(`<p>`),by=N(`<input type=checkbox disabled>`),xy=N(`<li>`),Sy=N(`<blockquote>`),Cy=N(`<div class=table-wrap><table><thead><tr></tr></thead><tbody>`),wy=N(`<th>`),Ty=N(`<tr>`),Ey=N(`<td>`),Dy=N(`<div class=md>`),[Oy,ky]=x(),Ay=!1;function jy(){Ay||(Ay=!0,uy(()=>import(`./highlight-y4rJE6Tt.js`).then(e=>ky({run:e.highlight,languageOf:e.languageOf}),()=>Ay=!1),[]))}var My=65536;function Ny(e){return O(He,{get each(){return e.nodes},children:e=>O(Ue,{get children(){return[O(j,{get when(){return M(()=>e().type===`text`)()&&e()},children:e=>M(()=>e().text)}),O(j,{get when(){return e().type===`br`},get children(){return dy()}}),O(j,{get when(){return M(()=>e().type===`code`)()&&e()},children:e=>(()=>{var t=fy();return R(t,()=>e().text),t})()}),O(j,{get when(){return M(()=>e().type===`link`)()&&e()},children:e=>(()=>{var t=py();return R(t,O(Ny,{get nodes(){return e().children}})),S(n=>{var r=e().href,i=e().href.startsWith(`/`)?void 0:`_blank`;return r!==n.e&&F(t,`href`,n.e=r),i!==n.t&&F(t,`target`,n.t=i),n},{e:void 0,t:void 0}),t})()}),O(j,{get when(){return M(()=>e().type===`image`)()&&e()},children:e=>O(A,{get when(){return e().href},get fallback(){return(()=>{var t=hy();return R(t,()=>e().alt||`image`),t})()},get children(){var t=my();return R(t,()=>e().alt||`image`),S(()=>F(t,`href`,e().href)),t}})}),O(j,{get when(){return M(()=>`children`in e())()&&e()},children:e=>O(Ct,{get component(){return{strong:`strong`,em:`em`,del:`del`,mark:`mark`}[e().type]??`span`},get children(){return O(Ny,{get nodes(){return e().children}})}})})]}})})}async function Py(e){try{return await navigator.clipboard.writeText(e),!0}catch{let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,``),t.style.position=`fixed`,t.style.opacity=`0`,document.body.append(t),t.select();let n=document.execCommand(`copy`);return t.remove(),n}}function Fy(e){let[t,n]=x(!1),[r,i]=x(!1),a;D(()=>clearTimeout(a)),jy();let o=w(()=>{let t=Oy();return!t||!e.lang||e.text.length>My||!t.languageOf(e.lang)?[{text:e.text}]:t.run(e.text,e.lang)}),s=()=>e.lang||`text`;return(()=>{var c=gy(),l=c.firstChild,u=l.firstChild,d=u.nextSibling,f=d.nextSibling,p=l.nextSibling,m=p.firstChild;return R(u,s),d.$$click=()=>i(!r()),R(d,()=>r()?`No wrap`:`Wrap`),f.$$click=async()=>{await Py(e.text)&&(n(!0),clearTimeout(a),a=setTimeout(()=>n(!1),1500))},R(f,()=>t()?`Copied`:`Copy`),R(m,O(He,{get each(){return o()},children:e=>O(A,{get when(){return e().kind},get fallback(){return e().text},get children(){var t=_y();return R(t,()=>e().text),S(()=>I(t,`tok-${e().kind}`)),t}})})),S(n=>{var i=`code-block${r()?` wrap`:``}`,a=r(),o=r()?`Scroll long lines`:`Wrap long lines`,l=t()?`Copied`:`Copy ${s()} code`,u=e.lang||void 0;return i!==n.e&&I(c,n.e=i),a!==n.t&&F(d,`aria-pressed`,n.t=a),o!==n.a&&F(d,`title`,n.a=o),l!==n.o&&F(f,`aria-label`,n.o=l),u!==n.i&&F(p,`data-lang`,n.i=u),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),c})()}var Iy={left:`left`,center:`center`,right:`right`};function Ly(e){return O(He,{get each(){return e.blocks},children:e=>O(Ue,{get children(){return[O(j,{get when(){return M(()=>e().type===`paragraph`)()&&e()},children:e=>(()=>{var t=yy();return R(t,O(Ny,{get nodes(){return e().children}})),t})()}),O(j,{get when(){return M(()=>e().type===`heading`)()&&e()},children:e=>O(Ct,{get component(){return`h${Math.min(6,e().level+2)}`},get children(){return O(Ny,{get nodes(){return e().children}})}})}),O(j,{get when(){return M(()=>e().type===`list`)()&&e()},children:e=>O(Ct,{get component(){return e().ordered?`ol`:`ul`},get start(){return M(()=>!!(e().ordered&&e().start!==1))()?e().start:void 0},get class(){return e().loose?`loose`:void 0},get children(){return O(He,{get each(){return e().items},children:e=>(()=>{var t=xy();return R(t,O(A,{get when(){return e().checked!==void 0},get children(){var t=by();return S(()=>F(t,`aria-label`,e().checked?`Done`:`Not done`)),S(()=>t.checked=e().checked),t}}),null),R(t,O(Ly,{get blocks(){return e().blocks}}),null),S(()=>I(t,e().checked===void 0?void 0:`task`)),t})()})}})}),O(j,{get when(){return M(()=>e().type===`code`)()&&e()},children:e=>O(Fy,{get lang(){return e().lang},get text(){return e().text}})}),O(j,{get when(){return M(()=>e().type===`quote`)()&&e()},children:e=>(()=>{var t=Sy();return R(t,O(Ly,{get blocks(){return e().blocks}})),t})()}),O(j,{get when(){return M(()=>e().type===`table`)()&&e()},children:e=>(()=>{var t=Cy(),n=t.firstChild.firstChild,r=n.firstChild,i=n.nextSibling;return R(r,O(He,{get each(){return e().head},children:(t,n)=>(()=>{var r=wy();return R(r,O(Ny,{get nodes(){return t()}})),S(t=>at(r,e().align[n]?{"text-align":Iy[e().align[n]]}:void 0,t)),r})()})),R(i,O(He,{get each(){return e().rows},children:t=>(()=>{var n=Ty();return R(n,O(He,{get each(){return t()},children:(t,n)=>(()=>{var r=Ey();return R(r,O(Ny,{get nodes(){return t()}})),S(t=>at(r,e().align[n]?{"text-align":Iy[e().align[n]]}:void 0,t)),r})()})),n})()})),t})()}),O(j,{get when(){return e().type===`rule`},get children(){return vy()}})]}})})}function Ry(e){let t=w(()=>Iv(e.text,{streaming:e.streaming}));return(()=>{var e=Dy();return R(e,O(Ly,{get blocks(){return t()}})),e})()}P([`click`]);var zy=N(`<a class=msg-image target=_blank rel=noopener><img loading=lazy>`,!0,!1,!1),By=N(`<span class=file-chip> `),Vy=N(`<div class=transcript aria-label=Conversation>`),Hy=N(`<div class=msg-images>`),Uy=N(`<div class=pill>`),Wy=N(`<div class="msg user"><div class=user-body>`),Gy=N(`<span>`),Ky=N(`<div>`),qy=N(`<span class=turn-error-status>`),Jy=N(`<div class=turn-error-message>`),Yy=N(`<div class="msg turn-error"role=group><span class=turn-error-mark aria-hidden=true>✕</span><div class=turn-error-body><div class=turn-error-head><strong class=turn-error-label>`),Xy=N(`<p><span class=turn-retry-mark aria-hidden=true>↻</span><span>`),Zy=N(`<a><span class=sub-mark aria-hidden=true></span><span class=sub-label>Subagent · <strong></strong></span><span class="sub-state muted">`),Qy=N(`<span class=spinner>`),$y=N(`<span class=hub-msg-kind>`),eb=N(`<span class="hub-msg-state muted">`),tb=N(`<span class="hub-msg-delivery muted"title="Not delivered into a turn yet: the recipient's harness takes it at its next step">`),nb=N(`<div role=group><div class=hub-msg-head><span class=hub-msg-mark aria-hidden=true></span><span class=hub-msg-label></span></div><div class=hub-msg-text>`),rb=N(`<div class="fold-body hub-msg-text">`),ib=N(`<div class="fold hub-note"><button type=button class=fold-head><span class=hub-msg-mark aria-hidden=true>⇄</span><span>`),ab=N(`<span class="spinner small">`),ob=N(`<div class="fold thought"><button type=button class=fold-head><span>`),sb=N(`<ul class="fold-body tool-list">`),cb=N(`<div><button type=button class=fold-head><span>`),lb=N(`<pre class=code>`),ub=N(`<div class=tool-detail>`),db=N(`<li><button type=button class=tool-head><span class=tool-mark></span><span class=tool-name></span><span class="tool-summary muted"></span><span class="tool-time muted">`),fb=N(`<span class="muted small">Loading full details…`),pb=N(`<span class="error small">`),mb={pending:[`…`,`Sending`],sent:[`✓`,`Sent`],queued:[`◷`,`Queued: the harness takes it at its next step`],heard:[`✓✓`,`Heard by the agent`],failed:[`!`,`Not sent`]};function hb(e){let[t,n]=x(!1);return O(A,{get when(){return M(()=>!!e.image.src)()&&!t()},get fallback(){return(()=>{var t=By(),n=t.firstChild;return R(t,O(Z,{name:`file`}),n),R(t,()=>e.image.name,null),S(()=>F(t,`title`,e.image.mime)),t})()},get children(){var t=zy(),r=t.firstChild;return r.addEventListener(`error`,()=>n(!0)),S(n=>{var i=e.image.src,a=e.image.name,o=e.image.src,s=e.image.name;return i!==n.e&&F(t,`href`,n.e=i),a!==n.t&&F(t,`title`,n.t=a),o!==n.a&&F(r,`src`,n.a=o),s!==n.o&&F(r,`alt`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t}})}function gb(e){return(()=>{var t=Vy();return R(t,O(k,{get each(){return e.blocks},children:t=>O(Ue,{get children(){return[O(j,{get when(){return t.type===`user`&&t},children:t=>(()=>{var n=Wy(),r=n.firstChild;return R(r,O(A,{get when(){return t().images?.length},get children(){var e=Hy();return R(e,O(k,{get each(){return t().images},children:e=>O(hb,{image:e})})),e}}),null),R(r,O(A,{get when(){return t().text},get children(){var e=Uy();return R(e,()=>t().text),e}}),null),R(n,O(A,{get when(){return e.ticks[t().key]},children:e=>(()=>{var t=Gy();return R(t,()=>mb[e()][0]),S(n=>{var r=`tick ${e()}`,i=mb[e()][1],a=mb[e()][1];return r!==n.e&&I(t,n.e=r),i!==n.t&&F(t,`aria-label`,n.t=i),a!==n.a&&F(t,`title`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),S(()=>F(n,`data-key`,t().key)),n})()}),O(j,{get when(){return t.type===`assistant`&&t},children:e=>(()=>{var t=Ky();return R(t,O(Ry,{get text(){return e().text},get streaming(){return e().live}})),S(n=>{var r=`msg assistant${e().live?` live`:``}`,i=e().key;return r!==n.e&&I(t,n.e=r),i!==n.t&&F(t,`data-key`,n.t=i),n},{e:void 0,t:void 0}),t})()}),O(j,{get when(){return t.type===`thought`&&t},children:t=>O(vb,{get block(){return t()},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})}),O(j,{get when(){return t.type===`tools`&&t},children:t=>O(yb,{get block(){return t()},get sessionID(){return e.sessionID},get onDetail(){return e.onDetail},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})}),O(j,{get when(){return t.type===`message`&&t},children:t=>O(_b,{get block(){return t()},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})}),O(j,{get when(){return t.type===`error`&&t},children:e=>(()=>{var t=Yy(),n=t.firstChild.nextSibling,r=n.firstChild,i=r.firstChild;return R(i,()=>e().label),R(r,O(A,{get when(){return e().status},get children(){var t=qy();return R(t,()=>e().status),t}}),null),R(n,O(A,{get when(){return e().message},get children(){var t=Jy();return R(t,()=>e().message),t}}),null),S(n=>{var r=e().key,i=`Error: ${e().label}`;return r!==n.e&&F(t,`data-key`,n.e=r),i!==n.t&&F(t,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),t})()}),O(j,{get when(){return t.type===`retry`&&t},children:e=>{let t=()=>Xh(e(),ic());return(()=>{var n=Xy(),r=n.firstChild.nextSibling;return R(r,()=>t().text),S(r=>{var i=`msg turn-retry${t().waiting?` waiting`:``}`,a=e().key;return i!==r.e&&I(n,r.e=i),a!==r.t&&F(n,`data-key`,r.t=a),r},{e:void 0,t:void 0}),n})()}}),O(j,{get when(){return t.type===`subagent`&&t},children:e=>(()=>{var t=Zy(),n=t.firstChild,r=n.nextSibling,i=r.firstChild.nextSibling,a=r.nextSibling;return R(n,(()=>{var t=M(()=>e().state===`working`);return()=>t()?Qy():`◆`})()),R(i,()=>e().label),R(a,()=>e().state),R(t,O(Z,{name:`chevron`,class:`chev`}),null),S(n=>{var r=`subagent ${e().state}`,i=ao(e().sessionID),a=e().key;return r!==n.e&&I(t,n.e=r),i!==n.t&&F(t,`href`,n.t=i),a!==n.a&&F(t,`data-key`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})]}})})),t})()}function _b(e){let t=()=>!!e.expanded[e.block.key];return O(A,{get when(){return!e.block.primer},get fallback(){return(()=>{var n=ib(),r=n.firstChild,i=r.firstChild.nextSibling;return r.$$click=()=>e.onToggle(e.block.key,!t()),R(i,()=>e.block.label),R(r,O(Z,{name:`chevron`,class:`chev`}),null),R(n,O(A,{get when(){return t()},get children(){var t=rb();return R(t,()=>e.block.text),t}}),null),S(i=>{var a=e.block.key,o=t();return a!==i.e&&F(n,`data-key`,i.e=a),o!==i.t&&F(r,`aria-expanded`,i.t=o),i},{e:void 0,t:void 0}),n})()},get children(){var t=nb(),n=t.firstChild,r=n.firstChild,i=r.nextSibling,a=n.nextSibling;return R(r,()=>e.block.direction===`out`?`↗`:`↘`),R(n,O(A,{get when(){return e.block.kind!==`msg`},get children(){var t=$y();return R(t,()=>e.block.kind),t}}),i),R(i,()=>e.block.label),R(n,O(A,{get when(){return e.block.state===`open`||e.block.state===`answered`||e.block.state===`declined`||e.block.state===`expired`},get children(){var t=eb();return R(t,()=>e.block.state),t}}),null),R(n,O(A,{get when(){return e.block.delivery},get children(){var t=tb();return R(t,()=>e.block.delivery),S(()=>F(t,`data-delivery`,e.block.delivery)),t}}),null),R(a,()=>e.block.text),S(n=>{var r=`msg hub-msg ${e.block.direction}`,i=e.block.key,a=`Hub ${e.block.kind} ${e.block.label}`;return r!==n.e&&I(t,n.e=r),i!==n.t&&F(t,`data-key`,n.t=i),a!==n.a&&F(t,`aria-label`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t}})}function vb(e){let t=()=>!!e.expanded[e.block.key],n=t=>e.onToggle(e.block.key,t),r=()=>$h(e.block);return(()=>{var i=ob(),a=i.firstChild,o=a.firstChild;return a.$$click=()=>n(!t()),R(a,O(A,{get when(){return e.block.running},get children(){return ab()}}),o),R(o,()=>r().label),R(a,O(Z,{name:`chevron`,class:`chev`}),null),R(i,O(A,{get when(){return t()},get children(){var e=Ky();return R(e,()=>r().body),S(()=>I(e,`fold-body reasoning${r().muted?` hidden-reasoning`:``}`)),e}}),null),S(n=>{var r=e.block.key,o=t();return r!==n.e&&F(i,`data-key`,n.e=r),o!==n.t&&F(a,`aria-expanded`,n.t=o),n},{e:void 0,t:void 0}),i})()}function yb(e){let t=()=>!!e.expanded[e.block.key],n=t=>e.onToggle(e.block.key,t),r=()=>e.block.items.length,i=()=>{let t=e.block;return t.running?`Using ${r()===1?t.items[0].name??`a tool`:`${r()} tools`}…`:`Used ${r()} tool${r()===1?``:`s`}${t.failed?` (${t.failed} failed)`:``}`};return(()=>{var r=cb(),a=r.firstChild,o=a.firstChild;return a.$$click=()=>n(!t()),R(a,O(A,{get when(){return e.block.running},get children(){return ab()}}),o),R(o,i),R(a,O(Z,{name:`chevron`,class:`chev`}),null),R(r,O(A,{get when(){return t()},get children(){var t=sb();return R(t,O(k,{get each(){return e.block.items},children:t=>O(bb,{row:t,get sessionID(){return e.sessionID},get onDetail(){return e.onDetail},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})})),t}}),null),S(n=>{var i=`fold tools${e.block.failed?` has-failed`:``}`,o=e.block.key,s=t();return i!==n.e&&I(r,n.e=i),o!==n.t&&F(r,`data-key`,n.t=o),s!==n.a&&F(a,`aria-expanded`,n.a=s),n},{e:void 0,t:void 0,a:void 0}),r})()}function bb(e){let t=()=>!!e.expanded[`tool:${e.row.key}`],n=t=>e.onToggle(`tool:${e.row.key}`,t),[r,i]=x(!1),[a,o]=x(``),s=()=>e.row,c=()=>s().completed&&s().at?xa(s().completed-s().at):``,l=async()=>{let r=!t();if(n(r),r&&s().detail===void 0&&s().messageID&&s().partID!==void 0){i(!0),o(``);try{let t=await H(`${W(e.sessionID)}/timeline/messages/${U(s().messageID)}/parts/${U(String(s().partID))}`);e.onDetail(s().key,t.detail)}catch(e){o(G(e))}finally{i(!1)}}},u=()=>typeof s().summary==`string`?s().summary:``;return(()=>{var e=db(),n=e.firstChild,i=n.firstChild,o=i.nextSibling,d=o.nextSibling,f=d.nextSibling;return n.$$click=l,R(i,(()=>{var e=M(()=>s().state===`running`);return()=>e()?ab():s().state===`failed`?`✕`:`✓`})()),R(o,()=>s().name??`tool`),R(d,u),R(f,c),R(e,O(A,{get when(){return t()},get children(){var e=ub();return R(e,O(A,{get when(){return!r()},get fallback(){return fb()},get children(){return O(A,{get when(){return!a()},get fallback(){return(()=>{var e=pb();return R(e,a),e})()},get children(){var e=lb();return R(e,()=>JSON.stringify(s().detail??{summary:u()||void 0,error:s().error},null,2)),e}})}})),e}}),null),S(r=>{var a=`tool ${s().state??``}`,o=t(),c=s().state??``;return a!==r.e&&I(e,r.e=a),o!==r.t&&F(n,`aria-expanded`,r.t=o),c!==r.a&&F(i,`aria-label`,r.a=c),r},{e:void 0,t:void 0,a:void 0}),e})()}P([`click`]);var xb=N(`<button type=button class="btn small changes"aria-label="Show changes"><span class=add>+</span> <span class=del>−`),Sb=N(`<div class="banner warn">No connected OpenCode process reports this session. It is read-only until its machine reconnects.`),Cb=N(`<p class="muted pad no-timeline"data-unavailable=timeline>The hub can't show this <!> session's transcript; follow it in its terminal. Hub messages and live activity still appear here.`),wb=N(`<div class=history-sentinel aria-hidden=true>`),Tb=N(`<p class="history-edge loading muted small"role=status><span class="spinner small"></span> Loading earlier messages…`),Eb=N(`<p class="history-edge muted small">Beginning of conversation`),Db=N(`<p class="history-edge error small"role=alert>Couldn't load earlier messages: <!> <button type=button class="btn small">Retry`),Ob=N(`<p class="working-line muted"role=status><span class="spinner small"></span> `),kb=N(`<p class="idle-line muted small"> · last activity `),Ab=N(`<button type=button class="btn primary tap-to-start">Tap to start Voice mode`),jb=N(`<p class="note err voice-error"role=alert>Voice mode: `),Mb=N(`<div class=sheet-backdrop>`),Nb=N(`<div><div class=session-main><header class=topbar><div class=topbar-title></div></header><div class=scroller><div class=column></div></div><div class=dock><div class=column>`),Pb=N(`<a class="crumb muted"> <span class=crumb-sep aria-hidden=true>/`),Fb=N(`<h1 class=title>`),Ib=N(`<h1 class=title><button type=button class=title-btn>`),Lb=N(`<span class=chip-server><span aria-hidden=true></span><span class=place-sep aria-hidden=true>·</span><span class=place-where>`),Rb=N(`<span> · `),zb=N(`<span class=place-branch>`),Bb=N(`<div class=session-place><span aria-hidden=true></span><span class=place-machine></span><span class=place-sep aria-hidden=true>·</span><span class=place-where>`),Vb=N(`<span class=session-error-status>`),Hb=N(`<span class="session-error-where muted">in subagent `),Ub=N(`<div class=session-error-message>`),Wb=N(`<div class="banner session-error"role=alert><span class=session-error-mark aria-hidden=true>✕</span><div class=session-error-body><div class=session-error-head><strong>`),Gb=N(`<p class="muted pad">Loading conversation…`),Kb=N(`<p class="muted pad empty-session">No messages yet. Type below, or start Voice mode.`),qb=N(`<p>`),Jb=N(`<p class="answered-by small muted">`),Yb=N(`<button type=button class="btn stop"aria-label="Stop the session and its subagents"> Stop`),Xb=N(`<div class=composer-unavailable data-no-prompt><p class="muted small">`),Zb=N(`<div class=empty><p class=display>Session not found</p><p class=muted>It may belong to another account, or it no longer exists.</p><a class="btn primary"href=/>Back to sessions`),Qb=3e4,$b=80,ex=2e3,tx;function nx(e){let t=e.id,n=()=>jo(t),r=()=>Ao().find(e=>e.id===t),i=()=>{let e=n();return e?Si(e.machine.name,e.session,Re()?.branch):void 0},a=()=>n()?.session.status,o=()=>qa(p()?a()?.filter(e=>m().has(e.id)):a()),s=()=>!n(),c=w(()=>Lh(n()?.process)),l=()=>zh(c()),u=()=>!!n()&&!c().timeline,d=()=>n()?.session.exposed!==!1,f=()=>typeof n()?.session.rootID==`string`?n().session.rootID:t,p=()=>f()!==t;C(()=>{let e=n()?.session;if(!Q()||!e)return;let r=f()===t?e.parentID:f();Oh(window.history,location.pathname+location.search+location.hash,typeof r==`string`?r:void 0)});let m=w(()=>Ka(a(),t)),h=(e,t)=>e===f()&&(!p()||typeof t==`string`&&m().has(t)),g=()=>{let e=n()?.session.parentID;if(typeof e==`string`&&e)return{id:e,title:a()?.find(t=>t.id===e)?.title||jo(e)?.session.title||`Parent session`}},_=new $t,[v,y]=x(0),b=()=>y(e=>e+1),[ee,te]=x(!1),[ne,ae]=x(!1),[oe,se]=x([]),[ce,le]=x({}),ue=0,de=(e,t=``)=>se(n=>[...n.slice(-20),{key:`n${++ue}`,text:e,kind:t}]),fe=new Map,pe=w(()=>{v(),_.status(a(),t);let e=new Map,n=qh(_.rows()).map(t=>{let n=JSON.stringify(t),r=fe.get(t.key),i=r&&r.json===n?r:{json:n,block:t};return e.set(t.key,i),i.block});return fe=e,n}),[me,he]=Or({}),ge,_e=!0,ve=()=>requestAnimationFrame(()=>ge&&(ge.scrollTop=ge.scrollHeight));C(ie(pe,()=>_e&&ve()));let[ye,be]=x(0),xe=e=>new URLSearchParams(Object.entries(e).flatMap(([e,t])=>t===void 0?[]:[[e,String(t)]])).toString(),Se=new Nh(_,e=>H(`${W(t)}/timeline?${xe(e)}`),{limit:$b,onChange:()=>{we(()=>re(()=>{be(e=>e+1),b()})),Se.state===`idle`&&De()}}),Ce=()=>(ye(),{state:Se.state,error:Se.error});function we(e){let t=ge;if(!t||_e)return e();let n=t.getBoundingClientRect().top,r=Array.from(t.querySelectorAll(`.transcript > [data-key]`)).find(e=>e.getBoundingClientRect().bottom>n+1),i=r?.dataset.key,a=r?r.getBoundingClientRect().top:0;if(e(),!i)return;let o=Array.from(t.querySelectorAll(`.transcript > [data-key]`)).find(e=>e.dataset.key===i);o&&(t.scrollTop+=o.getBoundingClientRect().top-a)}let Te,Ee;function De(){Ee&&ge&&typeof IntersectionObserver<`u`&&(Te??=new IntersectionObserver(e=>e.some(e=>e.isIntersecting)&&void Se.older(),{root:ge,rootMargin:`${Math.round(window.innerHeight*1.5)}px 0px 0px 0px`}),Te.unobserve(Ee),Te.observe(Ee))}D(()=>Te?.disconnect());let Oe=e=>{Ee=e,requestAnimationFrame(()=>requestAnimationFrame(De))};async function ke(){if(u())return te(!0);try{await Se.first(),te(!0),b(),ve()}catch(e){e instanceof or&&e.status===404&&!n()?ae(!0):u()||Wh(e)||de(e instanceof or&&e.status===409?`No OpenCode process for this session is connected; history is unavailable until it reconnects.`:`Could not load the conversation: ${G(e)}`,`err`),te(!0)}}async function Ae(){try{let{messages:e}=await H(`${W(t)}/messages?limit=200`);for(let n of e??[]){let e=nn(t,n);e&&_.hubMessage(e)}b()}catch{}}async function je(){try{let e=await H(W(t)),n=po.feed(f());n.load(e.activity??[]),e.status&&n.status(e.status)}catch{}}let Me=T(()=>a()),Ne=ko(e=>{if(e.type===`resync`){ee()?Se.resync().catch(e=>de(`Could not refresh the conversation: ${G(e)}`,`err`)).then(Ae):ke().then(Ae),je(),Je();return}let n=typeof e.rootID==`string`?e.rootID:e.sessionID;if(e.type===`activity`&&h(n,e.sessionID)&&e.item&&e.item.kind!==`thinking`)_.activity(e.sessionID,e.item),b();else if(e.type===`reasoning`&&h(n,e.sessionID)&&typeof e.messageID==`string`&&typeof e.delta==`string`)_.appendReasoning({sessionID:e.sessionID,messageID:e.messageID,delta:e.delta}),b();else if(e.type===`delta`&&h(n,e.sessionID)&&typeof e.messageID==`string`&&typeof e.text==`string`)_.appendText({sessionID:e.sessionID,messageID:e.messageID,...Number.isInteger(e.ordinal)?{ordinal:e.ordinal}:{},delta:e.text}),b();else if(e.type===`message`){let n=nn(t,e.message);n&&(_.hubMessage(n),b())}else if(e.type===`turn`&&e.sessionID===t&&ut){let{sub:t,sentAt:n}=ut;ut=void 0,dt(e,t,n)}else if(e.type===`status`&&e.sessionID===f()){for(let n of Cf(Me,e.sessions,t))de(n,`sys`);if(Me=e.sessions,!qa(e.sessions)){for(let e of _.rows())e.live&&_.upsert({key:e.key,live:!1});_.endReasoning(void 0)}b(),Ye()}}),Pe;C(ie(()=>n()?.session.updated,()=>{clearTimeout(Pe),Pe=setTimeout(()=>document.visibilityState===`visible`&&void ns(t),400)}));let Fe=(e,n=!1)=>V(`${W(t)}/presence`,{method:`POST`,json:{visible:e},keepalive:n}).catch(()=>{}),Ie=()=>{Fe(document.visibilityState===`visible`,document.visibilityState!==`visible`),document.visibilityState===`visible`&&ns(t)},Le,[Re,ze]=x(),[Be,Ve]=x(``),[He,We]=x(!0),Ge=0,Ke,qe=0;async function Je(){if(Ge=Date.now(),n()&&!c().summary)return Ve(`Details aren't available for ${c().harnessName} sessions.`),We(!1);try{let e=await H(`${W(t)}/summary`);ze(e),Ve(``),(!e.branch||!e.changes)&&qe<2&&(qe++,clearTimeout(Ke),Ke=setTimeout(Je,4e3))}catch(e){Ve(e instanceof or&&e.status===409?`The machine is disconnected.`:`Could not load details: ${G(e)}`)}finally{We(!1)}}function Ye(){clearTimeout(Ke),Ke=setTimeout(Je,Math.max(0,ex-(Date.now()-Ge)))}let[Xe,Ze]=x(),Qe=t_(()=>t),[$e,et]=x(),[N,P]=x({...Zu(),draft:$p.get(t)}),tt=e=>{P(t=>Qu(t,e)),$p.set(t,N().draft)};D($p.subscribe(e=>{e===t&&$p.get(t)!==N().draft&&P(e=>Qu(e,{type:`input`,text:$p.get(t)}))}));let nt=()=>Bh(c(),o()),rt=()=>{let e=$u(N(),{running:o(),offline:s()}),t=nt();return{...e,canSubmit:e.canSubmit&&t.allowed,showStop:e.showStop&&c().stop,...!e.hint&&t.hint?{hint:t.hint}:{}}},it=0,[at,ot]=x(!1),st=Promise.resolve();function ct(e){st=st.then(async()=>{ot(!0);try{for(let t of e)try{tt({type:`attach`,image:await Xm(t,N().images)})}catch(e){tt({type:`attachError`,message:G(e)})}}finally{ot(!1)}})}async function lt(){let e=N().draft.trim(),n=N().images;if(!e&&!n.length)return;if(ht()&&!n.length){tt({type:`input`,text:``}),Vp.sendTyped(t,e);return}let r=++it,i=`local:${r}`,a=o(),s=Date.now();re(()=>{tt({type:`submit`,id:r}),_.upsert({key:i,kind:`user`,text:e,at:s,...n.length?{images:n.map(({name:e,mime:t,preview:n})=>({name:e,mime:t,preview:n}))}:{}}),le(e=>({...e,[i]:`pending`})),b()}),_e=!0,ve();try{let a={text:e,...n.length?{images:n.map(({mime:e,data:t,name:n})=>({mime:e,data:t,name:n}))}:{}},o=await V(`${W(t)}/turn`,{method:`POST`,json:a,headers:{prefer:`respond-async`}}),l=await o.json().catch(()=>({})),u=ed(o.status,l);tt({type:`accepted`,id:r});let d=Vh(c(),u);le(e=>({...e,[i]:d.tick})),d.toast&&q(d.toast),u===`accepted`?ut={sub:r,sentAt:s}:dt(l,r,s)}catch(e){if(e instanceof sr&&!a&&await nd(o)){tt({type:`accepted`,id:r}),le(e=>({...e,[i]:`sent`})),de(`Lost the connection to the hub after sending; the session is working on your message and its reply will appear here.`,`sys`);return}let t=Wh(e);t&&q(t,`err`);let n=t??(e instanceof or&&e.status===504?`OpenCode did not answer in time. The session may still be working.`:G(e));re(()=>{tt({type:`rejected`,id:r,message:n}),_.upsert({key:i,kind:`user`,text:``,images:[]}),b()})}}let ut;function dt(e,t,n){let r=_.rows().some(e=>e.kind===`assistant`&&(e.at??0)>=n&&e.text);e.reply&&!r&&_.upsert({key:`reply:${t}`,kind:`assistant`,text:e.reply,at:Date.now()});let i=td(e);i&&de(i.text,i.kind),b()}async function ft(){tt({type:`stop`});try{let{stopped:e}=await(await V(`${W(t)}/stop`,{method:`POST`,json:{}})).json(),n=Array.isArray(e)?e.length:0;q(n?`Stopped ${n} session${n===1?``:`s`}`:`Nothing was running`)}catch(e){q(Wh(e)??`Could not stop: ${G(e)}`,`err`)}finally{tt({type:`stopped`})}}let pt=()=>rm(t),mt=()=>em.toggle(t),z=Zp,ht=()=>z().phase!==`off`&&z().sessionID===t,gt=()=>z().phase!==`off`&&z().sessionID!==void 0&&z().sessionID!==t,_t=()=>z().error?.sessionID===t&&!z().error.gesture?z().error.message:void 0,vt=()=>z().error?.sessionID===t&&z().error.gesture===!0,yt=()=>za(bo()??void 0,X()?.publicURL)?.micBlocked?`Set up speech in Settings to use the microphone`:void 0;D(Vp.attach(t,{user:e=>{let t=`voice:${++ue}`;return _.upsert({key:t,kind:`user`,text:e,at:Date.now()}),le(e=>({...e,[t]:`pending`})),b(),t},tick:(e,t)=>le(n=>({...n,[e]:t})),agent:e=>{let t=e.messageID?_.liveTextKey(e.messageID):`say:${++ue}`,{mode:n,text:r}=Sf(_.get(t)?.text??``,e.text);n!==`keep`&&(_.upsert({key:t,messageID:e.messageID,kind:`assistant`,text:r,at:_.get(t)?.at??Date.now()}),b())},note:(e,t)=>de(e,t??`sys`)}));async function bt(){ht()||(Mp(),em.cancel()),await Vp.toggle(t),Vp.isOn(t)&&Vp.state.phase===`on`&&de(`Voice mode on${Vp.state.agent?` (${Vp.state.agent} agent)`:``}. Speak naturally; say “stop” to interrupt, “pause listening” to end.`,`sys`)}let xt=If(location.href);xt.voice&&(tx=t,io(xt.path,{replace:!0})),C(()=>{tx===t&&n()&&!yt()&&(tx=void 0,ht()||bt())}),E(()=>{let e=ah(t);e&&(re(()=>{tt({type:`input`,text:e.text});for(let t of e.images)tt({type:`attach`,image:t})}),lt()),je(),ns(t),Fe(document.visibilityState===`visible`),Le=setInterval(()=>document.visibilityState===`visible`&&void Fe(!0),Qb),document.addEventListener(`visibilitychange`,Ie)});let St=!1;C(()=>{!St&&J.machines&&(St=!0,T(()=>{ke().then(Ae),Je(),(!n()||c().models)&&Qe.load()}))});let Ct=()=>void Fe(!1,!0);window.addEventListener(`pagehide`,Ct),D(()=>{Ne(),clearInterval(Le),clearTimeout(Ke),clearTimeout(Pe),document.removeEventListener(`visibilitychange`,Ie),window.removeEventListener(`pagehide`,Ct),Ct()});let B=!1;C(()=>{n()?B=!0:B&&J.machines&&(q(`That session is gone (deleted, or its machine was revoked).`,`warn`),io(`/`,{replace:!0}))});let wt=()=>Br(n()?.session).filter(e=>!p()||e.sessionID!==void 0&&m().has(e.sessionID)),Tt=w(()=>new Map(wt().map(e=>[`${e.kind}:${e.id}`,e]))),Et=w((e=[])=>{let t=[...Tt().keys()];return t.length===e.length&&t.every((t,n)=>t===e[n])?e:t}),Dt=()=>{let e=new Set(wt().map(e=>e.id));return er(Eo(),new Set([t,...m()]),kt()).filter(t=>!e.has(t.key))},Ot=()=>(go(),tc(),po.has(f())?po.feed(f()).pulse():void 0),[kt,At]=x(Date.now()),jt=setInterval(()=>At(Date.now()),1e3);D(()=>clearInterval(jt));let Mt=()=>{if(p()){let e=a()?.find(e=>e.id===t);return e?.state===`working`?(kt(),`Working${e.since?` · ${xa(Date.now()-e.since)}`:``}`):void 0}let e=Ot();if(!o()||!e?.busy)return;kt();let n=qi(a(),t),r=Hi(a());return`${n??e.label}${e.since?` · ${xa(Date.now()-e.since)}`:``}${r?` · ${Ki(r)}`:``}`},Nt=()=>Ri(a(),t),Pt=()=>{let e=n()?.session;if(!e)return`Not connected`;let t=wt().length;return c().voice?`${ht()&&z().agent?`${z().agent} agent`:e.conversation?`Voice agent`:`Session agent`} · ${t?`${t} request${t===1?``:`s`} waiting`:d()?`Voice on`:`Voice off`}`:t?`${t} request${t===1?``:`s`} waiting`:`${c().harnessName} session`},Ft=()=>Re()?.changes?.files.map(e=>e.file)??[];return(()=>{var e=Nb(),a=e.firstChild,d=a.firstChild,f=d.firstChild,p=d.nextSibling,m=p.firstChild,h=p.nextSibling.firstChild;R(d,O(A,{get when(){return Q()},get children(){return O(Xs,{icon:`menu`,label:`Open sidebar`,onClick:du})}}),f),R(f,O(A,{get when(){return g()},children:e=>(()=>{var t=Pb(),n=t.firstChild,r=n.nextSibling;return R(t,O(Z,{name:`chevron`,class:`crumb-chev`}),n),R(t,()=>e().title,r),S(n=>{var r=ao(e().id),i=`Back to ${e().title}`,a=`Back to ${e().title}`;return r!==n.e&&F(t,`href`,n.e=r),i!==n.t&&F(t,`title`,n.t=i),a!==n.a&&F(t,`aria-label`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),R(f,O(A,{get when(){return r()},get fallback(){return(()=>{var e=Fb();return R(e,()=>n()?.session.title||(J.machines?`Session`:`Loading…`)),e})()},children:e=>[O(Ys,{get state(){return e().state}}),O(Du,{get id(){return e().id},get title(){return e().title},place:`topbar`,class:`title`,get children(){var t=Ib(),n=t.firstChild;return n.$$click=()=>hl({id:e().id,place:`topbar`}),R(n,()=>e().title),S(()=>F(n,`title`,`${e().title} · click to rename`)),t}}),O(Ou,{get id(){return e().id}}),O(Zs,{label:`Session actions`,class:`icon-btn small`,items:()=>vl(e(),{open:!1,place:`topbar`})})]}),null),R(d,O(A,{get when(){return i()},children:e=>(()=>{var t=Lb(),r=t.firstChild,i=r.nextSibling,a=i.nextSibling;return R(t,()=>e().machine,i),R(a,()=>e().where),R(t,O(A,{get when(){return e().branch},get children(){return[O(Z,{name:`branch`}),M(()=>e().branch)]}}),null),S(i=>{var a=`${e().text} · ${n().session.directory}`,o=`Runs on ${e().text}`,s=`online-dot${n().machine.online?` on`:``}`;return a!==i.e&&F(t,`title`,i.e=a),o!==i.t&&F(t,`aria-label`,i.t=o),s!==i.a&&I(r,i.a=s),i},{e:void 0,t:void 0,a:void 0}),t})()}),null),R(d,O(A,{get when(){return l()},children:e=>(()=>{var t=Rb(),n=t.firstChild;return R(t,()=>c().harnessName,n),R(t,()=>e().label,null),S(n=>{var r=`chip-evidence ${e().level}`,i=e().level,a=e().detail,o=`${c().harnessName} · evidence: ${e().label}. ${e().detail}`;return r!==n.e&&I(t,n.e=r),i!==n.t&&F(t,`data-evidence`,n.t=i),a!==n.a&&F(t,`title`,n.a=a),o!==n.o&&F(t,`aria-label`,n.o=o),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),null),R(d,O(A,{get when(){return Re()?.changes?.files.length},get children(){var e=xb(),t=e.firstChild;t.firstChild;var n=t.nextSibling.nextSibling;return n.firstChild,e.$$click=()=>Ze(Ft()[0]),R(t,()=>Re().changes.additions,null),R(n,()=>Re().changes.deletions,null),e}}),null),R(d,O(A,{get when(){return gt()},get children(){return O(B_,{})}}),null),R(d,O(Xs,{icon:`rail`,get label(){return su()?`Hide details`:`Show details`},get"aria-pressed"(){return su()},onClick:()=>uu(!su())}),null),R(a,O(A,{get when(){return M(()=>!!Q())()&&i()},children:e=>(()=>{var t=Bb(),r=t.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return R(i,()=>e().machine),R(a,()=>e().where),R(t,O(A,{get when(){return e().branch},get children(){return[O(Z,{name:`branch`}),(()=>{var t=zb();return R(t,()=>e().branch),t})()]}}),null),S(i=>{var a=n().session.directory,o=`Runs on ${e().text}`,s=`online-dot${n().machine.online?` on`:``}`;return a!==i.e&&F(t,`title`,i.e=a),o!==i.t&&F(t,`aria-label`,i.t=o),s!==i.a&&I(r,i.a=s),i},{e:void 0,t:void 0,a:void 0}),t})()}),p),R(a,O(A,{get when(){return Nt()},children:e=>(()=>{var n=Wb(),r=n.firstChild.nextSibling,i=r.firstChild,a=i.firstChild;return R(a,()=>e().label),R(i,O(A,{get when(){return e().status},get children(){var t=Vb();return R(t,()=>e().status),t}}),null),R(i,O(A,{get when(){return M(()=>e().sessionID!==t)()&&e().title},get children(){var t=Hb();return t.firstChild,R(t,()=>e().title,null),t}}),null),R(r,O(A,{get when(){return M(()=>!!e().message)()&&e().message!==e().label},get children(){var t=Ub();return R(t,()=>e().message),t}}),null),S(()=>F(n,`data-error-session`,e().sessionID)),n})()}),p),R(a,O(A,{get when(){return M(()=>!!s())()&&J.machines},get children(){return Sb()}}),p),p.addEventListener(`scroll`,e=>_e=e.currentTarget.scrollHeight-e.currentTarget.scrollTop-e.currentTarget.clientHeight<80);var v=ge;return typeof v==`function`?L(v,p):ge=p,R(m,O(A,{get when(){return!ne()},get fallback(){return O(rx,{})},get children(){return[O(A,{get when(){return ee()},get fallback(){return Gb()},get children(){return[O(A,{get when(){return u()},get children(){var e=Cb(),t=e.firstChild.nextSibling;return t.nextSibling,R(e,()=>c().harnessName,t),e}}),O(A,{get when(){return pe().length||oe().length},get fallback(){return O(A,{get when(){return!u()},get children(){return Kb()}})},get children(){return[(()=>{var e=wb();return L(Oe,e),e})(),O(Ue,{get children(){return[O(j,{get when(){return Ce().state===`loading`},get children(){return Tb()}}),O(j,{get when(){return M(()=>Ce().state===`done`)()&&pe().length},get children(){return Eb()}}),O(j,{get when(){return Ce().state===`error`},get children(){var e=Db(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return R(e,()=>Ce().error,t),n.$$click=()=>void Se.retry(),e}})]}}),O(gb,{sessionID:t,get blocks(){return pe()},get ticks(){return ce()},expanded:me,onToggle:(e,t)=>he(e,t),onDetail:(e,t)=>{_.detail(e,t),b()}})]}})]}}),O(k,{get each(){return oe()},children:e=>(()=>{var t=qb();return R(t,()=>e.text),S(n=>{var r=`note ${e.kind}`,i=e.kind===`err`?`alert`:void 0;return r!==n.e&&I(t,n.e=r),i!==n.t&&F(t,`role`,n.t=i),n},{e:void 0,t:void 0}),t})()}),O(Vl,{get decisions(){return un(wo(),t)}}),O(k,{get each(){return Et()},children:e=>O(A,{get when(){return Tt().get(e)},children:e=>O(bv,{sessionID:t,get blocker(){return e()},rootID:t,get canAnswer(){return M(()=>e().kind===`permission`)()?c().permission:c().form},get harnessName(){return c().harnessName}})})}),O(k,{get each(){return Dt()},children:e=>(()=>{var t=Jb();return R(t,()=>e.text),S(()=>F(t,`data-answered-by`,e.key)),t})()}),O(A,{get when(){return Mt()},get children(){var e=Ob();return e.firstChild.nextSibling,R(e,Mt,null),e}}),O(A,{get when(){return M(()=>!(o()||!n()))()&&r()},get children(){var e=kb(),t=e.firstChild;return R(e,()=>qs[r().state],t),R(e,()=>oc(r().updated,tc()),null),e}})]}})),R(h,O(A,{get when(){return ht()},get children(){return O(Tg,{get state(){return z().voice},get level(){return z().level},get held(){return z().held},get ignored(){return z().ignored},get working(){return o()},get model(){return e_(Qe.prefs(),`voice`)},onMute:()=>Vp.mute(),onEnd:()=>void Vp.end(),onModel:()=>et(`voice`),get notifyHint(){return Yp()},onAllowNotifications:()=>void Xp(),get timing(){return z().timing},get detector(){return z().detector}})}}),null),R(h,O(A,{get when(){return vt()},get children(){var e=Ab();return e.$$click=()=>void bt(),e}}),null),R(h,O(A,{get when(){return _t()},get children(){var e=jb();return e.firstChild,R(e,_t,null),e}}),null),R(h,O(A,{get when(){return nt().show},get fallback(){return(()=>{var e=Xb(),t=e.firstChild;return R(t,()=>nt().hint),R(e,O(A,{get when(){return rt().showStop},get children(){var e=Yb(),t=e.firstChild;return e.$$click=()=>void ft(),R(e,O(Z,{name:`stop`}),t),S(()=>e.disabled=!rt().canStop),e}}),null),e})()},get children(){return O(xg,{get draft(){return N().draft},get images(){return N().images},get attaching(){return at()},get view(){return rt()},get error(){return N().error},get voiceOn(){return ht()},get voiceBlocked(){return yt()},get dictating(){return pt().recording},get transcribing(){return pt().transcribing},get metaLeft(){return Pt()},get voiceModel(){return M(()=>!!Qe.error())()?`unavailable`:e_(Qe.prefs(),`voice`)},get workerModel(){return M(()=>!!Qe.error())()?`unavailable`:e_(Qe.prefs(),`worker`)},onInput:e=>tt({type:`input`,text:e}),onAttach:ct,onDetach:e=>{let t=N().images.find(t=>t.id===e);t?.preview.startsWith(`blob:`)&&URL.revokeObjectURL(t.preview),tt({type:`detach`,id:e})},onSubmit:()=>void lt(),onStop:()=>void ft(),onDictate:()=>void mt(),onVoice:()=>void bt(),onModel:e=>et(e),get showModels(){return c().models},get showVoice(){return c().voice}})}}),null),R(a,O(A,{get when(){return Xe()},get children(){return O(R_,{sessionID:t,get file(){return Xe()},get files(){return M(()=>!!Ft().length)()?Ft():[Xe()]},onFile:Ze,onClose:()=>Ze(void 0)})}}),null),R(e,O(A,{get when(){return su()},get children(){return[O(A,{get when(){return Q()},get children(){var e=Mb();return e.$$click=()=>uu(!1),e}}),O(A,{get when(){return!Q()},get children(){return O(Im,{panel:`rail`,label:`Resize details`})}}),O(L_,{get found(){return n()},get summary(){return Re()},get summaryError(){return Be()},get loading(){return He()},onFile:e=>Ze(e),onClose:()=>uu(!1)})]}}),null),R(e,O(n_,{get kind(){return $e()},models:Qe,onClose:()=>et(void 0)}),null),S(()=>I(e,`session-layout${su()?` with-rail`:``}`)),e})()}function rx(){return Zb()}P([`click`]);var ix=N(`<input type=search class=picker-search autofocus>`),ax=N(`<button type=button class="btn small">Retry`),ox=N(`<p class="muted small"role=status>`),sx=N(`<p class="muted small picker-note">`),cx=N(`<li><button type=button><span class=po-name>Use “<!>”</span><span class="po-id muted">as a custom `),lx=N(`<ul class=picker-list role=listbox>`),ux=N(`<div class="picker-group muted small">`),dx=N(`<span class="po-id muted">`),fx=N(`<span class=po-mark>✓ Current`),px=N(`<li><button type=button><span class=po-name>`);function mx(e){let[t,n]=x(``),[r,i]=x(),[a,o]=x(``),[s,c]=x(``),[l,u]=x(0),d=()=>{let t=e.request;t&&(i(void 0),o(``),c(``),t.load().then(e=>{if(Array.isArray(e))return i(e);c(e.note??``),i(e.options)},e=>o(G(e))))};C(ie(()=>e.request,e=>{e&&(n(``),u(0),d())}));let f=w(()=>Ag(r()??[],t(),{current:e.request?.current,grouped:e.request?.grouped})),p=()=>[...f().items.map(e=>e.id),...f().custom?[f().custom]:[]],m=t=>{let n=e.request;e.onClose(),n?.onPick(t)},h=()=>e.request?.noun??`option`;return O(Qs,{get open(){return!!e.request},get title(){return e.request?.title??``},get onClose(){return e.onClose},class:`picker`,get children(){return[(()=>{var e=ix();return e.$$keydown=e=>{let t={ArrowDown:1,ArrowUp:-1};if(e.key in t)e.preventDefault(),u(jg(l(),t[e.key],p().length));else if(e.key===`Enter`){e.preventDefault();let t=p()[l()];t&&m(t)}},e.$$input=e=>{n(e.currentTarget.value),u(0)},S(t=>{var n=`Search or type a ${h()}`,r=`Search ${h()}s`;return n!==t.e&&F(e,`placeholder`,t.e=n),r!==t.t&&F(e,`aria-label`,t.t=r),t},{e:void 0,t:void 0}),S(()=>e.value=t()),e})(),(()=>{var e=ox();return R(e,(()=>{var e=M(()=>!!a());return()=>e()?`Couldn't load the ${h()} list: ${a()}. Type any ${h()}.`:M(()=>r()===void 0)()?`Loading ${h()}s…`:M(()=>!r().length)()?`No suggestions. Type any ${h()}.`:`${f().total} ${f().total===1?h():`${h()}s`}`})(),null),R(e,O(A,{get when(){return a()},get children(){return[` `,(()=>{var e=ax();return e.$$click=d,e})()]}}),null),e})(),O(A,{get when(){return s()},get children(){var e=sx();return R(e,s),e}}),(()=>{var t=lx();return R(t,O(k,{get each(){return f().items},children:(t,n)=>(()=>{var r=px(),i=r.firstChild,a=i.firstChild;return R(r,O(A,{get when(){return M(()=>!!e.request?.grouped)()&&(n()===0||kg(f().items[n()-1].id)!==kg(t.id))},get children(){var e=ux();return R(e,()=>kg(t.id)||`Other`),e}}),i),i.$$click=()=>m(t.id),R(a,()=>t.id),R(i,O(A,{get when(){return t.name},get children(){var e=dx();return R(e,()=>t.name),e}}),null),R(i,O(A,{get when(){return t.current},get children(){return fx()}}),null),S(e=>{var r=`picker-opt${l()===n()?` active`:``}`,a=!!t.current;return r!==e.e&&I(i,e.e=r),a!==e.t&&F(i,`aria-selected`,e.t=a),e},{e:void 0,t:void 0}),r})()}),null),R(t,O(A,{get when(){return f().custom},get children(){var e=cx(),t=e.firstChild,n=t.firstChild,r=n.firstChild.nextSibling;r.nextSibling;var i=n.nextSibling;return i.firstChild,t.$$click=()=>m(f().custom),R(n,()=>f().custom,r),R(i,h,null),S(()=>I(t,`picker-opt${l()===f().items.length?` active`:``}`)),e}}),null),t})()]}})}P([`input`,`keydown`,`click`]);var hx=N(`<div class=chips role=group aria-label="Which speech settings"><button type=button class=chip>Yours</button><button type=button class=chip>Server default`),gx=N(`<div class="speech-panel stack">`),_x=N(`<p class=error>`),vx=N(`<p class=muted>Loading…`),yx=N(`<p class="small inherit">`),bx=N(`<p class="small muted">`),xx=N(`<p class=field-error>`),Sx=N(`<div class=field><label>`),Cx=N(`<input type=text autocomplete=off autocapitalize=off>`),wx=N(`<div class=row><button type=button class="btn small">Browse…`),Tx=N(`<input type=password autocomplete=new-password placeholder="Paste the new key"aria-label="New API key">`),Ex=N(`<div class=row><button type=button class="btn small">Cancel`),Dx=N(`<div class="field key-field"><span class=field-label>API key`),Ox=N(`<p>`),kx=N(`<button type=button class="btn small">Undo`),Ax=N(`<button type=button class="btn small danger">Clear`),jx=N(`<div class=row><button type=button class="btn small">`),Mx=N(`<fieldset class="card speech-card"><legend>`),Nx=N(`<div class="row reset-row"><span class="small muted grow"></span><button type=button class="btn small">Reset to server default`),Px=N(`<option>`),Fx=N(`<select>`),Ix=N(`<p class="small muted">The server default is used by everyone on this hub for whatever they have not set themselves. Their own keys stay private.`),Lx=N(`<button type=button class=btn>Preview voice`),Rx=N(`<form class=stack novalidate><div class=row><button type=submit class="btn primary">Save</button></div><p role=status>`),zx=N(`<div class=banner><div><strong>Speech is not set up yet</strong><p class=small></p><p class="small muted">OpenRouter covers both directions with one key (openrouter.ai/keys). Or point both at your own OpenAI-compatible servers.`),Bx=[[`openrouter`,`OpenRouter`],[`openai-compatible`,`OpenAI-compatible`]],Vx={settings:`from settings`,config:`from hub.json`,env:`from env`,user:`yours`},Hx={user:`/api/settings/speech`,default:`/api/settings/speech/default`},Ux={stt:`Speech-to-text`,tts:`Text-to-speech`};function Wx(){let[e,t]=x(`user`),[n,r]=x(!1),[i,a]=x(),[o,s]=x(``),c=async t=>{a(void 0),s(``);try{let n=await H(Hx[t]);t===`user`&&r(jt(X(),n).length>1),e()===t&&a(n)}catch(e){s(e instanceof or&&e.status===403?t==="default"?`Only admins can change the server default.`:`This account cannot change speech settings.`:e instanceof or&&e.status===404?`This hub does not support speech settings.`:`Could not load speech settings: ${G(e)}`)}};E(()=>void c(`user`));let l=n=>{n!==e()&&(t(n),c(n))};return(()=>{var t=gx();return R(t,O(A,{get when(){return n()},get children(){var t=hx(),n=t.firstChild,r=n.nextSibling;return n.$$click=()=>l(`user`),r.$$click=()=>l(`default`),S(t=>{var i=e()===`user`,a=e()==="default";return i!==t.e&&F(n,`aria-pressed`,t.e=i),a!==t.t&&F(r,`aria-pressed`,t.t=a),t},{e:void 0,t:void 0}),t}}),null),R(t,O(A,{get when(){return!o()},get fallback(){return(()=>{var e=_x();return R(e,o),e})()},get children(){return O(A,{get when(){return i()},get fallback(){return vx()},keyed:!0,children:t=>O(Gx,{settings:t,get scope(){return e()},onSaved:e=>a(e)})})}}),null),t})()}function Gx(e){let[t,n]=Or(Pa(e.settings)),[r,i]=x({}),[a,o]=x({text:``,kind:``}),[s,c]=x(!1),[l,u]=x(),d=()=>e.scope===`user`?It(e.settings):void 0,f=()=>e.scope===`user`?za(e.settings.ready,X()?.publicURL):void 0,p=()=>Object.keys(Fa(e.settings,gr(t))).length>0,m={},h=e=>(m[e]??=H(`/api/settings/speech/models?kind=${e}`).then(e=>({options:Dg(e),note:Og(e)})),m[e].catch(()=>delete m[e]),m[e]),g=(e,t,n,i,a)=>{let o=()=>d()?.[e]?.[t];return(()=>{var s=Sx(),c=s.firstChild;return F(c,`for`,`sp-${e}-${t}`),R(c,n),R(s,i,null),R(s,O(A,{get when(){return o()?.inherited},get children(){var e=yx();return R(e,()=>o().note),e}}),null),R(s,O(A,{when:a,get children(){var e=bx();return R(e,a),e}}),null),R(s,O(A,{get when(){return r()[`${e}.${t}`]},get children(){var n=xx();return R(n,()=>r()[`${e}.${t}`]),n}}),null),s})()},_=(e,i,a={})=>(()=>{var o=Cx();return F(o,`id`,`sp-${e}-${i}`),F(o,`spellcheck`,!1),st(o,ze(a,{get value(){return t[e][i]},get"aria-invalid"(){return!!r()[`${e}.${i}`]},onInput:t=>n(e,i,t.currentTarget.value)}),!1,!1),o})(),v=(e,r,i,a,o)=>(()=>{var s=wx(),c=s.firstChild;return R(s,()=>_(e,r,{placeholder:`Choose or type a ${a}`}),c),c.$$click=()=>u({title:i,noun:a,current:t[e][r]??``,load:o,grouped:r===`model`,onPick:t=>n(e,r,t)}),s})(),y=i=>{let a=e.settings[i].apiKey??{set:!1,source:`none`},o=()=>d()?.[i].apiKey,s=()=>t[i].apiKey,c=()=>d()?!o()?.inherited&&a.set:a.set&&a.source===`settings`;return(()=>{var e=Dx();return e.firstChild,R(e,O(A,{get when(){return s().action===`set`},get fallback(){return[(()=>{var e=Ox();return R(e,(()=>{var e=M(()=>s().action===`clear`);return()=>e()?`Key will be removed when you save.`:M(()=>!!o()?.inherited)()?o().note:M(()=>!!a.set)()?`Key set${a.last4?` ••••${a.last4}`:``} (${Vx[a.source]??a.source})`:`No key set`})()),S(()=>I(e,`key-summary${o()?.inherited&&s().action!==`clear`?` inherit`:``}`)),e})(),(()=>{var e=jx(),t=e.firstChild;return t.$$click=()=>n(i,`apiKey`,{action:`set`,value:``}),R(t,(()=>{var e=M(()=>!!o()?.inherited);return()=>e()?`Use your own key`:a.set?`Replace`:`Add key`})()),R(e,O(A,{get when(){return s().action===`clear`},get children(){var e=kx();return e.$$click=()=>n(i,`apiKey`,{action:`keep`,value:``}),e}}),null),R(e,O(A,{get when(){return M(()=>s().action!==`clear`)()&&c()},get children(){var e=Ax();return e.$$click=()=>n(i,`apiKey`,{action:`clear`,value:``}),e}}),null),e})()]},get children(){return[(()=>{var e=Tx();return e.$$input=e=>n(i,`apiKey`,`value`,e.currentTarget.value),F(e,`id`,`sp-${i}-apiKey`),S(()=>e.value=s().value),e})(),(()=>{var e=Ex(),t=e.firstChild;return t.$$click=()=>n(i,`apiKey`,{action:`keep`,value:``}),e})()]}}),null),R(e,O(A,{get when(){return r()[`${i}.apiKey`]},get children(){var e=xx();return R(e,()=>r()[`${i}.apiKey`]),e}}),null),e})()},b=async t=>{if(confirm(`Reset ${Ux[t].toLowerCase()} to the server default? Your own ${Ux[t].toLowerCase()} settings are removed.`))try{let n=await(await V(Hx.user,{method:`PUT`,json:Lt(t)})).json().catch(()=>({})),r=n?.stt&&n?.tts?n:await H(Hx.user);xo(r.ready??null),e.onSaved(r),q(`${Ux[t]} reset to the server default`)}catch(e){q(`Could not reset: ${G(e)}`,`err`)}},ee=r=>(()=>{var i=Mx(),a=i.firstChild;return R(a,()=>Ux[r]),R(i,O(A,{get when(){return d()},children:e=>(()=>{var t=Nx(),n=t.firstChild,i=n.nextSibling;return R(n,(()=>{var t=M(()=>!!e().own[r]);return()=>t()?`${e().own[r]} of your own setting${e().own[r]===1?``:`s`}`:`All from the server default`})()),i.$$click=()=>void b(r),S(()=>i.disabled=!e().own[r]),t})()}),null),R(i,()=>g(r,`provider`,`Provider`,(()=>{var e=Fx();return e.addEventListener(`change`,e=>n(r,`provider`,e.currentTarget.value)),F(e,`id`,`sp-${r}-provider`),R(e,O(k,{each:Bx,children:([e,t])=>(()=>{var n=Px();return n.value=e,R(n,t),n})()}),null),R(e,O(A,{get when(){return!Bx.some(([e])=>e===t[r].provider)},get children(){var e=Px();return R(e,()=>t[r].provider||`—`),S(()=>e.value=t[r].provider),e}}),null),S(()=>e.value=t[r].provider),e})()),null),R(i,O(A,{get when(){return t[r].provider===`openai-compatible`},get children(){return g(r,`baseURL`,`Base URL`,_(r,`baseURL`,{inputmode:`url`,placeholder:`http://host:port/v1`}))}}),null),R(i,()=>g(r,`model`,`Model`,v(r,`model`,r===`stt`?`Speech-to-text model`:`Text-to-speech model`,`model`,()=>h(r))),null),R(i,O(A,{when:r===`tts`,get fallback(){return g(r,`language`,`Language (optional)`,_(r,`language`,{placeholder:`auto, e.g. en`}))},get children(){return[M(()=>g(r,`voice`,`Voice`,v(r,`voice`,`Voice`,`voice`,async()=>Dg(La(e.settings.voiceHints,t.tts.model))))),M(()=>g(r,`speed`,`Server-side speed (optional)`,_(r,`speed`,{inputmode:`decimal`,placeholder:`default`}),`0.25–4, applied by the TTS provider. Your device's voice speed is separate.`))]}}),null),R(i,()=>y(r),null),i})(),C=async r=>{r.preventDefault();let a=gr(t),s=Ia(a);if(i(s),Object.keys(s).length)return o({text:`Fix the highlighted fields.`,kind:`error`});let l=Fa(e.settings,a);if(!Object.keys(l).length)return o({text:`Nothing to save.`,kind:`muted`});c(!0),o({text:`Saving…`,kind:`muted`});try{let t=await(await V(Hx[e.scope],{method:`PUT`,json:l})).json().catch(()=>({})),r=t?.stt&&t?.tts?t:await H(Hx[e.scope]);e.scope===`user`?xo(r.ready??null):ss(),n(Mr(Pa(r))),e.onSaved(r),q(e.scope==="default"?`Server default saved`:`Speech settings saved`)}catch(e){let t=e.field;t&&i({[t]:G(e)}),o({text:`Could not save: ${G(e)}`,kind:`error`})}finally{c(!1)}},w=async()=>{o({text:p()?`Previewing the saved voice (save to hear your changes)…`:`Previewing…`,kind:`muted`});let e;try{let t=await(await V(`/api/settings/speech/test`,{method:`POST`,json:{kind:`tts`,text:`Hi! This is how replies will sound.`}})).blob();if(e=URL.createObjectURL(t),$.src=e,Bd($,jp.speed),!await $.play().then(()=>!0,()=>!1))throw Error(`the browser blocked playback`);o({text:`Playing preview.`,kind:`muted`}),await new Promise(e=>$.onended=$.onpause=$.onerror=()=>e()),o({text:``,kind:``})}catch(e){o({text:`Preview failed: ${G(e)}`,kind:`error`})}finally{$.onended=$.onpause=$.onerror=null,e&&URL.revokeObjectURL(e)}};return(()=>{var t=Rx(),n=t.firstChild,r=n.firstChild,i=n.nextSibling;return t.$$input=()=>o({text:p()?`Unsaved changes.`:``,kind:`muted`}),t.addEventListener(`submit`,C),R(t,O(A,{get when(){return e.scope==="default"},get children(){return Ix()}}),n),R(t,O(A,{get when(){return f()},children:e=>(()=>{var t=zx(),n=t.firstChild,r=n.firstChild.nextSibling;return r.nextSibling,R(r,()=>e().reason),R(n,O(A,{get when(){return e().storage},get children(){var t=bx();return R(t,()=>e().storage),t}}),null),t})()}),n),R(t,()=>ee(`stt`),n),R(t,()=>ee(`tts`),n),R(n,O(A,{get when(){return e.scope===`user`},get children(){var e=Lx();return e.$$click=()=>void w(),e}}),null),R(i,()=>a().text),R(t,O(mx,{get request(){return l()},onClose:()=>u(void 0)}),null),S(e=>{var t=s(),n=`small ${a().kind}`;return t!==e.e&&(r.disabled=e.e=t),n!==e.t&&I(i,e.t=n),e},{e:void 0,t:void 0}),t})()}P([`click`,`input`]);var Kx=N(`<section class=settings-section id=agents aria-labelledby=h-agents><h2 id=h-agents>Agents</h2><p class="small muted">What sessions and apps may do for you: approve, deny, answer, prompt or stop in your sessions, only within a grant. Anything outside a grant comes to you as a Decision.</p><div class=chips role=group aria-label="Agents sections"><button type=button class=chip>Grants</button><button type=button class=chip>Activity`),qx=N(`<ul class=list>`),Jx=N(`<div class="stack app-tokens"><div class=row><div class=grow><h3>App tokens</h3><p class="small muted">For MCP gateways, CLIs and other apps. The secret is shown once; grants use the non-secret token ID.</p></div><button type=button class="btn small primary">New token`),Yx=N(`<p class="small muted">`),Xx=N(`<p class="small muted">No app tokens yet.`),Zx=N(`<li class=row><div class=grow><div class=name></div><div class="small muted mono">app:</div><div class="small muted"></div></div><button type=button class="btn small danger">Revoke`),Qx=N(`<div class=stack><p class=warn><strong>Copy this token now.</strong> It will not be shown again.</p><label class=text-field><span class=field-title>Bearer token</span><textarea class=mono readonly rows=3></textarea></label><button type=button class="btn primary">Copy token</button><label class=text-field><span class=field-title>Grant holder</span><span class="field-desc muted small">Use this non-secret value if you later create an acting or launch grant.</span><input class=mono readonly></label><button type=button class="btn small">Copy holder</button><button type=button class="btn small">Done`),$x=N(`<p class=error role=alert>`),eS=N(`<form class=grant-form novalidate><label class=text-field><span class=field-title>Label</span><span class="field-desc muted small">Where this token will be used.</span><input maxlength=100></label><fieldset class=grant-verbs><legend class=field-title>Scopes</legend></fieldset><p class="small muted">Act and launch scopes still require grants. Start with read and message scopes unless the app needs more.</p><div class=row><button type=submit class="btn small primary">Create token</button><button type=button class="btn small">Cancel`),tS=N(`<label class=check><input type=checkbox><span>`),nS=N(`<li><label class=switch><span class=notify-kind><span>Agent actions on this hub</span><span class="small muted">Admin: the switch for every user of this hub.</span></span><input type=checkbox data-hub-acting>`),rS=N(`<ul class=switches><li><label class=switch><span class=notify-kind><span>Agent actions</span><span class="small muted">Let agents act for you within their grants. Off: every agent action is refused (paused).</span></span><input type=checkbox data-acting>`),iS=N(`<p class="small warn"role=status data-acting-note>`),aS=N(`<ul class="list grants">`),oS=N(`<div class=stack><div class=row><p class="small muted grow">Each grant lets one holder (a session, a reserved role like @@orchestrator, or an app) act in some projects, for a while.</p><button type=button class="btn small primary">New grant`),sS=N(`<p class="small muted">No grants. Agents can still ask you (Decisions).`),cS=N(`<dt>Permissions`),lS=N(`<dd class=mono>`),uS=N(`<dt>Never`),dS=N(`<button type=button class="btn small">Edit`),fS=N(`<button type=button class="btn small danger">Revoke`),pS=N(`<li><div class=grow><div class=name><span></span></div><dl class="grant-facts small"><dt>Projects</dt><dd></dd><dt>May</dt><dd></dd><dt>Limits</dt><dd></dd></dl><div class="small muted"data-expiry>`),mS=N(`<p class="field-error small"role=alert>`),hS=N(`<span class="field-desc muted small">`),gS=N(`<label class="text-field grow"><span class=field-title></span><input type=text>`),_S=N(`<label class=text-field><span class=field-title></span><span class="field-desc muted small"></span><textarea rows=2>`),vS=N(`<p class=error role=alert data-error=form>`),yS=N(`<form class=grant-form novalidate><fieldset class=grant-verbs aria-label=Actions><span class=field-title>May</span></fieldset><div class=row></div><label class=check><input type=checkbox aria-label="May allow always"><span>May answer “Always allow” (still only for patterns it may approve)</span></label><div class=row><button type=submit class="btn small primary"></button><button type=button class="btn small">Cancel`),bS=N(`<ol class="list audit agent-audit">`),xS=N(`<p class="small muted">Loading…`),SS=N(`<button type=button class="btn small">Load older`),CS=N(`<div class=stack>`),wS=N(`<p class="small err">Could not load: `),TS=N(`<p class="small muted">No agent actions yet.`),ES=N(`<li class=audit-row><div class=grow><div class=name> <span class=muted></span></div><div class="small muted"><span></span></div></div><time class="small muted">`),DS=50,OS=`/api/agent/grants`,kS=`/api/agent/app-tokens`;function AS(){let[e,t]=x(`grants`);return(()=>{var n=Kx(),r=n.firstChild.nextSibling.nextSibling,i=r.firstChild,a=i.nextSibling;return R(n,O(NS,{}),r),R(n,O(jS,{}),r),i.$$click=()=>t(`grants`),a.$$click=()=>t(`activity`),R(n,O(A,{get when(){return e()===`grants`},get children(){return O(PS,{})}}),null),R(n,O(A,{get when(){return e()===`activity`},get children(){return O(IS,{})}}),null),S(t=>{var n=e()===`grants`,r=e()===`activity`;return n!==t.e&&F(i,`aria-pressed`,t.e=n),r!==t.t&&F(a,`aria-pressed`,t.t=r),t},{e:void 0,t:void 0}),n})()}function jS(){let[e,{mutate:t,refetch:n}]=ne(()=>H(kS).then(Sn)),[r,i]=x(!1),a=async e=>{if(confirm(`Revoke ${e.label||e.id}? Apps using it will stop working immediately.`))try{await V(`${kS}/${U(e.id)}`,{method:`DELETE`}),t(t=>(t??[]).filter(t=>t.id!==e.id)),q(`App token revoked`)}catch(e){q(G(e),`err`),n()}};return(()=>{var n=Jx(),o=n.firstChild.firstChild.nextSibling;return o.$$click=()=>i(!0),R(n,O(A,{get when(){return r()},get children(){return O(MS,{onClose:()=>i(!1),onCreated:e=>t(t=>[e,...(t??[]).filter(t=>t.id!==e.id)])})}}),null),R(n,O(A,{get when(){return e()},get fallback(){return(()=>{var t=Yx();return R(t,(()=>{var t=M(()=>!!e.error);return()=>t()?`Could not load: ${G(e.error)}`:`Loading…`})()),t})()},get children(){return O(A,{get when(){return e().length},get fallback(){return Xx()},get children(){var t=qx();return R(t,O(k,{get each(){return e()},children:e=>(()=>{var t=Zx(),n=t.firstChild,r=n.firstChild,i=r.nextSibling;i.firstChild;var o=i.nextSibling,s=n.nextSibling;return R(r,()=>e.label||`Unnamed app`),R(i,()=>e.id,null),R(o,()=>e.scopes.join(`, `)||`No scopes`,null),R(o,(()=>{var t=M(()=>!!e.created);return()=>t()?` · created ${oc(e.created,tc())}`:``})(),null),s.$$click=()=>void a(e),S(()=>F(t,`data-app-token`,e.id)),t})()})),t}})}}),null),n})()}function MS(e){let[t,n]=x(`MCP Gateway`),[r,i]=x([`sessions:read`,`messages:send`,`messages:read`]),[a,o]=x(``),[s,c]=x(``),[l,u]=x(``),[d,f]=x(!1),p=async n=>{n.preventDefault();let i=Cn(t(),r());if(!i.ok)return u(i.error);f(!0),u(``);try{let t=await(await V(kS,{method:`POST`,json:i.body})).json(),n=xn(t);if(!n||typeof t?.token!=`string`)throw Error(`The hub did not return the new token`);e.onCreated(n),o(t.token),c(`app:${n.id}`)}catch(e){u(G(e))}finally{f(!1)}},m=async(e,t)=>{try{await navigator.clipboard.writeText(e),q(`${t} copied`)}catch{q(`Could not copy ${t.toLowerCase()}`,`err`)}};return O(Qs,{open:!0,get title(){return a()?`Save your app token`:`New app token`},get onClose(){return e.onClose},class:`app-token-dialog`,get children(){return O(A,{get when(){return a()},get fallback(){return(()=>{var a=eS(),o=a.firstChild,s=o.firstChild.nextSibling.nextSibling,c=o.nextSibling;c.firstChild;var u=c.nextSibling.nextSibling,f=u.firstChild,m=f.nextSibling;return a.addEventListener(`submit`,e=>void p(e)),s.$$input=e=>n(e.currentTarget.value),R(c,O(k,{each:bn,children:e=>(()=>{var t=tS(),n=t.firstChild,a=n.nextSibling;return n.addEventListener(`change`,t=>i(t.currentTarget.checked?[...r(),e]:r().filter(t=>t!==e))),R(a,e),S(()=>n.checked=r().includes(e)),t})()}),null),R(a,O(A,{get when(){return l()},get children(){var e=$x();return R(e,l),e}}),u),rt(m,`click`,e.onClose,!0),S(()=>f.disabled=d()),S(()=>s.value=t()),a})()},get children(){var t=Qx(),n=t.firstChild.nextSibling,r=n.firstChild.nextSibling,i=n.nextSibling,o=i.nextSibling,c=o.firstChild.nextSibling.nextSibling,l=o.nextSibling,u=l.nextSibling;return i.$$click=()=>void m(a(),`Token`),l.$$click=()=>void m(s(),`Holder`),rt(u,`click`,e.onClose,!0),S(()=>r.value=a()),S(()=>c.value=s()),t}})}})}function NS(){let[e,{mutate:t}]=ne(()=>H(`/api/agent/acting`).then(tr)),[n,r]=ne(()=>Dt(X())||void 0,()=>H(`/api/admin/agents/acting`).then(e=>e?.enabled!==!1)),[i,a]=x(!1),o=async e=>{let n=e.checked;a(!0);try{t(tr(await(await V(`/api/agent/acting`,{method:`PUT`,json:{enabled:n}})).json())),q(n?`Agent actions are on for you`:`Agent actions are off for you`)}catch(t){e.checked=!n,q(G(t),`err`)}finally{a(!1)}},s=async e=>{let n=e.checked;if(!n&&!confirm(`Turn agent actions off for everyone on this hub? No agent can act until an admin turns them on again.`))e.checked=!0;else{a(!0);try{let e=await(await V(`/api/admin/agents/acting`,{method:`PUT`,json:{enabled:n}})).json();r.mutate(e?.enabled!==!1),q(n?`Agent actions are on for this hub`:`Agent actions are off for this hub`);let i=await H(`/api/agent/acting`).catch(()=>void 0);i&&t(tr(i))}catch(t){e.checked=!n,q(G(t),`err`)}finally{a(!1)}}};return O(A,{get when(){return e()},get fallback(){return(()=>{var t=Yx();return R(t,(()=>{var t=M(()=>!!e.error);return()=>t()?`Could not load: ${G(e.error)}`:`Loading…`})()),t})()},children:e=>[(()=>{var t=rS(),r=t.firstChild.firstChild.firstChild.nextSibling;return r.addEventListener(`change`,e=>void o(e.currentTarget)),R(t,O(A,{get when(){return M(()=>!!Dt(X()))()&&n()!==void 0},get children(){var e=nS(),t=e.firstChild.firstChild.nextSibling;return t.addEventListener(`change`,e=>void s(e.currentTarget)),S(()=>t.disabled=i()),S(()=>t.checked=n()),e}}),null),S(()=>r.disabled=i()),S(()=>r.checked=e().on),t})(),O(A,{get when(){return e().note},get children(){var t=iS();return R(t,()=>e().note),t}})]})}function PS(){let[e,{refetch:t,mutate:n}]=ne(()=>H(OS).then(An)),[r,i]=x(),[a,o]=x(Date.now()),s=setInterval(()=>o(Date.now()),1e3);D(()=>clearInterval(s));let c=async e=>{if(confirm(`Revoke the grant of ${e.holder}? It stops at once.`))try{let r=kn((await(await V(`${OS}/${U(e.id)}`,{method:`DELETE`})).json())?.grant);r?n(e=>(e??[]).map(e=>e.id===r.id?r:e)):t(),q(`Grant of ${e.holder} revoked`)}catch(e){q(G(e),`err`),t()}},l=e=>{n(t=>[e,...(t??[]).filter(t=>t.id!==e.id)].sort((e,t)=>t.created-e.created)),i(void 0)};return(()=>{var t=oS(),n=t.firstChild.firstChild.nextSibling;return n.$$click=()=>i(`new`),R(t,O(A,{get when(){return r()},keyed:!0,children:e=>O(FS,{grant:e===`new`?void 0:e,onSaved:l,onClose:()=>i(void 0)})}),null),R(t,O(A,{get when(){return e()},get fallback(){return(()=>{var t=Yx();return R(t,(()=>{var t=M(()=>!!e.error);return()=>t()?`Could not load: ${G(e.error)}`:`Loading…`})()),t})()},get children(){return O(A,{get when(){return e().length},get fallback(){return sS()},get children(){var t=aS();return R(t,O(k,{get each(){return e()},children:e=>{let t=()=>Nn(e,a());return(()=>{var n=pS(),r=n.firstChild.firstChild,a=r.firstChild,o=r.nextSibling,s=o.firstChild.nextSibling,l=s.nextSibling.nextSibling,u=l.nextSibling,d=u.nextSibling,f=o.nextSibling;return R(r,()=>t().holder,a),R(a,()=>t().stateLabel),R(s,()=>t().projects),R(l,()=>t().verbs),R(o,O(A,{get when(){return t().permit},get children(){return[cS(),(()=>{var e=lS();return R(e,()=>t().permit),e})()]}}),u),R(o,O(A,{get when(){return t().never},get children(){return[uS(),(()=>{var e=lS();return R(e,()=>t().never),e})()]}}),u),R(d,()=>t().limits),R(f,()=>t().expiry),R(n,O(A,{get when(){return t().editable},get children(){return[(()=>{var t=dS();return t.$$click=()=>i(e),S(()=>F(t,`aria-label`,`Edit grant of ${e.holder}`)),t})(),(()=>{var t=fS();return t.$$click=()=>void c(e),S(()=>F(t,`aria-label`,`Revoke grant of ${e.holder}`)),t})()]}}),null),S(r=>{var i=`grant-row${t().editable?``:` ended`}`,o=e.id,s=`badge-pill ${t().state}`;return i!==r.e&&I(n,r.e=i),o!==r.t&&F(n,`data-grant`,r.t=o),s!==r.a&&I(a,r.a=s),r},{e:void 0,t:void 0,a:void 0}),n})()}})),t}})}}),null),t})()}function FS(e){let[t,n]=x(Pn(e.grant)),[r,i]=x({}),[a,o]=x(``),[s,c]=x(!1),l=(e,t)=>{n(n=>({...n,[e]:t})),r()[e]&&i(t=>({...t,[e]:void 0}))},u=async n=>{n.preventDefault(),o(``);let r=Rn(t());if(!r.ok)i(r.errors);else{i({}),c(!0);try{let t=kn((await(await V(e.grant?`${OS}/${U(e.grant.id)}`:OS,{method:e.grant?`PUT`:`POST`,json:r.body})).json())?.grant);q(e.grant?`Grant updated`:`Grant created`),t?e.onSaved(t):e.onClose()}catch(e){let t=G(e),n=e instanceof or&&(e.status===400||e.status===404)?zn(t):void 0;n?i({[n]:t}):o(e instanceof or&&e.hint?`${t} (${e.hint})`:t)}finally{c(!1)}}},d=e=>O(A,{get when(){return r()[e.field]},get children(){var t=mS();return R(t,()=>r()[e.field]),S(()=>F(t,`data-error`,e.field)),t}}),f=e=>(()=>{var n=gS(),r=n.firstChild,i=r.nextSibling;return R(r,()=>e.label),R(n,O(A,{get when(){return e.hint},get children(){var t=hS();return R(t,()=>e.hint),t}}),i),i.$$input=t=>l(e.field,t.currentTarget.value),R(n,O(d,{get field(){return e.field}}),null),S(t=>{var n=e.label,r=e.placeholder??``,a=e.disabled;return n!==t.e&&F(i,`aria-label`,t.e=n),r!==t.t&&F(i,`placeholder`,t.t=r),a!==t.a&&(i.disabled=t.a=a),t},{e:void 0,t:void 0,a:void 0}),S(()=>i.value=t()[e.field]),n})(),p=e=>(()=>{var n=_S(),r=n.firstChild,i=r.nextSibling,a=i.nextSibling;return R(r,()=>e.label),R(i,()=>e.hint),a.$$input=t=>l(e.field,t.currentTarget.value),R(n,O(d,{get field(){return e.field}}),null),S(t=>{var n=e.label,r=e.placeholder??``;return n!==t.e&&F(a,`aria-label`,t.e=n),r!==t.t&&F(a,`placeholder`,t.t=r),t},{e:void 0,t:void 0}),S(()=>a.value=t()[e.field]),n})();return O(Qs,{open:!0,get title(){return M(()=>!!e.grant)()?`Edit grant of ${e.grant.holder}`:`New grant`},get onClose(){return e.onClose},wide:!0,class:`grant-dialog`,get children(){var n=yS(),r=n.firstChild;r.firstChild;var i=r.nextSibling,o=i.nextSibling,c=o.firstChild,m=o.nextSibling,h=m.firstChild,g=h.nextSibling;return n.addEventListener(`submit`,e=>void u(e)),R(n,O(f,{field:`holder`,label:`Holder`,get hint(){return e.grant?`A grant's holder cannot change: revoke it and create another.`:`@@orchestrator (a reserved role), @name or ses_… (pinned to that session), or app:<token id>`},placeholder:`@@orchestrator`,get disabled(){return!!e.grant}}),r),R(n,O(p,{field:`projects`,label:`Projects`,hint:`Absolute project directories, one per line (subdirectories and worktrees included).`,placeholder:`/home/you/projects/api`}),r),R(r,O(k,{each:gn,children:e=>(()=>{var n=tS(),r=n.firstChild,i=r.nextSibling;return r.addEventListener(`change`,n=>l(`allow`,n.currentTarget.checked?[...t().allow,e]:t().allow.filter(t=>t!==e))),F(r,`aria-label`,e),R(i,e),S(()=>r.checked=t().allow.includes(e)),n})()}),null),R(n,O(d,{field:`allow`}),i),R(n,O(p,{field:`permit`,label:`Permissions it may approve`,hint:`Patterns action[:glob], one per line (e.g. shell:bun test *).`}),i),R(n,O(p,{field:`never`,label:`Never`,hint:`Patterns it may never approve, one per line; never wins.`,placeholder:`shell:rm *`}),i),R(i,O(f,{field:`expires`,label:`Expires after`,get hint(){return e.grant?`From now: saving restarts the countdown.`:`30m, 8h, 2d (at most 30 days)`}}),null),R(i,O(f,{field:`maxActionsPerHour`,label:`Actions per hour`,hint:`1–1000`}),null),c.addEventListener(`change`,e=>l(`allowAlways`,e.currentTarget.checked)),R(n,O(d,{field:`allowAlways`}),m),R(n,O(A,{get when(){return a()},get children(){var e=vS();return R(e,a),e}}),m),R(h,()=>e.grant?`Save`:`Create grant`),rt(g,`click`,e.onClose,!0),S(()=>h.disabled=s()),S(()=>c.checked=t().allowAlways),n}})}function IS(){let[e,t]=x([]),[n,r]=x(),[i,a]=x(`loading`),[o,s]=x(``),c=async e=>{a(`loading`);try{let n=Vn(await H(`/api/agent/audit?limit=${DS}${e===void 0?``:`&before=${e}`}`));t(t=>{if(e===void 0)return n.entries;let r=new Set(t.map(e=>e.seq));return[...t,...n.entries.filter(e=>!r.has(e.seq))]}),r(n.next),a(`ready`)}catch(e){s(G(e)),a(`failed`)}};c();let l=()=>{let t=e()[0]?.seq??0;return[...Eo().filter(e=>e.seq>t),...e()]};return(()=>{var e=CS();return R(e,O(A,{get when(){return i()!==`failed`},get fallback(){return(()=>{var e=wS();return e.firstChild,R(e,o,null),e})()},get children(){return[O(A,{get when(){return l().length||i()!==`ready`},get fallback(){return TS()},get children(){var e=bS();return R(e,O(k,{get each(){return l()},children:e=>{let t=Jn(e);return(()=>{var n=ES(),r=n.firstChild,i=r.firstChild,a=i.firstChild,o=a.nextSibling,s=i.nextSibling,c=s.firstChild,l=r.nextSibling;return R(i,()=>t.who,a),R(o,()=>t.what),R(c,()=>t.result),R(s,(()=>{var e=M(()=>!!t.grant);return()=>e()?` · ${t.grant}`:``})(),null),R(s,(()=>{var e=M(()=>!!t.reason);return()=>e()?` · ${t.reason}`:``})(),null),R(l,()=>oc(e.at,tc())),S(r=>{var i=e.seq,a=`audit-result ${t.tone}`,o=new Date(e.at).toISOString(),s=new Date(e.at).toLocaleString();return i!==r.e&&F(n,`data-seq`,r.e=i),a!==r.t&&I(c,r.t=a),o!==r.a&&F(l,`datetime`,r.a=o),s!==r.o&&F(l,`title`,r.o=s),r},{e:void 0,t:void 0,a:void 0,o:void 0}),n})()}})),e}}),O(A,{get when(){return i()===`loading`},get children(){return xS()}}),O(A,{get when(){return M(()=>i()===`ready`)()&&n()!==void 0},get children(){var e=SS();return e.$$click=()=>void c(n()),e}})]}})),e})()}P([`click`,`input`]);function LS(e,t){let n=Math.max(0,Math.ceil((e-t)/1e3));return`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}`}function RS(e,t){return t.find(t=>!e.has(t.id))}function zS(e,t,n){let r=t?Date.parse(t):NaN;return Number.isFinite(r)?n+Math.max(0,e-r-1e3):e}var BS={L:0,M:1,Q:2,H:3},VS={L:1,M:0,Q:3,H:2},HS=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],US=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],WS=(e,t)=>!!(e>>>t&1);function GS(e){let t=(16*e+128)*e+64;if(e>=2){let n=Math.floor(e/7)+2;t-=(25*n-10)*n-55,e>=7&&(t-=36)}return t}function KS(e,t){let n=BS[t];return Math.floor(GS(e)/8)-HS[n][e]*US[n][e]}function qS(e,t){let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return n}function JS(e){let t=Array(e).fill(0);t[e-1]=1;let n=1;for(let r=0;r<e;r++){for(let e=0;e<t.length;e++)t[e]=qS(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=qS(n,2)}return t}function YS(e,t){let n=t.map(()=>0);for(let r of e){let e=r^n.shift();n.push(0),t.forEach((t,r)=>n[r]^=qS(t,e))}return n}function XS(e,t,n){let r=BS[n],i=US[r][t],a=HS[r][t],o=Math.floor(GS(t)/8),s=i-o%i,c=Math.floor(o/i),l=JS(a),u=[];for(let t=0,n=0;t<i;t++){let r=e.slice(n,n+c-a+(t<s?0:1));n+=r.length;let i=YS(r,l);t<s&&r.push(0),u.push(r.concat(i))}let d=[];for(let e=0;e<u[0].length;e++)u.forEach((t,n)=>{(e!==c-a||n>=s)&&d.push(t[e])});return d}function ZS(e,t,n){let r=[],i=(e,t)=>{for(let n=t-1;n>=0;n--)r.push(e>>>n&1)};i(4,4),i(e.length,t<=9?8:16);for(let t of e)i(t,8);let a=KS(t,n)*8;i(0,Math.min(4,a-r.length)),i(0,(8-r.length%8)%8);for(let e=236;r.length<a;e^=253)i(e,8);let o=[];for(let e=0;e<r.length;e+=8)o.push(r.slice(e,e+8).reduce((e,t)=>e<<1|t,0));return o}var QS=class{version;ecc;size;modules;fixed;constructor(e,t){this.version=e,this.ecc=t,this.size=e*4+17,this.modules=Array.from({length:this.size},()=>Array(this.size).fill(!1)),this.fixed=Array.from({length:this.size},()=>Array(this.size).fill(!1)),this.functionPatterns()}set(e,t,n){this.modules[t][e]=n,this.fixed[t][e]=!0}functionPatterns(){let e=this.size;for(let t=0;t<e;t++)this.set(6,t,t%2==0),this.set(t,6,t%2==0);this.finder(3,3),this.finder(e-4,3),this.finder(3,e-4);let t=this.alignmentPositions(),n=t.length-1;t.forEach((e,r)=>t.forEach((t,i)=>{r===0&&i===0||r===0&&i===n||r===n&&i===0||this.alignment(e,t)})),this.formatBits(0),this.versionBits()}finder(e,t){for(let n=-4;n<=4;n++)for(let r=-4;r<=4;r++){let i=e+r,a=t+n;if(i<0||i>=this.size||a<0||a>=this.size)continue;let o=Math.max(Math.abs(r),Math.abs(n));this.set(i,a,o!==2&&o!==4)}}alignment(e,t){for(let n=-2;n<=2;n++)for(let r=-2;r<=2;r++)this.set(e+r,t+n,Math.max(Math.abs(r),Math.abs(n))!==1)}alignmentPositions(){if(this.version===1)return[];let e=Math.floor(this.version/7)+2,t=Math.floor((this.version*8+e*3+5)/(e*4-4))*2,n=[6];for(let r=this.size-7;n.length<e;r-=t)n.splice(1,0,r);return n}formatBits(e){let t=VS[this.ecc]<<3|e,n=t;for(let e=0;e<10;e++)n=n<<1^(n>>>9)*1335;let r=(t<<10|n)^21522,i=this.size;for(let e=0;e<=5;e++)this.set(8,e,WS(r,e));this.set(8,7,WS(r,6)),this.set(8,8,WS(r,7)),this.set(7,8,WS(r,8));for(let e=9;e<15;e++)this.set(14-e,8,WS(r,e));for(let e=0;e<8;e++)this.set(i-1-e,8,WS(r,e));for(let e=8;e<15;e++)this.set(8,i-15+e,WS(r,e));this.set(8,i-8,!0)}versionBits(){if(this.version<7)return;let e=this.version;for(let t=0;t<12;t++)e=e<<1^(e>>>11)*7973;let t=this.version<<12|e;for(let e=0;e<18;e++){let n=this.size-11+e%3,r=Math.floor(e/3);this.set(n,r,WS(t,e)),this.set(r,n,WS(t,e))}}codewords(e){let t=this.size,n=0;for(let r=t-1;r>=1;r-=2){r===6&&(r=5);for(let i=0;i<t;i++)for(let a=0;a<2;a++){let o=r-a,s=r+1&2?i:t-1-i;!this.fixed[s][o]&&n<e.length*8&&(this.modules[s][o]=WS(e[n>>>3],7-(n&7)),n++)}}}applyMask(e){for(let t=0;t<this.size;t++)for(let n=0;n<this.size;n++){if(this.fixed[t][n])continue;let r;switch(e){case 0:r=(n+t)%2==0;break;case 1:r=t%2==0;break;case 2:r=n%3==0;break;case 3:r=(n+t)%3==0;break;case 4:r=(Math.floor(n/3)+Math.floor(t/2))%2==0;break;case 5:r=n*t%2+n*t%3==0;break;case 6:r=(n*t%2+n*t%3)%2==0;break;default:r=((n+t)%2+n*t%3)%2==0}r&&(this.modules[t][n]=!this.modules[t][n])}}penalty(){let e=this.size,t=this.modules,n=0,r=[];for(let n=0;n<e;n++)r.push(t[n]),r.push(t.map(e=>e[n]));let i=[!0,!1,!0,!0,!0,!1,!0];for(let t of r){let r=1;for(let i=1;i<=e;i++)i<e&&t[i]===t[i-1]?r++:(r>=5&&(n+=r-2),r=1);for(let r=0;r+7<=e;r++){if(!i.every((e,n)=>t[r+n]===e))continue;let a=r>=4&&[1,2,3,4].every(e=>!t[r-e]),o=r+11<=e&&[7,8,9,10].every(e=>!t[r+e]);a&&(n+=40),o&&(n+=40)}}for(let r=0;r<e-1;r++)for(let i=0;i<e-1;i++){let e=t[r][i];e===t[r][i+1]&&e===t[r+1][i]&&e===t[r+1][i+1]&&(n+=3)}let a=t.reduce((e,t)=>e+t.filter(Boolean).length,0),o=e*e;return n+=(Math.ceil(Math.abs(a*20-o*10)/o)-1)*10,n}};function $S(e,t={}){let n=t.ecc??`M`,r=new TextEncoder().encode(e),i=1;for(;4+(i<=9?8:16)+r.length*8>KS(i,n)*8;)if(++i>40)throw Error(`Text too long for a QR code`);let a=new QS(i,n);a.codewords(XS(ZS(r,i,n),i,n));let o=t.mask;if(o===void 0){let e=1/0;for(let t=0;t<8;t++){a.applyMask(t),a.formatBits(t);let n=a.penalty();n<e&&(e=n,o=t),a.applyMask(t)}}if(o===void 0||!Number.isInteger(o)||o<0||o>7)throw Error(`Invalid QR mask`);return a.applyMask(o),a.formatBits(o),{version:i,size:a.size,mask:o,modules:a.modules}}function eC(e,t=4){let n=``;return e.modules.forEach((e,r)=>e.forEach((e,i)=>{e&&(n+=`M${i+t} ${r+t}h1v1h-1z`)})),n}var tC=.8,nC=1.8,rC=.05,iC=`hub.fontScale`,aC=e=>Math.min(nC,Math.max(tC,e)),oC=(e,t)=>Number((Math.round(e/t)*t).toFixed(2));function sC(e){return Number.isFinite(e)?oC(aC(e),rC):1}function cC(e){return e?sC(Number(e)):1}function lC(e,t,n){return sC(!(t>0)||!(n>0)?e:n/t*e)}function uC(e,t){let n=aC((Number.isFinite(e)?e:1)*Math.exp(-t*.01));return Number(n.toFixed(3))}var dC=e=>`${Math.round(e*100)}%`;function fC(e){try{return cC(e.getItem(iC))}catch{return 1}}function pC(e,t){let n=sC(t);try{n===1?e.removeItem(iC):e.setItem(iC,String(n))}catch{}return n}var mC=()=>typeof localStorage>`u`?void 0:localStorage,[hC,gC]=x(mC()?fC(mC()):1),_C=hC;function vC(e){document.documentElement.style.setProperty(`--font-scale`,String(e))}var yC;function bC(e,t={}){let n=t.settle===!1?e:sC(e);gC(n),vC(n),clearTimeout(yC);let r=()=>{let e=mC();if(!e)return;let t=pC(e,n);t!==hC()&&(gC(t),vC(t))};t.settle===!1?yC=setTimeout(r,250):r()}var xC=`.scroller, .home-scroll`,SC=e=>e instanceof Element&&e.closest(xC)!==null;function CC(e=document){vC(hC());let t=new Map,n,r=()=>{let[e,n]=[...t.values()];return e&&n?Math.hypot(e.x-n.x,e.y-n.y):0},i=e=>{e.pointerType===`touch`&&SC(e.target)&&(t.set(e.pointerId,{x:e.clientX,y:e.clientY}),t.size===2&&(n={scale:hC(),distance:r()}))},a=e=>{if(t.has(e.pointerId)&&(t.set(e.pointerId,{x:e.clientX,y:e.clientY}),n&&t.size===2)){let e=lC(n.scale,n.distance,r());e!==hC()&&bC(e,{settle:!1})}},o=e=>{t.delete(e.pointerId)&&t.size<2&&n&&(n=void 0,bC(hC()))},s=e=>{e.touches.length>=2&&SC(e.target)&&e.preventDefault()},c=e=>{e.ctrlKey&&SC(e.target)&&(e.preventDefault(),bC(uC(hC(),e.deltaMode===1?e.deltaY*16:e.deltaY),{settle:!1}))},l,u=e=>{SC(e.target)&&(e.preventDefault(),e.type===`gesturestart`?l=hC():e.type===`gesturechange`&&l!==void 0&&e.scale?bC(lC(l,1,e.scale),{settle:!1}):e.type===`gestureend`&&(l=void 0,bC(hC())))},d=[[`pointerdown`,i,{capture:!0,passive:!0}],[`pointermove`,a,{capture:!0,passive:!0}],[`pointerup`,o,{capture:!0,passive:!0}],[`pointercancel`,o,{capture:!0,passive:!0}],[`touchmove`,s,{capture:!0,passive:!1}],[`wheel`,c,{capture:!0,passive:!1}],[`gesturestart`,u,{capture:!0,passive:!1}],[`gesturechange`,u,{capture:!0,passive:!1}],[`gestureend`,u,{capture:!0,passive:!1}]];for(let[t,n,r]of d)e.addEventListener(t,n,r);return()=>{for(let[t,n,r]of d)e.removeEventListener(t,n,r)}}var wC=[`light`,`system`,`dark`],TC=`hub.theme`;function EC(e){return e===`light`||e===`dark`||e===`system`?e:`system`}function DC(e){return e===`system`?void 0:e}function OC(){try{return EC(localStorage.getItem(TC))}catch{return`system`}}var[kC,AC]=x(OC());function jC(e){let t=DC(e);t?document.documentElement.dataset.theme=t:delete document.documentElement.dataset.theme;try{e===`system`?localStorage.removeItem(TC):localStorage.setItem(TC,e)}catch{}AC(e)}var MC=N(`<section class=settings-section><h2>`),NC=N(`<div class=settings><header class=topbar><h1 class=title>Settings</h1></header><div class=settings-body><nav class=settings-nav aria-label="Settings sections"></nav><div class=settings-content><p class="small muted">Server <!> · v`),PC=N(`<a>`),FC=N(`<span class=badge-pill>`),IC=N(`<div class="small muted">`),LC=N(`<div class=account-card><span aria-hidden=true></span><div class=grow><div><strong></strong></div><div class="small muted">This device: </div></div><button type=button class="btn danger">Sign out`),RC=N(`<h3>Notify me when`),zC=N(`<p class="small notify-summary"data-notify-summary>`),BC=N(`<p class="small warn">These apply once this device is subscribed.`),VC=N(`<p class=activity-hint data-activity-hint><strong>Know what happens with the screen off:</strong> turn on <em>All done</em> for one notification when a session and its subagents finish, or the <em>Activity digest</em> for one quiet, self-replacing summary per session.`),HC=N(`<h4>When`),UC=N(`<ul class=switches><li><label class=switch><span>Quiet hours</span><input type=checkbox>`),WC=N(`<p class="small muted"> muted (⋯ menu of a session → Unmute notifications).`),GC=N(`<p class="small muted">Checking this device…`),KC=N(`<p role=status>`),qC=N(`<dl class="notify-facts small muted"><dt>Permission</dt><dd></dd><dt>Service worker</dt><dd></dd><dt>Subscribed on this hub</dt><dd>`),JC=N(`<button type=button class="btn small primary">Enable notifications on this device`),YC=N(`<button type=button class="btn small">Turn off on this device`),XC=N(`<span class=notify-test><select aria-label="Test notification kind"data-test-kind><option value>Basic test</option></select><button type=button class="btn small">Send test notification`),ZC=N(`<div class=row-actions>`),QC=N(`<option>`),$C=N(`<p data-test-result>`),ew=N(`<section class=notify-group><h4></h4><ul class=switches>`),tw=N(`<div class=quiet-hours><label>At most one per session every <select data-activity-minutes></select></label><span class="small muted">Collapses into one notification per session; respects quiet hours and muted sessions.`),nw=N(`<li><label class=switch><span class=notify-kind><span></span><span class="small muted"></span></span><input type=checkbox>`),rw=N(`<div class=quiet-hours><label>From <input type=time></label><label>to <input type=time></label><span class="small muted">. Hand-offs still come through.`),iw=N(`<ul class=switches><li class=appearance-theme><span id=color-theme>Color theme</span><div class=theme-toggle role=radiogroup aria-labelledby=color-theme></div></li><li class=speed><label for=text-size>Text size</label><input id=text-size type=range><output for=text-size></output><button type=button class="btn small"aria-label="Reset text size">Reset`),aw=N(`<p class="small muted">On this device. Pinch the conversation or the session list to change it too (a trackpad pinch works on desktop).`),ow=N(`<button type=button role=radio class=theme-choice><span>`),sw=N(`<ul class=switches><li class=speed><label for=voice-speed>Voice speed</label><input id=voice-speed type=range><output for=voice-speed></output></li><li><div class=switch><span id=voice-sensitivity>Mic sensitivity</span><div class=chips role=radiogroup aria-labelledby=voice-sensitivity></div></div><p class="small muted">How sure Voice mode must be that you are speaking to it. Low: noisy places (only clear, sustained speech counts). High: quiet rooms and soft voices. On this device; applies at once, also while Voice mode is on.</p></li><li><label class=switch><span>Progress cues</span><input type=checkbox></label><p class="small muted">In Voice mode: a soft tone when the agent hears you, then short, varied acknowledgements while it works (“On it.”, “One moment.”, “I’ll hand that off.”, “Still on it.” …).</p></li><li><label class=switch><span>Keep listening when the screen is off</span><input type=checkbox></label><p class="small muted">Off: the screen stays on while listening. On: lock-screen controls and listening with the screen off. Best effort. Android Chrome usually stops the microphone when the screen turns off; Hub shows when listening is paused and resumes when you unlock. Applies the next time Voice mode starts.`),cw=N(`<button type=button class=chip role=radio>`),lw=N(`<h3>Waiting for approval`),uw=N(`<ul class=list>`),dw=N(`<li><div class=grow><div class=name></div><div class="small muted">Code <!> · requested </div></div><button type=button class="btn small primary">Approve</button><button type=button class="btn small danger">Deny`),fw=N(`<p class="small muted">None. In OpenCode run /hub → Connect to a hub….`),pw=N(`<li><div class=grow><div class=name><span aria-hidden=true></span> </div><div class="small muted"></div></div><button type=button class="btn small danger">Revoke`),mw=N(`<div class=row><p class="small muted grow">Browsers and the Hub app signed in to your account. Add the app on a phone or tablet by scanning a code.</p><button type=button class="btn small">Add app`),hw=N(`<p class="small muted">`),gw=N(`<span class=muted> · this device`),_w=N(`<li><div class=grow><div class=name></div><div class="small muted">last seen </div></div><button type=button class="btn small danger">`),vw=N(`<svg class=qr role=img aria-label="QR code for the app link"shape-rendering=crispEdges><rect width=100% height=100% fill=#fff></rect><path fill=#000>`),yw=N(`<p class="small muted">Expires in <span class=add-app-countdown></span> · single use`),bw=N(`<div class=row><code class="add-app-link grow"></code><button type=button class="btn small">Copy</button><a class="btn small">Open`),xw=N(`<div class=add-app-body><p class=small>In the Hub app, choose <b>Add hub</b> and scan this code, or open the link on the phone with the app. It links the app to your account on <b></b>.</p><p class="small muted">Anyone with this code can sign in as you until it is used or expires; show it only to your own device.`),Sw=N(`<div class=add-app-expired><p class="small warn">This code expired.</p><button type=button class="btn small primary">New code`),Cw=N(`<div class=chips role=group aria-label="Admin sections">`),ww=N(`<p class=error role=alert>`),Tw=N(`<p class="small muted">Approving a machine makes it yours. Someone else's machine: let them approve it from their phone with the code OpenCode shows (/approve?code=…).`),Ew=N(`<span class=count>`),Dw=N(`<button type=button class=chip>`),Ow=N(`<p class=muted>No machines are waiting for approval.`),kw=N(`<div class=stack><div class=row><input type=search class=grow placeholder="Search by email or name"aria-label="Search users"><select aria-label=Show></select><select aria-label="Sort by">`),Aw=N(`<p class=muted>`),jw=N(`<li class=muted>No users match.`),Mw=N(`<span class=badge-pill>Admin`),Nw=N(`<span class="badge-pill off">Disabled`),Pw=N(`<span class=badge-pill>You`),Fw=N(`<li><div class=grow><div class=name></div><div class="small muted"> · <!> · seen `),Iw=N(`<button type=button>`),Lw=N(`<p class=muted>No machines are connected to this hub yet.`),Rw=N(`<li><div class=grow><div class=name><span aria-hidden=true></span> </div><div class="small muted"> · </div></div><button type=button class="btn small danger">Revoke`),zw=N(`<ol class="list audit">`),Bw=N(`<p class=muted>Nothing recorded yet.`),Vw=N(`<li><div class=grow><div class=name></div><div class="small muted"></div></div><time class="small muted">`),Hw=[[`account`,`Account`],[`appearance`,`Appearance`],[`notifications`,`Notifications`],[`voice`,`Voice`],[`speech`,`Speech`],[`machines`,`Machines`],[`devices`,`Devices`],[`agents`,`Agents`],[`admin`,`Admin`]];function Uw(e){return(()=>{var t=MC(),n=t.firstChild;return R(n,()=>e.title),R(t,()=>e.children,null),S(r=>{var i=e.id,a=`h-${e.id}`,o=`h-${e.id}`;return i!==r.e&&F(t,`id`,r.e=i),a!==r.t&&F(t,`aria-labelledby`,r.t=a),o!==r.a&&F(n,`id`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),t})()}function Ww(){E(()=>{let e=no().hash.slice(1);e&&requestAnimationFrame(()=>document.getElementById(e)?.scrollIntoView({block:`start`}))});let e=()=>Hw.filter(([e])=>e!==`admin`||Dt(X()));return(()=>{var t=NC(),n=t.firstChild,r=n.firstChild,i=n.nextSibling.firstChild,a=i.nextSibling,o=a.firstChild,s=o.firstChild.nextSibling;return s.nextSibling,R(n,O(A,{get when(){return Q()},get children(){return O(Xs,{icon:`menu`,label:`Open sidebar`,onClick:du})}}),r),R(i,O(k,{get each(){return e()},children:([e,t])=>(()=>{var n=PC();return n.$$click=t=>(t.preventDefault(),document.getElementById(e)?.scrollIntoView({behavior:`smooth`,block:`start`}),history.replaceState(null,``,`#${e}`)),F(n,`href`,`#${e}`),R(n,t),n})()})),R(a,O(Kw,{}),o),R(a,O(Jw,{}),o),R(a,O(qw,{}),o),R(a,O(Xw,{}),o),R(a,O(Uw,{id:`speech`,title:`Speech`,get children(){return O(Wx,{})}}),o),R(a,O($w,{}),o),R(a,O(eT,{}),o),R(a,O(AS,{}),o),R(a,O(A,{get when(){return Dt(X())},get children(){return O(aT,{})}}),o),R(o,()=>X()?.publicURL??location.origin,s),R(o,()=>X()?.version??`?`,null),t})()}async function Gw(){(Ot(X()).mode!==`pairing`||confirm(`Sign out this device? You will need a new pairing code.`))&&(await(await nl().catch(()=>void 0))?.unsubscribe().catch(()=>{}),await V(`/api/logout`,{method:`POST`,json:{}}).catch(()=>{}),$o(),location.href=`/`)}function Kw(){let e=()=>Ot(X());return O(Uw,{id:`account`,title:`Account`,get children(){var t=LC(),n=t.firstChild,r=n.nextSibling,i=r.firstChild,a=i.firstChild,o=i.nextSibling;o.firstChild;var s=r.nextSibling;return R(n,()=>e().initial),R(a,()=>e().title),R(i,O(A,{get when(){return e().badge},get children(){var t=FC();return R(t,()=>e().badge),t}}),null),R(r,O(A,{get when(){return e().subtitle},get children(){var t=IC();return R(t,()=>e().subtitle),t}}),o),R(o,()=>X()?.device?.name??`paired`,null),s.$$click=()=>void Gw(),S(()=>I(n,`avatar large${e().badge?` admin`:``}`)),t}})}function qw(){let[e,{refetch:t}]=ne(Xc,()=>il()),[n,r]=x(!1),[i,a]=x(),[o,s]=x(``),[c,l]=x(),[u,d]=x(null),[f,p]=x(),m=()=>f()??g()?.activityMinutes??5,h=()=>e()?zc(e().env):void 0,g=()=>e()?.view,_=()=>c()??g()?.prefs,v=()=>c()?u():g()?.quietHours??null,y=async(e,n)=>{r(!0);try{await e(),n&&q(n)}catch(e){q(G(e),`err`)}finally{r(!1),l(void 0),t()}},b=async e=>{try{let t=await(await V(`/api/push/prefs`,{method:`PUT`,json:e})).json();l(t.prefs),d(t.quietHours??null),t.activityMinutes!==void 0&&p(t.activityMinutes)}catch(e){q(G(e),`err`)}},ee=async()=>{a(void 0);try{a(Vc(await cl(o()||void 0)))}catch(e){a({ok:!1,text:G(e)})}};return O(Uw,{id:`notifications`,title:`Notifications`,get children(){return[O(A,{get when(){return h()},get fallback(){return GC()},children:t=>[(()=>{var e=KC();return R(e,()=>t().message),S(n=>{var r=t().warn?`notify-status warn`:`notify-status ok`,i=t().state;return r!==n.e&&I(e,n.e=r),i!==n.t&&F(e,`data-state`,n.t=i),n},{e:void 0,t:void 0}),e})(),(()=>{var t=qC(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling;return R(n,(()=>{var t=M(()=>!!e().env.supported);return()=>t()?e().env.permission:`unsupported`})()),R(r,()=>e().env.worker?`registered`:`not registered`),R(i,()=>e().env.hubSubscribed?`yes`:`no`),t})(),(()=>{var r=ZC();return R(r,O(A,{get when(){return t().action===`enable`},get children(){var e=JC();return e.$$click=()=>void y(ol,`Notifications are on for this device`),S(()=>e.disabled=n()),e}}),null),R(r,O(A,{get when(){return t().action===`disable`},get children(){var e=YC();return e.$$click=()=>void y(sl,`Notifications are off for this device`),S(()=>e.disabled=n()),e}}),null),R(r,O(A,{get when(){return e().env.hubSubscriptions>0},get children(){var e=XC(),t=e.firstChild;t.firstChild;var n=t.nextSibling;return t.addEventListener(`change`,e=>s(e.currentTarget.value)),R(t,O(k,{each:Wc,children:e=>(()=>{var t=QC();return R(t,()=>e.label),S(()=>t.value=e.key),t})()}),null),n.$$click=()=>void ee(),S(()=>t.value=o()),e}}),null),r})(),O(A,{get when(){return i()},children:e=>(()=>{var t=$C();return R(t,()=>e().text),S(()=>I(t,e().ok?`small ok`:`small err`)),t})()})]}),O(A,{get when(){return _()},get children(){return[RC(),(()=>{var e=zC();return R(e,()=>Gc(_())),e})(),O(A,{get when(){return M(()=>!!h())()&&h().state!==`on`},get children(){return BC()}}),O(A,{get when(){return M(()=>`activity`in _()&&!_().activity)()&&!_().done},get children(){return VC()}}),O(k,{each:Uc,children:e=>(()=>{var t=ew(),n=t.firstChild,r=n.nextSibling;return R(n,()=>e.title),R(r,O(k,{get each(){return e.kinds.filter(e=>e.key in _())},children:e=>(()=>{var t=nw(),n=t.firstChild.firstChild,r=n.firstChild,i=r.nextSibling,a=n.nextSibling;return R(r,()=>e.label),R(i,()=>e.description),a.addEventListener(`change`,t=>void b({[e.key]:t.currentTarget.checked})),R(t,O(A,{get when(){return M(()=>e.key===`activity`)()&&_().activity},get children(){var e=tw(),t=e.firstChild.firstChild.nextSibling;return t.addEventListener(`change`,e=>void b({activityMinutes:Number(e.currentTarget.value)})),R(t,O(k,{each:Hc,children:e=>(()=>{var t=QC();return R(t,e===1?`minute`:`${e} minutes`),S(()=>t.value=String(e)),t})()})),S(()=>t.value=String(m())),e}}),null),S(()=>F(a,`data-pref`,e.key)),S(()=>a.checked=!!_()[e.key]),t})()})),S(()=>F(t,`data-notify-group`,e.title)),t})()}),HC(),(()=>{var e=UC(),t=e.firstChild,n=t.firstChild.firstChild.nextSibling;return n.addEventListener(`change`,e=>void b({quietHours:e.currentTarget.checked?{start:`22:00`,end:`07:00`,timeZone:Kc()}:null})),R(t,O(A,{get when(){return v()},children:e=>(()=>{var t=rw(),n=t.firstChild,r=n.firstChild.nextSibling,i=n.nextSibling,a=i.firstChild.nextSibling,o=i.nextSibling,s=o.firstChild;return r.addEventListener(`change`,t=>void b({quietHours:{...e(),start:t.currentTarget.value,timeZone:Kc()}})),a.addEventListener(`change`,t=>void b({quietHours:{...e(),end:t.currentTarget.value,timeZone:Kc()}})),R(o,()=>e().timeZone,s),S(()=>r.value=e().start),S(()=>a.value=e().end),t})()}),null),S(()=>n.checked=!!v()),e})(),O(A,{get when(){return Qc().size},get children(){var e=WC(),t=e.firstChild;return R(e,()=>cc(Qc().size,`session`),t),e}})]}})]}})}function Jw(){return O(Uw,{id:`appearance`,title:`Appearance`,get children(){return[(()=>{var e=iw(),t=e.firstChild,n=t.firstChild.nextSibling,r=t.nextSibling.firstChild.nextSibling,i=r.nextSibling,a=i.nextSibling;return R(n,O(k,{each:wC,children:e=>(()=>{var t=ow(),n=t.firstChild;return t.$$click=()=>jC(e),R(t,e===`light`?`☀`:e===`dark`?`☾`:`▣`,n),R(n,()=>e[0].toUpperCase()+e.slice(1)),S(()=>F(t,`aria-checked`,kC()===e)),t})()})),r.$$input=e=>bC(Number(e.currentTarget.value)),F(r,`min`,tC),F(r,`max`,nC),F(r,`step`,rC),R(i,()=>dC(_C())),a.$$click=()=>bC(1),S(e=>{var t=dC(_C()),n=_C()===1;return t!==e.e&&F(r,`aria-valuetext`,e.e=t),n!==e.t&&(a.disabled=e.t=n),e},{e:void 0,t:void 0}),S(()=>r.value=_C()),e})(),aw()]}})}var Yw={low:`Low`,normal:`Normal`,high:`High`};function Xw(){let[e,t]=x(jp.speed),[n,r]=x(jp.sensitivity);return O(Uw,{id:`voice`,title:`Voice`,get children(){var i=sw(),a=i.firstChild,o=a.firstChild.nextSibling,s=o.nextSibling,c=a.nextSibling,l=c.firstChild.firstChild.nextSibling,u=c.nextSibling,d=u.firstChild.firstChild.nextSibling,f=u.nextSibling.firstChild.firstChild.nextSibling;return o.$$input=e=>{jp.speed=Number(e.currentTarget.value),t(jp.speed)},F(o,`min`,ma),F(o,`max`,2),F(o,`step`,ha),R(s,()=>_a(e())),R(l,O(k,{each:Df,children:e=>(()=>{var t=cw();return t.$$click=()=>{jp.sensitivity=e,r(e)},R(t,()=>Yw[e]),S(r=>{var i=n()===e,a=n()===e;return i!==r.e&&F(t,`aria-checked`,r.e=i),a!==r.t&&F(t,`aria-pressed`,r.t=a),r},{e:void 0,t:void 0}),t})()})),d.addEventListener(`change`,e=>jp.cues=e.currentTarget.checked),f.addEventListener(`change`,e=>jp.background=e.currentTarget.checked),S(()=>F(o,`aria-valuetext`,_a(e()))),S(()=>o.value=e()),S(()=>d.checked=jp.cues),S(()=>f.checked=jp.background),i}})}async function Zw(e,t){try{await V(`/api/enrollments/${U(e.userCode)}/${t}`,{method:`POST`,json:{}}),q(t===`approve`?`${e.machineName} approved; it belongs to you`:`Request denied`)}catch(e){q(G(e),`err`)}os()}function Qw(){return O(A,{get when(){return So().length},get children(){return[lw(),(()=>{var e=uw();return R(e,O(k,{get each(){return So()},children:e=>(()=>{var t=dw(),n=t.firstChild,r=n.firstChild,i=r.nextSibling,a=i.firstChild.nextSibling;a.nextSibling;var o=n.nextSibling,s=o.nextSibling;return R(r,()=>e.machineName),R(i,()=>e.userCode,a),R(i,()=>oc(e.created,tc()),null),o.$$click=()=>void Zw(e,`approve`),s.$$click=()=>void Zw(e,`deny`),t})()})),e})()]}})}function $w(){let e=async e=>{if(confirm(`Revoke ${e.name}? Its OpenCode processes disconnect and it must be connected again.`))try{await V(`/api/machines/${U(e.id)}`,{method:`DELETE`}),q(`${e.name} revoked`)}catch(e){q(G(e),`err`)}};return O(Uw,{id:`machines`,title:`Machines`,get children(){return[O(Qw,{}),O(A,{get when(){return(J.machines??[]).length},get fallback(){return fw()},get children(){var t=uw();return R(t,O(k,{get each(){return J.machines},children:t=>(()=>{var n=pw(),r=n.firstChild,i=r.firstChild,a=i.firstChild;a.nextSibling;var o=i.nextSibling,s=r.nextSibling;return R(i,()=>t.name,null),R(o,(()=>{var e=M(()=>!!t.online);return()=>e()?`online · ${cc(t.processes.length,`OpenCode process`)}`:`offline · seen ${oc(t.lastSeen,tc())}`})()),s.$$click=()=>void e(t),S(e=>{var n=`online-dot${t.online?` on`:``}`,r=`Revoke machine ${t.name}`;return n!==e.e&&I(a,e.e=n),r!==e.t&&F(s,`aria-label`,e.t=r),e},{e:void 0,t:void 0}),n})()})),t}})]}})}function eT(){let[e,{refetch:t,mutate:n}]=ne(()=>H(`/api/devices`).then(e=>e.devices)),[r,i]=x(!1),a=async e=>{if(e.current)return void Gw();if(confirm(`Revoke ${e.name}?`)){try{await V(`/api/devices/${U(e.id)}`,{method:`DELETE`}),q(`${e.name} revoked`)}catch(e){q(G(e),`err`)}t()}};return O(Uw,{id:`devices`,title:`Devices`,get children(){return[(()=>{var e=mw(),t=e.firstChild.nextSibling;return t.$$click=()=>i(!0),e})(),O(A,{get when(){return r()},get children(){return O(nT,{get known(){return new Set((e()??[]).map(e=>e.id))},onLinked:e=>n(e),onClose:()=>{i(!1),t()}})}}),O(A,{get when(){return e()},get fallback(){return(()=>{var t=hw();return R(t,(()=>{var t=M(()=>!!e.error);return()=>t()?G(e.error):`Loading…`})()),t})()},get children(){var t=uw();return R(t,O(k,{get each(){return e()},children:e=>(()=>{var t=_w(),n=t.firstChild,r=n.firstChild,i=r.nextSibling;i.firstChild;var o=n.nextSibling;return R(r,()=>e.name,null),R(r,O(A,{get when(){return e.current},get children(){return gw()}}),null),R(i,()=>oc(e.lastSeen,tc()),null),o.$$click=()=>void a(e),R(o,()=>e.current?`Sign out`:`Revoke`),t})()})),t}})]}})}var tT=2e3;function nT(e){let[t,n]=x(),[r,i]=x(``),[a,o]=x(Date.now()),s=async()=>{i(``);try{let e=await V(`/api/devices/link`,{method:`POST`,json:{}}),t=await e.json(),r=Date.now();o(r),n({...t,expiresAt:zS(t.expiresAt,e.headers.get(`date`),r)})}catch(e){i(G(e))}},c=()=>(t()?.expiresAt??0)<=a(),l=()=>{let e=t();return e?$S(e.url,{ecc:`M`}):void 0},u=setInterval(()=>o(Date.now()),1e3),d=!1,f=setInterval(async()=>{if(!(d||!t()||c())){d=!0;try{let t=(await H(`/api/devices`)).devices,n=RS(e.known,t);n&&(e.onLinked(t),q(`${n.name} linked`),e.onClose())}catch{}finally{d=!1}}},tT);return D(()=>{clearInterval(u),clearInterval(f)}),s(),O(Qs,{open:!0,title:`Add the Hub app`,get onClose(){return e.onClose},class:`add-app`,get children(){return O(A,{get when(){return t()},get fallback(){return(()=>{var e=hw();return R(e,()=>r()||`Creating a link code…`),e})()},children:e=>(()=>{var t=xw(),n=t.firstChild,r=n.firstChild.nextSibling.nextSibling.nextSibling,i=n.nextSibling;return R(r,()=>e().hub),R(t,O(A,{get when(){return!c()},get fallback(){return(()=>{var e=Sw(),t=e.firstChild.nextSibling;return t.$$click=()=>void s(),e})()},get children(){return[(()=>{var e=vw(),t=e.firstChild.nextSibling;return S(n=>{var r=`0 0 ${l().size+8} ${l().size+8}`,i=eC(l(),4);return r!==n.e&&F(e,`viewBox`,n.e=r),i!==n.t&&F(t,`d`,n.t=i),n},{e:void 0,t:void 0}),e})(),(()=>{var t=yw(),n=t.firstChild.nextSibling;return R(n,()=>LS(e().expiresAt,a())),t})(),(()=>{var t=bw(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling;return R(n,()=>e().url),r.$$click=()=>void navigator.clipboard?.writeText(e().url).then(()=>q(`Link copied`),()=>q(`Copy failed`,`err`)),S(()=>F(i,`href`,e().url)),t})()]}}),i),t})()})}})}var rT=(e,t)=>Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[],iT=e=>e.id===`local`?`Hub owner (pairing)`:e.name||e.email||e.id;function aT(){let e=()=>At(X()),[t,n]=x(e()[0]?.[0]??`machines`),[r,i]=x(``),a=async(e,t)=>{try{return await e(),i(``),q(t),!0}catch(e){return i(Ut(e)),q(r(),`err`),!1}};return O(Uw,{id:`admin`,title:`Admin`,get children(){return[(()=>{var r=Cw();return R(r,O(k,{get each(){return e()},children:([e,r])=>(()=>{var a=Dw();return a.$$click=()=>(n(e),i(``)),R(a,r,null),R(a,O(A,{get when(){return e===`approvals`&&So().length},get children(){var e=Ew();return R(e,()=>So().length),e}}),null),S(()=>F(a,`aria-pressed`,t()===e)),a})()})),r})(),O(A,{get when(){return r()},get children(){var e=ww();return R(e,r),e}}),O(A,{get when(){return t()===`users`},get children(){return O(oT,{change:a})}}),O(A,{get when(){return t()===`machines`},get children(){return O(sT,{change:a})}}),O(A,{get when(){return t()===`approvals`},get children(){return[Tw(),O(A,{get when(){return So().length},get fallback(){return Ow()},get children(){return O(Qw,{})}})]}}),O(A,{get when(){return t()===`audit`},get children(){return O(cT,{})}})]}})}function oT(e){let[t,{refetch:n}]=ne(()=>H(`/api/admin/users`).then(e=>rT(e,`users`))),[r,i]=x(``),[a,o]=x(`all`),[s,c]=x(`role`),l=async(t,r)=>{confirm(r.confirm)&&(await e.change(()=>V(`/api/admin/users/${U(t.id)}`,{method:`PUT`,json:r.change}),`${iT(t)}: ${r.label.toLowerCase()} done`)&&t.id===X()?.user?.id&&(_o(void 0),await Po().catch(()=>!1)),n())};return(()=>{var e=kw(),n=e.firstChild.firstChild,u=n.nextSibling,d=u.nextSibling;return n.$$input=e=>i(e.currentTarget.value),u.addEventListener(`change`,e=>o(e.currentTarget.value)),R(u,O(k,{each:Tt,children:([e,t])=>(()=>{var n=QC();return n.value=e,R(n,t),n})()})),d.addEventListener(`change`,e=>c(e.currentTarget.value)),R(d,O(k,{each:wt,children:([e,t])=>(()=>{var n=QC();return n.value=e,R(n,t),n})()})),R(e,O(A,{get when(){return t()},get fallback(){return(()=>{var e=Aw();return R(e,(()=>{var e=M(()=>!!t.error);return()=>e()?`Could not load: ${Ut(t.error)}`:`Loading…`})()),e})()},get children(){var e=uw();return R(e,O(k,{get each(){return Vt(t(),{query:r(),filter:a(),sort:s()})},get fallback(){return jw()},children:e=>(()=>{var n=Fw(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=o.nextSibling;return s.nextSibling,R(i,()=>iT(e),null),R(i,O(A,{get when(){return e.role===`admin`},get children(){return Mw()}}),null),R(i,O(A,{get when(){return e.disabled},get children(){return Nw()}}),null),R(i,O(A,{get when(){return e.id===X()?.user?.id},get children(){return Pw()}}),null),R(r,O(A,{get when(){return M(()=>!!e.name)()&&e.email},get children(){var t=IC();return R(t,()=>e.email),t}}),a),R(a,()=>cc(e.machines??0,`machine`),o),R(a,()=>cc(e.devices??0,`device`),s),R(a,()=>oc(e.lastSeen,tc())||`never`,null),R(n,O(k,{get each(){return Ht(e,t(),X()?.user?.id)},children:t=>(()=>{var n=Iw();return n.$$click=()=>void l(e,t),R(n,()=>t.label),S(()=>I(n,`btn small${t.danger?` danger`:``}`)),n})()}),null),S(()=>I(n,e.disabled?`disabled`:``)),n})()})),e}}),null),S(()=>n.value=r()),S(()=>u.value=a()),S(()=>d.value=s()),e})()}function sT(e){let[t,{refetch:n}]=ne(()=>H(`/api/admin/machines`).then(e=>rT(e,`machines`)));return O(A,{get when(){return t()},get fallback(){return(()=>{var e=Aw();return R(e,(()=>{var e=M(()=>!!t.error);return()=>e()?`Could not load: ${Ut(t.error)}`:`Loading…`})()),e})()},get children(){return O(A,{get when(){return t().length},get fallback(){return Lw()},get children(){var r=uw();return R(r,O(k,{get each(){return t()},children:t=>{let r=t.ownerEmail??(t.ownerID===`local`?`hub owner`:t.ownerID)??`unknown`;return(()=>{var i=Rw(),a=i.firstChild,o=a.firstChild,s=o.firstChild;s.nextSibling;var c=o.nextSibling,l=c.firstChild,u=a.nextSibling;return R(o,()=>t.name,null),R(c,r,l),R(c,()=>t.ownerID===X()?.user?.id?` (you)`:``,l),R(c,(()=>{var e=M(()=>!!t.online);return()=>e()?`online`:`offline · seen ${oc(t.lastSeen,tc())}`})(),null),u.$$click=async()=>{confirm(`Revoke ${t.name} (${r})? Its OpenCode processes disconnect and it must be connected again.`)&&(await e.change(()=>V(`/api/admin/machines/${U(t.id)}`,{method:`DELETE`}),`${t.name} revoked`),n())},S(()=>I(s,`online-dot${t.online?` on`:``}`)),i})()}})),r}})}})}function cT(){let[e]=ne(async()=>{let[e,t,n]=await Promise.all([H(`/api/admin/audit`),H(`/api/admin/users`).then(e=>rT(e,`users`),()=>[]),H(`/api/admin/machines`).then(e=>rT(e,`machines`),()=>[])]),r=[...t.map(e=>({id:e.id,email:e.id===`local`?`hub owner`:e.email,name:e.name})),...n.map(e=>({id:e.id,name:e.name}))];return zt(rT(e,`audit`).length?rT(e,`audit`):rT(e,`entries`),r)});return O(A,{get when(){return e()},get fallback(){return(()=>{var t=Aw();return R(t,(()=>{var t=M(()=>!!e.error);return()=>t()?`Could not load: ${Ut(e.error)}`:`Loading…`})()),t})()},get children(){return O(A,{get when(){return e().length},get fallback(){return Bw()},get children(){var t=zw();return R(t,O(k,{get each(){return e()},children:e=>(()=>{var t=Vw(),n=t.firstChild,r=n.firstChild,i=r.nextSibling,a=n.nextSibling;return R(r,()=>e.action),R(i,()=>e.actor,null),R(i,(()=>{var t=M(()=>!!e.target);return()=>t()?` → ${e.target}`:``})(),null),R(i,(()=>{var t=M(()=>!!e.detail);return()=>t()?` · ${e.detail}`:``})(),null),R(a,()=>oc(e.at,tc())),S(t=>{var n=new Date(e.at).toISOString(),r=new Date(e.at).toLocaleString();return n!==t.e&&F(a,`datetime`,t.e=n),r!==t.t&&F(a,`title`,t.t=r),t},{e:void 0,t:void 0}),t})()})),t}})}})}P([`click`,`input`]);var lT=N(`<span class=badge title="Machines waiting for approval">`),uT=N(`<nav class=sidebar aria-label=Sessions><div class=side-top><a class=brand href=/><span class=brand-name>Hub</span></a></div><div class=side-search><input type=search placeholder="Search sessions"aria-label="Search sessions"></div><a class=side-new href=/new> New session</a><a href=/> All sessions</a><div class=side-head><span>Sessions</span></div><div class=side-scroll></div><div class=side-foot><a class=account href=/settings><span aria-hidden=true></span><span class=account-name>`),dT=N(`<p class=side-empty>`),fT=N(`<a class="icon-btn small">`),pT=N(`<section><div class=side-section-head><span class=side-section-title></span></div><ul class=side-list>`),mT=N(`<span class=jobs-badge>`),hT=N(`<span class=unread-dot role=img aria-label=Unread>`),gT=N(`<a class=side-row-link><span class=side-title>`),_T=N(`<li>`),vT=N(`<span class=side-row-link>`),yT=`hub.sidebar.groupBy`,bT=`hub.sidebar.sort`;function xT(e){let[t,n]=x(``),[r,i]=x(localStorage.getItem(yT)===`machine`?`machine`:`project`),[a,o]=x(localStorage.getItem(bT)===`title`?`title`:`recent`),s=w(()=>ua(Ao(),{query:t(),groupBy:r(),sortBy:a()})),c=()=>{let e=K();return e.name===`session`?e.id:void 0},l=()=>Ot(X()),u=(e,t)=>{e&&(i(e),localStorage.setItem(yT,e)),t&&(o(t),localStorage.setItem(bT,t))};return(()=>{var i=uT(),o=i.firstChild,d=o.firstChild,f=d.firstChild,p=o.nextSibling,m=p.firstChild,h=p.nextSibling,g=h.firstChild,_=h.nextSibling,v=_.firstChild,y=_.nextSibling;y.firstChild;var b=y.nextSibling,x=b.nextSibling.firstChild,ee=x.firstChild,C=ee.nextSibling;return d.$$click=()=>e.phone&&e.onClose(),R(d,O(Ds,{class:`brand-mark`}),f),R(o,O(A,{get when(){return e.phone},get fallback(){return O(Xs,{icon:`sidebar`,label:`Collapse sidebar (⌘B)`,get onClick(){return e.onCollapse}})},get children(){return O(Xs,{icon:`close`,label:`Close sidebar`,get onClick(){return e.onClose}})}}),null),R(p,O(Z,{name:`search`}),m),m.$$keydown=e=>e.key===`Escape`&&n(``),m.$$input=e=>n(e.currentTarget.value),h.$$click=()=>e.phone&&e.onClose(),R(h,O(Z,{name:`plus`}),g),_.$$click=()=>e.phone&&e.onClose(),R(_,O(Z,{name:`home`}),v),R(y,O(Zs,{label:`Group and sort`,items:()=>[{section:`Group by`},{label:`Project`,checked:r()===`project`,run:()=>u(`project`,void 0)},{label:`Server`,checked:r()===`machine`,run:()=>u(`machine`,void 0)},{section:`Sort by`},{label:`Recent activity`,checked:a()===`recent`,run:()=>u(void 0,`recent`)},{label:`Title`,checked:a()===`title`,run:()=>u(void 0,`title`)}]}),null),R(b,O(A,{get when(){return s().length},get fallback(){return(()=>{var e=dT();return R(e,()=>t()?`No sessions match.`:`No sessions yet.`),e})()},get children(){return O(k,{get each(){return s()},children:t=>(()=>{var n=pT(),r=n.firstChild,i=r.firstChild,a=r.nextSibling;return R(i,()=>t.title),R(r,O(A,{get when(){return M(()=>t.kind===`group`)()&&t.machineID},get children(){var e=fT();return R(e,O(Z,{name:`plus`})),S(n=>{var r=`New session in ${t.title}`,i=`New session in ${t.title}`,a=`/new?machine=${encodeURIComponent(t.machineID)}${t.directory?`&dir=${encodeURIComponent(t.directory)}`:``}${t.key?`&key=${encodeURIComponent(t.key)}`:``}`;return r!==n.e&&F(e,`aria-label`,n.e=r),i!==n.t&&F(e,`title`,n.t=i),a!==n.a&&F(e,`href`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),e}}),null),R(a,O(k,{get each(){return t.rows},children:t=>O(ST,{row:t,get active(){return c()===t.id},onPick:()=>e.phone&&e.onClose()})})),S(e=>{var r=`side-section ${t.kind}`,i=t.title;return r!==e.e&&I(n,e.e=r),i!==e.t&&F(n,`aria-label`,e.t=i),e},{e:void 0,t:void 0}),n})()})}})),x.$$click=()=>e.phone&&e.onClose(),R(ee,()=>l().initial),R(C,()=>l().title),R(x,O(A,{get when(){return So().length},get children(){var e=lT();return R(e,()=>So().length),e}}),null),R(x,O(Z,{name:`settings`}),null),S(e=>{var t=`side-link${K().name===`home`?` active`:``}`,n=`Settings (${l().title})`,r=`avatar${l().badge?` admin`:``}`;return t!==e.e&&I(_,e.e=t),n!==e.t&&F(x,`aria-label`,e.t=n),r!==e.a&&I(ee,e.a=r),e},{e:void 0,t:void 0,a:void 0}),S(()=>m.value=t()),i})()}function ST(e){let t=()=>e.row,n=()=>Zp().phase!==`off`&&Zp().sessionID===t().id;return(()=>{var r=_T();return R(r,O(A,{get when(){return!gl(t().id,`sidebar`)},get fallback(){return(()=>{var e=vT();return R(e,O(Ys,{get state(){return t().state}}),null),R(e,O(Du,{get id(){return t().id},get title(){return t().title},place:`sidebar`,class:`side-title`,children:null}),null),e})()},get children(){var n=gT(),r=n.firstChild;return rt(n,`click`,e.onPick,!0),R(n,O(Ys,{get state(){return t().state}}),r),R(n,O(A,{get when(){return pa(t(),Zp())},get children(){return O(Js,{})}}),r),R(r,()=>t().title),R(n,O(Ou,{get id(){return t().id}}),null),R(n,O(A,{get when(){return t().error},children:e=>O(ac,{get text(){return e()}})}),null),R(n,O(A,{get when(){return t().jobs},get children(){var e=mT();return R(e,()=>t().jobs),S(n=>{var r=Ki(t().jobs),i=Ki(t().jobs);return r!==n.e&&F(e,`title`,n.e=r),i!==n.t&&F(e,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),e}}),null),R(n,O(A,{get when(){return t().unread},get children(){return hT()}}),null),S(r=>{var i=ao(t().id),a=e.active?`page`:void 0,o=`${t().title} · ${t().where} · ${t().machineName}${t().error?` · ${t().error}`:``}`;return i!==r.e&&F(n,`href`,r.e=i),a!==r.t&&F(n,`aria-current`,r.t=a),o!==r.a&&F(n,`title`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n}}),null),R(r,O(Zs,{get label(){return`More actions for ${t().title}`},class:`icon-btn small row-more`,items:()=>vl(t(),{open:!1,place:`sidebar`})}),null),S(()=>I(r,`side-row${e.active?` active`:``}${t().unread?` unread`:``}${n()?` voice-here`:``}`)),r})()}P([`click`,`input`,`keydown`]);var CT=N(`<main class=entry><p></p><button type=button class=btn>Retry`),wT=N(`<main class=entry><p class=muted>Loading…`),TT=N(`<div class=drawer-backdrop>`),ET=N(`<div class=voice-strip>`),DT=N(`<div class=conn-banner role=status>Reconnecting to the hub…`),OT=N(`<div role=status aria-live=polite>`),kT=N(`<div><main class=main>`),AT=N(`<button type=button class="btn small">`),jT=N(`<div role=status aria-live=polite><span>`),MT=N(`<header class=topbar><span class="title display">Hub`),NT=N(`<div class=home-shell><div class=home-scroll>`),PT=()=>{let e=K();return{lite:Zp().phase===`off`,...e.name===`session`?{session:e.id}:{}}};function FT(){Go(()=>Zp().phase!==`off`),C(()=>Ko(PT()));let[e,t]=x(``),[n,r]=x(!1),i=async()=>{t(``);try{if(!await Po())return;Yo(PT()),ss(),ul(),r(!0)}catch(e){t(`Cannot reach the hub: ${e.message}`)}};return C(ie(()=>K().name,e=>{e!==`pair`&&!n()&&i(),Q()&&ou(!1)})),C(()=>{!X()&&n()&&K().name!==`pair`&&r(!1)}),C(()=>{let e=K();em.viewing(e.name===`session`?e.id:void 0)}),E(()=>D(CC())),E(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`b`&&(e.preventDefault(),du())};document.addEventListener(`keydown`,e),D(()=>document.removeEventListener(`keydown`,e))}),C(()=>{let e=bu(),t=document.documentElement.style;t.setProperty(`--side-w`,`${e.side}px`),t.setProperty(`--rail-w`,`${e.rail}px`)}),C(()=>{n()&&location.hash===`#speech`&&K().name!==`settings`&&io(`/settings#speech`,{replace:!0})}),[O(Ue,{get children(){return[O(j,{get when(){return M(()=>K().name===`pair`)()&&K()},children:e=>O(Fc,{get next(){return e().next},get error(){return e().error}})}),O(j,{get when(){return e()},get children(){var t=CT(),n=t.firstChild,r=n.nextSibling;return R(n,e),r.$$click=()=>void i(),t}}),O(j,{get when(){return!n()},get children(){return wT()}}),O(j,{get when(){return M(()=>K().name===`approve`)()&&K()},children:e=>O(Lc,{get code(){return e().code}})}),O(j,{when:!0,get children(){var e=kT(),t=e.firstChild;return R(e,O(A,{get when(){return!Q()||au()},get children(){return[O(A,{get when(){return Q()},get children(){var e=TT();return e.$$click=()=>ou(!1),e}}),O(A,{get when(){return!ru()||Q()},get children(){return[O(xT,{get phone(){return Q()},onClose:()=>ou(!1),onCollapse:du}),O(A,{get when(){return!Q()},get children(){return O(Im,{panel:`side`,label:`Resize sidebar`})}})]}})]}}),t),R(t,O(A,{get when(){return M(()=>!!ru())()&&!Q()},get children(){return O(Xs,{icon:`sidebar`,label:`Show sidebar (⌘B)`,class:`expand-sidebar`,onClick:du})}}),null),R(t,O(A,{get when(){return M(()=>Zp().phase!==`off`)()&&K().name!==`session`},get children(){var e=ET();return R(e,O(B_,{})),e}}),null),R(t,O(A,{get when(){return J.connection===`down`},get children(){return DT()}}),null),R(t,O(A,{get when(){return M(()=>J.connection!==`down`)()&&Bo()},get children(){var e=OT();return R(e,()=>Bo()===`reconnecting`?`Reconnecting…`:`Updated`),S(()=>I(e,`sync-note ${Bo()}`)),e}}),null),R(t,O(Ue,{get children(){return[O(j,{get when(){return M(()=>K().name===`session`)()&&K()},keyed:!0,children:e=>O(nx,{get id(){return e.id}})}),O(j,{get when(){return M(()=>K().name===`new`)()&&K()},children:e=>O(Eh,ze(()=>e()))}),O(j,{get when(){return K().name===`settings`},get children(){return O(Ww,{})}}),O(j,{when:!0,get children(){return O(IT,{})}})]}}),null),S(()=>I(e,`shell${ru()&&!Q()?` collapsed`:``}${Q()?` phone`:``}${au()?` drawer`:``}`)),e}})]}}),O(A,{get when(){return co()},children:e=>(()=>{var t=jT(),n=t.firstChild;return R(n,()=>e().text),R(t,O(A,{get when(){return e().action},get children(){var t=AT();return t.$$click=()=>{e().action.run(),fo()},R(t,()=>e().action.label),t}}),null),S(()=>I(t,`toast ${e().kind}`)),t})()})]}function IT(){return(()=>{var e=NT(),t=e.firstChild;return R(e,O(A,{get when(){return Q()},get children(){var e=MT(),t=e.firstChild;return R(e,O(Xs,{icon:`menu`,label:`Open sidebar`,onClick:du}),t),e}}),t),R(t,O(Am,{})),e})()}P([`click`]),et(()=>O(FT,{}),document.getElementById(`root`)),dl();