@huynle/hub 0.10.1 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +80 -0
- package/README.md +36 -8
- package/package.json +1 -1
- package/packages/claude-code/package.json +1 -1
- package/packages/claude-code/src/sessions.ts +4 -1
- package/packages/cli/dist/hub-cli.js +851 -466
- package/packages/cli/package.json +1 -1
- package/packages/cli/src/cli.ts +12 -7
- package/packages/cli/src/decisions.ts +52 -4
- package/packages/cli/src/format.ts +9 -0
- package/packages/cli/src/grants-mcp.ts +65 -0
- package/packages/cli/src/mcp-operations.ts +49 -0
- package/packages/cli/src/mcp.ts +26 -4
- package/packages/cli/src/subscriptions-mcp.ts +76 -0
- package/packages/cli/src/team-intake-mcp.ts +2 -1
- package/packages/cli/src/teams-mcp.ts +9 -3
- package/packages/codex/package.json +1 -1
- package/packages/codex/src/sessions.ts +14 -3
- package/packages/node/package.json +1 -1
- package/packages/preset/package.json +1 -1
- package/packages/protocol/package.json +1 -1
- package/packages/protocol/schema/api/v1/_root.json +119 -0
- package/packages/protocol/schema/api/v1/account.json +419 -0
- package/packages/protocol/schema/api/v1/decisions.json +635 -0
- package/packages/protocol/schema/api/v1/discovery.json +110 -0
- package/packages/protocol/schema/api/v1/events.json +679 -0
- package/packages/protocol/schema/api/v1/session-actions.json +660 -0
- package/packages/protocol/schema/api/v1/sessions.json +2055 -0
- package/packages/protocol/schema/api/v1/speech.json +492 -0
- package/packages/protocol/schema/api/v1/unspecified.json +282 -0
- package/packages/protocol/schema/app-delivery/v1.schema.json +67 -5
- package/packages/protocol/schema/app-front/v1.schema.json +7 -3
- package/packages/protocol/src/api-v1.ts +8 -0
- package/packages/protocol/src/index.ts +2 -0
- package/packages/protocol/src/teams.ts +16 -0
- package/packages/protocol/src/voice-recording.ts +39 -2
- package/packages/runtime-openshell/image/entry.sh +3 -1
- package/packages/runtime-openshell/image/start.sh +3 -1
- package/packages/runtime-openshell/package.json +1 -1
- package/packages/runtime-sdk/package.json +1 -1
- package/packages/sdk/package.json +1 -1
- package/packages/sdk/src/app-front.ts +2 -2
- package/packages/sdk/src/ask-fields.ts +76 -0
- package/packages/sdk/src/client.ts +24 -2
- package/packages/sdk/src/envelope.ts +3 -2
- package/packages/sdk/src/index.ts +1 -0
- package/packages/sdk/src/team-intake.ts +6 -0
- package/packages/sdk/src/teams.ts +4 -0
- package/packages/sdk/src/types.ts +36 -4
- package/packages/sdk/src/wake.ts +9 -4
- package/packages/spoke-sdk/package.json +1 -1
- package/src/central/agent/agent-limits.ts +185 -0
- package/src/central/agent/app-decisions.ts +6 -5
- package/src/central/agent/decisions.ts +136 -9
- package/src/central/agent/delivery.ts +164 -22
- package/src/central/agent/errors.ts +2 -1
- package/src/central/agent/events.ts +20 -2
- package/src/central/agent/grant-routes.ts +14 -1
- package/src/central/agent/grants.ts +23 -0
- package/src/central/agent/launch-engine.ts +9 -6
- package/src/central/agent/message-limits.ts +6 -0
- package/src/central/agent/message-routes.ts +33 -6
- package/src/central/agent/messages.ts +7 -0
- package/src/central/agent/placement.ts +4 -2
- package/src/central/agent/read-routes.ts +5 -0
- package/src/central/agent/routes.ts +13 -0
- package/src/central/agent/subscriptions.ts +15 -4
- package/src/central/api-v1.ts +115 -0
- package/src/central/artifacts/store.ts +4 -2
- package/src/central/concierge/board-results.ts +2 -1
- package/src/central/concierge/notifier.ts +4 -2
- package/src/central/config.ts +24 -3
- package/src/central/health/classify.ts +209 -0
- package/src/central/http.ts +380 -36
- package/src/central/recording/export.ts +57 -3
- package/src/central/recording/index.ts +236 -17
- package/src/central/recording/ingest.ts +11 -2
- package/src/central/recording/routes.ts +61 -7
- package/src/central/recording/schema.ts +68 -3
- package/src/central/recording/settings.ts +19 -5
- package/src/central/recording/store.ts +19 -0
- package/src/central/recording/taps.ts +45 -1
- package/src/central/registry.ts +34 -3
- package/src/central/speech/openai.ts +4 -4
- package/src/central/speech/openrouter.ts +4 -4
- package/src/central/speech/provider.ts +32 -1
- package/src/central/speech/service.ts +6 -5
- package/src/central/teams/budgets.ts +144 -0
- package/src/central/teams/hop-stalls.ts +80 -0
- package/src/central/teams/intake.ts +38 -6
- package/src/central/teams/involvement.ts +95 -0
- package/src/central/teams/item-decisions.ts +60 -0
- package/src/central/teams/item-eligibility.ts +35 -0
- package/src/central/teams/item-stalls.ts +87 -0
- package/src/central/teams/loops.ts +40 -0
- package/src/central/teams/policy.ts +10 -0
- package/src/central/teams/progress.ts +154 -0
- package/src/central/teams/routes.ts +2 -0
- package/src/central/teams/seats.ts +3 -3
- package/src/central/teams/staffing.ts +5 -0
- package/src/central/teams/store.ts +20 -1
- package/src/central/teams/validation.ts +16 -2
- package/src/central/workspaces/coordinator.ts +3 -1
- package/src/spoke/hub-tool.ts +26 -11
- package/web/dist/assets/{ArtifactPage-CsPjam8D.js → ArtifactPage-TbFJi59n.js} +1 -1
- package/web/dist/assets/{ArtifactPane-B9weO8L6.js → ArtifactPane-7D-M-Ich.js} +1 -1
- package/web/dist/assets/{ArtifactWorkbench-DzKhMs3l.js → ArtifactWorkbench-DlCLEjut.js} +1 -1
- package/web/dist/assets/{Diagram-CuRIffka.js → Diagram-PvOPetOI.js} +1 -1
- package/web/dist/assets/{Library-rv5DGtrm.js → Library-Cdi83pOV.js} +2 -2
- package/web/dist/assets/{ProfilesDestination-DUuQ9jmd.js → ProfilesDestination-cryC7P6j.js} +1 -1
- package/web/dist/assets/TeamsPage-B4xrlGhp.js +1 -0
- package/web/dist/assets/Watchtower-60B1JX_J.js +2 -0
- package/web/dist/assets/{artifacts-But87Jfo.js → artifacts-DlQEYmDl.js} +1 -1
- package/web/dist/assets/index-DA0gKIzv.js +33 -0
- package/web/dist/assets/{index-rW6LKQj1.css → index-Dyq-jBeE.css} +1 -1
- package/web/dist/assets/live-B2IfKm37.js +5 -0
- package/web/dist/assets/{live-BUofsQpz.css → live-De-kd3eW.css} +1 -1
- package/web/dist/assets/{pane-layout-BW0RdX5a.js → pane-layout-BAuu_pA3.js} +1 -1
- package/web/dist/assets/{renderer2d-DyANQ1WS.js → renderer2d-CsZnF3_o.js} +1 -1
- package/web/dist/assets/{renderer3d-vYYKFAJq.js → renderer3d-BIMA0wFn.js} +2 -2
- package/web/dist/assets/{safe-area-B2Bk__FK.js → safe-area-dtrnw9NF.js} +1 -1
- package/web/dist/assets/{silero-worker-e802lB5T.js → silero-worker-CC2etKS3.js} +1 -1
- package/web/dist/assets/{source-C-De8L3s.js → source-GYayxUxS.js} +1 -1
- package/web/dist/assets/{toast-CXTwTvDw.js → toast-q818mjUF.js} +1 -1
- package/web/dist/index.html +5 -5
- package/web/dist/assets/TeamsPage-D_17MkvN.js +0 -1
- package/web/dist/assets/Watchtower-DlrNOJ7X.js +0 -2
- package/web/dist/assets/index-bX8B6NLo.js +0 -33
- package/web/dist/assets/live-BGLA-peO.js +0 -5
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Diagram-PvOPetOI.js","assets/ui-CFB4wQfF.js","assets/MediaImage-Ch3ryIdR.js","assets/preload-helper-BLdHbfdN.js","assets/Lightbox-BlbivCkd.js","assets/Lightbox-C8KNKwOA.css","assets/Diagram-7y8kg3og.css","assets/ArtifactPane-7D-M-Ich.js","assets/ArtifactWorkbench-DlCLEjut.js","assets/toast-q818mjUF.js","assets/artifacts-DlQEYmDl.js","assets/pane-layout-BAuu_pA3.js","assets/source-GYayxUxS.js","assets/ArtifactWorkbench-9eTj1CeW.css","assets/Library-Cdi83pOV.js","assets/Library-DYsFj_5c.css","assets/TeamsPage-B4xrlGhp.js","assets/plural-Bspvoqfq.js","assets/live-B2IfKm37.js","assets/live-De-kd3eW.css","assets/Watchtower-60B1JX_J.js","assets/Watchtower-RphjcL0_.css","assets/ProfilesDestination-cryC7P6j.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as v,S as y,T as b,U as x,V as S,W as C,X as w,Y as T,Z as E,_ as D,a as O,b as k,c as A,d as j,et as M,f as N,g as ee,h as P,i as F,j as te,k as I,l as ne,m as re,n as ie,nt as ae,o as oe,p as se,q as ce,r as L,rt as le,s as ue,t as de,tt as R,u as z,v as fe,w as pe,x as B,y as V,z as me}from"./ui-CFB4wQfF.js";import{$ as he,A as ge,At as _e,B as H,Bt as ve,C as ye,Ct as be,D as xe,Dt as Se,E as Ce,Et as we,F as Te,Ft as Ee,G as U,Gt as De,H as W,Ht as Oe,It as ke,J as Ae,Jt as je,K as Me,Kt as Ne,L as Pe,Lt as Fe,M as Ie,Mt as Le,N as Re,Nt as ze,O as Be,Ot as Ve,P as He,Pt as Ue,Q as We,R as G,Rt as Ge,S as Ke,St as qe,T as Je,Tt as Ye,U as K,Ut as Xe,V as q,Vt as Ze,W as Qe,Wt as $e,X as et,Xt as tt,Y as nt,Yt as rt,Z as it,_ as at,_t as ot,at as st,b as ct,bt as lt,c as ut,ct as dt,d as ft,dt as pt,et as mt,f as ht,ft as gt,g as _t,gt as vt,h as yt,ht as bt,i as xt,it as St,j as Ct,jt as wt,k as Tt,kt as Et,l as Dt,lt as Ot,m as kt,mt as At,n as jt,nt as Mt,o as Nt,ot as Pt,p as Ft,pt as It,q as Lt,qt as Rt,r as J,rt as zt,s as Bt,st as Vt,t as Ht,tt as Ut,u as Wt,ut as Gt,v as Kt,vt as qt,w as Jt,wt as Yt,x as Xt,xt as Zt,y as Qt,yt as $t,z as en,zt as tn}from"./toast-q818mjUF.js";import{c as nn,d as rn,f as an,g as on,h as sn,i as cn,l as ln,m as un,n as dn,o as fn,r as pn,s as mn,t as hn}from"./pane-layout-BAuu_pA3.js";import{t as gn}from"./plural-Bspvoqfq.js";import{a as _n,c as vn,i as yn,l as bn,o as xn,r as Sn,s as Cn,t as wn,u as Tn}from"./artifacts-DlQEYmDl.js";import{_ as En,a as Dn,b as On,d as kn,f as An,g as jn,h as Mn,m as Nn,n as Pn,o as Fn,p as In,r as Ln,t as Rn,x as zn,y as Bn}from"./MediaImage-Ch3ryIdR.js";import{t as Vn}from"./preload-helper-BLdHbfdN.js";(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 Hn=e=>e==null?``:String(e).trim(),Un=Object.freeze([[`role`,`Admins first`],[`email`,`Email`],[`lastSeen`,`Last seen`]]),Wn=Object.freeze([[`all`,`All`],[`admins`,`Admins`],[`active`,`Active`],[`disabled`,`Disabled`]]),Gn=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`,"app-client.create":`Registered an app client`,"app-client.update":`Changed an app client`,"app-client.secret":`Rotated an app client's secret`,"app-client.delete":`Deleted an app client`,"connect.authorize":`An app asked to connect`,"connect.consent":`Connected an app`,"connect.deny":`Denied an app`,"connect.token":`Issued a connected app's tokens`,"connect.reuse":`Revoked a connected app (token reuse)`,"connect.revoke":`Revoked a connected app`});function Kn(e){return e?.user?.role===`admin`}function qn(e){let t=e?.user,n=e?.auth===`oidc`?`oidc`:`pairing`,r=Kn(e);if(n!==`oidc`)return{mode:n,admin:r,title:`This hub`,initial:`H`};let i=Hn(t?.name),a=Hn(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 Jn=Object.freeze([[`users`,`Users`],[`machines`,`Machines`],[`approvals`,`Approvals`],[`audit`,`Audit log`],[`agent-limits`,`Agent limits`]]);function Yn(e){return Kn(e)?Jn.filter(([t])=>t!==`users`||e?.auth===`oidc`):[]}function Xn(e,t){return Kn(e)&&t?.scope===`user`?[`user`,`default`]:[`user`]}function Zn(e){return e&&e.startsWith(`/`)&&!e.startsWith(`//`)&&!e.includes(`\\`)?e:`/`}function Qn(e,t){if(e?.mode===`oidc`&&typeof e.signIn==`string`&&e.signIn)return`${e.signIn}?next=${encodeURIComponent(Zn(t))}`}function $n(e){let t=e?.auth===`oidc`?Hn(e?.user?.email):``;return t?`This machine will belong to you (${t}).`:`This machine will belong to you.`}var er={stt:[`provider`,`model`,`baseURL`,`language`],tts:[`provider`,`model`,`voice`,`baseURL`,`speed`]};function tr(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 er[e]){let n=r?s[t]===void 0||s[t]===null:Hn(a[t])===Hn(o[t]),l=Hn(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 nr(e){return{[e]:Object.fromEntries([...er[e],`apiKey`].map(e=>[e,null]))}}function rr(e){let t=Hn(e);if(!t)return`Unknown action`;if(Gn[t])return Gn[t];let n=t.replace(/[._-]+/g,` `).trim().toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)}function ir(e,t=[]){let n=new Map(t.map(e=>[e.id,Hn(e.email)||Hn(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:rr(e.action),target:e.target===void 0?void 0:n.get(e.target)??e.target,detail:e.detail}))}var ar=e=>(Hn(e.email)||Hn(e.name)||e.id).toLowerCase();function or(e,{query:t=``,filter:n=`all`,sort:r=`role`}={}){let i=Hn(t).toLowerCase(),a=e=>(!i||`${Hn(e.email)} ${Hn(e.name)}`.toLowerCase().includes(i))&&(n===`admins`?e.role===`admin`:n===`disabled`?!!e.disabled:n!==`active`||!e.disabled),o=(e,t)=>ar(e).localeCompare(ar(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 sr(e,t,n){let r=Hn(e.email)||Hn(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 cr(e){let t=Hn(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 lr=1e4,ur=/^[1-9][0-9]*$/;function dr(e,t){let n=Number(e.ceiling.trim());if(!ur.test(e.ceiling.trim())||n>lr)return{ok:!1,field:`ceiling`,error:`The hop ceiling is a whole number from 1 to ${lr}`};let r=Number(e.hop.trim());if(!ur.test(e.hop.trim()))return{ok:!1,field:`hop`,error:`The hop limit is a whole number of at least 1`};if(r>n)return{ok:!1,field:`hop`,error:`The hop limit is above the hop ceiling (${n}): lower it, or raise the ceiling`};let i=e.lost.trim(),a={maxQueued:Number(e.maxQueued),maxActive:Number(e.maxActive),perHour:Number(e.perHour),...i?{lostAfterMinutes:i!==`false`&&Number(i)}:{}},o=n>t.hopCeiling;return{ok:!0,body:{revision:t.revision,hopLimit:r,hopCeiling:n,...o?{confirm:!0}:{},launches:a},...o?{confirm:`Raise the hop ceiling from ${t.hopCeiling} to ${n}? Agent-only chains can then run up to ${n} hops without you.`}:{}}}var fr=Symbol(`store-raw`),pr=Symbol(`store-node`),mr=Symbol(`store-has`),hr=Symbol(`store-self`);function gr(e){let t=e[te];if(!t&&(Object.defineProperty(e,te,{value:t=new Proxy(e,wr)}),!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 _r(e){let t;return typeof e==`object`&&!!e&&(e[te]||!(t=Object.getPrototypeOf(e))||t===Object.prototype||Array.isArray(e))}function vr(e,t=new Set){let n,r,i,a;if(n=e!=null&&e[fr])return n;if(!_r(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=vr(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=vr(i,t))!==i&&(e[a]=r))}return e}function yr(e,t){let n=e[t];return n||Object.defineProperty(e,t,{value:n=Object.create(null)}),n}function br(e,t,n){if(e[t])return e[t];let[r,i]=u(n,{equals:!1,internal:!0});return r.$=i,e[t]=r}function xr(e,t){let n=Reflect.getOwnPropertyDescriptor(e,t);return!n||n.get||!n.configurable||t===te||t===pr||(delete n.value,delete n.writable,n.get=()=>e[te][t]),n}function Sr(e){w()&&br(yr(e,pr),hr)()}function Cr(e){return Sr(e),Reflect.ownKeys(e)}var wr={get(e,t,n){if(t===fr)return e;if(t===te)return n;if(t===p)return Sr(e),n;let r=yr(e,pr),i=r[t],a=i?i():e[t];if(t===pr||t===mr||t===`__proto__`)return a;if(!i){let n=Object.getOwnPropertyDescriptor(e,t);w()&&(typeof a!=`function`||Object.prototype.hasOwnProperty.call(e,t))&&!(n&&n.get)&&(a=br(r,t,a)())}return _r(a)?gr(a):a},has(e,t){return t===fr||t===te||t===p||t===pr||t===mr||t===`__proto__`||(w()&&br(yr(e,mr),t)(),t in e)},set(){return!0},deleteProperty(){return!0},ownKeys:Cr,getOwnPropertyDescriptor:xr};function Tr(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[mr]&&e[mr][t]&&i!==void 0&&e[mr][t].$()):(e[t]=n,e[mr]&&e[mr][t]&&i===void 0&&e[mr][t].$());let o=yr(e,pr),s;if((s=br(o,t,i))&&s.$(()=>n),Array.isArray(e)&&e.length!==a){for(let t=e.length;t<a;t++)(s=o[t])&&s.$();(s=br(o,`length`,a))&&s.$(e.length)}(s=o[hr])&&s.$()}function Er(e,t){let n=Object.keys(t);for(let r=0;r<n.length;r+=1){let i=n[r];Dr(i)||Tr(e,i,t[i])}}function Dr(e){return e===`__proto__`||e===`constructor`||e===`prototype`}function Or(e,t){if(typeof t==`function`&&(t=t(e)),t=vr(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&&Tr(e,n,r)}Tr(e,`length`,r)}else Er(e,t)}function kr(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&&Dr(r)))return;if(Array.isArray(r)){for(let i=0;i<r.length;i++)kr(e,[r[i]].concat(t),n);return}if(o&&a===`function`){for(let i=0;i<e.length;i++)r(e[i],i)&&kr(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)kr(e,[r].concat(t),n);return}if(t.length>1){kr(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=vr(a),r===void 0||_r(i)&&_r(a)&&!Array.isArray(a)?Er(i,a):Tr(e,r,a))}function Ar(...[e,t]){let n=vr(e||{}),r=Array.isArray(n),i=gr(n);function a(...e){me(()=>{r&&e.length===1?Or(n,e[0]):kr(n,e)})}return[i,a]}var jr=Symbol(`store-root`);function Mr(e){return e===`__proto__`||e===`constructor`||e===`prototype`}function Nr(e,t,n,r,i){if(Mr(n))return;let a=t[n];if(e===a)return;let o=Array.isArray(e);if(n!==jr&&(!_r(e)||!_r(a)||o!==Array.isArray(a)||i&&e[i]!==a[i])){Tr(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++)Nr(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++)Tr(a,n,e[n]);for(;n<e.length;n++)Tr(a,n,f[n]),Nr(e[n],a,n,r,i);a.length>e.length&&Tr(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?(Tr(a,n,f[n]),Nr(e[n],a,n,r,i)):Tr(a,n,e[n])}else for(let t=0,n=e.length;t<n;t++)Nr(e[t],a,t,r,i);a.length>e.length&&Tr(a,`length`,e.length);return}let s=Object.keys(e);for(let t=0,n=s.length;t<n;t++)Mr(s[t])||Nr(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&&Tr(a,c[t],void 0)}function Pr(e,t={}){let{merge:n,key:r=`id`}=t,i=vr(e);return e=>{if(!_r(e)||!_r(i))return i;let t=Nr(i,{[jr]:e},jr,n,r);return t===void 0?e:t}}var Fr=new WeakMap,Ir={get(e,t){if(t===fr)return e;let n=e[t];if(t===te||t===p||t===pr||t===mr||t===`__proto__`)return n;let r;return _r(n)?Fr.get(n)||(Fr.set(n,r=new Proxy(n,Ir)),r):n},set(e,t,n){return Tr(e,t,vr(n)),!0},deleteProperty(e,t){return Tr(e,t,void 0,!0),!0}};function Lr(e){return t=>{if(_r(t)){let n;(n=Fr.get(t))||Fr.set(t,n=new Proxy(t,Ir)),e(n)}return t}}var Rr={blocked:0,working:1,error:2,idle:3},zr=e=>Rr[e]??3,Br=e=>String(e??``).replace(/(.)[\\/]+$/,`$1`);function Vr(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 Rr?e.state:`idle`}function Hr(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 Ur(e){let t=`idle`;for(let n of e)zr(n)<Rr[t]&&(t=n);return t}function Wr(e){if(!e)return;if(e.kind===`thinking`)return`Thinking…`;let t=e.tool||`tool`;return e.summary?`${t} · ${e.summary}`:t}function Gr(e){return String(e??``).normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase()}var Kr=e=>Gr(e).split(/\s+/).filter(Boolean);function qr(e,t){let n=Kr(t);if(!n.length)return!0;let r=[e.title||`Untitled`,e.projectName,e.project,e.directory].filter(Boolean).map(Gr);return n.every(e=>r.some(t=>t.includes(e)))}function Jr(e,t){let n=Br(e),r=Br(t);return n===r?``:n.startsWith(`${r}/`)?n.slice(r.length+1):n}var Yr=e=>String(e??``).replace(/(.)[\\/]+$/,`$1`),Xr=e=>Yr(e).split(/[\\/]/).pop()||String(e??``),Zr=[`hiddenSessions`,`hiddenWorkspaces`,`pinnedSessions`,`pinnedWorkspaces`],Qr=500,$r=5e3,ei=4096,ti=e=>e===`hiddenSessions`?$r:Qr,ni=(e,t=Qr)=>{if(!Array.isArray(e))return[];let n=[...new Set(e.filter(e=>typeof e==`string`&&e.length>0&&e.length<=ei))];return n.length>t?n.slice(n.length-t):n};function ri(e){let t=e,n=t&&typeof t==`object`&&t.prefs&&typeof t.prefs==`object`?t.prefs:e??{};return Object.fromEntries(Zr.map(e=>[e,ni(n[e],ti(e))]))}function ii(e){let t=e.trim();return t?t.length>200?{error:`Title is longer than 200 characters`}:{title:t}:{error:`Enter a title`}}function ai(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 oi=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=si(e,n);a===r||t-i>this.graceMs?this.pending.delete(n):a!==void 0&&ai(e,n,r)}}},si=(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 ci(e,t,n,r){if(!Zr.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?ni([...i,...o],ti(t)):i.filter(e=>!o.has(e));return{prefs:{...e,[t]:s},patch:{[t]:s}}}var li=e=>{try{let t=JSON.parse(e??`null`);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}};function ui(e,t,n){let r=e!=null||t!=null,i={};for(let[r,a]of[[`pinnedSessions`,e],[`pinnedWorkspaces`,t]]){let e=n[r]??[],t=li(a).filter(t=>!e.includes(t));t.length&&(i[r]=ni([...e,...t]))}return{clear:r,patch:Object.keys(i).length?i:void 0}}var di={working:`working`,blocked:`blocked`};function fi(e){let t=Vr(e);return Ur([t,e?.terminal?.status===`blocked`&&t!==`blocked`?`working`:di[e?.terminal?.status??``]??`idle`])}function pi(e){return e?.terminal?.status===`blocked`&&Vr(e)!==`blocked`}var mi=e=>!!e?.open&&e.terminal?.source===`herdr`&&!!e.terminal.workspaceID,hi=e=>Yr(e?.project||e?.directory);function gi(e){return mi(e)?`herdr:${e.terminal.workspaceID}`:hi(e)}var _i=(e,t)=>hi(e)===t||Yr(e.directory)===t||mi(e)&&gi(e)===t;function vi(e,t){if(t.sessions.has(e.id))return!0;for(let n of t.workspaces)if(_i(e,n))return!0;return!1}function yi(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 bi(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?yi(e,t):t)}return[...r.values()]}function xi(e){let t=Si(e);return e=>vi(e,t)}var Si=e=>({sessions:new Set(e?.hiddenSessions??[]),workspaces:new Set(e?.hiddenWorkspaces??[])}),Ci=e=>e?.terminals?.herdr?.workspaces??[];function wi(e){let t=Yr(e.project||e.directory),n=e.project?Jr(e.directory,t):``;return`${e.projectName||Xr(t)}${n?` › ${n}`:``}`}function Ti(e,t,n){let r=wi(t),i=n?.trim()||void 0;return{machine:e,where:r,...i?{branch:i}:{},text:[e,r,i].filter(Boolean).join(` · `)}}function Ei(e,t,n){let r=mi(e)?e.terminal.workspace||Ci(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:fi(e),waitingInTerminal:pi(e),blockers:Hr(e),exposed:e.exposed!==!1,pinned:n.has(e.id),nowText:Wr(e.now),where:wi(e),workspace:r??(e.projectName||Xr(hi(e))),machineID:t?.id}}var Di=50,Oi=200;function ki(e){let t=Ci(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(Yr))),r=bi(e),i=new Map,a=new Map;for(let e of r){let t=Yr(e.directory);t&&(i.set(t,Math.max(i.get(t)??0,e.updated??0)),a.set(t,wi(e)))}for(let e of r){let t=Yr(e.project);if(!t||a.has(t))continue;let n=Math.max(...r.filter(e=>Yr(e.project)===t).map(e=>e.updated??0));i.set(t,n),a.set(t,e.projectName||Xr(t))}let o=[...i.entries()].filter(([e])=>!n.has(e)).sort((e,t)=>t[1]-e[1]).slice(0,Di).map(([e])=>({kind:`folder`,key:e,label:a.get(e)??Xr(e),directories:[e]}));return{herdr:!!e?.terminals?.herdr,targets:[...t,...o]}}function Ai({target:e,directory:t,title:n,openInHerdr:r}){let i={directory:t},a=String(n??``).trim().slice(0,Oi);return a&&(i.title=a),r&&e?.kind===`herdr`&&e.workspaceID&&(i.herdrWorkspace=e.workspaceID),i}function ji(e){if(typeof e==`string`&&e)return e.includes(`budget`)?`Quota exceeded`:Mi[e]}var Mi={"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 Ni(e){return typeof e==`number`&&Number.isInteger(e)&&e>=100&&e<=999?`HTTP ${e}`:void 0}function Pi(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 Fi=e=>typeof e==`string`&&e.trim()?e.trim():void 0,Ii=(e,t)=>e.toLowerCase()===t.toLowerCase(),Li=(e,t)=>e&&t&&!Ii(e,t)?t:void 0;function Ri(e){let t=ji(e.errorType),n=Fi(e.message),r=Ni(e.errorStatus),i=Li(t,n);return`${t??n??`Error`}${r?` (${r})`:``}${i?`: ${i}`:``}`}function zi(e,t){let n=typeof e.attempt==`number`?` (attempt ${e.attempt})`:``,r=Pi(e.next,t),i=ji(e.errorType),a=Fi(e.message),o=Li(i,a),s=i?o?`${i} — ${o}`:i:a;return`Retrying${n}${r?` · next in ${r}`:``}${s?`: ${s}`:``}`}var Bi=e=>!!e&&typeof e==`object`&&typeof e.id==`string`;function Vi(e,t){let n=Array.isArray(e)?e.filter(Bi):[],r=t?n.find(e=>e.id===t):n[0];if(!r)return;if(r.state===`error`)return Hi(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?Hi(a):void 0}function Hi(e){let t=Fi(e.detail),n=Ni(e.errorStatus),r=Fi(e.title);return{sessionID:e.id,...r?{title:r}:{},label:ji(e.errorType)??t??`Error`,...t?{message:t}:{},...n?{status:n}:{},text:Ri({errorType:e.errorType,errorStatus:e.errorStatus,message:t})}}var Ui=e=>Array.isArray(e)?e:[];function Wi(e){return Ui(e).flatMap(e=>(Array.isArray(e.jobs)?e.jobs:[]).map(t=>({...t,sessionID:e.id,sessionTitle:e.title??``})))}function Gi(e){return Wi(e).filter(e=>e.status===`running`).length}function Ki(e,t){let n=Wi(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 qi(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 Ji(e,t){if(e.status===`running`)return e.started===void 0?`running`:`running · ${qi(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?qi(e.ended-e.started):void 0;return n?[n,r].filter(Boolean).join(` · `):[r??`ended`,i].filter(Boolean).join(` · `)}function Yi(e){return e<=0?``:`${e} job${e===1?``:`s`}`}function Xi(e,t,n=Date.now()){let r=Ui(e),i=(t?r.find(e=>e.id===t&&e.retry):void 0)??r.find(e=>e.retry);return i?.retry?zi(i.retry,n):void 0}var Zi=[`prompt-tui`,`prompt-web`,`voice`,`answer`,`view`],Qi=36e5,$i=24*Qi,ea=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ta=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0;function na(e){if(!ea(e))return;let t=Array.isArray(e.buckets)?e.buckets.filter(e=>Array.isArray(e)&&e.length===4&&e.every(ta)):[];return{...ta(e.at)?{at:e.at}:{},...Zi.includes(e.kind)?{kind:e.kind}:{},...ta(e.last)?{last:e.last}:{},buckets:t.map(e=>[e[0],e[1],e[2],e[3]])}}function ra(e){let t={};if(!ea(e))return t;for(let[n,r]of Object.entries(e)){let e=na(r);e&&(t[n]=e)}return t}var ia=(e,t)=>t-e[0]<$i&&e[0]<=t;function aa(e,t){let n=Array.from({length:24},()=>({human:0,agent:0}));for(let r of e??[]){if(!ia(r,t))continue;let e=n[23-Math.floor((t-r[0])/Qi)];e.human+=r[1],e.agent+=r[2]+r[3]}return n}function oa(e,t){let n=0,r=0,i=0;for(let a of e??[])ia(a,t)&&(n+=a[1],r+=a[2],i+=a[3]);return{human:n,turns:r,tools:i}}var sa=(e,t)=>{let n=oa(e,t);return n.human+n.turns+n.tools},ca=(e,t)=>`${e} ${t}${e===1?``:`s`}`;function la(e){return!e.human&&!e.turns&&!e.tools?`No activity in the last 24 h`:`You: ${ca(e.human,`action`)} · Agent: ${ca(e.turns,`turn`)} / ${ca(e.tools,`tool`)} in the last 24 h`}var ua={"prompt-tui":`typed`,"prompt-web":`prompted`,voice:`spoke`,answer:`answered`,view:`opened`},da=(e,t)=>{let n=Math.max(0,Math.round((t-e)/1e3));return n<60?void 0:n<3600?`${Math.round(n/60)}m`:n<86400?`${Math.round(n/3600)}h`:`${Math.round(n/86400)}d`};function fa(e,t,n){let r=da(t,n),i=r?`${r} ago`:`just now`;return e?`You ${ua[e]} ${i}`:`You ${i}`}function pa(e,t,n){return`${e?ua[e]:`touched`} ${da(t,n)??`now`}`}function ma(e,t,n,r=new Set,i={}){let a=new Set(t.pinnedSessions),o=new Set(t.hiddenSessions),s=xi(t),c=[];for(let t of e??[])for(let e of bi(t)){if(r.has(e.id))continue;let l=Ei(e,t,a),u=l.open?l.terminal?.source===`herdr`?`herdr`:`tui`:`background`,d=n[l.id],f=l.state===`working`?Xi(e.status,void 0,1/0):void 0,p=l.state===`error`?Vi(e.status,l.id)?.text??`Error`:void 0,m=i.activity?.[l.id],h=i.intents?.[l.id]?.text;c.push({...l,machineName:t.name,machineOnline:!!t.online,source:u,running:l.state===`working`||l.state===`blocked`,hidden:s(e),archived:o.has(l.id),unread:d!==void 0&&l.updated>d,group:gi(e),jobs:Gi(e.status),...f?{retry:f}:{},...p?{error:p}:{},...m?.at===void 0?{}:{touchedAt:m.last??m.at},...m?.at!==void 0&&m.kind?{touchedKind:m.kind,touchedKindAt:m.at}:{},...m?.buckets.length?{meter:m.buckets}:{},...h?{intent:h}:{}})}return c.sort((e,t)=>t.updated-e.updated)}function ha(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 ga=[`1h`,`24h`,`7d`],_a={"1h":36e5,"24h":864e5,"7d":6048e5},va=Object.freeze({query:``,filters:Object.freeze({status:`all`,source:`all`,machine:``,archived:!1,touched:``}),sort:Object.freeze({key:`activity`,dir:`desc`})}),ya=[`status`,`title`,`project`,`server`,`source`,`activity`,`touched`,`busy`],ba=[`all`,`needs`,`running`,`idle`],xa=[`all`,`open`,`background`],Sa=(e,t)=>e.localeCompare(t,void 0,{sensitivity:`base`}),Ca=(e,t)=>t.updated-e.updated,wa=e=>e.touchedAt??-1/0,Ta=e=>({status:(e,t)=>Rr[e.state]-Rr[t.state]||Ca(e,t),title:(e,t)=>Sa(e.title,t.title)||Ca(e,t),project:(e,t)=>Sa(e.workspace,t.workspace)||Ca(e,t),server:(e,t)=>Sa(e.machineName,t.machineName)||Ca(e,t),source:(e,t)=>Sa(e.source,t.source)||Ca(e,t),activity:(e,t)=>e.updated-t.updated,touched:(e,t)=>wa(e)-wa(t)||e.updated-t.updated,busy:(t,n)=>sa(t.meter,e)-sa(n.meter,e)||t.updated-n.updated});function Ea(e,t,n){if(t.touched&&(e.touchedAt===void 0||n-e.touchedAt>_a[t.touched]))return!1;let r=t.status===`needs`&&e.state===`blocked`;return!((t.archived?!e.hidden:e.hidden&&!r)||t.status===`needs`&&!Ma(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 Da(e,t){if(!t.trim()||qr(e,t))return!0;let n=Gr(t).split(/\s+/).filter(Boolean),r=[e.title,e.workspace,e.where,e.directory,e.machineName].map(Gr);return n.every(e=>r.some(t=>t.includes(e)))}function Oa(e,t,n=Date.now()){let r=Ta(n)[t.sort.key],i=t.sort.dir===`asc`?1:-1;return e.filter(e=>Ea(e,t.filters,n)&&Da(e,t.query)).sort((e,t)=>i*r(e,t))}var ka=(e,t,n)=>t.includes(e)?e:n;function Aa(e){let t;try{if(t=JSON.parse(e??`null`)??{},typeof t!=`object`||Array.isArray(t))return va}catch{return va}let n=t.filters??{},r=t.sort??{},i=va,a=ka(r.key,ya,i.sort.key),o=a===r.key?ka(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:ka(n.status,ba,i.filters.status),source:ka(n.source,xa,i.filters.source),machine:typeof n.machine==`string`&&n.machine.length<=200?n.machine:``,archived:n.archived===!0||n.hidden===!0,touched:ka(n.touched,ga,i.filters.touched)},l=Object.keys(c).every(e=>c[e]===i.filters[e]);return l&&s===i.sort?va:{query:``,filters:l?i.filters:c,sort:s}}function ja(e){return JSON.stringify({filters:e.filters,sort:e.sort})}var Ma=e=>e.state===`blocked`||e.state===`error`&&!e.hidden;function Na(e,{query:t,groupBy:n,sortBy:r,recentLimit:i=20,workingLimit:a=7,now:o=Date.now()}){let s=e.filter(e=>!e.hidden),c=e.filter(Ma),l=r===`title`?(e,t)=>Sa(e.title,t.title)||Ca(e,t):Ca;if(t.trim())return[{id:`results`,title:`Results`,kind:`results`,rows:s.filter(e=>Da(e,t)).sort(Ca)}];let u=new Set,d=e=>{for(let t of e)u.add(t.id);return e},f=[],p=e=>e.rows.length&&f.push(e);p({id:`needs`,title:`Needs you`,kind:`needs`,rows:d(c.sort(Ca))});let m=s.filter(e=>!u.has(e.id)&&e.touchedAt!==void 0&&o-e.touchedAt<=6048e5);if(m.length){let e=s.filter(e=>!u.has(e.id)&&e.pinned).sort(l),t=m.filter(e=>!e.pinned).sort((e,t)=>wa(t)-wa(e)).slice(0,a);p({id:`working`,title:`Working set`,kind:`working`,rows:d([...e,...t])})}p({id:`running`,title:`Running`,kind:`running`,rows:d(s.filter(e=>!u.has(e.id)&&e.running).sort(Ca))}),p({id:`pinned`,title:`Pinned`,kind:`pinned`,rows:d(s.filter(e=>!u.has(e.id)&&e.pinned).sort(l))});let h=new Map;for(let e of s){if(u.has(e.id)||!e.open)continue;let t=n===`machine`?e.machineID:`${e.machineID}\u0000${e.group}`,r=h.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:[]},h.set(t,r)),r.rows.push(e)}let g=e=>Math.max(...e.map(e=>e.updated)),_=[...h.values()].sort((e,t)=>r===`title`&&Sa(e.title,t.title)||g(t.rows)-g(e.rows));for(let e of _){e.rows.sort(l),d(e.rows);let t=[...e.rows].sort(Ca);p({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 p({id:`recents`,title:`Recents`,kind:`recents`,rows:s.filter(e=>!u.has(e.id)).sort(Ca).slice(0,i)}),f}var Pa=864e5;function Fa(e,t,n){if(!Number.isInteger(t)||t<1)return[];let r=n-t*Pa;return e.filter(e=>!e.hidden&&!e.running&&!e.pinned&&!e.open&&e.updated<r)}function Ia(e,t){return t.phase!==`off`&&t.sessionID===e.id||e.conversation===!0}function La(e,t,n,r){let i=`${e} of ${t} sessions`;return!r||!n?i:`${i} · ${n===1?`1 Decision waits`:`${n} Decisions wait`} for you (above)`}var Ra;function za(e){Ra=e}function Ba(e){for(let t of[Ra?.(e.id),e.intent]){let n=t?.trim();if(n&&n!==e.title)return n}}function Va(e,t){if(e.state!==`blocked`)return;let n=(e.status??[]).flatMap(e=>e.state===`blocked`&&typeof e.blockedSince==`number`?[e.blockedSince]:[]);if(!n.length)return;let r=Math.max(0,Math.floor((t-Math.min(...n))/1e3));return r<60?`<1m`:r<3600?`${Math.floor(r/60)}m`:r<86400?`${Math.floor(r/3600)}h`:`${Math.floor(r/86400)}d`}var Ha=.75,Ua=.05;function Wa(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/Ua)/Math.round(1/Ua);return Math.min(2,Math.max(Ha,Number(n.toFixed(2))))}function Ga(e){let t=Wa(e);return`${Number.isInteger(t)?t.toFixed(1):String(t)}×`}var Ka={working:`working`,blocked:`blocked`,error:`failed`,idle:`done`},qa=160,Ja=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(`
|
|
3
|
+
`).map(e=>e.trim()).filter(Boolean).at(-1);a&&(i.line=a.length>qa?`…${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=Ka[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`:Xa(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 Xa(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 ${Xa(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 Ya(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 Xa(e){if(e.kind===`thinking`)return`Thinking…`;let t=e.tool||`tool`;return e.summary?`${t} · ${e.summary}`:t}var Za=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 Qa(){let e=Object.values(Za),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 $a=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=Za[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}},eo=class{ackMs;quietMs;stillMs;enabled=!0;phrases=!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 $a;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.phrases&&!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.phrases||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)}]}},to=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}},no=new Set([`working`,`blocked`]);function ro(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`&&!no.has(t??``)?i.push(e.id):no.has(t??``)&&!no.has(e.state)&&a.push(e.id)}for(let[e,t]of r)no.has(t)&&a.push(e);return{started:i,finished:a}}function io(e){return(e??[]).some(e=>e.state===`working`)}var ao=Object.freeze([`openrouter`,`openai-compatible`]),oo={stt:[`provider`,`model`,`baseURL`,`language`],tts:[`provider`,`model`,`voice`,`baseURL`,`speed`]},so=e=>e==null?``:String(e).trim();function co(e){let t={};for(let n of[`stt`,`tts`]){let r=e?.[n]??{};t[n]=Object.fromEntries(oo[n].map(e=>[e,so(r[e])])),t[n].apiKey={action:`keep`,value:``}}return t}function lo(e,t){let n={};for(let r of[`stt`,`tts`]){let i=e?.[r]??{},a=t[r],o={};for(let e of oo[r]){if(e===`baseURL`&&so(a.provider)!==`openai-compatible`)continue;let t=so(a[e]);t!==so(i[e])&&(o[e]=t===``?null:e===`speed`?Number(t):t)}a.apiKey?.action===`set`?o.apiKey=so(a.apiKey.value):a.apiKey?.action===`clear`&&(o.apiKey=null),Object.keys(o).length&&(n[r]=o)}return n}function uo(e){let t={};for(let n of[`stt`,`tts`]){let r=e[n],i=(e,r)=>t[`${n}.${e}`]=r;if(ao.includes(so(r.provider))||i(`provider`,`Choose a provider.`),so(r.model)||i(`model`,`Enter a model.`),so(r.provider)===`openai-compatible`){let e=so(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`){so(r.voice)||i(`voice`,`Enter a voice.`);let e=so(r.speed);e&&!(Number(e)>=.25&&Number(e)<=4)&&i(`speed`,`Use a number from 0.25 to 4.`)}r.apiKey?.action===`set`&&!so(r.apiKey.value)&&i(`apiKey`,`Paste the new key, or cancel.`)}return t}function fo(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 po=/^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i;function mo(e,t){if(!e||e.stt&&e.tts)return;let n=!1;try{n=po.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 ho=()=>({machines:void 0,reads:{},activity:{},intents:{},prefs:ri({}),prefsSource:`unknown`,prefsPending:0,prefsStale:!1,connection:`connecting`,enrollmentRev:0}),go=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function _o(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 vo(e,t){if(!go(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 _o(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 _o(e.machines,t.sessionID,e=>{e.conversation=t.on,n=!0}),n}case`reads`:return go(t.reads)?(e.reads=Object.fromEntries(Object.entries(t.reads).filter(e=>typeof e[1]==`number`)),!0):!1;case`activity`:{let n=na(t.activity);return typeof t.sessionID!=`string`||!n?!1:(e.activity[t.sessionID]=n,!0)}case`prefs`:return e.prefsSource===`hub`?e.prefsPending?(e.prefsStale=!0,!0):(e.prefs=ri(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 yo(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??bo(e,t)}function bo(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=xo(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 xo(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 So(e){return(e??[]).some(e=>e.state===`working`||e.state===`blocked`)}var Co=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 Ja(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(!go(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 go(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 wo(e,t){let n=new URLSearchParams;e.lite&&n.set(`lite`,`1`),e.session&&n.set(`session`,e.session),e.sessions&&e.sessions.length>1&&n.set(`sessions`,e.sessions.join(`,`)),t&&n.set(`last`,t);let r=n.toString().replace(/\+/g,`%20`);return r?`/api/events?${r}`:`/api/events`}var To=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=wo(e)===wo(this.scope);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(wo(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 Eo(e,t){return t===`scope`&&e===`live`?{connection:`live`,reconnecting:!1}:{connection:`connecting`,reconnecting:e!==`connecting`}}var Do=e=>e===`app:concierge`||e===`app concierge`,Oo=/^(ses_[A-Za-z0-9]+)(?: \(sub ses_[A-Za-z0-9]+\))? (.*)$/,ko=/^[!+-] (.*)$/,Ao=/^… (\d+) more updates not listed$/,jo=2,Mo={permission:`needs a permission`,question:`has a question`};function No(e,t){let n=/^machine \S+ (online|offline)$/.exec(e);if(n)return`a machine went ${n[1]}`;let r=Oo.exec(e);if(!r)return`something changed`;let i=t(r[1])??r[1],a=r[2];if(/^turn_done\b/.test(a))return`${i} finished a turn`;let o=/^blocker:(\w+)/.exec(a);if(o)return`${i} ${Mo[o[1]]??`is blocked (${o[1]})`}`;if(/^blocker_closed\b/.test(a))return`${i} was unblocked`;if(a===`state:error`)return`${i} hit an error`;if(a===`online`)return`${i} came online`;if(a===`offline`||a===`state:offline`)return`${i} went offline`;if(a===`state:working`)return`${i} started working`;let s=/^state:(\w+)$/.exec(a);if(s)return`${i} is ${s[1]}`;if(/^decision dec_/.test(a))return`${i} has a Decision for you`;let c=/^launch \S+ ended:(\w+)$/.exec(a);return c?`${i}'s launch ended (${c[1]})`:/^intent_cleared\b/.test(a)||/^intent:title\b/.test(a)?`${i}'s intent was cleared (it shows its title again)`:/^intent:/.test(a)?`${i}'s intent changed`:a===`pinned`||a===`unpinned`?`${i} was ${a}`:`${i} changed`}function Po(e,t){if(typeof e!=`string`)return;let[n=``,...r]=e.split(`
|
|
4
|
+
`),i=/^Concierge digest \(.*?\) b\d+ .*?: (.*)$/.exec(n);if(i)return`Digest: ${i[1]}`;if(!/^Concierge update b\d+ /.test(n))return;if(/ changes were missed | some changes were missed/.test(n))return`Update: some changes were missed — catching up`;let a=[],o=0;for(let e of r){let n=Ao.exec(e);n&&(o+=Number(n[1]));let r=ko.exec(e);r&&(a.length<jo?a.push(No(r[1],t)):o++)}return/· quiet hours ended: /.test(n)&&a.unshift(`quiet hours ended`),a.length||a.push(`something changed in your sessions`),`Update: ${[...a,...o?[`${o} more`]:[]].join(` · `)}`}var Fo=60,Io=/(`[^`]*`|\]\([^)]*\)|<[a-z][a-z0-9+.-]*:[^>\s]*>|\b[a-z][a-z0-9+.-]*:\/\/[^\s<>()]+)|(?<![\w#/[(])((?:Decision )?)(dec_[A-Za-z0-9]{1,64})(?!\w)/g,Lo=e=>{let t=Intl.Segmenter;return t?Array.from(new t(void 0,{granularity:`grapheme`}).segment(e),e=>e.segment):Array.from(e)},Ro=e=>{let t=e.replace(/\s+/g,` `).trim(),n=Lo(t);return n.length>Fo?`${n.slice(0,59).join(``)}…`:t};function zo(e){if(!e.includes(`dec_`))return[];let t=new Set;for(let n of e.matchAll(Io))!n[1]&&n[3]&&t.add(n[3]);return[...t]}function Bo(e,t,n={}){let r=n.unknown===`link`;if(!t.length&&!r||!e.includes(`dec_`))return[{text:e}];let i=new Map(t.map(e=>[e.id,e])),a=[],o=0,s=e=>{let t=a.at(-1);!e.href&&t&&!t.href?a[a.length-1]={text:t.text+e.text}:e.text&&a.push(e)};for(let t of e.matchAll(Io)){let[n,a,c,l]=t;if(a||!l)continue;let u=i.get(l);if(!u&&!r)continue;s({text:e.slice(o,t.index)});let d=`/concierge#decision-${l}`;if(u){let e=`Decision “${Ro(u.question)}”`;s({text:u.state===`open`?e:`${e} (${u.state})`,href:d})}else s({text:c&&e.startsWith(`: `,t.index+n.length)?`Decision (answered)`:c?`Decision`:`a Decision`,href:d});o=t.index+n.length}return s({text:e.slice(o)}),a.length?a:[{text:e}]}function Vo(e,t,n={}){return Bo(e,t,n).map(e=>e.href?`[${Ho(e.text)}](${e.href})`:e.text).join(``)}var Ho=e=>e.replace(/[\\`*_[\]<>~=]/g,`\\$&`);function Uo(e,t){return e.replace(/(?<![\w/])ses_[A-Za-z0-9]{1,64}(?!\w)/g,e=>t(e)??e)}function Wo(e){if(e.state===`expired`)return`Expired without an answer`;if(e.state===`closed`)return e.closed?.reason?`Closed: ${e.closed.reason}`:`Closed`;let t=e.answer,n=t?.option===void 0?t?.text:e.options.find(e=>e.id===t.option)?.label??t.option;return!t||n===void 0?`Answered`:t.answeredBy===`app`?`Answered “${n}” by ${ve(e)}`:t.answeredBy===`timeout`?`Answered “${n}” when it timed out`:`You answered “${n}”`}var Go=2e3,Ko=6e4,qo=class{options;found=new Map;missing=new Set;failures=new Map;asking=new Map;queue=[];running=0;now;constructor(e){this.options=e,this.now=e.now??Date.now}recall(e){let t=this.found.get(e);if(t!==void 0)return Promise.resolve(t);if(this.missing.has(e))return Promise.resolve(void 0);let n=this.asking.get(e);if(n)return n;let r=this.failures.get(e);if(r&&this.now()<r.retryAt)return Promise.resolve(void 0);let i=this.running<4?this.ask(e):new Promise(e=>this.queue.push(e)).then(()=>this.ask(e));return this.asking.set(e,i),i}async ask(e){this.running++;try{let t=this.options.parse(await this.options.fetch(e));return this.failures.delete(e),t===void 0?this.missing.add(e):this.found.set(e,t),t}catch(t){let n=this.options.status(t);if(n!==void 0&&n!==429&&n<500)this.failures.delete(e),this.missing.add(e);else{let t=(this.failures.get(e)?.count??0)+1;this.failures.set(e,{count:t,retryAt:this.now()+Math.min(Go*2**(t-1),Ko)})}return}finally{this.running--,this.asking.delete(e),this.queue.shift()?.()}}};function Jo(e,t){let n=new Set;for(let r of e)if((r.type===`assistant`?r.live!==!0:r.type===`message`&&!r.primer&&!Do(r.from))&&typeof r.text==`string`)for(let e of zo(r.text))t.has(e)||n.add(e);return[...n]}var Yo=new Set([`disabled`,`starting`,`running`,`waiting_machine`,`backoff`,`failed`,`stopping`]),Xo=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Zo=e=>typeof e==`string`,Qo=e=>typeof e==`number`&&Number.isFinite(e);function $o(e){if(Xo(e)&&Zo(e.state)&&Yo.has(e.state))return{state:e.state,...Zo(e.reason)?{reason:e.reason.slice(0,200)}:{},...Zo(e.sessionID)?{sessionID:e.sessionID}:{},hiddenSessionIDs:Array.isArray(e.hiddenSessionIDs)?e.hiddenSessionIDs.filter(Zo):[],...Zo(e.launchID)?{launchID:e.launchID}:{},...Zo(e.machineID)?{machineID:e.machineID}:{},generation:Qo(e.generation)?e.generation:0,since:Qo(e.since)?e.since:0,...Qo(e.nextAttemptAt)?{nextAttemptAt:e.nextAttemptAt}:{}}}function es(e){if(!Xo(e)||!Xo(e.settings))return;let t=$o(e.status);if(!t)return;let n=Array.isArray(e.machines)?e.machines.filter(Xo).filter(e=>Zo(e.id)&&Zo(e.name)).map(e=>({id:e.id,name:e.name,eligible:e.eligible===!0,online:e.online===!0,...Zo(e.reason)?{reason:e.reason}:{},roots:Array.isArray(e.roots)?e.roots.filter(Zo):[]})):[];return{settings:e.settings,status:t,machines:n}}function ts(e,t,n){let r=new Set(e?e.hiddenSessionIDs:n??[]);for(let e of t??[])for(let t of e.processes??[])for(let e of t.sessions??[])(e.agent===`concierge`||e.contextRevision!==void 0)&&r.add(e.id);return r}var ns=4e3,rs=(e,t,n)=>e||t&&n;function is(e,t,n,r,i,a){return ts(t,r,a).has(e)?`concierge`:!n||i===!1&&!as(e,r)?`wait`:`session`}var as=(e,t)=>(t??[]).some(t=>(t.processes??[]).some(t=>(t.sessions??[]).some(t=>t.id===e))),os=e=>`concierge.hidden.${e??`local`}`;function ss(e){let t=[];for(let n=0;n<e.length;n++){let r=e.key(n);(r===`concierge.hidden`||r?.startsWith(`concierge.hidden.`))&&t.push(r)}for(let n of t)e.removeItem(n)}function cs(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`&&e.length<=128).slice(-20):[]}catch{return[]}}var ls=e=>e<6e4?`${Math.max(1,Math.ceil(e/1e3))} s`:`${Math.ceil(e/6e4)} min`;function us(e,t,n){if(!e)return`Off`;let r=t.find(t=>t.id===e.machineID)?.name??`its machine`;switch(e.state){case`disabled`:return`Off`;case`starting`:return e.reason?.startsWith(`Waiting`)?e.reason:`Starting on ${r}`;case`running`:return`Running on ${r}`;case`waiting_machine`:return`Waiting for ${r}${e.reason?`: ${e.reason}`:``}`;case`backoff`:return e.nextAttemptAt===void 0?`Relaunching`:`Relaunching in ${ls(e.nextAttemptAt-n)}`;case`failed`:return`Failed${e.reason?`: ${e.reason}`:``}`;case`stopping`:return`Stopping`}}function ds(e){let t=e=>e.eligible?0:e.online?2:1;return[...e].sort((e,n)=>t(e)-t(n)||e.name.localeCompare(n.name)).map(e=>({...e,selectable:e.eligible||!e.online,note:e.eligible?`Ready`:e.online?e.reason??`Cannot host the Concierge`:`Offline: the Concierge waits for it`}))}var fs=(e,t)=>{let n=t.replace(/\/+$/,``);return e===n||e.startsWith(`${n}/`)};function ps(e,t){if(!e.machineID)return`Pick a machine`;let n=t.find(t=>t.id===e.machineID);if(!n)return`That machine is not yours any more: pick another`;if(!n.eligible&&n.online)return`${n.name} cannot host the Concierge: ${n.reason??`not eligible`}`;if(!e.directory)return`Pick a directory (a git repo on ${n.name})`;if(n.roots.length&&!n.roots.some(t=>fs(e.directory,t)))return`The directory must be under one of ${n.name}'s workspace roots: ${n.roots.join(`, `)}`}var ms=e=>({allow:[`answer`,`deny`,`approve`],projects:[...e],permissions:{allow:[`read`,`edit`],never:[`shell:git push*`,`shell:rm *`]},allowAlways:!1,expires:`7d`,maxActionsPerHour:60}),hs=[`answer`,`deny`,`approve`,`stop`,`prompt`];function gs(e,t){let n=e??ms(t?[t]:[]);return{projects:[...n.projects],allow:[...n.allow],permit:n.permissions.allow.join(`
|
|
5
|
+
`),never:n.permissions.never.join(`
|
|
6
|
+
`),expires:n.expires,maxActionsPerHour:String(n.maxActionsPerHour)}}var _s=e=>e.split(`
|
|
7
|
+
`).map(e=>e.trim()).filter(Boolean),vs=/^(\d+)(h|d)$/;function ys(e){let t={},n=[...new Set(e.projects.map(e=>e.trim()).filter(Boolean))];n.length||(t.projects=`Pick at least one project`),hs.filter(t=>e.allow.includes(t)).length||(t.allow=`Pick at least one action`);let r=e.expires.trim(),i=vs.exec(r),a=i?Number(i[1])*(i[2]===`d`?24:1):NaN;a>=1&&a<=720||(t.expires=`1h to 30d, for example 8h or 7d`);let o=e.maxActionsPerHour.trim(),s=/^\d+$/.test(o)?Number(o):NaN;return s>=1&&s<=1e3||(t.maxActionsPerHour=`A whole number from 1 to 1000`),Object.keys(t).length?{ok:!1,errors:t}:{ok:!0,body:{allow:e.allow.filter(e=>hs.includes(e)),projects:n,permissions:{allow:_s(e.permit),never:_s(e.never)},allowAlways:!1,expires:r,maxActionsPerHour:s}}}function bs(e){let t=_s(e).filter(e=>/^(shell|bash)\b/.test(e));return t.length?`Shell rules (${t.join(`, `)}) never auto-approve: the Concierge always asks for your tap on a shell request. In shell patterns * also matches &&, | and ;.`:void 0}function xs(e){if(/^grant\.permissions\.never/.test(e))return`never`;if(/^grant\.permissions/.test(e))return`permit`;if(/^grant\.projects|^scope/.test(e))return`projects`;if(/^grant\.allow\b/.test(e))return`allow`;if(/^grant\.expires/.test(e))return`expires`;if(/^grant\.maxActionsPerHour/.test(e))return`maxActionsPerHour`;if(/^permissions\.never/.test(e))return`never`;if(/^permissions/.test(e))return`permit`}function Ss(e,t,n){let r=[...(e?.processes??[]).flatMap(e=>e.sessions.map(e=>(e.project||e.directory).replace(/\/+$/,``)))].filter(Boolean).sort();return[...new Set([...t?[t]:[],...n,...r])]}function Cs(e){let t=e.permissions.allow,n=e.permissions.never;return{head:`${e.allow.join(`, `)} in ${e.projects.join(`, `)}`,permissions:t.length?`Permissions ${t.join(`, `)}${n.length?` · never ${n.join(`, `)}`:``}`:`Permissions: none (it approves nothing)`}}function ws(e,t){let n=ot(e,t);return n?`expires in ${n}`:`expired`}var Ts=[`machineID`,`directory`,`model`,`grant`,`connectors`,`timeZone`,`quietHours`,`quietAllowsUrgent`,`digests`];function Es(e,t){let n={};for(let r of Ts)JSON.stringify(e[r])!==JSON.stringify(t[r])&&(n[r]=t[r]===void 0?null:t[r]);return{...n,expectedRevision:e.revision}}var Ds=`__other__`,Os=e=>(e??``).replace(/\/+$/,``);function ks(e,t){if(!e)return{projects:[],roots:[]};let n=[...new Set(e.roots.map(Os).filter(Boolean))],r=(t??[]).find(t=>t.id===e.id)?.processes.flatMap(e=>e.sessions.map(e=>Os(e.project)||Os(e.directory)))??[],i=[...new Set(r)].filter(e=>e.startsWith(`/`)&&(!n.length||n.some(t=>fs(e,t)))).sort();return{projects:i,roots:n.filter(e=>!i.includes(e))}}function As(e,t){if(!e)return`Pick a machine first.`;if(!e.online)return`${e.name} is offline: its projects show when it is back; you can type a folder.`;let n=[...new Set(e.roots.map(Os).filter(Boolean))],r=n.length?` under ${n.join(`, `)}`:``;return t.projects.length?`A git repo on ${e.name}${r}. It is used as is: no branch switch.`:`${e.name} reports no projects${r} yet: pick a root or type a folder.`}var js=(e,t)=>e?t.includes(e)?e:Ds:``;function Ms(e,t,n,r){if(e.machineID===t.id)return e;let{projects:i,roots:a}=ks(t,n),o=e.directory!==void 0&&(i.includes(e.directory)||a.includes(e.directory)),s=e.model!==void 0&&r!==void 0&&!r.includes(e.model)?void 0:e.model;return{...e,machineID:t.id,directory:o?e.directory:void 0,model:s}}var Ns=(e,t)=>e.model!==void 0&&!t.includes(e.model)?{...e,model:void 0}:e,Ps=/^[A-Za-z0-9._-]{1,80}\/[!-~]{1,200}$/;function Fs(e){let t=Xo(e)&&Array.isArray(e.models)?e.models:[],n=new Map;for(let e of t){if(!Xo(e)||!Zo(e.providerID)||!Zo(e.modelID)||e.enabled===!1)continue;let t=`${e.providerID}/${e.modelID}`;Ps.test(t)&&!n.has(t)&&n.set(t,{value:t,label:Zo(e.name)&&e.name?e.name.slice(0,120):e.modelID,provider:e.providerID})}return[...n.values()].sort((e,t)=>e.provider.localeCompare(t.provider)||e.label.localeCompare(t.label))}function Is(e){if(!e)return`Pick a machine first`;if(!e.online)return`${e.name} is offline: type a model, or keep the machine default`;if(!e.eligible)return e.reason??`It cannot host the Concierge`}var Ls=new Set([`yes`,`approve`,`go ahead`,`do it`]),Rs=new Set([`no`,`deny`,`don't`,`dont`,`hold`]),zs=new Set([`um`,`umm`,`uh`,`uhm`,`uhh`,`er`,`erm`,`hm`,`hmm`,`ah`,`please`]),Bs=80;function Vs(e){if(typeof e!=`string`||e.length>Bs||/[??]/.test(e))return;let t=e.normalize(`NFC`).toLowerCase().replace(/[\u2018\u2019\u02bc`´]/g,`'`).replace(/[.,!?;:…"“”«»()[\]{}\-–—]+/g,` `).split(/\s+/).filter(Boolean),n=0,r=t.length;for(;n<r&&zs.has(t[n]);)n++;for(;r>n&&zs.has(t[r-1]);)r--;let i=t.slice(n,r).join(` `);if(Ls.has(i))return`yes`;if(Rs.has(i))return`no`}function Hs(e){if(e===null)return null;if(!e||typeof e!=`object`||Array.isArray(e))return;let{decisionID:t,expiresAt:n}=e;if(typeof t==`string`&&/^dec_[A-Za-z0-9]{1,64}$/.test(t))return{decisionID:t,...typeof n==`number`&&Number.isFinite(n)?{expiresAt:n}:{}}}function Us(e,t,n){if(!t||t.expiresAt!==void 0&&t.expiresAt<=n)return;let r=e.find(e=>e.id===t.decisionID);return r&&r.state===`open`&&r.tier===`confirm`?r:void 0}function Ws(e,t,{tiers:n=`confirm`}={}){if(!t)return[];let r=new Set([...t.hiddenSessionIDs,...t.sessionID?[t.sessionID]:[]]);return e.filter(e=>e.state===`open`&&(n===`all`||e.tier===`confirm`)&&(e.from.kind===`session`&&r.has(e.from.sessionID)||e.as===`concierge`)).sort((e,t)=>t.at-e.at)}function Gs(e,t){if(t===`yes`&&e.action?.kind===`grant`)return;let n=e.options.filter(e=>t===`yes`?!e.safe&&e.id!==`always`:e.safe===!0);return n.length===1?n[0].id:void 0}function Ks(e,t){if(!t||t.tier!==`confirm`||t.state!==`open`)return{kind:`speech`};let n=Vs(e),r=n&&Gs(t,n);return n&&r?{kind:`answer`,decisionID:t.id,option:r,intent:n}:{kind:`speech`}}var qs=60;function Js(e,t){if(!e)return`Answered a Decision by text`;let n=Array.from(e.question.replace(/\s+/g,` `).trim());return`Answered Decision “${n.length>qs?`${n.slice(0,59).join(``)}…`:n.join(``)}” by text: ${e.options.find(e=>e.id===t)?.label??t}`}var Ys=e=>e&&e.state!==`disabled`?!0:`hidden`,Xs={starting:`starting`,backoff:`restarting soon`,waiting_machine:`waiting for its machine`,stopping:`stopping`};function Zs(e,t,n,r,i=0,a){if(e.state===`disabled`)return{label:`Concierge (off — set it up)`,title:`Concierge is off — click to set it up in Settings → Concierge`,indicator:`off`};let o=!!t&&(t.expiresAt===void 0||t.expiresAt>r)&&(a===void 0||a.has(t.decisionID)),s=Math.max(i,+!!o),c=s>1?` — ${s} Decisions wait for your answer`:s?` — a Decision waits for your answer`:``,[l,u]=e.state===`failed`?[`Concierge (stopped — restart it)`,`attention`]:e.state===`running`?[`Concierge (running${c})`,s?`attention`:`running`]:[`Concierge (${Xs[e.state]}${c})`,s?`attention`:`busy`];return{label:l,title:`${l} — ${n?`close`:`open`} it`,indicator:u,...i>0?{count:s}:{}}}var Qs=e=>e?`Ask what needs you, or start Voice and talk.`:`Ask what needs you.`,$s=e=>`${e?`Say or type`:`Type`} “yes” or “no” (or tap). Anything else goes to the Concierge.`,ec=`The Concierge is off. Turn it on in Settings → Concierge.`;function tc(e,t){if(!e||e.state===`disabled`)return ec;let n=t?.name??`its machine`;switch(e.state){case`failed`:return e.reason?`Stopped: ${e.reason}. Restart it when you are ready.`:`Stopped. Restart it when you are ready.`;case`stopping`:return`Stopping…`;case`backoff`:return`Relaunching…`}if(e.state===`waiting_machine`||t?.online===!1)return`Concierge runs on ${n}, which is offline`;if(e.state===`starting`)return`Starting on ${n}…`}function nc(e,t){let n=`/api/sessions/${encodeURIComponent(t.sessionID)}/utterance`;return async(r,i)=>{let a=i?.json?.text;if(r!==n||i?.method!==`POST`||typeof a!=`string`||t.current()!==t.sessionID||t.present?.()===!1)return e(r,i);let o=Ks(a,t.armed());return o.kind===`speech`?e(r,i):(await t.answer(o.decisionID,o.option),Response.json({inboxID:`decision:${o.decisionID}`}))}}var rc=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function ic(e,t,n){let r=new Set(e??[0,1,2,3,4,5,6]);n?r.add(t):r.size>1&&r.delete(t);let i=[...r].filter(e=>Number.isInteger(e)&&e>=0&&e<=6).sort((e,t)=>e-t);return i.length===7?void 0:i}function ac(e,t,n){return n===void 0||!e||e.sessionID===t.sessionID?n:null}function oc(e,t){let n=e;for(let e=n.panes.length-1;e>=0;e--){let r=n.panes[e].sessionID;r!==void 0&&t.has(r)&&(n=dn(n,e))}return n}function sc(e,t){if(e&&e.expiresAt!==void 0)return Math.max(0,e.expiresAt-t)}function cc(e,t){return e&&e.expiresAt!==void 0&&e.expiresAt<=t?null:e}var lc=class{events=0;seq=0;settled=0;started=new Map;begin(){let e=++this.seq;return this.started.set(e,this.events),e}event(){this.events++}fresh(e){let t=this.started.get(e);return this.started.delete(e),t!==this.events||e<this.settled?!1:(this.settled=e,!0)}};function uc(e,t,n){return Ws(e,t,{tiers:`all`}).filter(e=>e.id!==n?.id)}var dc=class{onChange;entries=[];focusedID;seq=0;constructor(e=()=>{}){this.onChange=e}register(e,t=()=>!0){let n=`pane_${++this.seq}`;return this.entries.push({paneID:n,sessionID:e,visible:t}),this.focusedID===void 0&&(this.focusedID=n),this.onChange(),n}release(e){let t=this.entries.length;this.entries=this.entries.filter(t=>t.paneID!==e),this.entries.length!==t&&(this.focusedID===e&&(this.focusedID=this.entries[0]?.paneID),this.onChange())}focus(e){return this.entries.some(t=>t.paneID===e)?(this.focusedID!==e&&(this.focusedID=e,this.onChange()),!0):!1}focused(){return this.focusedID}views(){return this.entries.map(e=>({paneID:e.paneID,sessionID:e.sessionID,visible:e.visible(),focused:e.paneID===this.focusedID}))}};function fc(e){let t=e.find(e=>e.focused);return t?.visible?t:void 0}function pc(e,t=hn){let n=[],r=fc(e);for(let i of r?[r,...e]:e){if(n.length>=t)break;i.visible&&!n.includes(i.sessionID)&&n.push(i.sessionID)}return n}function mc(e,t,n){let r=t.length?pc(t):n?[n]:[],[i]=r;return i?r.length>1?{lite:e,session:i,sessions:r}:{lite:e,session:i}:{lite:e}}function hc(e,t,n=hn){if(!t)return e;let r=e.sessions??(e.session?[e.session]:[]);if(r.includes(t))return e;let i=[...r.slice(0,Math.max(0,n-1)),t],[a]=i;return i.length>1?{lite:e.lite,session:a,sessions:i}:{lite:e.lite,session:a}}function gc(e){return fc(e)?.sessionID}function _c(e,t){return fc(e)?.paneID===t}var vc=class{all=!1;requested=new Set;confirmed=new Set;pending=!1;opened(e){this.all=!e.lite,this.confirmed=new Set(e.session?[e.session]:[]),this.requested=new Set([...this.confirmed,...e.sessions??[]]),this.pending=this.requested.size>this.confirmed.size}message(e){if(!this.pending||typeof e!=`object`||!e)return!1;let{type:t,sessions:n}=e;if(t===`scope`){if(!Array.isArray(n))return!1;for(let e of n)typeof e==`string`&&this.requested.has(e)&&this.confirmed.add(e);return this.pending=!1,!0}return typeof t==`string`&&(this.pending=!1,!0)}covers(e){return this.all||this.confirmed.has(e)?!0:this.pending&&this.requested.has(e)?void 0:!1}},[yc,bc]=u(0),xc=new dc(()=>bc(e=>e+1));function Sc(){return yc(),xc.views()}var Cc=()=>gc(Sc()),wc=(e,t)=>mc(e,Sc(),t);function Tc(e,t=()=>!0){let n=xc.register(e,t);return{paneID:n,focus:()=>void xc.focus(n),takesInput:()=>_c(Sc(),n),streamed:()=>jc(e),release:()=>xc.release(n)}}var Ec=new vc,[Dc,Oc]=u(0);function kc(e){Ec.opened(e),Oc(e=>e+1)}function Ac(e){Ec.message(e)&&Oc(e=>e+1)}function jc(e){return Dc(),Ec.covers(e)}var Mc=`x-hub-recording`,Nc=`x-hub-segment`,Pc=`x-hub-tts-ref`,Fc=`x-hub-recording-audio`,Ic={retentionMs:6048e5,userBytes:524288e3,recordingBytes:157286400,segmentBytes:2097152,segmentsPerRecording:5e3,eventsPerBatch:200,batchBytes:262144,keepaliveBatchBytes:61440,eventsPerRecording:5e4,eventBytesPerRecording:33554432,recordingsStored:200,activePerUser:4,maxDurationMs:144e5,idleEndMs:6e5,sweepMs:9e5,textChars:2e3,utteranceChars:4e3,replyChars:32e3,messageChars:300,consoleBufferEvents:2e3,flushMs:5e3,flushEvents:100,hubFlushMs:2e3,hubFlushEvents:100},Lc={clipsPerRecording:200,clipPreMs:3e3,clipPostMs:2e3,clipBytes:196608,clipGapMs:2e3,repliesPerRecording:2e3,replyBytes:1048576,userHeadroomBytes:52428800,recordingHeadroomBytes:15728640,tracesPerMinute:30,logsPerMinute:20},Rc=[`vad.trace`,`audio.clip`,`device.info`,`resource.timing`,`console.log`],zc=6e4,Bc=1e4,Vc=[`echoCancellation`,`noiseSuppression`,`autoGainControl`,`sampleRate`,`channelCount`];function Hc(e){let t;try{t=new URL(e,`http://local`).pathname}catch{return}if(t===`/api/transcribe`)return`transcribe`;if(t===`/api/speak`)return`speak`;if(/^\/api\/recordings\/[^/]+\/events$/.test(t))return`events`;if(/^\/api\/recordings\//.test(t))return`recording`;if(/^\/api\/sessions\/[^/]+\/utterance$/.test(t))return`utterance`}var Uc=e=>{let t=[...e].sort((e,t)=>e-t),n=t.length/2;return Math.round(t.length%2?t[Math.floor(n)]:(t[n-1]+t[n])/2)},Wc=e=>e.slice(0,Ic.messageChars);function Gc(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}var Kc=e=>typeof e==`string`?e.split(/[/?#]/).filter(Boolean).at(-1)??``:``,qc=class{record;env;now;timers;logsPerMinute;last=``;track;wake;unhook=[];interval;seen=new WeakSet;logged=[];repeats=new Map;inLog=!1;running=!1;constructor(e){this.record=e.record,this.env=e.env??globalThis,this.now=e.now??(()=>Date.now()),this.timers=e.timers!==!1,this.logsPerMinute=e.logsPerMinute??Lc.logsPerMinute}async start(){if(this.running)return;this.running=!0;for(let e of this.entries())this.seen.add(e);this.hookConsole();let e=()=>void this.snapshot(`change`);this.listen(this.env.navigator?.connection,`change`,e),this.listen(this.env.navigator?.mediaDevices,`devicechange`,e),this.listen(this.env.document,`visibilitychange`,e),this.listen(this.env.window,`error`,e=>this.windowError(e)),this.listen(this.env.window,`unhandledrejection`,e=>this.log(`unhandled`,e?.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:Gc(e?.reason),`window`));let t=await this.env.navigator?.getBattery?.().catch?.(()=>void 0);t&&this.running&&(this.listen(t,`chargingchange`,e),this.listen(t,`levelchange`,e)),this.timers&&(this.interval=setInterval(()=>this.flushTiming(),zc)),await this.snapshot(`start`,t)}stop(){if(this.running){this.flushTiming(),this.running=!1;for(let e of this.unhook.splice(0))e();this.interval!==void 0&&clearInterval(this.interval),this.interval=void 0}}micTrack(e,t){let n={};for(let t of Vc)e[t]!==void 0&&typeof e[t]==(t.endsWith(`Rate`)||t.endsWith(`Count`)?`number`:`boolean`)&&(n[t]=e[t]);t&&(n.label=t),this.track=n,this.snapshot(`change`)}wakeLock(e){this.wake=e,this.snapshot(`change`)}log(e,t,n){if(!this.running)return;let r=Wc(t),i=`${e}\n${r}`,a=this.now(),o=this.repeats.get(i);if(o&&a-o.at<Bc){o.count++;return}for(;this.logged.length&&a-this.logged[0]>=6e4;)this.logged.shift();if(this.logged.length>=this.logsPerMinute)return;this.logged.push(a),this.repeats.set(i,{at:a,count:0}),this.repeats.size>200&&this.repeats.delete(this.repeats.keys().next().value);let s=o?o.count+1:0;this.record(`console.log`,{level:e,message:r,...s>1?{count:s}:{},...n?{source:n}:{}})}flushTiming(){if(!this.running)return;let e=new Map;for(let t of this.entries()){if(this.seen.has(t))continue;this.seen.add(t);let n=Hc(String(t.name??``));if(!n)continue;let r=e.get(n);r||e.set(n,r={durations:[],ttfb:[],bytes:0}),typeof t.duration==`number`&&r.durations.push(t.duration),typeof t.responseStart==`number`&&typeof t.requestStart==`number`&&t.responseStart>0&&t.requestStart>0&&r.ttfb.push(t.responseStart-t.requestStart),typeof t.transferSize==`number`&&(r.bytes+=t.transferSize)}for(let[t,n]of e)n.durations.length&&this.record(`resource.timing`,{route:t,n:n.durations.length,medianMs:Uc(n.durations),maxMs:Math.round(Math.max(...n.durations)),...n.ttfb.length?{medianTtfbMs:Uc(n.ttfb)}:{},bytes:Math.round(n.bytes)})}entries(){try{return this.env.performance?.getEntriesByType?.(`resource`)??[]}catch{return[]}}listen(e,t,n){e?.addEventListener&&(e.addEventListener(t,n),this.unhook.push(()=>e.removeEventListener?.(t,n)))}hookConsole(){let e=this.env.console;if(e)for(let t of[`error`,`warn`]){let n=e[t];if(typeof n!=`function`)continue;let r=(...r)=>{if(n.apply(e,r),!this.inLog){this.inLog=!0;try{this.log(t,r.map(Gc).join(` `),`console`)}catch{}finally{this.inLog=!1}}};e[t]=r,this.unhook.push(()=>{e[t]===r&&(e[t]=n)})}}windowError(e){let t=Kc(e?.filename),n=String(e?.message??(e?.error instanceof Error?e.error.message:`error`));this.log(`error`,t?`${n} (${t}${typeof e?.lineno==`number`?`:${e.lineno}`:``})`:n,`window`)}async snapshot(e,t){if(!this.running)return;let n={};try{let e=await this.env.navigator?.mediaDevices?.enumerateDevices?.()??[],t=t=>e.filter(e=>e.kind===t).slice(0,20).map(e=>({kind:t,...typeof e.label==`string`&&e.label?{label:e.label.slice(0,120)}:{}})),r=t(`audioinput`),i=t(`audiooutput`);r.length&&(n.inputs=r),i.length&&(n.outputs=i)}catch{}this.track&&(n.track=this.track);let r=this.env.navigator?.connection;if(r){let e={};typeof r.effectiveType==`string`&&(e.effectiveType=r.effectiveType.slice(0,60));for(let t of[`rtt`,`downlink`])typeof r[t]==`number`&&Number.isFinite(r[t])&&(e[t]=r[t]);typeof r.saveData==`boolean`&&(e.saveData=r.saveData),n.network=e}typeof this.env.document?.visibilityState==`string`&&(n.visibility=this.env.document.visibilityState.slice(0,60)),this.wake!==void 0&&(n.wakeLock=this.wake);let i=t??await this.env.navigator?.getBattery?.().catch?.(()=>void 0);if(i&&typeof i.level==`number`&&(n.battery={level:Math.round(i.level*100)/100,...typeof i.charging==`boolean`?{charging:i.charging}:{}}),!this.running)return;let a=JSON.stringify(n);(e!==`change`||a!==this.last)&&(this.last=a,this.record(`device.info`,{reason:e,...n}))}},Y=(e,t=[])=>({required:e,optional:t}),Jc={state:Y([`state`]),detector:Y([`mode`],[`avgMs`]),"speech.start":Y([`bargeIn`]),"speech.end":Y([`segment`,`durationMs`,`speechMs`,`forced`]),"segment.closed":Y([`segment`,`bytes`,`durationMs`,`speechMs`,`forced`]),"stt.sent":Y([`segment`,`bytes`]),"stt.received":Y([`segment`,`text`],[`junk`,`empty`,`failed`,`audio`,`junkReason`,`held`,`speechMs`]),"utterance.held":Y([`text`]),"utterance.merged":Y([`segments`,`pauseMs`]),"utterance.sent":Y([`text`,`segments`,`reason`,`holdMs`]),"utterance.accepted":Y([`inboxID`]),"utterance.failed":Y([`message`],[`status`]),"utterance.command":Y([`command`,`text`]),heard:Y([`inboxID`]),"say.received":Y([`messageID`,`ordinal`,`chars`,`sentences`,`muted`],[`seq`]),"tts.sentence.queued":Y([`ref`,`text`]),"tts.request":Y([`ref`]),"tts.first.byte":Y([`ref`]),"tts.sentence.played":Y([`ref`]),"tts.sentence.ended":Y([`ref`,`playedMs`,`completed`],[`durationMs`]),"barge.in":Y([`cause`,`spoken`,`unplayed`,`mutedMessages`],[`playing`]),"cue.played":Y([`cue`],[`name`,`text`]),mic:Y([`live`],[`reason`]),control:Y([`action`],[`on`]),"turn.timing":Y([`firstAudio`],[`speechEnd`,`transcript`,`accepted`,`firstSay`,`firstByte`]),"turn.predict":Y([`ms`,`silenceMs`,`decision`],[`p`,`error`]),"vad.near":Y([`ms`,`threshold`,`echoGuard`,`mode`,`reason`],[`voicedMs`,`peakProb`,`peakDb`]),"vad.summary":Y([`frames`,`framesAboveStart`,`framesAboveSpeakingStart`,`msEchoGuard`,`mode`,`sensitivity`],[`maxProb`,`p90Prob`,`maxDb`,`noiseFloorDb`,`nearDropped`]),"stt.slow":Y([`segment`,`ms`]),mark:Y([`via`],[`note`]),"vad.trace":Y([`reason`,`mode`,`frameMs`,`scale`,`values`,`threshold`,`guard`]),"audio.clip":Y([`clip`,`for`,`preMs`,`postMs`,`bytes`]),"device.info":Y([`reason`],[`outputs`,`inputs`,`track`,`network`,`visibility`,`wakeLock`,`battery`]),"resource.timing":Y([`route`,`n`,`medianMs`,`maxMs`],[`medianTtfbMs`,`bytes`]),"console.log":Y([`level`,`message`],[`count`,`source`]),"decision.voice":Y([`decisionID`,`outcome`],[`option`,`picks`]),"clock.sync":Y([`t0`,`t1`,`hubAt`]),error:Y([`where`,`message`])},Yc=Ic,Xc=60,Zc={"stt.received":{text:Yc.textChars,failed:Yc.messageChars,held:Yc.utteranceChars,junkReason:Xc},"utterance.held":{text:Yc.utteranceChars},"utterance.sent":{text:Yc.utteranceChars},"utterance.failed":{message:Yc.messageChars},"utterance.command":{text:Yc.utteranceChars},"tts.sentence.queued":{text:Yc.textChars},"cue.played":{text:Yc.textChars},"turn.predict":{error:Yc.messageChars},mark:{note:Yc.textChars},"console.log":{message:Yc.messageChars,source:Xc},error:{message:Yc.messageChars}},Qc={smart:`finished`,"smart-fallback":`hold`},$c=new Set([`vad.near`,`vad.summary`,`stt.slow`,`mark`]),el=[`junkReason`,`held`,`speechMs`],tl=new Set(Rc);function nl(e,t){let n=e;if(!tl.has(n.kind)||t?.includes(`dev.v1`)){if(!t?.includes(`turn.predict`)){if(n.kind===`turn.predict`)return;n.kind===`utterance.sent`&&typeof n.reason==`string`&&Qc[n.reason]&&(n={...n,reason:Qc[n.reason]})}if(!t?.includes(`capture.v2`)){if($c.has(n.kind)||n.kind===`utterance.command`&&n.command===`mark`)return;if(n.kind===`stt.received`&&el.some(e=>e in n)){let e={...n};for(let t of el)delete e[t];n=e}}return n}}function rl(e,t){if(e.length<=t)return e;let n=e.slice(0,t),r=n.charCodeAt(n.length-1);return r>=55296&&r<=56319?n.slice(0,-1):n}function il(e,t){let n=Jc[e],r={kind:e};for(let[i,a]of Object.entries(t)){if(a===void 0)continue;if(!n.required.includes(i)&&!n.optional.includes(i))throw Error(`${e}: unknown field ${i}`);let t=Zc[e]?.[i];r[i]=t!==void 0&&typeof a==`string`?rl(a,t):a}for(let t of n.required)if(r[t]===void 0)throw Error(`${e}: missing field ${t}`);if(e===`barge.in`){let e=e=>({...e,text:rl(e.text,Yc.textChars)}),t=r.spoken;r.spoken={text:rl(t.text,Yc.replyChars),estimated:t.estimated},r.playing&&=e(r.playing),r.unplayed=r.unplayed.slice(0,sl).map(e),r.mutedMessages=r.mutedMessages.slice(0,sl)}return r}var al=e=>`${e.messageID}:${e.ordinal}:${e.seq??``}:${e.i}`;function ol(e){let t=e||``,n=/Android/i.test(t)?`android`:/iPhone|iPad|iPod/i.test(t)?`ios`:`desktop`;return`${n}-${n===`ios`?/CriOS/.test(t)?`chrome`:/FxiOS/.test(t)?`firefox`:`safari`:/Firefox\//.test(t)?`firefox`:/SamsungBrowser/.test(t)?`samsung`:/Edg\//.test(t)?`edge`:/Chrome\//.test(t)?`chrome`:/Safari\//.test(t)?`safari`:`other`}`.slice(0,60)}var sl=20,cl=14;function ll(e,t,n){let r=n&&n>0?n:e.length/cl*1e3,i=r>0?Math.min(1,Math.max(0,t/r)):0;if(i>=1)return e.trim();let a=i*e.length,o=0;for(let t=0;t<=e.length;t++)t<e.length&&!/\s/.test(e[t])||Math.abs(t-a)<Math.abs(o-a)&&(o=t);return e.slice(0,o).trim()}function ul(e){let{cause:t,completed:n,playing:r,unplayed:i}=e,a=new Set([...r?[r.ref.messageID]:[],...i.map(e=>e.ref.messageID)]),o=e.turnRunning===!1?e.mutedMessages.filter(e=>a.has(e)):e.mutedMessages;if(!r&&!i.length&&!o.length)return;let s=new Set([...r?[r.ref.messageID]:[],...i.map(e=>e.ref.messageID),...o]),c=n.filter(e=>s.has(e.ref.messageID)).map(e=>e.text.trim());return r&&c.push(ll(r.text,r.playedMs,r.durationMs)),il(`barge.in`,{cause:t,...r?{playing:{ref:r.ref,text:r.text,playedMs:Math.round(r.playedMs),...r.durationMs===void 0?{}:{durationMs:Math.round(r.durationMs)}}}:{},spoken:{text:c.filter(Boolean).join(` `),estimated:!!r},unplayed:i.map(e=>({ref:e.ref,text:e.text})),mutedMessages:[...o]})}function dl(e,t){if((e===200||e===201)&&typeof t?.recording?.id==`string`){let e=Array.isArray(t.features)?t.features.filter(e=>typeof e==`string`):void 0;return{kind:`started`,recording:t.recording,audio:t.audio!==!1,...typeof t.hubAt==`number`?{hubAt:t.hubAt}:{},...e?{features:e}:{},...t.developer===!0?{developer:!0}:{}}}return e===404||e===405||e===501||e===409&&t?.code===`recording_off`?{kind:`off`}:e===0?{kind:`failed`,reason:`offline`}:e===429&&t?.code===`rate_limited`?{kind:`failed`,reason:`${t.limit??Yc.activePerUser} recordings are already running`}:e===429&&t?.code===`limit`?{kind:`failed`,reason:`${t.limit??Yc.recordingsStored} recordings stored; delete some in Settings → Voice`}:{kind:`failed`,reason:typeof t?.error==`string`&&t.error?t.error:`HTTP ${e}`}}var fl=new TextEncoder,pl=e=>fl.encode(e).length,ml=pl(`{"events":[]}`),hl=e=>e.kind===`clock.sync`,gl=e=>Math.max(0,Math.round(e*10)/10);function _l(e,t){let n=[],r=ml;for(let i of e){if(n.length&&i.seq!==n[n.length-1].seq+1)break;let e=pl(JSON.stringify(i))+ +!!n.length;if(r+e>t)break;n.push(i),r+=e}let i=e.length-n.length,a=n[n.length-1];if(!i||!a)return n;let o={seq:a.seq+1,t:a.t,kind:`error`,where:`upload`,message:`dropped ${i} events at page close`};return r+1+pl(JSON.stringify(o))<=t&&n.push(o),n}var vl=class{deps;limits;now;setTimer;clearTimer;seq=0;pending=[];batch;sending=!1;ready=!1;flushTimer;retryTimer;attempt=0;acked=0;flushTarget=0;waiters=[];kickQueued=!1;dropped=0;audio;stopped=!1;constructor(e){this.deps=e,this.limits={...Ic,...e.limits},this.now=e.now??(()=>performance.now()),this.setTimer=e.setTimer??((e,t)=>setTimeout(e,t)),this.clearTimer=e.clearTimer??(e=>clearTimeout(e))}get buffered(){return this.pending.length+(this.batch?.length??0)}record(e){return this.add(e,!0)}add(e,t){if(this.stopped)return;let n=++this.seq,r=gl(this.now()),i={...e,seq:n,t:r},a=pl(JSON.stringify(i));for(ml+a>this.limits.batchBytes&&(i={seq:n,t:r,kind:`error`,where:`upload`,message:`event too large: ${e.kind}`},a=pl(JSON.stringify(i))),this.pending.push({e:i,bytes:a});t&&this.pending.length>this.limits.consoleBufferEvents;)this.pending.shift(),this.dropped++;return this.ready&&!hl(i)&&this.scheduled(),n}open(e){this.stopped||this.ready||(this.ready=!0,e&&this.record(il(`clock.sync`,e)),this.pending.some(e=>!hl(e.e))&&this.scheduled())}flush(){let e=this.lastActiveSeq();if(this.stopped||e<=this.acked)return Promise.resolve();this.flushTarget=Math.max(this.flushTarget,e);let t=new Promise(t=>this.waiters.push({target:e,resolve:t}));return this.kick(),t}discard(){this.halt()}close(){if(this.stopped)return;let e=[...this.batch??[],...this.pending.map(e=>e.e)],t=this.ready;if(this.halt(),!t||!e.length)return;let n=_l(e,this.limits.keepaliveBatchBytes);n.length&&this.deps.send(n,{keepalive:!0}).catch(()=>{})}halt(){this.stopped=!0,this.pending=[],this.batch=void 0,this.clearTimer(this.flushTimer),this.clearTimer(this.retryTimer),this.flushTimer=this.retryTimer=void 0,this.settle()}lastActiveSeq(){for(let e=this.pending.length-1;e>=0;e--)if(!hl(this.pending[e].e))return this.pending[e].e.seq;let e=this.batch??[];for(let t=e.length-1;t>=0;t--)if(!hl(e[t]))return e[t].seq;return 0}activePending(){let e=0;for(let t of this.pending)hl(t.e)||e++;return e}scheduled(){if(this.activePending()>=this.limits.flushEvents){if(this.kickQueued)return;this.kickQueued=!0,queueMicrotask(()=>{this.kickQueued=!1,this.kick()})}else this.flushTimer===void 0&&(this.flushTimer=this.setTimer(()=>{this.flushTimer=void 0,this.kick()},this.limits.flushMs))}take(){let e=[],t=ml;for(;this.pending.length&&e.length<this.limits.eventsPerBatch;){let n=this.pending[0],r=n.bytes+ +!!e.length;if(e.length&&t+r>this.limits.batchBytes)break;e.push(n.e),t+=r,this.pending.shift()}return e}kick(){if(!(!this.ready||this.stopped||this.sending||this.retryTimer!==void 0)){if(!this.batch){if(!this.pending.some(e=>!hl(e.e)))return;this.batch=this.take()}this.clearTimer(this.flushTimer),this.flushTimer=void 0,this.sending=!0,this.send(this.batch)}}async send(e){let t=this.now(),n;try{n=await this.deps.send(e,{})}catch{n={status:0}}if(this.sending=!1,this.stopped||this.batch!==e)return;let r=this.now(),{status:i,body:a}=n;if(i>=200&&i<300){if(this.batch=void 0,this.attempt=0,this.acked=Math.max(this.acked,e[e.length-1].seq),typeof a?.hubAt==`number`&&this.add(il(`clock.sync`,{t0:gl(t),t1:gl(r),hubAt:a.hubAt}),!1),typeof a?.audio==`boolean`&&a.audio!==this.audio&&(this.audio=a.audio,this.deps.onAudio?.(a.audio)),this.dropped){let e=this.dropped;this.dropped=0,this.add(il(`error`,{where:`upload`,message:`dropped ${e} events (offline too long)`}),!1)}}else if(i===400)this.batch=void 0,this.attempt=0,this.acked=Math.max(this.acked,e[e.length-1].seq);else if(i===404||i===409||i===413){let e=typeof a?.code==`string`?a.code:i===404?`gone`:i===413?`limit`:`ended`;this.halt(),this.deps.onStop?.({status:i,code:e,...typeof a?.reason==`string`?{reason:a.reason}:{}});return}else{let e=(this.deps.backoffMs??(e=>Math.min(3e4,1e3*2**e)))(this.attempt++);this.retryTimer=this.setTimer(()=>{this.retryTimer=void 0,this.kick()},e);return}this.settle(),this.acked<this.flushTarget||this.activePending()>=this.limits.flushEvents?this.kick():this.activePending()>0&&this.flushTimer===void 0&&this.scheduled()}settle(){let e=this.waiters;this.waiters=[];for(let t of e)this.stopped||t.target<=this.acked?t.resolve():this.waiters.push(t)}},yl=1048576,bl={label:`Record voice conversations (developer)`,description:`Saves your voice segments, transcripts, replies, timing and Concierge actions on this hub, for 7 days. Only you can see them.`,details:[`While Voice mode runs on this device: each speech segment exactly as sent to speech-to-text, what was heard and sent, the replies and what was actually spoken before you interrupted, the timing, and the Concierge's tool calls and Decisions. Not recorded: costs, other sessions' text, the replies' audio.`,`Applies the next time Voice mode starts; a device shows ● Recording while it records. Kept 7 days, then deleted; at most ${Yc.userBytes/yl} MB in all (${Yc.recordingBytes/yl} MB per recording, ${Yc.recordingsStored} recordings).`,`Secrets in known token formats are scrubbed from the text. Audio is kept even when a secret is scrubbed from the text, and secrets spoken in a way the patterns do not match stay in the text and the audio.`,`Recordings are not encrypted at rest: whoever runs this hub can read them on its disk or database. Delete is immediate.`]},xl={label:`Developer mode`,description:`Records much more of each voice conversation, for debugging Voice: raw audio, reply audio and diagnostics. This is more private data. It turns recording on.`,details:[`Also kept, only while a recording runs: raw microphone audio around near-misses and marks (5 s clips, not only what was sent to speech-to-text), the reply audio as you heard it, the speech detector's frame traces, your audio devices, microphone settings, network, battery and screen state, console errors and warnings, request timings, and per turn the model, agent and token counts (never the prompt text).`,`The same limits as recordings: 7 days, ${Yc.userBytes/yl} MB in all and ${Yc.recordingBytes/yl} MB per recording, counted together; near the limit the extra audio stops first, segments and events go on.`,`Turning it off stops the extras at once; what was kept is deleted with its recording. Turning recording off turns Developer mode off too.`]};function Sl(e){let t=[`B`,`KB`,`MB`,`GB`],n=Math.max(0,e),r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${r===0||n>=10?String(Math.round(n)):n.toFixed(1)} ${t[r]}`}var Cl=e=>`${Sl(e.bytes)} of ${Sl(e.capBytes)}`;function wl(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t} s`;let n=Math.floor(t/60);return n<60?`${n} min`:`${Math.floor(n/60)} h${n%60?` ${n%60} min`:``}`}var Tl={date:e=>new Date(e).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),time:e=>new Date(e).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})};function El(e){let t=e?.name?.trim().replace(/^@+/,``);if(t)return`@${t}`;let n=e?.directory?.replace(/[/\\]+$/,``).split(/[/\\]/).pop();return n?`OpenCode session · ${n}`:`OpenCode session`}function Dl(e,t,n=Tl,r=()=>El(void 0)){let i=e.state===`active`;return{kind:e.kind===`concierge`?`Concierge`:`Voice`,title:e.sessionTitle||r(e.sessionID),device:e.deviceName||`a device`,started:`${n.date(e.startedAt)} ${n.time(e.startedAt)}`,time:n.time(e.startedAt),length:i?`${wl(t-e.startedAt)} · recording now`:wl((e.endedAt??t)-e.startedAt),segments:`${e.segments} segment${e.segments===1?``:`s`}`,size:Sl(e.bytes),expires:`deleted on ${n.date(e.expiresAt)}`,active:i,...e.audio?{}:{note:`no audio (storage full)`}}}function Ol(e,t,n){let r=e?`${e}${t?`+`:``} recording${e===1&&!t?``:`s`}`:`No recordings`;return n?`${r} · ${Cl(n)}`:r}var kl=e=>{let t=new Date(e);return`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()}`};function Al(e,t,n=Tl.date){let r=kl(e);if(r===kl(t))return`Today`;let i=new Date(t);return i.setDate(i.getDate()-1),r===kl(i.getTime())?`Yesterday`:n(e)}function jl(e){return e.title.trim().toLowerCase()===e.kind.toLowerCase()?{kind:e.kind}:{kind:e.kind,title:e.title}}function Ml(e){let t=e,n=new Set;return{get:()=>t,set(e){t=e;for(let e of[...n])e()},subscribe(e){return n.add(e),()=>n.delete(e)}}}var Nl={on:!1,audio:!0},Pl=Ml(Nl),Fl=e=>`${e.audio?`Recording`:`Recording · no audio (storage full)`}${e.developer?` · developer`:``}`,Il=e=>e.on?` · recording`:``,Ll=Ml({}),Rl=5e3,zl=new Set([`stored`,`skipped-cap`,`failed`,`off`]),Bl=e=>e&&zl.has(e)?e:void 0,Vl=()=>{let e=globalThis.crypto;if(e?.randomUUID)return e.randomUUID();let t=Array.from({length:32},()=>Math.floor(Math.random()*16).toString(16)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-a${t.slice(17,20)}-${t.slice(20)}`},Hl=(e,t=!1)=>({method:`POST`,credentials:`same-origin`,headers:{"content-type":`application/json`},body:JSON.stringify(e),...t?{keepalive:!0}:{}}),Ul;function Wl(e){e?.type===`recording`&&(e.settings&&typeof e.settings.enabled==`boolean`&&Gl(e.settings),Ul?.onMessage(e))}function Gl(e){Ll.set({supported:!0,settings:e}),e.enabled?e.developer!==!0&&Ul?.recordingID&&Ul.onMessage({type:`recording`,recordingID:Ul.recordingID,developer:!1}):Ul?.turnedOff()}function Kl(e){return Ul?.mark(`button`,e)??!1}var ql=`Marked`;function Jl(e,t){Ul?.event(e,t)}var Yl=class{fetch;now;epoch;limits;take;running=!1;rolled=!1;sessionID=``;client={};retried=new Set;audio=!0;track;wake;onNote;constructor(e={}){this.fetch=e.fetch??((e,t)=>globalThis.fetch(e,{credentials:`same-origin`,...t})),this.now=e.now??(()=>performance.now()),this.epoch=e.epoch??(()=>Date.now()),this.limits=e.limits}get recordingID(){let e=this.take;return e?.id&&!e.uploader.stopped?e.id:void 0}get active(){return this.recordingID!==void 0}get marks(){return this.active&&this.take?.features?.includes(`capture.v2`)===!0}mark(e,t){if(!this.marks)return!1;let n=this.event(`mark`,t?{via:e,note:t}:{via:e});return this.onNote?.(ql),n!==void 0&&this.developer&&this.onMarked?.(n),!0}get buffered(){return this.take?.uploader.buffered??0}start(e,t={}){if(this.running)return;this.running=!0,this.rolled=!1,this.sessionID=e;let n=globalThis.navigator;this.client={platform:ol(n?.userAgent??``),...t},Ul=this,this.indicate(Nl),this.begin()}event(e,t){try{let n=this.take;if(!n)return;let r=n.developer?n.features:n.features?.filter(e=>e!==`dev.v1`),i=nl(il(e,t),r);return i?n.uploader.record(i):void 0}catch{return}}get developer(){let e=this.take;return this.active&&e?.developer===!0&&e.features?.includes(`dev.v1`)===!0}onMarked;clip(e,t,n,r){let i=this.take,a=this.recordingID;if(!i||!a||!this.developer||i.clips>=Lc.clipsPerRecording||n.byteLength>Lc.clipBytes)return;let o=++i.clips;this.event(`audio.clip`,{clip:o,for:{kind:e,seq:t},preMs:r.preMs,postMs:r.postMs,bytes:n.byteLength}),this.fetch(`/api/recordings/${encodeURIComponent(a)}/clips/${o}`,{method:`PUT`,credentials:`same-origin`,headers:{"content-type":`audio/wav`},body:n}).catch(()=>{})}micTrack(e,t){this.track={settings:e,...t?{label:t}:{}},this.take?.probe?.micTrack(e,t)}wakeLock(e){this.wake=e,this.take?.probe?.wakeLock(e)}record(e){try{this.take?.uploader.record(e)}catch{}}barge(e){let t=ul(e);t&&this.record(t)}audioResult(e){return Bl(e?.get?.(Fc))}transcribeHeaders(e){let t=this.recordingID;return t?{[Mc]:t,[Nc]:String(e)}:{}}speakHeaders(e){let t=this.recordingID;return t&&e?{[Mc]:t,[Pc]:al(e)}:{}}segmentAudio(e,t,n){let r=this.recordingID;t===`failed`&&r&&!this.retried.has(e)&&(this.retried.add(e),this.fetch(`/api/recordings/${encodeURIComponent(r)}/segments/${e}`,{method:`PUT`,credentials:`same-origin`,headers:{"content-type":`audio/wav`},body:n}).catch(()=>{}))}async stop({keepalive:e=!1,reason:t=`stopped`}={}){if(!this.running)return;this.running=!1,Ul===this&&(Ul=void 0);let n=this.take;this.take=void 0,this.indicate(Nl),n&&(this.stopProbe(n),e?(n.uploader.close(),n.id&&this.end(n.id,t,!0)):(await n.started,n.id&&!n.uploader.stopped&&(await Promise.race([n.uploader.flush(),new Promise(e=>setTimeout(e,Rl))]),n.uploader.close(),await this.end(n.id,t,!1))))}turnedOff(){let e=this.take;e&&(this.stopProbe(e),e.uploader.discard(),this.take=void 0,this.indicate(Nl))}onMessage(e){if(e?.type!==`recording`)return;e.settings?.enabled===!1&&this.turnedOff();let t=this.take;if(t?.id&&e.recordingID===t.id){if(typeof e.audio==`boolean`&&this.audioChanged(t,e.audio),e.developer===!1&&t.developer){t.developer=!1,this.stopProbe(t);let e=Pl.get();e.on&&e.recordingID===t.id&&this.indicate({...e,developer:!1})}if(e.state===`deleted`)this.stopProbe(t),t.uploader.discard(),this.take=void 0,this.indicate(Nl);else if(e.state===`ended`){if(e.reason===`conversation_off`)return;t.uploader.discard(),this.ended(t,{status:409,code:`recording_ended`,...typeof e.reason==`string`?{reason:e.reason}:{}})}}}begin(){let e;e={uploader:new vl({send:(t,{keepalive:n})=>this.sendEvents(e,t,!!n),now:this.now,onStop:t=>this.ended(e,t),onAudio:t=>this.audioChanged(e,t),...this.limits?{limits:this.limits}:{}}),started:Promise.resolve(),clips:0},this.take=e,e.started=this.open(e).catch(()=>e.uploader.discard())}async open(e){let t;try{let n=await this.fetch(`/api/settings/recording`);if(n.status===404||n.status===405)return Ll.set({supported:!1}),e.uploader.discard();if(n.ok){let{settings:e}=await n.json();e&&Ll.set({supported:!0,settings:e}),t=e?.enabled}}catch{}if(t===!1||this.take!==e||!this.running)return e.uploader.discard();let n={perf:this.now(),epoch:this.epoch()},r=this.now(),i=0,a;try{let e=await this.fetch(`/api/recordings`,Hl({sessionID:this.sessionID,clientID:Vl(),anchor:n,client:this.client}));i=e.status,a=await e.json().catch(()=>({}))}catch{}let o=this.now(),s=dl(i,a);if(s.kind!==`started`){e.uploader.discard(),s.kind===`failed`&&t===!0&&this.take===e&&this.running&&this.onNote?.(`Not recording: ${s.reason}`);return}e.id=s.recording.id,e.features=s.features,e.developer=s.developer===!0,this.audio=s.audio,e.uploader.open(s.hubAt===void 0?void 0:{t0:r,t1:o,hubAt:s.hubAt});let c=e.features?.includes(`capture.v2`)===!0;this.take===e&&this.running&&(this.indicate({on:!0,audio:this.audio,sessionID:this.sessionID,recordingID:e.id,...c?{marks:c}:{},...this.developer?{developer:!0}:{}}),this.developer&&this.startProbe(e))}startProbe(e){try{let t=new qc({record:(e,t)=>void this.event(e,t)});e.probe=t,this.track&&t.micTrack(this.track.settings,this.track.label),this.wake!==void 0&&t.wakeLock(this.wake),t.start().catch(()=>{})}catch{}}stopProbe(e){try{e.probe?.stop()}catch{}e.probe=void 0}async sendEvents(e,t,n){let r=await this.fetch(`/api/recordings/${encodeURIComponent(e.id??``)}/events`,Hl({events:t},n));return{status:r.status,body:await r.json().catch(()=>({}))}}end(e,t,n){return this.fetch(`/api/recordings/${encodeURIComponent(e)}/end`,Hl({reason:t},n)).then(()=>{},()=>{})}ended(e,t){if(this.take!==e)return;this.stopProbe(e),this.take=void 0;let n=t.reason;if(n===`max_duration`&&this.running&&!this.rolled){this.rolled=!0,this.indicate(Nl),this.begin();return}let r=t.code===`limit`||n===`limit`?`Recording stopped: limit reached`:void 0;this.indicate(r?{...Nl,note:r}:Nl),r&&this.onNote?.(r)}audioChanged(e,t){if(this.take!==e||t===this.audio)return;this.audio=t;let n=Pl.get();n.on&&n.recordingID===e.id&&this.indicate({...n,audio:t})}indicate(e){Pl.set(e)}};async function Xl(e,t,n={}){let r=await(n.fetch??((e,t)=>globalThis.fetch(e,{credentials:`same-origin`,...t})))(`/api/recordings/${encodeURIComponent(e)}/segments/${t}`);if(!r.ok){let e=await r.json().catch(()=>({}));throw Error(typeof e.error==`string`&&e.error?e.error:`HTTP ${r.status}`)}let i=await r.blob(),a=(n.createURL??(e=>URL.createObjectURL(e)))(i),o=n.revokeURL??(e=>URL.revokeObjectURL(e)),s=!1,c=()=>{s||(s=!0,o(a))},l=(n.audio??(()=>new Audio))();l.addEventListener(`ended`,c),l.addEventListener(`error`,c),l.src=a;try{await l.play()}catch(e){throw c(),e}}var[X,Zl]=Ar(ho()),Ql=new Co,[$l,eu]=u(0),tu=$l,[Z,nu]=u(),[ru,iu]=u(),[au,ou]=u(),[su,cu]=u([]),[lu,uu]=u([]),[du,fu]=u(new Map),pu=du,mu=200;function hu(e){e.length&&fu(t=>{let n=new Map(t);for(let t of e)n.delete(t.id),n.set(t.id,t);for(;n.size>mu;)n.delete(n.keys().next().value);return n})}var[gu,_u]=u(),[vu,yu]=u(!1),[bu,xu]=u(!1),Su=()=>rs(vu(),bu(),X.machines!==void 0),[Cu,wu]=u();ce(()=>x(()=>{let e=Cu(),t=sc(e,Date.now());if(t===void 0)return;let n=setTimeout(()=>wu(t=>t===e?cc(t,Date.now()):t),t+50);M(()=>clearTimeout(n))}));var Tu=ce(()=>C(()=>{let e=Z();if(!e)return[];try{return cs(localStorage.getItem(os(e.user?.id)))}catch{return[]}}));ce(()=>x(()=>{let e=gu(),t=Z();if(vu()&&t)try{localStorage.setItem(os(t.user?.id),JSON.stringify((e?.hiddenSessionIDs??[]).slice(-20)))}catch{}}));var Eu=ce(()=>C(()=>ts(gu(),X.machines,vu()?[]:Tu()),void 0,{equals:(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e))}));Wt(()=>Eu());var[Du,Ou]=u([]),[ku,Au]=u(new Map),ju=new Set;async function Mu(){try{Au(new Map(Se(await K(`/api/agent/grants`)).map(e=>[e.id,e])))}catch{}}var Nu=e=>ku().get(e),Pu=new Set;function Fu(e){return Pu.add(e),()=>Pu.delete(e)}var Iu=ce(()=>C(e=>ha(e,ma(X.machines,X.prefs,X.reads,Eu(),{activity:X.activity,intents:X.intents})))),Lu=e=>yo(X.machines,e),Ru=e=>Eu().has(e)?`the Concierge`:Lu(e)?.session.title||void 0,[zu,Bu]=u(new Map);async function Vu(){try{let e=await K(`/api/agent/who`),t=Array.isArray(e?.sessions)?e.sessions:[];Bu(new Map(t.flatMap(e=>e&&typeof e==`object`&&typeof e.sessionID==`string`&&typeof e.name==`string`&&e.name?[[e.sessionID,e.name]]:[])))}catch{}}function Hu(e){if(Eu().has(e))return Ue(e,void 0,!0);let t=Lu(e)?.session,n=zu().get(e);if(!n)for(let t of pu().values())t.from.kind===`session`&&t.from.sessionID===e&&t.from.name&&(n=t.from.name);return Ue(e,{name:n,title:t?.title,directory:typeof t?.project==`string`&&t.project||t?.directory})}var Uu=new oi;Me(()=>{ut().name!==`pair`&&(dd(),nu(void 0),Wu())});function Wu(){let e=location.pathname+location.search;Bt(`/pair${e===`/`||e.startsWith(`/pair`)?``:`?next=${q(e)}`}`,{replace:!0})}async function Gu(){if(Z())return!0;let e=await fetch(`/api/me`,{credentials:`same-origin`});if(e.status===401)return Wu(),!1;if(!e.ok)throw Error(`HTTP ${e.status}`);return nu(await e.json()),!0}async function Ku(){if(ru()!==void 0)return ru()??null;try{let e=await fetch(`/api/auth`,{credentials:`same-origin`}),t=e.ok?await e.json():null;return iu(t),t}catch{return null}}var qu,Ju,Yu=1e3,Xu=()=>!1,Zu={lite:!1},[Qu,$u]=u(``),ed,td=!1,nd=new To({setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e),open:(e,t)=>ld(e,t),close:()=>cd(),keepOpen:()=>Xu()});function rd(e){Xu=e}function id(e){Zu=e,nd.setScope(e)}var ad=!1;function od(){ad||(ad=!0,document.addEventListener(`visibilitychange`,()=>document.visibilityState===`hidden`?nd.hidden():nd.visible()),window.addEventListener(`pageshow`,e=>{e.persisted&&nd.state!==`stopped`&&nd.reopen()}),window.addEventListener(`online`,()=>nd.state===`open`&&X.connection===`down`&&nd.reopen()))}function sd(e={lite:!1}){nd.state===`stopped`&&(od(),Zu=e,nd.start(e),vu()||(Sd(),setTimeout(()=>!vu()&&xu(!0),ns)),document.visibilityState===`hidden`&&nd.hidden())}function cd(){clearTimeout(Ju),qu?.close(),qu=void 0,nd.state===`paused`&&Zl(`connection`,`paused`)}function ld(e,t){clearTimeout(Ju),qu?.close();let n=Eo(X.connection,t);td=n.reconnecting,n.reconnecting&&ud(`reconnecting`),Zl(`connection`,n.connection),kc(Zu);let r=new EventSource(e,{withCredentials:!0});qu=r,r.onopen=()=>{Yu=1e3,Zl(`connection`,`live`),td&&ud(`updated`,2e3),td=!1,Ld(),_d(),pd(),hd(),Md(),Dd(),Vu(),Mu(),Sd()},r.onerror=async()=>{qu===r&&(Zl(`connection`,`down`),(await fetch(`/api/me`,{credentials:`same-origin`}).catch(()=>void 0))?.status===401?(dd(),nu(void 0),Wu()):r.readyState===EventSource.CLOSED&&qu===r&&(qu=void 0,Ju=setTimeout(()=>nd.state===`open`&&nd.reopen(),Yu),Yu=Math.min(3e4,Yu*2)))},r.addEventListener(`ping`,()=>nd.received()),r.onmessage=e=>{nd.received(e.lastEventId||void 0);let t;try{t=JSON.parse(e.data)}catch{return}fd(t)}}function ud(e,t){clearTimeout(ed),$u(e),t&&(ed=setTimeout(()=>$u(``),t))}function dd(){nd.stop(),qu?.close(),qu=void 0,clearTimeout(Ju)}function fd(e){me(()=>{if(Ac(e),e.type===`prefs`?(Zl(Lr(t=>vo(t,e))),X.prefsStale&&!X.prefsPending&&Rd()):e.type===`catalog`?Zl(Lr(t=>{vo(t,e),Uu.apply(t.machines,Date.now())})):Zl(Lr(t=>vo(t,e))),e.type===`status`){let t=Lu(e.sessionID);!Ql.has(e.sessionID)&&t&&Ql.feed(e.sessionID)}if(Ql.apply(e)!==void 0&&eu(e=>e+1),e.type===`enrollment`&&Md(),e.type===`intent`&&typeof e.sessionID==`string`&&gd(e.sessionID),e.type===`recording`&&Wl(e),e.type===`decision`){let t=Ne(e.decision);if(t){Ed.event(t);let e=Ze(lu(),t);e&&J(e),uu(e=>Oe(e,t)),hu([t])}}if(e.type===`concierge`){let t=$o(e.status);t&&(wu(e=>ac(gu(),t,e)),_u(t),yu(!0),yd++);let n=Hs(e.armed);n!==void 0&&(wd.event(),wu(n))}if(e.type===`agent`){let t=be(e.entry);t&&Ou(e=>Vt(e,t)),t?.grant&&!ku().has(t.grant)&&!ju.has(t.grant)&&(ju.add(t.grant),Mu())}if(e.type===`resync`&&(_d(),pd(),hd(),Rd(),Md(),Dd(),Vu(),Mu(),Sd()),e.type===`handoff`&&(ut().name!==`session`||ut().id!==e.sessionID)){let t=Lu(e.sessionID);J(`Handed off: ${t?.session.title||e.sessionID}`,``,{label:`Open`,run:()=>Bt(`/s/${q(e.sessionID)}`)})}});for(let t of Pu)t(e)}async function pd(){try{let{activity:e}=await K(`/api/activity/mine`);Zl(`activity`,ra(e))}catch{}}var md=e=>{let t=e;return t&&typeof t.text==`string`&&t.text&&t.source!==`title`?{text:t.text,...typeof t.source==`string`?{source:t.source}:{}}:void 0};async function hd(){try{let{intents:e}=await K(`/api/intents/mine`),t={};for(let[n,r]of Object.entries(e??{})){let e=md(r);e&&(t[n]=e)}Zl(`intents`,t)}catch{}}async function gd(e){try{let{intent:t}=await K(`/api/agent/sessions/${q(e)}/intent`),n=md(t);Zl(`intents`,Lr(t=>{n?t[e]=n:delete t[e]}))}catch{}}async function _d(){try{let{reads:e}=await K(`/api/reads`);Zl(`reads`,e??{})}catch{}}async function vd(e,t=!1){try{let{reads:n}=await(await H(`${U(e)}/read`,{method:`POST`,json:t?{open:!0}:{}})).json();n&&typeof n==`object`&&Zl(`reads`,n)}catch{}}var yd=0,bd,xd;function Sd(){return bd?(xd??=bd.then(()=>(xd=void 0,Sd())),xd):(bd=Cd().finally(()=>bd=void 0),bd)}async function Cd(){let e=yd;try{let t=es(await K(`/api/agent/concierge`));t&&e===yd&&_u(t.status)}catch(t){t instanceof G&&t.status===404&&e===yd&&_u(void 0);return}finally{yu(!0)}await Td()}var wd=new lc;async function Td(){let e=wd.begin();try{let t=Hs((await K(`/api/agent/concierge/arm`)).armed);wd.fresh(e)&&t!==void 0&&wu(cc(t,Date.now()))}catch(t){wd.fresh(e)&&t instanceof G&&(t.status===404||t.status===403)&&wu(void 0)}}var Ed=new Ge;async function Dd(){let e=Ed.begin();try{let{decisions:t}=await K(`/api/decisions?state=open`),n=Ed.settle(e,(t??[]).map(Ne).filter(e=>!!e));if(!n)return;uu(n),hu(n)}catch(t){Ed.fail(e),t instanceof G&&t.status===404&&uu([])}}var Od=new qo({fetch:e=>K(`/api/decisions/${q(e)}`),parse:e=>Ne(e?.decision)??void 0,status:e=>e instanceof G?e.status:void 0});function kd(e){let t=du().get(e);return t?Promise.resolve(t):Od.recall(e).then(t=>(t&&!du().has(e)&&hu([t]),t))}function Ad(e){Ed.event(e),uu(t=>Oe(t,e)),hu([e])}function jd(e){let t=lu().find(t=>t.id===e);t&&Ed.event({...t,state:`closed`}),uu(t=>t.filter(t=>t.id!==e)),Dd()}async function Md(){if(!Kn(Z()))cu([]);else try{cu((await K(`/api/enrollments`)).enrollments??[])}catch{cu([])}}async function Nd(){try{ou((await K(`/api/settings/speech`)).ready??null)}catch{ou(null)}}var Pd=`voice.viewPrefs`,Fd=!1,Id=()=>X.prefsSource===`hub`||X.prefsSource===`local`;async function Ld(){if(!(Id()||Fd)){Fd=!0;try{Zl({prefs:ri(await K(`/api/prefs/view`)),prefsSource:`hub`})}catch(e){if(e instanceof G&&e.status===404){let e;try{e=JSON.parse(localStorage.getItem(Pd)??`null`)}catch{}Zl({prefs:ri(e),prefsSource:`local`})}else Zl(`prefsSource`,`error`)}finally{Fd=!1}Id()&&await zd()}}async function Rd(){Zl({prefsStale:!1,prefsSource:`unknown`}),await Ld()}async function zd(){let{clear:e,patch:t}=ui(localStorage.getItem(`voice.pins`),localStorage.getItem(`voice.pinnedWorkspaces`),X.prefs);e&&(t&&(Zl(`prefs`,e=>({...e,...t})),!(await Bd(t)).ok)||(localStorage.removeItem(`voice.pins`),localStorage.removeItem(`voice.pinnedWorkspaces`)))}async function Bd(e){if(X.prefsSource===`local`)return localStorage.setItem(Pd,JSON.stringify(X.prefs)),{ok:!0};Zl(`prefsPending`,e=>e+1);try{let t=await(await H(`/api/prefs/view`,{method:`PUT`,json:e})).json().catch(()=>void 0);return X.prefsPending===1&&t&&!X.prefsStale&&Zl(`prefs`,ri(t)),{ok:!0}}catch(e){return{ok:!1,error:e}}finally{Zl(`prefsPending`,e=>e-1),!X.prefsPending&&X.prefsStale&&Rd()}}function Vd(e,t,n,r={}){Hd(e,[t],n,r)}function Hd(e,t,n,{message:r,undo:i=!1}={}){if(!Id()){J(`Your view settings are still loading. Try again in a moment.`,`err`),Ld();return}let a=new Set(X.prefs[e]),o=t.filter(e=>a.has(e)!==n),{prefs:s,patch:c}=ci(X.prefs,e,o,n);c&&(Zl(`prefs`,s),r&&J(r,``,i?{label:`Undo`,run:()=>Hd(e,o,!n)}:void 0),Bd(c).then(({ok:t,error:r})=>{t||(Zl(`prefs`,ci(X.prefs,e,o,!n).prefs),J(`Could not save that change: ${W(r)}`,`err`))}))}async function Ud(e,t){try{return await H(`${U(e)}/expose`,{method:`POST`,json:{on:t}}),J(t?`Voice enabled`:`Voice disabled`),!0}catch(e){return J(`Could not ${t?`enable`:`disable`} Voice: ${W(e)}`,`err`),!1}}async function Wd(e,t){let n=ii(t);if(`error`in n)return J(n.error,`err`),!1;let{title:r}=n,i=Lu(e)?.session.title;if(i===r)return!1;Uu.set(e,r,Date.now()),Zl(Lr(t=>void ai(t.machines,e,r)));try{let t=await(await H(`${U(e)}/rename`,{method:`POST`,json:{title:r}})).json().catch(()=>void 0),n=typeof t?.title==`string`&&t.title?t.title:r;return n!==r&&Lu(e)?.session.title===r&&(Uu.drop(e,r),Uu.set(e,n,Date.now()),Zl(Lr(t=>void ai(t.machines,e,n)))),!0}catch(t){return Uu.drop(e,r),i!==void 0&&Lu(e)?.session.title===r&&Zl(Lr(t=>void ai(t.machines,e,i))),J(`Could not rename: ${W(t)}`,`err`),!1}}var[Gd,Kd]=u(new Set),qd=e=>Gd().has(e),Jd=(e,t)=>Kd(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r}),Yd=6e4;async function Xd(e){if(qd(e))return;let t=Lu(e)?.session.title;Jd(e,!0);let n=!1;try{let r=await(await H(`${U(e)}/rename`,{method:`POST`,json:{auto:!0}})).json().catch(()=>void 0);if(r?.pending){n=!0,J(`OpenCode is still naming it; the title changes when it's ready`);let r=Date.now()+Yd,i=()=>{let n=Lu(e)?.session.title;n!==void 0&&n!==t?(Jd(e,!1),J(`Renamed to “${n}”`)):Date.now()>=r?Jd(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){J(`OpenCode kept the title`);return}Uu.set(e,i,Date.now()),Zl(Lr(t=>void ai(t.machines,e,i))),J(`Renamed to “${i}”`)}catch(e){J(`Could not auto-name: ${W(e)}`,`err`)}finally{n||Jd(e,!1)}}async function Zd(e){try{await H(`${U(e)}/error/dismiss`,{method:`POST`,json:{}})}catch(e){J(`Could not dismiss the error: ${W(e)}`,`err`)}}async function Qd(e){try{let{stopped:t}=await(await H(`${U(e)}/stop`,{method:`POST`,json:{}})).json(),n=Array.isArray(t)?t.length:0;J(n?`Stopped ${n} session${n===1?``:`s`}`:`Nothing was running`)}catch(e){J(`Could not stop: ${W(e)}`,`err`)}}var $d=I(`<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 ef(e){let t=()=>e.size??18;return(()=>{var n=$d();return s(r=>{var i=`hub-mark${e.class?` ${e.class}`:``}`,a=t(),o=t();return i!==r.e&&b(n,`class`,r.e=i),a!==r.t&&b(n,`width`,r.t=a),o!==r.a&&b(n,`height`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})()}var tf=I(`<p class=error role=alert>`),nf=I(`<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`),rf=I(`<p class=muted>Sign in to see and control your own OpenCode sessions.`),af=I(`<a class="btn primary signin">Sign in with Google`),of=I(`<details class=card><summary>Have a pairing code?`),sf=I(`<main class=entry><h1 class="display brand-big"> Hub`),cf=I(`<p class=muted>Loading…`),lf=I(`<p class=muted>Pair this browser with your hub to see and control your OpenCode sessions.`),uf=I(`<p>A terminal on <strong></strong> asks to act as you through the hub CLI.`),df=I(`<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.`),ff=I(`<fieldset class=stack><legend class=small>What it may do`),pf=I(`<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.`),mf=I(`<div class=row><button type=button class="btn primary">Approve</button><button type=button class="btn danger">Deny`),hf=I(`<p role=status>`),gf=I(`<main class=entry><h1 class=display>CLI login for </h1><div class="card stack"><a class=btn href=/>Back to sessions`),_f=I(`<label class=check><input type=checkbox><span><span class=mono></span> `),vf=I(`<main class=entry><p class=muted>Loading…`),yf=I(`<strong>`),bf=I(`<p>`),xf=I(`<p class="small muted">Approve only if this code matches the one shown in OpenCode.`),Sf=I(`<p class=small>`),Cf=I(`<main class=entry><h1 class=display>Approve machine</h1><div class="card stack"><a class=btn href=/>Back to sessions`),wf=I(`<p>No code given.`),Tf=I(`<strong class=mono>`),Ef=I(`<main class=entry><h1 class=display>Connect an app</h1><div class="card stack"><p role=status data-consent-missing></p><a class=btn href=/>Back to sessions`),Df=I(`<p><strong></strong> wants to use this hub as <!>.`),Of=I(`<p class="small muted">After you decide, your browser goes back to <span class=mono data-consent-origin></span>. Approve only if you started this from that app.`),kf=I(`<fieldset class=stack><legend class=small>What it may do (untick what it should not)`),Af=I(`<p class="small muted">Acting still needs a grant from you (Settings → Agents & access). You can revoke this app there at any time.`),jf=I(`<main class="entry consent"><h1 class=display>Connect </h1><div class="card stack">`),Mf=I(`<p class=small data-consent-current>It is already connected with <!>. Approving replaces that.`),Nf=I(`<span class="badge-pill warn"title="Only within a grant you create">acts in your sessions`);function Pf(){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 Ff(e){let[t,i]=u(),[a,o]=u(!1),[c,d]=u(``),[f,p]=u(Pf()),[m,h]=u(e.error?`Sign-in did not work: ${e.error}`:``),[g,_]=u(!1);R(async()=>{let[t,n]=await Promise.all([fetch(`/api/me`,{credentials:`same-origin`}).catch(()=>void 0),Ku()]);if(t?.ok)return nu(await t.json()),Bt(e.next,{replace:!0});i(Qn(n??void 0,e.next)),o(!0)});let v=async t=>{t.preventDefault();let n=c().replace(/\D/g,``);if(n.length!==6)return h(`Enter the 6-digit code.`);_(!0),h(``);try{await H(`/api/pair`,{method:`POST`,json:{code:n,deviceName:f().trim()||Pf()}}),nu(void 0),Bt(e.next,{replace:!0})}catch(e){h(e instanceof G&&e.status===401?`That code is wrong or expired. Get a fresh one and try again.`:W(e)),_(!1)}},x=()=>(()=>{var e=nf(),t=e.firstChild,r=t.firstChild.nextSibling,i=t.nextSibling.nextSibling,a=i.firstChild.nextSibling,o=i.nextSibling;return e.addEventListener(`submit`,v),r.$$input=e=>d(e.currentTarget.value),a.$$input=e=>p(e.currentTarget.value),y(e,n(l,{get when(){return m()},get children(){var e=tf();return y(e,m),e}}),o),s(()=>o.disabled=g()),s(()=>r.value=c()),s(()=>a.value=f()),e})();return(()=>{var i=sf(),o=i.firstChild,c=o.firstChild;return y(o,n(ef,{class:`brand-mark`,size:30}),c),y(i,n(l,{get when(){return a()},get fallback(){return cf()},get children(){return n(l,{get when(){return t()},get fallback(){return[lf(),r(x)]},get children(){return[rf(),(()=>{var e=af();return s(()=>b(e,`href`,t())),e})(),(()=>{var t=of();return t.firstChild,y(t,x,null),s(()=>t.open=!!e.error),t})()]}})}}),null),i})()}function If(e){let t=pt(e.login),[r,i]=u(t.filter(e=>e.checked).map(e=>e.scope)),[a,o]=u(``),[c,d]=u(``),[f,p]=u(!1),h=()=>e.login.userCode,g=async t=>{let n=t===`approve`?Gt(r()):{ok:!0,body:{}};if(!n.ok)return o(n.error);p(!0);try{await H(`/api/cli-logins/${q(h())}/${t}`,{method:`POST`,json:n.body}),d(t===`approve`?`The terminal on ${e.login.clientName} is logged in as you, with ${r().join(`, `)}.${r().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){o(e instanceof G&&e.status===404?`No pending request with code ${h()}. It may have expired or been answered already.`:W(e)),p(!1)}};return(()=>{var o=gf(),u=o.firstChild;u.firstChild;var d=u.nextSibling,p=d.firstChild;return y(u,()=>e.login.clientName,null),y(d,n(l,{get when(){return!c()},get fallback(){return(()=>{var e=hf();return y(e,c),e})()},get children(){return[(()=>{var t=uf(),n=t.firstChild.nextSibling;return y(n,()=>e.login.clientName),t})(),(()=>{var t=df(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(t,h,n),y(t,()=>z(e.login.created),r),t})(),(()=>{var e=ff();return e.firstChild,y(e,n(m,{each:t,children:e=>(()=>{var t=_f(),n=t.firstChild,a=n.nextSibling,o=a.firstChild;return o.nextSibling,n.addEventListener(`change`,t=>i(t.currentTarget.checked?[...r(),e.scope]:r().filter(t=>t!==e.scope))),y(o,()=>e.scope),y(a,()=>e.label,null),y(a,()=>e.requested?` (requested)`:``,null),s(()=>n.disabled=f()),s(()=>n.checked=e.checked),t})()}),null),e})(),n(l,{get when(){return r().includes(`sessions:launch`)},get children(){return pf()}}),(()=>{var e=mf(),t=e.firstChild,n=t.nextSibling;return t.$$click=()=>void g(`approve`),n.$$click=()=>void g(`deny`),s(e=>{var r=f(),i=f();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})(),n(l,{get when(){return a()},get children(){var e=hf();return y(e,a),e}})]}}),p),o})()}function Lf(e){let[t,r]=u(),[i,a]=u(!e.code);return R(async()=>{if(e.code){try{r(Ye(await(await H(`/api/cli-logins/${q(e.code.toUpperCase())}`)).json()))}catch{}a(!0)}}),n(l,{get when(){return i()},get fallback(){return vf()},get children(){return n(l,{get when(){return t()},get fallback(){return n(Rf,{get code(){return e.code}})},children:e=>n(If,{get login(){return e()}})})}})}function Rf(e){let t=()=>e.code.toUpperCase(),[i,a]=u(``),[o,c]=u(``),[d,f]=u(!1),[p,m]=u(!Kn(Z()));R(async()=>{await Md(),m(!0)});let h=()=>su().find(e=>e.userCode===t()),g=()=>`No pending request with code ${t()}. It may have expired or been answered already.`,_=async e=>{f(!0);let n=h()?.machineName;try{await H(`/api/enrollments/${q(t())}/${e}`,{method:`POST`,json:{}}),c(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){a(e instanceof G&&e.status===404?g():W(e)),f(!1)}};return(()=>{var e=Cf(),a=e.firstChild.nextSibling,c=a.firstChild;return y(a,n(l,{get when(){return!o()},get fallback(){return(()=>{var e=hf();return y(e,o),e})()},get children(){return n(l,{get when(){return t()},get fallback(){return wf()},get children(){return n(l,{get when(){return p()},get fallback(){return cf()},get children(){return n(l,{get when(){return!Kn(Z())||h()},get fallback(){return(()=>{var e=bf();return y(e,g),e})()},get children(){return[(()=>{var e=bf();return y(e,n(l,{get when(){return h()},get fallback(){return[`A machine showing code `,(()=>{var e=Tf();return y(e,t),e})(),` wants to connect to this hub.`]},get children(){return[(()=>{var e=yf();return y(e,()=>h().machineName),e})(),` wants to connect to this hub.`]}})),e})(),(()=>{var e=xf(),t=e.firstChild;return y(e,(()=>{var e=r(()=>!!h());return()=>e()?`Code ${h().userCode} · requested ${z(h().created)}. `:``})(),t),e})(),(()=>{var e=Sf();return y(e,()=>$n(Z())),e})(),(()=>{var e=mf(),t=e.firstChild,n=t.nextSibling;return t.$$click=()=>void _(`approve`),n.$$click=()=>void _(`deny`),s(e=>{var r=d(),i=d();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})(),n(l,{get when(){return i()},get children(){var e=hf();return y(e,i),e}})]}})}})}})}}),c),e})()}function zf(e){let[t,r]=u(),[i,a]=u(``);return R(async()=>{try{let t=mt(await(await H(`/api/connect/flows/${q(e.flow)}`)).json());t?r(t):a(`The hub sent a request this console cannot show.`)}catch(e){a(e instanceof G&&e.status===404?`This request expired: start again from the app.`:W(e))}}),n(l,{get when(){return t()},get fallback(){return(()=>{var e=Ef(),t=e.firstChild.nextSibling.firstChild;return y(t,()=>i()||`Loading…`),e})()},children:e=>n(Bf,{get flow(){return e()}})})}function Bf(e){let t=it(e.flow),[i,a]=u(t.map(e=>e.scope)),[o,c]=u(``),[d,f]=u(``),[p,h]=u(!1),g=()=>{let e=qn(Z());return e.mode===`oidc`?e.title:`you`},_=async t=>{let n=t===`approve`?et(e.flow,i()):{ok:!0,body:{}};if(!n.ok)return c(n.error);h(!0),c(``);try{let r=await(await H(`/api/connect/flows/${q(e.flow.id)}/${t}`,{method:`POST`,json:n.body})).json();if(typeof r.redirect!=`string`)throw Error(`The hub did not say where to go next`);f(t===`approve`?`Connected. Taking you back to ${e.flow.client.redirectOrigin}…`:`Denied. Taking you back to ${e.flow.client.redirectOrigin}…`),location.assign(r.redirect)}catch(e){c(e instanceof G&&e.status===404?`This request expired: start again from the app.`:W(e)),h(!1)}};return(()=>{var c=jf(),u=c.firstChild;u.firstChild;var f=u.nextSibling;return y(u,()=>e.flow.client.name,null),y(f,n(l,{get when(){return!d()},get fallback(){return(()=>{var e=hf();return y(e,d),e})()},get children(){return[(()=>{var t=Df(),n=t.firstChild,r=n.nextSibling.nextSibling;return r.nextSibling,y(n,()=>e.flow.client.name),y(t,g,r),t})(),(()=>{var t=Of(),n=t.firstChild.nextSibling;return y(n,()=>e.flow.client.redirectOrigin),t})(),n(l,{get when(){return e.flow.connection},children:e=>(()=>{var t=Mf(),n=t.firstChild.nextSibling;return n.nextSibling,y(t,()=>e().scopes.join(`, `)||`no scopes`,n),t})()}),(()=>{var e=kf();return e.firstChild,y(e,n(m,{each:t,children:e=>(()=>{var t=_f(),o=t.firstChild,c=o.nextSibling,u=c.firstChild;return u.nextSibling,o.addEventListener(`change`,t=>a(t.currentTarget.checked?[...i(),e.scope]:i().filter(t=>t!==e.scope))),y(u,()=>e.scope),y(c,(()=>{var t=r(()=>e.label!==e.scope);return()=>t()?e.label:``})(),null),y(c,n(l,{get when(){return e.act},get children(){return Nf()}}),null),s(t=>{var n=p(),r=e.scope;return n!==t.e&&(o.disabled=t.e=n),r!==t.t&&b(o,`data-consent-scope`,t.t=r),t},{e:void 0,t:void 0}),s(()=>o.checked=e.checked),t})()}),null),e})(),Af(),(()=>{var e=mf(),t=e.firstChild,n=t.nextSibling;return t.$$click=()=>void _(`approve`),n.$$click=()=>void _(`deny`),s(e=>{var r=p(),i=p();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})(),n(l,{get when(){return o()},get children(){var e=tf();return y(e,o),e}})]}})),s(()=>b(c,`data-consent`,e.flow.id)),c})()}B([`input`,`click`]);var Vf=I(`<svg class=activity-meter height=16 role=img data-activity-meter><title></title><rect class=meter-base x=0 y=11 height=0.5>`),Hf=I(`<svg><rect class=meter-agent width=3></svg>`,!1,!0,!1),Uf=I(`<svg><rect class=meter-human y=12 width=3 height=4></svg>`,!1,!0,!1),Wf=4,Gf=11,Kf=4,qf=(e,t,n)=>e<=0||t<=0?0:Math.max(Kf,Math.round(n*Math.log2(1+e)/Math.log2(1+t)));function Jf(e){let t=()=>aa(e.buckets,e.now),i=()=>la(oa(e.buckets,e.now)),a=()=>Math.max(0,...t().map(e=>e.agent)),o=24*Wf;return(()=>{var e=Vf(),c=e.firstChild,l=c.nextSibling;return b(e,`width`,o),b(e,`viewBox`,`0 0 ${o} 16`),y(c,i),b(l,`width`,o),y(e,n(m,{get each(){return t()},children:(e,t)=>[r(()=>r(()=>e.agent>0)()&&(()=>{var n=Hf();return s(r=>{var i=t()*Wf,o=Gf-qf(e.agent,a(),Gf),s=qf(e.agent,a(),Gf);return i!==r.e&&b(n,`x`,r.e=i),o!==r.t&&b(n,`y`,r.t=o),s!==r.a&&b(n,`height`,r.a=s),r},{e:void 0,t:void 0,a:void 0}),n})()),r(()=>r(()=>e.human>0)()&&(()=>{var e=Uf();return s(()=>b(e,`x`,t()*Wf)),e})())]}),null),s(()=>b(e,`aria-label`,i())),e})()}var Yf=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window&&window.isSecureContext;function Xf(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 Zf=(e,t)=>!e||e.byteLength!==t.byteLength?!1:new Uint8Array(e).every((e,n)=>e===t[n]),[Qf,$f]=u(0),[ep,tp]=u(new Set),np=()=>`Notification`in window?Notification.permission:`default`;async function rp(){if(`serviceWorker`in navigator)return await navigator.serviceWorker.getRegistration(`/`).catch(()=>void 0)??void 0}async function ip(){if(Yf())return await(await rp())?.pushManager.getSubscription()??void 0}async function ap(e){let t=await K(`/api/push/prefs${e?`?endpoint=${encodeURIComponent(e)}`:``}`);return tp(new Set(t.muted??[])),t}async function op(){let e=Yf(),t=e?await rp():void 0,n=await t?.pushManager.getSubscription().catch(()=>null)??void 0,r=await ap(n?.endpoint).catch(()=>void 0);return{env:{supported:e,permission:np(),worker:!!t,...n?{endpoint:n.endpoint}:{},hubSubscribed:!!r?.subscribed,hubSubscriptions:r?.subscriptions??0},view:r}}async function sp(){let{publicKey:e}=await K(`/api/push/key`),t=Xf(e);await rp()||await navigator.serviceWorker.register(`/sw.js`,{scope:`/`});let n=await navigator.serviceWorker.ready,r=await n.pushManager.getSubscription();return r&&!Zf(r.options?.applicationServerKey,t)&&(await r.unsubscribe(),r=null),r??=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),await H(`/api/push/subscribe`,{method:`POST`,json:{subscription:r.toJSON()}}),r}async function cp(){if(!Yf())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 sp()}async function lp(){let e=await ip();e&&(await H(`/api/push/unsubscribe`,{method:`POST`,json:{endpoint:e.endpoint}}).catch(()=>{}),await e.unsubscribe().catch(()=>{}))}async function up(e){return(await H(`/api/push/test`,{method:`POST`,json:e?{kind:e}:{}})).json()}async function dp(e,t){let n=ep(),r=new Set(n);t?r.add(e):r.delete(e),tp(r);try{let n=await(await H(`/api/push/mute`,{method:`PUT`,json:{sessionID:e,muted:t}})).json();tp(new Set(n.muted)),J(t?`Notifications muted for this session`:`Notifications on for this session`)}catch(e){tp(n),J(e instanceof Error?e.message:String(e),`err`)}}async function fp(){let{env:e}=await op().catch(()=>({env:void 0}));e&&Jt(e)&&await sp().then(()=>$f(e=>e+1),e=>console.warn(`push re-subscribe:`,e?.message??e))}function pp(){`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&&Bt(e.pathname+e.search)}for(let e of mp)e(t)}))}var mp=new Set;function hp(e){return mp.add(e),()=>mp.delete(e)}function gp(e,t,n,r){if(!(n>0)||!(r>0)||!Number.isFinite(e)||!Number.isFinite(t))return`center`;let i=e/n,a=t/r,[o,s]=[[`left`,i],[`right`,1-i],[`top`,a],[`bottom`,1-a]].reduce((e,t)=>t[1]<e[1]?t:e);return s<.25?o:`center`}var _p=e=>e===`left`||e===`right`?`vertical`:`horizontal`;function vp(e,t,n,r){let i=r?t+1:t;if(i<=1)return`single`;let a=_p(n);return i===2?a:e===`grid`?`grid`:e===a?r&&i>=hn?`grid`:a:`grid`}function yp(e,t,n,r){return r===`grid`&&n===`bottom`?Math.min(e,t+2):n===`left`||n===`top`?t:t+1}var bp=(e,t)=>Number.isInteger(t)&&t>=0&&t<e.panes.length;function xp(e,t,n){if(!bp(e,t))return{layout:e,outcome:`invalid`};let r=()=>({layout:an(e.split,e.panes,t),outcome:`focused`});if(`empty`in n)return r();let{index:i,zone:a}=n;if(!bp(e,i))return{layout:e,outcome:`invalid`};if(i===t)return r();let o=e.panes[t];if(a===`center`){let n=e.panes.map((n,r)=>r===t?e.panes[i]:r===i?o:n);return{layout:an(e.split,n,i),outcome:`moved`}}let s=e.panes.filter((e,n)=>n!==t),c=vp(e.split,e.panes.length,a,!1),l=yp(s.length,i>t?i-1:i,a,c),u=[...s.slice(0,l),o,...s.slice(l)],d=c===e.split&&u.every((t,n)=>t===e.panes[n]);return{layout:an(c,u,l),outcome:d?`focused`:`moved`}}function Sp(e,t,n){let r=un(t);if(!r)return{layout:e,outcome:`invalid`};let i=e.panes.findIndex(e=>ln(e,r));if(i>=0)return xp(e,i,n);let a=e.panes.length;if(!a)return{layout:an(e.split,[r],0),outcome:`added`};let{index:o,zone:s}=`empty`in n?{index:a-1,zone:`right`}:n;if(!bp(e,o))return{layout:e,outcome:`invalid`};if(s===`center`)return{layout:an(e.split,e.panes.map((e,t)=>t===o?r:e),o),outcome:`replaced`};if(a>=hn)return{layout:e,outcome:`limit`};let c=vp(e.split,a,s,!0),l=yp(a,o,s,c);return{layout:an(c,[...e.panes.slice(0,l),r,...e.panes.slice(l)],l),outcome:`added`}}var Cp={side:{min:180,max:480,default:235},rail:{min:220,max:640,default:260}},wp=`hub.panels`,Tp=(e,{min:t,max:n})=>Math.min(n,Math.max(t,e));function Ep(e,t,n){let{min:r,max:i}=Cp[e];return{min:r,max:Math.max(r,Math.min(i,Math.floor(t-420-n)))}}var Dp={min:320,max:440,share:.4};function Op(e,t,n){let r=e=>t-(n.concierge&&e?Dp.min:0),i=Tp(e.side,Ep(`side`,r(n.side),n.rail?Cp.rail.min:0)),a=Tp(e.rail,Ep(`rail`,r(n.rail),n.side?i:0));if(!n.concierge)return{side:i,rail:a};let o=Math.min(Dp.max,Math.floor(t*Dp.share)),s=t-420-(n.side?i:0)-(n.rail?a:0);return{side:i,rail:a,concierge:Math.max(Dp.min,Math.min(o,s))}}function kp(e,t,n,r,i){let a=r?64:16,o=e===`side`?`ArrowRight`:`ArrowLeft`,s=e===`side`?`ArrowLeft`:`ArrowRight`;if(n===o)return Tp(t+a,i);if(n===s)return Tp(t-a,i);if(n===`Home`)return i.min;if(n===`End`)return i.max}function Ap(e,t,n,r){let i=e===`side`?t+n:t-n;return e===`side`&&i<r.min-48?{collapse:!0}:{width:Tp(Math.round(i),r)}}var jp=(e,t)=>{let{min:n,max:r,default:i}=Cp[e];return typeof t==`number`&&Number.isFinite(t)?Tp(Math.round(t),{min:n,max:r}):i};function Mp(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:jp(`side`,n.side),rail:jp(`rail`,n.rail)}}function Np(e,t,n){try{e.setItem(wp,JSON.stringify({...Mp(e),[t]:jp(t,n)}))}catch{}}var Pp=window.matchMedia(`(max-width: 760px)`),[Fp,Ip]=u(Pp.matches);Pp.addEventListener(`change`,()=>{Ip(Pp.matches),Wp(!Pp.matches&&localStorage.getItem(Rp)!==`0`)});var Q=Fp,Lp=`hub.sidebar.collapsed`,Rp=`hub.rail.open`,[zp,Bp]=u(localStorage.getItem(Lp)===`1`),[Vp,Hp]=u(!1),[Up,Wp]=u(!Pp.matches&&localStorage.getItem(Rp)!==`0`);function Gp(e){Bp(e),localStorage.setItem(Lp,e?`1`:`0`)}function Kp(e){Wp(e),Fp()||localStorage.setItem(Rp,e?`1`:`0`)}function qp(){Fp()?Hp(!Vp()):Gp(!zp())}var[Jp,Yp]=u(window.innerWidth);window.addEventListener(`resize`,()=>Yp(window.innerWidth));var[Xp,Zp]=u(Mp(localStorage)),[Qp,$p]=u(!1),[em,tm]=u(),[nm,rm]=u(!1),im=()=>Op(Xp(),Jp(),{side:!zp()&&!Fp(),rail:Qp(),concierge:nm()&&!Fp()});function am(e){let t=im(),n=e===`side`?Qp()?t.rail:0:!zp()&&!Fp()?t.side:0;return Ep(e,Jp()-(t.concierge??0),n)}function om(e,t,n=!0){Zp(n=>({...n,[e]:t})),n&&Np(localStorage,e,t)}var sm=`application/x-hub-pane`,[cm,lm]=u(),um=``,dm=0,fm=cm,pm=()=>typeof globalThis.crypto?.randomUUID==`function`?crypto.randomUUID():`${Date.now()}-${Math.random()}`;function mm(e,t){let n=e.dataTransfer;return Q()||!n?!1:(n.clearData(),um=pm(),n.setData(sm,um),n.effectAllowed=t.move?`move`:`copyMove`,cancelAnimationFrame(dm),dm=requestAnimationFrame(()=>lm(t)),!0)}function hm(){cancelAnimationFrame(dm),dm=0,um=``,lm(void 0)}function gm(e){return!!cm()&&[...e.dataTransfer?.types??[]].includes(`application/x-hub-pane`)}function _m(e){let t=cm();return t?Sp(bn(),t.target,e).outcome:void 0}function vm(e,t){let{layout:n,outcome:r}=Sp(bn(),e,t);if(r===`limit`&&J(_n,`warn`),r===`limit`||r===`invalid`)return r;Tn(()=>n);let i=n.panes[n.focused],a=i&&!i.sideChatID?i.sessionID:void 0,o=ut();return o.name!==`session`&&o.name!==`panes`?Bt(a?Dt(a):`/panes`):o.name===`session`&&!a&&!n.panes.some(e=>e.sessionID===o.id&&!e.sideChatID)&&Bt(`/panes`,{replace:!0}),r}function ym(e,t){let n=cm(),r=n&&e.dataTransfer?.getData(`application/x-hub-pane`)===um;return hm(),r?vm(n.target,t):`invalid`}function bm(e,t){let n=bn();return vm(e,n.panes.length?{index:n.focused,zone:t}:{empty:!0})}if(typeof document<`u`){let e=()=>cm()&&hm();document.addEventListener(`dragend`,e,!0),document.addEventListener(`drop`,()=>queueMicrotask(e)),document.addEventListener(`mousemove`,t=>t.buttons===0&&e(),{passive:!0})}var xm=e=>!!e&&typeof e==`object`&&!Array.isArray(e),Sm=e=>typeof e==`string`&&e.length>0,Cm=e=>typeof e==`number`&&Number.isFinite(e),wm=new Set([`online`,`offline`,`archived`,`deleted`,`unknown`]),Tm=new Set([`current`,`left`,`missing`]),Em=new Set([`open`,`in_progress`,`blocked`,`done`,`cancelled`]),Dm=new Set([`done`,`cancelled`]),Om=e=>Cm(e)&&e>=0?e:0;function km(e){if(!xm(e)||!Sm(e.memberID)||!Sm(e.sessionID)||!Sm(e.role))return;let t=xm(e.session)&&typeof e.session.state==`string`?e.session:void 0,n=xm(e.assignments)?e.assignments:{};return{memberID:e.memberID,sessionID:e.sessionID,role:e.role,master:e.master===!0,presence:wm.has(e.presence)?e.presence:`unknown`,generation:Cm(e.generation)?e.generation:1,...t?{session:{state:t.state,online:t.online===!0,...Sm(t.machineID)?{machineID:t.machineID}:{},...Sm(t.name)?{name:t.name}:{},...Cm(t.lastSeen)?{lastSeen:t.lastSeen}:{}}}:{},workload:{open:Om(n.open),in_progress:Om(n.in_progress),blocked:Om(n.blocked)},...xm(e.blockers)&&e.blockers.reported===!0&&Cm(e.blockers.count)?{blockers:e.blockers.count}:{}}}function Am(e){if(xm(e)&&Sm(e.memberID)&&Sm(e.supervisorMemberID)&&Cm(e.order))return{memberID:e.memberID,supervisorMemberID:e.supervisorMemberID,order:e.order,member:Tm.has(e.member)?e.member:`missing`,supervisor:Tm.has(e.supervisor)?e.supervisor:`missing`}}function jm(e){if(xm(e)&&Sm(e.id)&&Sm(e.memberID)&&Sm(e.title)&&Em.has(e.status))return{id:e.id,memberID:e.memberID,title:e.title,status:e.status,...Sm(e.ref)?{ref:e.ref}:{},assignee:Tm.has(e.assignee)?e.assignee:`missing`,...Array.isArray(e.stale)?{stale:e.stale.filter(Sm)}:{}}}function Mm(e){if(xm(e)){if(e.status===`ok`)return{status:`ok`,count:Array.isArray(e.items)?e.items.length:0,truncated:e.truncated===!0};if(e.status===`omitted`)return{status:`omitted`,reason:String(e.reason??`scope`),scope:String(e.scope??``)};if(e.status===`unsupported`)return{status:`unsupported`,feature:String(e.feature??``)};if(e.status===`failed`)return{status:`failed`}}}var Nm=(e,t)=>Array.isArray(e)?e.map(t).filter(e=>e!==void 0):[];function Pm(e){if(!xm(e)||!xm(e.workspace)||!xm(e.members)||!xm(e.supervision))return;let t=e.workspace;if(!Sm(t.id)||typeof t.title!=`string`||!Sm(t.state)||!Cm(t.revision)||!Cm(e.supervision.revision))return;let n=xm(e.assignments)?e.assignments:{},r=Mm(e.decisions),i=Mm(e.artifacts);return{workspace:{id:t.id,title:t.title,state:t.state,revision:t.revision,...Sm(t.masterMemberID)?{masterMemberID:t.masterMemberID}:{}},revision:e.supervision.revision,members:Nm(e.members.items,km),membersTruncated:e.members.truncated===!0,links:Nm(e.supervision.links,Am),linksTruncated:e.supervision.truncated===!0,assignments:Nm(n.items,jm),assignmentsTruncated:n.truncated===!0,sections:{...r?{decisions:r}:{},...i?{artifacts:i}:{}}}}function Fm(e){return xm(e)?{items:Nm(e.items,e=>xm(e)&&Sm(e.id)&&typeof e.title==`string`&&Sm(e.state)&&Cm(e.revision)?{id:e.id,title:e.title,...Sm(e.description)?{goal:e.description}:{},state:e.state,revision:e.revision}:void 0),...Sm(e.cursor)?{cursor:e.cursor}:{}}:{items:[]}}function Im(e){let t=new Set(e.members.map(e=>e.memberID)),n=new Map,r=0;for(let i of e.links)i.member!==`current`||i.supervisor!==`current`||!t.has(i.memberID)||!t.has(i.supervisorMemberID)||n.has(i.memberID)?r++:n.set(i.memberID,i);return{links:n,stale:r}}function Lm(e){let{links:t,stale:n}=Im(e),r=new Map(e.members.map((e,t)=>[e.memberID,t])),i=new Map;for(let n of e.members){let e=t.get(n.memberID);e&&i.set(e.supervisorMemberID,[...i.get(e.supervisorMemberID)??[],n])}let a=new Map;for(let t of e.assignments)Dm.has(t.status)||a.set(t.memberID,[...a.get(t.memberID)??[],t]);let o=[],s=new Set,c=(e,n)=>{s.add(e.memberID);let l=t.get(e.memberID),u={member:e,depth:n,...l&&n>0?{supervisorMemberID:l.supervisorMemberID}:{},order:l?.order??0,children:[],assignments:a.get(e.memberID)??[]};o.push(u);let d=(i.get(e.memberID)??[]).filter(e=>!s.has(e.memberID)).sort((e,n)=>t.get(e.memberID).order-t.get(n.memberID).order||r.get(e.memberID)-r.get(n.memberID));for(let e of d)s.has(e.memberID)||u.children.push(c(e,n+1));return u},l=t=>t.master||t.memberID===e.workspace.masterMemberID,u=[...e.members].filter(e=>!t.has(e.memberID)).sort((e,t)=>Number(l(t))-Number(l(e))||r.get(e.memberID)-r.get(t.memberID)),d=[];for(let e of u)d.push(c(e,0));for(let t of e.members)s.has(t.memberID)||d.push(c(t,0));return{roots:d,flat:o,staleLinks:n}}function Rm(e,t){if(e.workspace.state!==`active`)return`archived`;let n=new Set(e.members.map(e=>e.memberID));if(!n.has(t.memberID)||t.supervisorMemberID!==null&&!n.has(t.supervisorMemberID))return`unknown`;if(t.supervisorMemberID===t.memberID)return`self`;let{links:r}=Im(e),i=r.get(t.memberID);if((i?.supervisorMemberID??null)===t.supervisorMemberID&&(t.order===void 0||t.supervisorMemberID===null||t.order===i?.order))return`unchanged`;if(t.supervisorMemberID===null)return;let a=e.workspace.masterMemberID??e.members.find(e=>e.master)?.memberID;if(t.memberID===a)return`master`;let o=new Map([...r].map(([e,t])=>[e,t.supervisorMemberID]));return on(o,t.memberID,t.supervisorMemberID)}function zm(e,t){return e===void 0&&t===void 0?0:e===void 0?t-1:t===void 0?e+1:(e+t)/2}var Bm=(e,t)=>e.flat.find(e=>e.member.memberID===t),Vm=(e,t)=>t.supervisorMemberID===void 0?e.roots:Bm(e,t.supervisorMemberID).children,Hm=(e,t)=>{let n=e.children.filter(e=>e.member.memberID!==t);return n.length?n[n.length-1].order+1:0};function Um(e,t,n){if(!Bm(e,t))return;if(`root`in n)return{memberID:t,supervisorMemberID:null};if(n.memberID===t)return;let r=Bm(e,n.memberID);if(!r)return;if(n.position===`inside`)return{memberID:t,supervisorMemberID:r.member.memberID,order:Hm(r,t)};if(r.supervisorMemberID===void 0)return{memberID:t,supervisorMemberID:null};let i=Vm(e,r).filter(e=>e.member.memberID!==t),a=i.indexOf(r),o=n.position===`before`?zm(i[a-1]?.order,r.order):zm(r.order,i[a+1]?.order);return{memberID:t,supervisorMemberID:r.supervisorMemberID,order:o}}function Wm(e,t,n){let r=Bm(e,t);if(!r)return;let i=Vm(e,r),a=i.indexOf(r),o=r.supervisorMemberID;switch(n){case`indent`:{let e=i[a-1];return e?{memberID:t,supervisorMemberID:e.member.memberID,order:Hm(e)}:void 0}case`outdent`:{if(o===void 0)return;let n=Bm(e,o);if(n.supervisorMemberID===void 0)return{memberID:t,supervisorMemberID:null};let r=Vm(e,n);return{memberID:t,supervisorMemberID:n.supervisorMemberID,order:zm(n.order,r[r.indexOf(n)+1]?.order)}}case`up`:return o===void 0||a===0?void 0:{memberID:t,supervisorMemberID:o,order:zm(i[a-2]?.order,i[a-1].order)};case`down`:return o===void 0||a===i.length-1?void 0:{memberID:t,supervisorMemberID:o,order:zm(i[a+1].order,i[a+2]?.order)};case`detach`:return o===void 0?void 0:{memberID:t,supervisorMemberID:null}}}function Gm(e,t){return{memberID:e.memberID,supervisorMemberID:e.supervisorMemberID,...e.order!==void 0&&e.supervisorMemberID!==null?{order:e.order}:{},expectedRevision:t}}var Km={self:`A member cannot supervise itself.`,master:`The master is the root of the workspace and cannot be supervised.`,cycle:`That would make a supervision loop.`,depth:`Supervision is at most ${sn.supervisionDepth} levels deep.`,unknown:`That member is no longer in the workspace.`,unchanged:`Nothing to change.`,archived:`The workspace is archived: supervision is read-only.`},qm=e=>Km[e];function Jm(e,t){let n=Rm(t,e);return n===`unchanged`?{kind:`done`}:n===`unknown`?{kind:`dropped`,reason:`Your change was not applied: a member it moves is no longer in the workspace.`}:n?{kind:`dropped`,reason:`Your change was not applied after the workspace changed elsewhere. ${Km[n]}`}:{kind:`reapply`,body:Gm(e,t.revision)}}function Ym(e){let t=e.details?.violation;if(e.status===400&&(t===`cycle`||t===`depth`))return Km[t];switch(e.code){case`conflict`:return`The workspace changed elsewhere. Reloaded it.`;case`forbidden`:return`Not allowed${e.message?`: ${e.message}`:`.`}`;case`not_found`:return`That workspace or member no longer exists.`;case`unsupported`:return`This hub does not support ${typeof e.details?.feature==`string`?e.details.feature:`this`} yet.`;case`offline`:return`The machine is offline. Try again when it is back.`;case`rate_limited`:return`A workspace limit was reached.`}return e.message||`HTTP ${e.status}`}function Xm(e,t){for(let n of e??[])for(let e of n.processes??[])for(let r of e.sessions??[])if(r.id===t)return{machine:n,process:e,session:r}}function Zm(e,t){let n=Xm(e,t);if(!n)return{found:!1};let{machine:r,process:i,session:a}=n,o=a.parentID,s=o?Xm(e,o):void 0;return{found:!0,title:a.title||t,host:r.name,hostOnline:!!r.online,harness:i.harness||`opencode`,...a.directory?{directory:a.directory}:{},...o?{parentID:o,...s?{parentTitle:s.session.title||o}:{}}:{}}}function Qm(e,t,n){let r=Zm(n,e.member.sessionID),i=e.supervisorMemberID?t.members.find(t=>t.memberID===e.supervisorMemberID):void 0,a=i?Zm(n,i.sessionID):void 0;return{...r.found&&r.parentID?{spawnedBy:{sessionID:r.parentID,title:r.parentTitle??r.parentID}}:{},...i?{supervisedBy:{memberID:i.memberID,sessionID:i.sessionID,title:a?.found?a.title:i.session?.name??i.sessionID}}:{}}}var $m={offline:`No machine reports this session right now`,archived:`The session is archived`,deleted:`The session was deleted`,unknown:`The hub does not know this session`};function eh(e,t){let n=[];e.master&&n.push({kind:`master`,label:`master`,title:`The workspace's master (root of supervision)`});let r=t.found?t.host:e.session?.machineID;return r&&n.push({kind:`host`,label:r,title:t.found&&!t.hostOnline?`Host ${r} (offline)`:`Host ${r}`}),t.found&&n.push({kind:`harness`,label:t.harness,title:`Harness: ${t.harness}`}),e.presence!==`online`&&n.push({kind:`offline`,label:e.presence,title:$m[e.presence]}),n}var th=e=>e.length>1?e.replace(/\/+$/,``):e,nh=(e,t)=>{let n=th(e),r=th(t);return n===r||n.startsWith(`${r}/`)};function rh(e,t,n,r){return e.filter(e=>e.state===`active`&&e.expiresAt>r&&(e.holderSessionID===t||e.holder===t)).map(e=>({grantID:e.id,verbs:e.allow,projects:e.scope.projects,expiresAt:e.expiresAt,...n===void 0?{}:{covers:e.scope.projects.some(e=>nh(n,e))}}))}var ih=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ah=e=>typeof e==`string`&&e.length>0,oh=e=>typeof e==`number`&&Number.isFinite(e),sh=[`launching`,`ready`,`failed`,`unknown`];function ch(e){if(ih(e)&&ah(e.id)&&typeof e.text==`string`)return{id:e.id,role:ah(e.role)?e.role:`message`,text:e.text,...oh(e.at)?{at:e.at}:{},...e.clipped===!0?{clipped:!0}:{},...e.changed===!0?{changed:!0}:{},...e.stale?{stale:!0}:{}}}function lh(e){if(!ih(e)||!ah(e.id)||!ah(e.workspaceID)||!ah(e.sourceSessionID)||!oh(e.revision))return;let t=e.snapshot;if(!ih(t)||!oh(t.generation)||!oh(t.takenAt))return;let n=ih(e.launch)&&ah(e.launch.state)?e.launch:void 0;return{id:e.id,workspaceID:e.workspaceID,sourceSessionID:e.sourceSessionID,...ah(e.sessionID)?{sessionID:e.sessionID}:{},...ah(e.machineID)?{machineID:e.machineID}:{},revision:e.revision,status:sh.includes(e.status)?e.status:`unknown`,...n?{launch:{state:n.state,...ah(n.outcome)?{outcome:n.outcome}:{},...ah(n.reason)?{reason:n.reason}:{}}}:{},snapshot:{generation:t.generation,takenAt:t.takenAt,omitted:oh(t.omitted)?t.omitted:0,items:Array.isArray(t.items)?t.items.map(ch).filter(e=>e!==void 0):[]},...typeof e.stale==`boolean`?{stale:e.stale}:{}}}function uh(e){if(e.sessionID)return{kind:`ready`,sessionID:e.sessionID};let t=e.launch;return e.status===`failed`?t?{kind:`failed`,text:`The side chat couldn't start${t.outcome?` (${t.outcome})`:``}${t.reason?`: ${t.reason}`:`.`}`}:{kind:`failed`,text:`The side chat couldn't start.`}:e.status===`launching`?t&&(t.state===`queued`||t.state===`placing`)?{kind:`launching`,text:`Waiting for the workspace's machine${t.reason?`: ${t.reason}`:`.`}`}:{kind:`launching`,text:`Starting the side chat on its machine…`}:{kind:`unknown`,text:`This hub can't tell whether the side chat started.`}}function dh(e,t){let n=Math.round(Math.max(0,t-e)/6e4);return n<1?`just now`:n<60?`${n} min ago`:n<1440?`${Math.round(n/60)} h ago`:`${Math.round(n/1440)} d ago`}function fh(e,t){let n=e.snapshot,r=[`${gn(n.items.length,`message`)} from the main session`,`copied ${dh(n.takenAt,t)}`];return n.generation>1&&r.push(`refreshed ${gn(n.generation-1,`time`)}`),n.omitted>0&&r.push(`${n.omitted} older left out`),{summary:r.join(` · `),stale:e.stale?`The main session changed after this copy. Refresh to update it.`:void 0}}function ph(e){let t=ih(e)?e:{};return t.status===`sent`?`Context refreshed and sent to the side chat.`:t.status===`not_started`?`Context refreshed. The side chat gets it once it has started.`:t.status===`failed`?`Context refreshed, but it couldn't be sent to the side chat${ah(t.message)?`: ${t.message}`:`.`}`:`Context refreshed.`}var mh=9900;function hh(e){if(!e.trim())return`Write what to send to the main session.`;if(e.length>9900)return`At most ${mh} characters.`}var gh=encodeURIComponent,_h=e=>`/api/agent/workspaces/${gh(e.workspaceID)}/side-chats/${gh(e.id)}`,vh={one:e=>`/api/agent/side-chats/${gh(e)}`,create:e=>`/api/agent/workspaces/${gh(e)}/side-chats`,refresh:e=>`${_h(e)}/refresh`,send:e=>`${_h(e)}/send`},yh=e=>Math.min(3e4,2e3*2**Math.max(0,e)),bh=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function xh(e,t){return t?{sourceSessionID:e,bindingID:t}:{sourceSessionID:e}}function Sh(e){return(bh(e)&&Array.isArray(e.bindings)?e.bindings:[]).flatMap(e=>bh(e)&&typeof e.id==`string`&&typeof e.machineID==`string`&&typeof e.repo==`string`?[{id:e.id,machineID:e.machineID,repo:e.repo,...typeof e.label==`string`?{label:e.label}:{}}]:[])}function Ch(e,t){return e.length?e.length===1?{kind:`ready`}:t&&e.some(e=>e.id===t)?{kind:`ready`,bindingID:t}:{kind:`pick`}:{kind:`none`}}var wh=`This workspace has no host repository binding, so no machine can host a side chat for it. Bind a repository on a machine to the workspace first (workspace bindings), then try again.`;function Th(e){return e.status===0?`The hub can't be reached. Check your connection and try again.`:e.status===422&&e.details?.feature===`sideChatHost`?wh:e.status===422?`This hub can't start side chats here.`:e.status===404?`That workspace or session isn't available to you.`:e.status===429?`Too many side chats right now. Close one or try again later.`:e.message||`Starting the side chat failed (${e.status}).`}var Eh=I(`<label><span>Workspace</span><select aria-label=Workspace><option value>Choose a workspace…`),Dh=I(`<p class=cmp-note role=status>`),Oh=I(`<label><span>Host repository</span><select aria-label="Host repository"><option value>Choose a repository…`),kh=I(`<p class="cmp-note err"role=alert>`),Ah=I(`<form class=cmp-start aria-label="Start a side chat"><p class=muted>A new session that starts from a copy of <strong></strong>'s recent messages, on a workspace's host repository. The main session keeps working; you send things back to it explicitly.</p><div class=cmp-actions><button type=submit class="btn primary"></button><button type=button class=btn>Cancel`),jh=I(`<p class=muted role=status>Loading workspaces…`),Mh=I(`<p class=cmp-note role=status>You have no active workspaces. A side chat runs in a workspace: create one and bind a repository to it first.`),Nh=I(`<option>`),[Ph,Fh]=u(),Ih=(e,t={})=>Fh({sessionID:e,...t});function Lh(){return n(l,{get when(){return Ph()},keyed:!0,children:e=>n(Bh,{request:e,onClose:()=>Fh(void 0)})})}var Rh=()=>`console-sidechat-${[...crypto.getRandomValues(new Uint8Array(12))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`,zh=e=>e instanceof G?{status:e.status,...e.code?{code:e.code}:{},message:e.message,...e.details?{details:e.details}:{}}:{status:e instanceof en?0:-1,message:e instanceof Error?e.message:String(e)};function Bh(e){let[t,i]=u(),[a,o]=u(),[c,d]=u(e.request.workspaceID??``),[f,p]=u(),[h,g]=u(``),[_,v]=u(!1),[x,S]=u(),w,T=()=>{let t=Lu(e.request.sessionID)?.session.title;return typeof t==`string`&&t?t:e.request.sessionID};async function E(e){if(p(void 0),g(``),e)try{p(Sh(await K(`/api/agent/workspaces/${q(e)}/bindings`)))}catch(e){p([]),S(Th(zh(e)))}}R(async()=>{try{i(Fm(await K(`/api/agent/workspaces?state=active&limit=50`)).items)}catch(e){i([]),o(Th(zh(e)))}c()&&E(c())});let D=C(()=>f()?Ch(f(),h()||void 0):void 0);async function O(t){t.preventDefault();let n=c(),r=D();if(!n||!r||r.kind===`pick`||_())return;let i=xh(e.request.sessionID,r.kind===`ready`?r.bindingID:void 0),a=JSON.stringify([n,i]);w?.body!==a&&(w={body:a,value:Rh()}),v(!0),S(void 0);try{let t=lh((await(await H(`/api/agent/workspaces/${q(n)}/side-chats`,{method:`POST`,json:i,headers:{"idempotency-key":w.value}})).json()).sideChat);if(!t)throw new G(502,`The hub answered a side chat this console can't read.`);e.onClose(),vn(e.request.sessionID,t.id)&&J(`Side chat started beside the main session.`)}catch(e){e instanceof en||(w=void 0),S(Th(zh(e)))}finally{v(!1)}}return n(de,{open:!0,title:`Start a side chat`,get onClose(){return e.onClose},get children(){var i=Ah(),o=i.firstChild,u=o.firstChild.nextSibling,p=o.nextSibling,v=p.firstChild,C=v.nextSibling;return i.addEventListener(`submit`,O),y(u,T),y(i,n(l,{get when(){return t()},get fallback(){return jh()},get children(){return n(l,{get when(){return!a()},get fallback(){return(()=>{var e=kh();return y(e,a),e})()},get children(){return n(l,{get when(){return t().length},get fallback(){return Mh()},get children(){var e=Eh(),r=e.firstChild.nextSibling;return r.firstChild,r.addEventListener(`change`,e=>{d(e.currentTarget.value),S(void 0),E(e.currentTarget.value)}),y(r,n(m,{get each(){return t()},children:e=>(()=>{var t=Nh();return y(t,()=>e.title||e.id),s(()=>t.value=e.id),t})()}),null),s(()=>r.value=c()),e}})}})}}),p),y(i,n(l,{get when(){return D()?.kind===`none`},get children(){var e=Dh();return y(e,wh),e}}),p),y(i,n(l,{get when(){return r(()=>!!f())()&&f().length>1},get children(){var e=Oh(),t=e.firstChild.nextSibling;return t.firstChild,t.addEventListener(`change`,e=>g(e.currentTarget.value)),y(t,n(m,{get each(){return f()},children:e=>(()=>{var t=Nh();return y(t,(()=>{var t=r(()=>!!e.label);return()=>t()?`${e.label} (${e.repo})`:e.repo})()),s(()=>t.value=e.id),t})()}),null),s(()=>t.value=h()),e}}),p),y(i,n(l,{get when(){return x()},get children(){var e=kh();return y(e,x),e}}),p),y(v,()=>_()?`Starting…`:`Start side chat`),V(C,`click`,e.onClose,!0),s(e=>{var t=!c()||!D()||D().kind===`pick`||_(),n=_();return t!==e.e&&(v.disabled=e.e=t),n!==e.t&&b(v,`aria-busy`,e.t=n),e},{e:void 0,t:void 0}),i}})}B([`click`]);var[Vh,Hh]=u(),Uh=(e,t)=>Vh()?.id===e&&Vh()?.place===t;function Wh(e,t){if(!e.length)return;let n=t?`Archived`:`Unarchived`,r=e.length===1?`${n} “${e[0].title}”`:`${n} ${e.length} sessions`;Hd(`hiddenSessions`,e.map(e=>e.id),t,{message:r,undo:!0})}function Gh(e,{open:t=!0,place:n}={}){return[...t?[{label:`Open`,run:()=>Bt(Dt(e.id))}]:[],...n===`topbar`?[]:[{label:`Open beside`,run:()=>Cn(e.id)}],{label:`Start side chat…`,run:()=>Ih(e.id)},...n?[{label:`Rename…`,run:()=>Hh({id:e.id,place:n})}]:[],{label:qd(e.id)?`Naming…`:`Auto-name`,run:()=>void Xd(e.id),disabled:qd(e.id)},{label:e.pinned?`Unpin`:`Pin`,run:()=>Vd(`pinnedSessions`,e.id,!e.pinned)},{label:e.archived?`Unarchive`:`Archive`,run:()=>Wh([e],!e.archived)},...e.running?[{label:`Stop`,run:()=>void Qd(e.id),danger:!0}]:[],...e.state===`error`?[{label:`Dismiss error`,run:()=>void Zd(e.id)}]:[],`sep`,{label:e.exposed?`Disallow Voice`:`Allow Voice`,run:()=>void Ud(e.id,!e.exposed)},ep().has(e.id)?{label:`Unmute notifications`,run:()=>void dp(e.id,!1)}:{label:`Mute notifications`,run:()=>void dp(e.id,!0)},...n!==`topbar`&&!Q()?[`sep`,...[`left`,`right`,`top`,`bottom`].map(t=>({label:`Open in pane → ${t}`,run:()=>void bm({sessionID:e.id},t)}))]:[]]}var Kh=I(`<button type=button class="link-btn small clamp-toggle">`),qh=I(`<span>`),Jh=I(`<p>`),Yh=I(`<span class="muted small cut-note"data-cut>… cut at <!> characters (of <!>)`),Xh=I(`<span class="muted small cut-note"data-more>+<!> more <!> not stored`),Zh=I(`<dt>Requested by`),Qh=I(`<dd>`),$h=I(`<dt>Proposes`),eg=I(`<dt>Action`),tg=I(`<dd class=mono data-action>`),ng=I(`<dt>`),rg=I(`<span class="muted small cut-note"data-incomplete>The hub received this request already shortened`),ig=I(`<dd data-resources>`),ag=I(`<dt>Always saves`),og=I(`<dd data-saves>`),sg=I(`<dt>Shown from`),cg=I(`<dd class=muted>`),lg=I(`<dt>Prompt`),ug=I(`<dt>Form`),dg=I(`<dt>Answer`),fg=I(`<dd data-answer>`),pg=I(`<dt>Outside its grant`),mg=I(`<dl class="escalation-details decision-details small">`),hg=I(`<dt>Session`),gg=I(`<dd><a>`),_g=I(`<span class=decision-answer-field><span class=muted>:</span> `),vg=I(`<dt>Purpose`),yg=I(`<dd data-purpose> <span class=muted>(<!>)`),bg={label:Hu,blockers:e=>Hr(Lu(e)?.session)};function xg(e){let[t,i]=u(!1),a=T(),o=C(()=>e.reveal?Fe(e.text):e.text),c=C(()=>Ee(o(),{chars:e.chars,lines:e.lines})),d=()=>t()||!c().cut?o():c().text,f=()=>n(l,{get when(){return c().cut},get children(){var n=Kh();return n.$$click=()=>i(!t()),b(n,`aria-controls`,`clamp-${a}`),y(n,()=>t()?`Show less`:`Show all`),s(r=>{var i=t(),a=`${t()?`Show less`:`Show all`} of ${e.what??`the text`}`;return i!==r.e&&b(n,`aria-expanded`,r.e=i),a!==r.t&&b(n,`aria-label`,r.t=a),r},{e:void 0,t:void 0}),n}});return n(l,{get when(){return e.tag===`span`},get fallback(){return[(()=>{var n=Jh();return b(n,`id`,`clamp-${a}`),y(n,d),s(r=>{var i=e.class,a=c().cut&&!t()?``:void 0;return i!==r.e&&k(n,r.e=i),a!==r.t&&b(n,`data-clamped`,r.t=a),r},{e:void 0,t:void 0}),n})(),r(f)]},get children(){return[(()=>{var n=qh();return b(n,`id`,`clamp-${a}`),y(n,d),s(r=>{var i=e.class,a=c().cut&&!t()?``:void 0;return i!==r.e&&k(n,r.e=i),a!==r.t&&b(n,`data-clamped`,r.t=a),r},{e:void 0,t:void 0}),n})(),r(()=>f())]}})}var Sg={live:`Live request`,request:`The hub's record of the request`,text:`From the request text`},Cg=new Set([`bash`,`shell`]),wg=e=>e&&Cg.has(e)?`the command`:`the request`,Tg=e=>e.toLocaleString(`en-US`);function Eg(e){let t=()=>e.detail.cut?.find(t=>t.field===e.field&&t.index===e.index);return n(l,{get when(){return t()},children:e=>(()=>{var t=Yh(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(t,()=>Tg(Og),n),y(t,()=>Tg(e().length),r),t})()})}function Dg(e){return n(l,{get when(){return e.count},get children(){var t=Xh(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(t,()=>Tg(e.count),n),y(t,()=>e.count===1?`item`:`items`,r),t}})}var Og=2e3,kg={stop:`Stop the session`,deny:`Deny its permission request`,prompt:`Send a prompt as you`,answer:`Answer its form as you`},Ag=e=>e.verb===`answer`&&e.cancel?`Dismiss its form`:kg[e.verb??``]??e.verb;function jg(e){let t=C(()=>ke(e.decision,e.context??bg));return n(l,{get when(){return t()},children:t=>(()=>{var i=mg();return y(i,n(l,{get when(){return t().requester},get children(){return[Zh(),(()=>{var n=Qh();return y(n,()=>t().requester),s(()=>b(n,`title`,wt(e.decision))),n})()]}}),null),y(i,n(l,{get when(){return t().verb},get children(){return[$h(),(()=>{var e=Qh();return y(e,()=>Ag(t())),s(()=>b(e,`data-verb`,t().verb)),e})()]}}),null),y(i,n(l,{get when(){return t().target},children:e=>[hg(),(()=>{var t=gg(),n=t.firstChild;return y(n,()=>e().label),s(t=>{var r=Dt(e().id),i=e().id;return r!==t.e&&b(n,`href`,t.e=r),i!==t.t&&b(n,`title`,t.t=i),t},{e:void 0,t:void 0}),t})()]}),null),y(i,n(l,{get when(){return t().action},get children(){return[eg(),(()=>{var e=tg();return y(e,()=>t().action,null),y(e,()=>t().always?` (always)`:``,null),e})()]}}),null),y(i,n(l,{get when(){return t().resources.length},get children(){return[(()=>{var e=ng();return y(e,()=>t().resources.length===1?`Resource`:`Resources`),e})(),(()=>{var e=ig();return y(e,n(m,{get each(){return t().resources},children:(e,r)=>[n(xg,{tag:`span`,class:`escalation-resource mono`,text:e,chars:240,lines:4,get what(){return wg(t().action)},reveal:!0}),n(Eg,{get detail(){return t()},field:`resources`,get index(){return r()}})]}),null),y(e,n(Dg,{get count(){return t().resourcesMore}}),null),y(e,n(l,{get when(){return t().incomplete},get children(){return rg()}}),null),e})()]}}),null),y(i,n(l,{get when(){return t().saves?.length},get children(){return[ag(),(()=>{var e=og();return y(e,n(m,{get each(){return t().saves},children:(e,r)=>[n(xg,{tag:`span`,class:`escalation-resource mono`,text:e,chars:240,lines:4,what:`the saved pattern`,reveal:!0}),n(Eg,{get detail(){return t()},field:`save`,get index(){return r()}})]}),null),y(e,n(Dg,{get count(){return t().savesMore}}),null),e})()]}}),null),y(i,n(l,{get when(){return r(()=>!!t().source)()&&(t().action||t().resources.length||t().form)},get children(){return[sg(),(()=>{var e=cg();return y(e,()=>Sg[t().source]),s(()=>b(e,`data-source`,t().source)),e})()]}}),null),y(i,n(l,{get when(){return t().text},get children(){return[lg(),(()=>{var e=Qh();return y(e,n(xg,{class:`decision-prompt mono`,get text(){return t().text},chars:400,lines:6,what:`the prompt`,reveal:!0})),e})()]}}),null),y(i,n(l,{get when(){return t().formID},get children(){return[ug(),(()=>{var e=Qh();return y(e,()=>t().form??t().formID),e})()]}}),null),y(i,n(l,{get when(){return t().answer?.length},get children(){return[dg(),(()=>{var e=fg();return y(e,n(m,{get each(){return t().answer},children:e=>(()=>{var t=_g(),r=t.firstChild,i=r.firstChild;return r.nextSibling,y(r,()=>e.key,i),y(t,n(xg,{tag:`span`,class:`decision-answer-value mono`,get text(){return e.value},chars:240,lines:4,get what(){return`the answer to ${e.key}`},reveal:!0}),null),t})()})),e})()]}}),null),y(i,n(l,{get when(){return t().outsideGrant},get children(){return[pg(),(()=>{var e=Qh();return y(e,()=>t().outsideGrant),e})()]}}),null),y(i,n(l,{get when(){return t().purpose},children:e=>[vg(),(()=>{var t=yg(),n=t.firstChild,r=n.nextSibling,i=r.firstChild.nextSibling;return i.nextSibling,y(t,()=>e().text,n),y(r,()=>e().by,i),t})()]}),null),s(e=>{var n=t().kind,r=t().kind===`permission`?``:void 0,a=t().source===`live`?``:void 0;return n!==e.e&&b(i,`data-decision-detail`,e.e=n),r!==e.t&&b(i,`data-escalation`,e.t=r),a!==e.a&&b(i,`data-live`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),i})()})}var Mg=(e,t=bg)=>ke(e,t)?.purpose?.text;B([`click`]);var Ng=I(`<span class="badge-pill agent-request"title="An agent asked to act outside its grant">Agent request`),Pg=I(`<span>`),Fg=I(`<p role=timer>`),Ig=I(`<div role=radiogroup aria-label=Options class=choice-group>`),Lg=I(`<p class="muted small decision-why">Why: `),Rg=I(`<input type=text class=decision-note aria-label="Note (optional)"placeholder="Note (optional)">`),zg=I(`<p class="muted small decision-tier">`),Bg=I(`<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`),Vg=I(`<a>`),Hg=I(`<label class=text-field><span class=field-title>Your answer</span><textarea rows=2 aria-label="Your answer">`),Ug=I(`<span class="badge-pill safe"title="A timeout may pick this option">safe`),Wg=I(`<span class="badge-pill recommended">Recommended`),Gg=I(`<label><input type=radio><span>`),Kg={low:`Low urgency`,normal:``,high:`Urgent`};function qg(e){let i=()=>e.decision,[a,o]=u(),[c,d]=u(``),[f,p]=u(!1),[h,g]=u(Date.now()),_=setInterval(()=>i().deadline!==void 0&&g(Date.now()),1e3);M(()=>clearInterval(_));let v=()=>Nt().searchParams.get(`decision`)===i().id,x;R(()=>{v()&&x?.scrollIntoView({block:`center`})});let S=()=>i().sessionID?Lu(i().sessionID):void 0,C=async e=>{e.preventDefault();let t=tn(i(),a(),c());if(!t.ok)J(t.problem,`err`);else{p(!0);try{let{decision:e}=await(await H(`/api/decisions/${q(i().id)}/answer`,{method:`POST`,json:t.body})).json();J(`Answer sent`),e?Ad(e):jd(i().id)}catch(e){if(e instanceof G&&e.status===409&&e.code===`gone`){J(`Already answered or expired`),jd(i().id);return}J(W(e),`err`),p(!1)}}},w=e=>i().recommendation?.option===e;return(()=>{var u=Bg(),p=u.firstChild,g=p.firstChild.nextSibling.nextSibling;g.firstChild;var _=p.nextSibling,T=_.nextSibling,E=T.firstChild,D=E.firstChild,O=x;return typeof O==`function`?t(O,u):x=u,y(g,()=>_e(i(),Hu,Eu()),null),y(p,n(l,{get when(){return At(i())},get children(){return Ng()}}),null),y(p,n(l,{get when(){return Kg[i().urgency]},get children(){var e=Pg();return y(e,()=>Kg[i().urgency]),s(()=>k(e,`badge-pill urgency ${i().urgency}`)),e}}),null),y(p,n(l,{get when(){return r(()=>!!e.showSession)()&&S()},children:e=>[` · `,(()=>{var t=Vg();return y(t,()=>e().session.title||e().session.id),s(()=>b(t,`href`,Dt(e().session.id))),t})()]}),null),y(_,()=>Le(i(),Hu,Eu())),y(u,n(jg,{get decision(){return i()}}),T),y(u,n(l,{get when(){return $e(i(),h())},get children(){var e=Fg();return y(e,()=>$e(i(),h())),s(()=>k(e,`decision-deadline small${i().escalatedAt!==void 0||i().deadline<=h()?` overdue`:``}`)),e}}),T),T.addEventListener(`submit`,e=>void C(e)),y(E,n(l,{get when(){return i().options.length},get fallback(){return(()=>{var e=Hg(),t=e.firstChild.nextSibling;return t.$$input=e=>d(e.currentTarget.value),s(()=>t.value=c()),e})()},get children(){return[(()=>{var e=Ig();return y(e,n(m,{get each(){return i().options},children:e=>(()=>{var t=Gg(),r=t.firstChild,c=r.nextSibling;return r.addEventListener(`change`,()=>o(e.id)),y(c,()=>e.label),y(t,n(l,{get when(){return e.safe},get children(){return Ug()}}),null),y(t,n(l,{get when(){return w(e.id)},get children(){return Wg()}}),null),s(n=>{var a=`choice${w(e.id)?` recommended`:``}`,o=`d-${i().id}`;return a!==n.e&&k(t,n.e=a),o!==n.t&&b(r,`name`,n.t=o),n},{e:void 0,t:void 0}),s(()=>r.value=e.id),s(()=>r.checked=a()===e.id),t})()})),e})(),n(l,{get when(){return r(()=>!!i().recommendation?.why)()&&i().recommendation.why!==Mg(i())},get children(){var e=Lg();return e.firstChild,y(e,()=>i().recommendation.why,null),e}}),(()=>{var e=Rg();return e.$$input=e=>d(e.currentTarget.value),s(()=>e.value=c()),e})()]}}),D),y(E,n(l,{get when(){return Rt(i())},get children(){var e=zg();return y(e,()=>Rt(i())),e}}),D),s(e=>{var t=`card decision urgency-${i().urgency}${v()?` targeted`:``}`,n=`Decision: ${i().question}`,r=i().id,a=wt(i()),o=i().question,s=f();return t!==e.e&&k(u,e.e=t),n!==e.t&&b(u,`aria-label`,e.t=n),r!==e.a&&b(u,`data-decision`,e.a=r),a!==e.o&&b(g,`title`,e.o=a),o!==e.i&&b(_,`title`,e.i=o),s!==e.n&&(E.disabled=e.n=s),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),u})()}function Jg(e){let t=C(()=>new Map(e.decisions.map(e=>[e.id,e]))),r=C((e=[])=>{let n=[...t().keys()];return n.length===e.length&&n.every((t,n)=>t===e[n])?e:n});return n(m,{get each(){return r()},children:r=>n(l,{get when(){return t().get(r)},children:t=>n(qg,{get decision(){return t()},get showSession(){return e.showSession}})})})}B([`input`]);var Yg=I(`<span class="naming muted small"role=status><span class="spinner small"aria-hidden=true></span>Naming…`),Xg=I(`<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">✨`),Zg,Qg=0;function $g(e){return n(l,{get when(){return Uh(e.id,e.place)},get fallback(){return e.children},get children(){return n(t_,{get id(){return e.id},get title(){return e.title},get place(){return e.place},get class(){return e.class}})}})}function e_(e){return n(l,{get when(){return qd(e.id)},get children(){return Yg()}})}function t_(e){let n,r=!1,i=Zg&&Zg.id===e.id&&Zg.place===e.place?Zg.value:void 0,a=()=>{r||(r=!0,Zg=void 0,Hh(void 0),Xd(e.id))},o=t=>{if(r)return;r=!0;let i=n.value;Zg=void 0,Hh(void 0),t&&i.trim()&&i.trim()!==e.title&&Wd(e.id,i)};return R(()=>{Qg++,n.focus(),i===void 0&&n.select()}),M(()=>{if(Qg--,setTimeout(()=>{Qg>0||(Zg=void 0,Vh()?.id===e.id&&Vh()?.place===e.place&&Hh(void 0))},0),r)return;r=!0;let t=Vh();t?.id===e.id&&t.place===e.place&&(Zg={id:e.id,place:e.place,value:n.value})}),(()=>{var r=Xg(),c=r.firstChild,l=c.nextSibling;c.addEventListener(`blur`,()=>o(!0)),c.$$keydown=e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),o(!0)):e.key===`Escape`&&(e.preventDefault(),o(!1))},c.$$mousedown=e=>e.stopPropagation(),c.$$click=e=>e.stopPropagation();var u=n;return typeof u==`function`?t(u,c):n=c,b(c,`maxlength`,200),l.$$click=e=>{e.preventDefault(),e.stopPropagation(),a()},l.$$mousedown=e=>{e.preventDefault(),e.stopPropagation()},s(()=>k(c,`rename-field${e.class?` ${e.class}`:``}`)),s(()=>c.value=i??e.title),r})()}B([`click`,`mousedown`,`keydown`]);var n_=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()}},r_={phase:`off`,voice:`off`,level:0,held:``,paused:!1},i_=class{deps;state=r_;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({...r_,phase:`starting`,sessionID:e,voice:`starting`});let i=await this.deps.expose(e);if(t!==this.run)return;if(!i)return this.set({...r_,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}),turn:e=>t===this.run&&this.set({...this.state,turn:e}),front:e=>t===this.run&&this.set({...this.state,front: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({...r_,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(r_))}});this.conversation=a;let o=await a.start();if(t===this.run){if(!o)return this.run++,this.conversation=void 0,this.set({...r_,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(r_),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()}},a_=3e3,o_=`Voice mode on`,s_=`Voice mode paused · unlock to talk`,c_={starting:`starting`,listening:`listening`,hearing:`listening`,transcribing:`thinking`,sent:`thinking`,speaking:`speaking`,paused:`muted`,suspended:`paused`,off:`off`},l_=(e,t,n,r=``)=>({sessionID:e,title:n===`suspended`?s_:o_,body:`${t} · ${c_[n]??n}${r}`}),u_=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),r=this.options.suffix?.()??``,i=`${t}\n${r}`;if(this.mediaFor!==i&&(this.mediaFor=i,this.surface.media({title:o_,artist:`${n}${r}`},()=>void this.controller.end())),!this.surface.allowed())return;let a=l_(t,n,e.voice,r);if(this.shown&&this.shown.sessionID===a.sessionID&&this.shown.body===a.body)return this.cancel();let o=a.title!==this.shown?.title,s=this.shown?.sessionID===t&&!o?this.shownAt+a_-this.now():0;if(s<=0)return this.show(a);this.timer===void 0&&(this.timer=this.setTimer(()=>{this.timer=void 0,this.refresh()},s))}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)}},d_=3e4,f_=1e4;function p_(e,{setTimer:t=(e,t)=>setTimeout(e,t),clearTimer:n=e=>clearTimeout(e)}={}){let r=new Map,i=1,a=e=>{let t=r.get(e);if(t)return r.delete(e),n(t.timer),t};return e.onmessage=e=>{let t=e.data;if(t.type!==`result`&&t.type!==`fail`)return;let n=a(t.id);t.type===`result`?n?.resolve({p:t.p,ms:t.ms}):n?.reject(Error(t.message||`turn detection failed`))},{get pending(){return r.size},predict(n){return new Promise((o,s)=>{let c=i++,l=t(()=>a(c)?.reject(Error(`the turn model did not answer`)),f_);r.set(c,{resolve:o,reject:s,timer:l}),e.postMessage({type:`predict`,id:c,samples:n},[n.buffer])})},fail(e){for(let t of[...r.keys()])a(t)?.reject(e)}}}var m_;function h_(){return m_??=g_().catch(e=>{throw m_=void 0,e}),m_}function g_(){return new Promise((e,t)=>{let n;try{n=new Worker(new URL(`/assets/smart-turn-worker-DaVJPdvJ.js`,``+import.meta.url),{type:`module`,name:`smart-turn`})}catch(e){return t(e)}let r,i=!1,a=e=>{r?.fail(e),n.terminate(),m_=void 0,i||t(e)},o=setTimeout(()=>a(Error(`the turn model took too long to load`)),d_);n.onerror=e=>{e.preventDefault(),clearTimeout(o),a(Error(e.message||`the turn detection worker failed`))},n.onmessage=t=>{let s=t.data;s.type===`ready`?(clearTimeout(o),i=!0,r=p_(n),e(r)):s.type===`error`&&(clearTimeout(o),a(Error(s.message||`the turn model could not load`)))}})}var __=16e3,v_=8*__,y_=400;1+Math.floor(v_/160),27/Math.log(6.4);var b_=new Float64Array(y_),x_=new Float64Array(y_);for(let e=0;e<y_;e++)b_[e]=Math.cos(2*Math.PI*e/y_),x_[e]=-Math.sin(2*Math.PI*e/y_);var S_=Object.freeze([`timers`,`smart`]);function C_(e){return e===`smart`?`smart`:`timers`}var w_=Object.freeze({threshold:.5,graceMs:150,recheckMs:400,fallbackMs:3e3,slowMs:1500}),T_=5e3;function E_(e,t){if(!t.length)return Math.min(T_,e);let n=[...t].sort((e,t)=>e-t),r=n.length>>1,i=n.length%2?n[r]:(n[r-1]+n[r])/2;return Math.min(T_,Math.max(e,2*i))}var D_=Object.freeze([{key:`voiceTurn.threshold`,field:`threshold`,min:.01,max:.99},{key:`voiceTurn.grace`,field:`graceMs`,min:0,max:2e3},{key:`voiceTurn.recheck`,field:`recheckMs`,min:100,max:5e3},{key:`voiceTurn.fallback`,field:`fallbackMs`,min:500,max:1e4},{key:`voiceTurn.slow`,field:`slowMs`,min:500,max:T_}]);function O_(e,t){let n=D_.find(t=>t.key===e);if(!n||t==null||t.trim()===``)return;let r=Number(t);if(Number.isFinite(r))return Math.min(n.max,Math.max(n.min,r))}function k_(...e){let t={...w_};for(let n of D_)for(let r of e){let e=O_(n.key,r(n.key));if(e!==void 0){t[n.field]=e;break}}return t}var A_=class{ring=new Float32Array(v_);write=0;filled=0;get durationMs(){return this.filled/__*1e3}push(e){let t=e.length>128e3?e.subarray(e.length-v_):e,n=Math.min(t.length,v_-this.write);this.ring.set(t.subarray(0,n),this.write),n<t.length&&this.ring.set(t.subarray(n),0),this.write=(this.write+t.length)%v_,this.filled=Math.min(v_,this.filled+t.length)}snapshot(){let e=new Float32Array(this.filled),t=(this.write-this.filled+v_)%v_,n=Math.min(this.filled,v_-t);return e.set(this.ring.subarray(t,t+n)),n<this.filled&&e.set(this.ring.subarray(0,this.filled-n),n),e}keepLast(e){this.filled=Math.min(this.filled,Math.max(0,Math.round(e/1e3*__)))}reset(){this.write=0,this.filled=0}};function j_(e){if(!e)return``;if(e.decision===`timer-fallback`||e.p===void 0)return e.error===`loading`?`turn: model loading`:e.error===`slow`?`turn: timers (slow)`:`turn: timers`;let t=`turn ${Math.round(e.p*100)}%`;return e.decision===`send`?`${t} → sending`:e.decision===`fallback`?`${t} → sending (quiet too long)`:t}var M_=1500;function N_({mode:e,load:t,env:n=globalThis}){if(e!==`smart`)return!1;let r=()=>void t().catch(()=>{});if(n.requestIdleCallback)n.requestIdleCallback(r,{timeout:5e3});else if(n.setTimeout)n.setTimeout(r,M_);else return!1;return!0}var P_=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(e){for(let t of[...this.listeners])t(e)}get size(){return this.listeners.size}};async function F_(e){return new Blob([await new Response(e??null).arrayBuffer()],{type:`audio/mpeg`})}var I_=[`image/png`,`image/jpeg`,`image/webp`,`image/gif`],L_={maxImages:4,maxSide:1600,perImageBase64:18e4,totalBase64:7e5},R_=[.85,.72,.6,.48,.36],z_=[1,.75,.55,.4,.28,.2],B_=class extends Error{constructor(e=`This image is too large to attach, even after shrinking it`){super(e),this.name=`ImageTooLargeError`}},V_=e=>4*Math.ceil(e/3),H_=e=>I_.includes(e);function U_(e,t,n=L_){if(e>=n.maxImages)return`Attach at most ${n.maxImages} images to a message`;if(!H_(t))return`Only PNG, JPEG, WebP or GIF images can be attached`}function W_(e,t=L_){return Math.max(0,Math.min(t.perImageBase64,t.totalBase64-e))}function G_(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 K_(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 q_(e,t,n,r=L_){if(t<=0)throw new B_(`No room for another image in this message`);let i=G_(e.width,e.height,r.maxSide);for(let r of z_){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}]:[],...R_.map(e=>({type:`image/jpeg`,quality:e,width:a,height:o}))];for(let e of s){let r=await n(e);if(V_(r.size)<=t)return{blob:r,request:e}}}throw new B_}var J_=()=>({draft:``,images:[],pending:[],stopping:!1});function Y_(e,t){switch(t.type){case`input`:return{...e,draft:t.text,error:void 0};case`attach`:return e.images.length>=L_.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,L_.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 X_(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 Z_(e,t){return e===202?t.mode===`turn`?`accepted`:`steered`:`result`}function Q_(e,t={}){if(e.outcome&&e.outcome!==`succeeded`){if(e.outcome===`timeout`)return{text:`The agent is still working; the reply may be partial.`,kind:`sys`};if(e.outcome===`interrupted`)switch(e.message){case`shutdown`:return t.denied?{text:`${t.denied}: the turn stopped`,kind:`sys`}:{text:`Turn stopped: OpenCode shut down`,kind:`err`};case`user`:return{text:`Turn stopped`,kind:`sys`};case`inactivity`:return{text:`Turn stopped after inactivity`,kind:`sys`};case`superseded`:return{text:`Turn stopped: a newer turn replaced it`,kind:`sys`}}return{text:`Turn ${e.outcome}${e.message?`: ${e.message}`:``}`,kind:`err`}}}async function $_(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 ev=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)}},tv=-19.5,nv=-50,rv=20,iv=9,av=2,ov=60,sv=.4,cv=.1,lv=-70,uv=-10,dv=e=>e>0?20*Math.log10(e):-1/0,fv=e=>e>0?-.691+10*Math.log10(e):-1/0;function pv(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 mv(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 hv(e,t){if(!e.length)return-1/0;let[n,r]=pv(t),i=mv(mv(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(sv*t),s=Math.round(cv*t);if(i.length<o){let e=fv(a[i.length]/i.length);return e>lv?e:-1/0}let c=[];for(let e=0;e+o<=i.length;e+=s){let t=(a[e+o]-a[e])/o;fv(t)>lv&&c.push(t)}if(!c.length)return-1/0;let l=e=>e.reduce((e,t)=>e+t,0)/e.length,u=fv(l(c))+uv,d=c.filter(e=>fv(e)>u);return fv(l(d.length?d:c))}function gv(e){let t=0;for(let n=0;n<e.length;n++)t=Math.max(t,Math.abs(e[n]));return dv(t)}function _v(e,t){let n=10**(nv/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 vv(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,av/1e3*t)),n=Math.exp(-1/Math.max(1,ov/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 yv(e,t,n){let r=_v(e,t),i=hv(r,t);if(!Number.isFinite(i))return{samples:r,gainDb:0,loudness:i};let a=10**(-1/20),o=Math.min(rv,-1-gv(r)+iv),s=Math.min(n-i,o),c=vv(r,t,10**(s/20),a);for(let e=0;e<3;e++){let e=n-hv(c,t);if(e<.1||s>=o)break;s=Math.min(s+e,o),c=vv(r,t,10**(s/20),a)}return{samples:c,gainDb:s,loudness:i}}function bv(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 xv=`voice.replyLoudness`,Sv=8;function Cv(e){try{let t=JSON.parse(e.getItem(xv)??`{}`);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}function wv(e,t){let n=Cv(e)[t];return Array.isArray(n)?n.filter(e=>typeof e==`number`&&Number.isFinite(e)):[]}function Tv(e,t,n){if(!(!Number.isFinite(n)||n<-50||n>0))try{let r=Cv(e),i=[...wv(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-Sv)))delete r[e];e.setItem(xv,JSON.stringify(r))}catch{}}var Ev=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 Dv(e,t){let n=[];try{t!==void 0&&(n=wv(e,t))}catch{n=[]}return n.length?Math.min(-14,Math.max(-26,Ev(n))):tv}var Ov={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}]},kv=`hub-cues-v2`,Av=[`hub-cues-v1`],jv=`x-hub-cue-target`,Mv=1,Nv=`https://hub-cues.invalid`,Pv=e=>`${Nv}/${encodeURIComponent(e)}/`,Fv=(e,t)=>`${Pv(e)}${encodeURIComponent(t)}`;async function Iv(){try{let e=globalThis.caches;return e?await e.open(kv):void 0}catch{return}}function Lv(e,t){e.defaultPlaybackRate=t,e.playbackRate=t,e.preservesPitch=!0,e.webkitPreservesPitch=!0}var Rv=new class{entries=new Map;get size(){return this.entries.size}get(e,t){return this.entries.get(`${e}\n${t}`)}set(e,t,n){let r=`${e}\n${t}`,i=this.entries.get(r);i&&i.url!==n.url&&URL.revokeObjectURL?.(i.url),this.entries.set(r,n)}keep(e){for(let[t,n]of this.entries)t.startsWith(`${e}\n`)||(this.entries.delete(t),URL.revokeObjectURL?.(n.url))}},zv=class{synthesize;speed;onSpeaking;onPlayed;normalize;target;phrases=new Map;urls=new Map;key=Promise.resolve(void 0);audio;ctx;loading=new AbortController;memory;speaking=!1;constructor({synthesize:e,speed:t,onSpeaking:n,onPlayed:r,audio:i,normalize:a,target:o,memory:s=Rv}){this.synthesize=e,this.speed=t,this.onSpeaking=n,this.onPlayed=r,this.normalize=a,this.target=o,this.memory=s,this.audio=i??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=Ov[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}this.onPlayed?.({cue:`earcon`,name:e})}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 Iv():void 0,i=n?Fv(n,e):``,a=this.target?.(n)??-19.5,o=e=>!this.normalize||Math.abs((e??NaN)-a)<=Mv,s=n?this.memory.get(n,e):void 0;if(s&&o(s.target))return this.urls.set(e,s.url),s.url;let c=s?.blob,l=s?.target;if(!c&&r){let e=await r.match(i).catch(()=>void 0);c=await e?.blob().catch(()=>void 0);let t=e?.headers.get(jv);l=t==null?void 0:Number(t)}if(!c||!o(l)){let n=c??await this.synthesize(e,t);c=n;let o={};if(this.normalize)try{c=await this.normalize(n,a),o[jv]=String(a),l=a}catch{}o[`content-type`]=c.type||`audio/mpeg`,await r?.put(i,new Response(c,{headers:o})).catch(()=>{})}let u=URL.createObjectURL(c);return this.urls.set(e,u),n&&this.memory.set(n,e,{blob:c,url:u,...l===void 0?{}:{target:l}}),u}async prune(){let e=await this.key;e&&this.memory.keep(e);let t=e?await Iv():void 0;if(!t||!e)return;let n=globalThis.caches;for(let e of Av)await n?.delete(e).catch(()=>!1);try{for(let n of await t.keys())n.url.startsWith(Pv(e))||await t.delete(n)}catch{}}say(e){let t=this.urls.get(e);return t?this.playURL(t,e):(this.earcon(`pending`),this.phrase(e).catch(()=>{}),Promise.resolve())}async playURL(e,t){let n=this.audio;this.setSpeaking(!0),n.src=e,n.volume=1,Lv(n,this.speed?.()??1);let r=new Promise(e=>{n.onended=n.onpause=n.onerror=()=>e()});await n.play().then(()=>!0,()=>!1)&&(t!==void 0&&this.onPlayed?.({cue:`phrase`,text:t}),await r),n.onended=n.onpause=n.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}},Bv=new Set([`um`,`umm`,`uh`,`uhh`,`uhm`,`erm`,`er`,`eh`,`ah`,`hmm`,`hm`,`mm`,`mmm`,`mhm`,`mm-hmm`,`uh-huh`]),Vv=new Set([...Bv,`and`,`but`,`so`,`or`,`because`,`cause`,`then`,`with`,`to`,`the`,`a`,`an`,`of`,`for`,`if`,`that`,`like`,`maybe`]),Hv=new Map([[`stop`,`interrupt`],[`cancel`,`interrupt`],[`never mind`,`interrupt`],[`nevermind`,`interrupt`],[`stop that`,`interrupt`],[`hold on`,`interrupt`],[`pause listening`,`pause`]]),Uv=new Set([`mark`,`mark that`,`bookmark`]);function Wv(e){return String(e??``).toLowerCase().replace(/[^\p{L}\p{N}'\s-]+/gu,` `).split(/\s+/).map(e=>e.replace(/^[-']+|[-']+$/g,``)).filter(Boolean)}function Gv(e,{mark:t=!1}={}){let n=Wv(e).join(` `);return t&&Uv.has(n)?`mark`:Hv.get(n)}function Kv(e){return Wv(e).every(e=>Bv.has(e))}function qv(e){let t=String(e??``).trim(),n=Wv(t);return!n.length||Vv.has(n[n.length-1])||/(\.\.\.|…|[,;:\-–—])["'”’)\]]*$/.test(t)?!1:/[.?!]["'”’)\]]*$/.test(t)?!0:n.length>=3}var Jv=new Set([`e.g.`,`i.e.`,`mr.`,`mrs.`,`ms.`,`dr.`,`st.`,`vs.`,`cf.`,`prof.`,`jr.`,`sr.`,`approx.`,`no.`,`fig.`]),Yv=/[.?!…]+["'”’)\]]*(?=\s|$)/g;function Xv(e,{minChars:t=4,maxChars:n=300,speakable:r}={}){let i=String(e??``),a=(r?r(i):i).replace(/```[\s\S]*?(?:```|$)/g,`
|
|
8
|
+
(code omitted)
|
|
9
|
+
`).split(/\r?\n/).map(e=>e.replace(/\s+/g,` `).trim()).filter(Boolean).flatMap(Zv),o=[],s=``;for(let e of a){let n=s?`${s} ${e}`:e;n.length<t?s=n:(o.push(n),s=``)}return s&&(o.length?o[o.length-1]+=` ${s}`:o.push(s)),o.flatMap(e=>Qv(e,n))}function Zv(e){let t=[],n=0;for(let r of e.matchAll(Yv)){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(Jv.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 Qv(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 $v=16e3;function ey(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 ty(e,t){return bv(ey(e,t,$v),$v)}function ny(e){return{audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,...e?{deviceId:{exact:e}}:{}}}}var ry=Object.freeze({minSpeechMs:300,endSilenceMs:350,trailingKeepMs:200,preRollMs:300,holdMs:1600,finishedHoldMs:1e3}),iy=ry.trailingKeepMs,ay=120,oy=4,sy=e=>e.reduce((e,t)=>e+t.ms,0);function cy(e,t){for(;e.length>1&&sy(e)-e[0].ms>=t;)e.shift()}var ly=class{sampleRate;minSpeechMs;endSilenceMs;preRollMs;maxSegmentMs;onsetGapMs;minVoicedRatio;state=`silence`;abandoned=void 0;broken=!1;preroll=[];frames=[];segmentMs=0;onsetMs=0;voicedMs=0;gapMs=0;silenceMs=0;constructor({sampleRate:e,minSpeechMs:t=ry.minSpeechMs,endSilenceMs:n=ry.endSilenceMs,preRollMs:r=ry.preRollMs,maxSegmentMs:i=6e4,onsetGapMs:a=ay,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.abandoned=void 0,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.abandoned=void 0,this.state===`silence`)t?(this.state=`onset`,this.frames=[...this.preroll,n],this.segmentMs=sy(this.frames),this.preroll=[],this.onsetMs=this.voicedMs=n.ms,this.gapMs=0,this.broken=!1):(this.preroll.push(n),cy(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.broken=!0),this.gapMs=0):((this.gapMs+=n.ms)>this.onsetGapMs||this.voicedMs<this.minVoicedRatio*this.onsetMs)&&(this.abandoned={reason:this.gapMs>this.onsetGapMs?`gap`:`ratio`,onsetMs:this.onsetMs,voicedMs:this.voicedMs,broken:this.broken},this.preroll=this.frames,cy(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-iy;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}}},uy=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-oy: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}}},dy=class{sendFn;holdMs;finishedHoldMs;maxUtteranceMs;onHeld;onSend;onMerge;setTimer;clearTimer;now;nextID=1;pending=[];text=``;ms=0;segments=[];lastEnd=0;speaking=!1;endedAt=0;timer;smart;predict;onPredict;turn;predictTimes=[];mark;constructor({send:e,holdMs:t=ry.holdMs,finishedHoldMs:n=ry.finishedHoldMs,maxUtteranceMs:r=6e4,onHeld:i,onSend:a,onMerge:o,setTimer:s=(e,t)=>setTimeout(e,t),clearTimer:c=e=>clearTimeout(e),now:l=()=>Date.now(),smart:u,predict:d,onPredict:f,mark:p}){this.sendFn=e,this.holdMs=t,this.finishedHoldMs=n,this.maxUtteranceMs=r,this.onHeld=i,this.onSend=a,this.onMerge=o,this.setTimer=s,this.clearTimer=c,this.now=l,this.smart=u,this.predict=d,this.onPredict=f,this.mark=p,this.reset()}get held(){return this.text}get busy(){return!!this.text||this.pending.length>0}reset(){this.cancelHold(),this.endTurn(),this.pending=[],this.text=``,this.ms=0,this.segments=[],this.speaking=!1,this.onHeld?.(``)}speechStarted(){this.speaking=!0,this.cancelHold(),this.endTurn()}segmentEnded(e){this.speaking=!1,this.endedAt=this.now();let t=this.nextID++;return this.pending.push({id:t,ms:e,endedAt:this.endedAt}),this.startTurn(),t}startTurn(){this.endTurn();let e=this.predict?this.smart?.():void 0;if(!e)return;let t={params:e,mode:`predicting`,decidedAt:0,lastMs:0,timers:[]};this.turn=t,t.timers.push(this.setTimer(()=>{this.turn===t&&t.mode!==`timers`&&t.mode!==`complete`&&(t.mode=`fallback`,this.evaluate())},e.fallbackMs)),this.score(t)}score(e){let t=this.now(),n=!1,r=this.setTimer(()=>{n||this.turn!==e||(n=!0,this.toTimers(e,`slow`,t))},E_(e.params.slowMs,this.predictTimes));e.timers.push(r);let i;try{i=this.predict()}catch(i){n=!0,this.clearTimer(r),this.toTimers(e,String(i?.message??i),t);return}i.then(({p:i,ms:a})=>{if(this.predictTimes.push(this.now()-t),this.predictTimes.length>9&&this.predictTimes.shift(),n||this.turn!==e||e.mode===`fallback`)return;n=!0,this.clearTimer(r),e.lastP=i,e.lastMs=a;let o=Math.max(0,this.now()-this.endedAt);i>=e.params.threshold?(e.mode=`complete`,e.decidedAt=this.now(),this.onPredict?.({p:i,ms:a,silenceMs:o,decision:`send`}),this.evaluate()):(e.mode=`hold`,this.onPredict?.({p:i,ms:a,silenceMs:o,decision:`hold`}),e.timers.push(this.setTimer(()=>{this.turn===e&&e.mode===`hold`&&this.score(e)},e.params.recheckMs)))},i=>{n||this.turn!==e||e.mode===`fallback`||(n=!0,this.clearTimer(r),this.toTimers(e,String(i?.message??i),t))})}toTimers(e,t,n){this.clearTurnTimers(e),e.mode=`timers`,this.onPredict?.({ms:Math.max(0,this.now()-n),silenceMs:Math.max(0,this.now()-this.endedAt),decision:`timer-fallback`,error:t}),this.evaluate()}clearTurnTimers(e){for(let t of e.timers)this.clearTimer(t);e.timers.length=0}endTurn(){this.turn&&this.clearTurnTimers(this.turn),this.turn=void 0}evaluateSmart(e){if(e.mode===`fallback`)return this.onPredict?.({...e.lastP===void 0?{}:{p:e.lastP},ms:e.lastMs,silenceMs:Math.max(0,this.now()-this.endedAt),decision:`fallback`}),this.flush(`smart-fallback`);if(e.mode!==`complete`)return;let t=e.params.graceMs-(this.now()-e.decidedAt);if(t<=0)return this.flush(`smart`);this.timer=this.setTimer(()=>{this.timer=void 0,this.flush(`smart`)},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({id:e,text:t,ms:n,endedAt:r}){let i=Gv(t,{mark:this.mark?.()===!0});if(i===`mark`)return this.sent(t,[e],`command`);i?(this.cancelHold(),this.text=``,this.ms=0,this.segments=[],this.sent(t,[e],`command`)):Kv(t)||(this.text&&this.onMerge&&this.onMerge({segments:[...this.segments,e],pauseMs:Math.max(0,r-n-this.lastEnd)}),this.text=this.text?`${this.text} ${t}`:t,this.ms+=n,this.segments.push(e),this.lastEnd=r,this.ms>=this.maxUtteranceMs&&this.flush(`max`))}sent(e,t,n){this.onSend?.({text:e,segments:t,reason:n,holdMs:Math.max(0,this.now()-this.endedAt)}),this.sendFn(e)}evaluate(){if(this.onHeld?.(this.text),!this.text||this.speaking||this.pending.length)return;if(this.cancelHold(),this.turn&&this.turn.mode!==`timers`)return this.evaluateSmart(this.turn);let e=qv(this.text),t=e?`finished`:`hold`,n=(e?this.finishedHoldMs:this.holdMs)-(this.now()-this.endedAt);if(n<=0)return this.flush(t);this.timer=this.setTimer(()=>{this.timer=void 0,this.flush(t)},n)}flush(e){this.cancelHold(),this.endTurn();let t=this.text,n=this.segments;this.text=``,this.ms=0,this.segments=[],t&&this.sent(t,n,e),this.onHeld?.(``)}cancelHold(){this.timer!==void 0&&this.clearTimer(this.timer),this.timer=void 0}},fy=2,py=class{synth;play;stop;onState;onError;onPlay;onEnd;now;items=[];generation=0;controller=new AbortController;speaking=!1;playing=!1;current;constructor({synth:e,play:t,stop:n,onState:r,onError:i,onPlay:a,onEnd:o,now:s=()=>Date.now()}){this.synth=e,this.play=t,this.stop=n,this.onState=r,this.onError=i,this.onPlay=a,this.onEnd=o,this.now=s}enqueue(e){for(let t of e){let e=typeof t==`string`?{text:t}:t,n=String(e.text??``).trim();n&&this.items.push(e.ref===void 0?{text:n}:{text:n,ref:e.ref})}this.items.length&&(this.speaking?this.prefetch():this.run(this.generation))}prefetch(){for(let e of this.items.slice(0,this.playing?fy:3))this.fetch(e)}clear(){let e=this.current,t=this.items.map(({text:e,ref:t})=>t===void 0?{text:e}:{text:e,ref:t});if(this.current=void 0,this.generation++,this.controller.abort(),this.controller=new AbortController,this.items=[],this.playing=!1,this.stop(),this.setSpeaking(!1),!e)return{dropped:t};let n=Math.max(0,this.now()-e.at);return this.onEnd?.(e.item,{playedMs:n,completed:!1}),{playing:{...e.item,playedMs:n},dropped:t}}fetch(e){e&&!e.audio&&(e.audio=e.ref===void 0?this.synth(e.text,this.controller.signal):this.synth(e.text,this.controller.signal,e.ref),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();let r=t.ref===void 0?{text:t.text}:{text:t.text,ref:t.ref};this.current={item:r,at:this.now()},this.onPlay?.(r);let i=!0;try{await this.play(n)}catch(n){i=!1,e===this.generation&&this.onError?.(n,t.text)}finally{if(e===this.generation){this.playing=!1;let e=this.current;this.current=void 0,e&&this.onEnd?.(e.item,{playedMs:Math.max(0,this.now()-e.at),completed:i})}}}e===this.generation&&this.setSpeaking(!1)}setSpeaking(e){e!==this.speaking&&(this.speaking=e,this.onState?.(e))}},my=class{parts=new Map;limit;speakable;constructor({limit:e=50,speakable:t}={}){this.limit=e,this.speakable=t}split(e){return Xv(e,this.speakable?{speakable:this.speakable}:{})}get size(){return this.parts.size}accept(e){let t=this.take(e);return t&&{sentences:t.sentences,text:t.text}}take(e){let t=String(e.text??``),n=e.messageID??``,r=e.ordinal??0;if(typeof e.seq!=`number`){let e=this.split(t);return{sentences:e,items:e.map((e,t)=>({text:e,ref:{messageID:n,ordinal:r,i:t}})),text:t,muted:!1}}let i=`${n} ${r}`,a=this.parts.get(i);if(a||(a={messageID:n,next:0,held:new Map,texts:[],muted:!1},this.parts.set(i,a),this.parts.size>this.limit&&this.parts.delete(this.parts.keys().next().value)),e.seq<a.next||a.held.has(e.seq))return;a.held.set(e.seq,t);let o=[];for(;a.held.has(a.next);)o.push({seq:a.next,text:a.held.get(a.next)}),a.held.delete(a.next++);if(!o.length)return;a.texts.push(...o.map(e=>e.text));let s=a.muted?[]:o.flatMap(e=>this.split(e.text).map((t,i)=>({text:t,ref:{messageID:n,ordinal:r,seq:e.seq,i}})));return{sentences:s.map(e=>e.text),items:s,text:a.texts.join(` `),muted:a.muted}}mute(){let e=new Set;for(let t of this.parts.values())!t.muted&&t.messageID&&e.add(t.messageID),t.muted=!0;return[...e]}},hy=class{pending={};turn;now;last;constructor({now:e=()=>Date.now()}={}){this.now=e}mark(e,t=this.now()){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)}}},gy=e=>`${(e/1e3).toFixed(1)} s`;function _y(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} ${gy(n-i)}`),i=n)}return{summary:`last turn: ${gy(e.firstAudio-t)} to first audio`,detail:r.join(` · `)}}var vy=12,yy=e=>String(e??``).replace(/\s+/g,` `).trim();function by(e,t){let n=yy(e),r=yy(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>=vy;e--)if(n.endsWith(r.slice(0,e)))return{mode:`update`,text:n+r.slice(e)};return{mode:`new`,text:t}}function xy(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 Sy=Object.freeze({nearMinMs:150,probMargin:.2,dbMargin:3,runGapMs:100,minOnsetVoicedMs:60,nearGapMs:500,nearPerMinute:20,summaryMs:1e4}),Cy=Object.freeze({preFrames:48,postFrames:16,perMinute:30,gapMs:1e3}),wy=(e,t)=>Math.round(e*10**t)/10**t,Ty=100,Ey=()=>({ms:0,frames:0,probFrames:0,hist:new Uint32Array(101),maxProb:0,maxDb:-1/0,aboveStart:0,aboveSpeaking:0,guardMs:0,near:0,dropped:0,close:!1,mode:`energy`}),Dy=class{onNear;onSummary;clock=0;run;onset;sent=[];window=Ey();quietAt;onTrace;recent=[];trace;traced=[];constructor({onNear:e,onSummary:t,onTrace:n}){this.onNear=e,this.onSummary=t,this.onTrace=n}reset(){this.run=void 0,this.onset=void 0}frame(e){this.clock+=e.ms;let t=e.mode===`silero`?e.prob??0:e.db,n=e.guarded?e.speakingThreshold:e.startThreshold,r=e.mode===`silero`?Sy.probMargin:Sy.dbMargin;this.tally(e,t,n-r),this.onTrace&&this.traceFrame({value:e.mode===`silero`?Math.round(Math.min(1,Math.max(0,t))*100):Math.round(t),guard:e.guarded,threshold:e.mode===`silero`?Math.round(n*100):Math.round(n),mode:e.mode,ms:e.ms}),this.track(e,t,n,n-r),this.onTrace&&(e.before!==`speech`&&e.after===`speech`?this.startTrace(`speech.start`):e.before===`speech`&&e.after!==`speech`&&this.startTrace(`speech.end`)),this.window.ms>=Sy.summaryMs&&this.summarize()}traceFrame(e){this.recent.push(e),this.recent.length>Cy.preFrames&&this.recent.shift();let t=this.trace;if(!t||(t.frames.push(e),--t.left>0))return;this.trace=void 0;let n=t.frames.at(-1);this.onTrace?.({reason:t.reason,mode:n.mode,frameMs:Math.round(n.ms*10)/10,scale:n.mode===`silero`?`p100`:`db`,values:t.frames.map(e=>e.value),threshold:n.threshold,guard:t.frames.map(e=>e.guard?`1`:`0`).join(``)})}startTrace(e){if(this.trace)return;for(;this.traced.length&&this.clock-this.traced[0]>=6e4;)this.traced.shift();let t=this.traced.at(-1);t!==void 0&&this.clock-t<Cy.gapMs||this.traced.length>=Cy.perMinute||(this.traced.push(this.clock),this.trace={reason:e,frames:[...this.recent],left:Cy.postFrames})}track(e,t,n,r){if(e.before===`silence`&&e.after===`onset`?(this.run=void 0,this.onset={ms:0,lastMs:this.clock,peak:t,threshold:n,guarded:e.guarded,mode:e.mode}):this.onset&&e.before===`onset`&&(this.onset.peak=Math.max(this.onset.peak,t),this.onset.guarded||=e.guarded),e.after===`speech`&&(this.onset=void 0),e.abandoned){let t=this.onset;if(this.onset=void 0,t&&e.abandoned.voicedMs>=Sy.minOnsetVoicedMs){let n=e.abandoned.reason===`ratio`&&e.abandoned.broken?`voiced-ratio`:`short-onset`;this.near({...t,ms:e.abandoned.onsetMs},n,e.abandoned.voicedMs)}}else e.before!==`silence`||e.after!==`silence`?this.run=void 0:t>=r?(this.run||={ms:0,lastMs:this.clock-e.ms,peak:t,threshold:n,guarded:e.guarded,mode:e.mode},this.run.ms+=this.clock-this.run.lastMs,this.run.lastMs=this.clock,this.run.peak=Math.max(this.run.peak,t),this.run.guarded||=e.guarded,this.run.threshold=Math.max(this.run.threshold,n)):this.run&&this.clock-this.run.lastMs>Sy.runGapMs&&this.endRun()}endRun(){let e=this.run;this.run=void 0,e&&e.ms>=Sy.nearMinMs&&this.near(e,`below-threshold`)}near(e,t,n){for(this.window.close=!0;this.sent.length&&this.clock-this.sent[0]>=6e4;)this.sent.shift();let r=this.sent.at(-1);if(r!==void 0&&this.clock-r<Sy.nearGapMs||this.sent.length>=Sy.nearPerMinute){this.window.dropped++;return}this.sent.push(this.clock),this.window.near++,this.onTrace&&this.startTrace(`vad.near`);let i=e.mode===`silero`?{peakProb:wy(e.peak,3)}:{peakDb:wy(e.peak,1)};this.onNear?.({ms:Math.round(e.ms),...n===void 0?{}:{voicedMs:Math.round(n)},...i,threshold:wy(e.threshold,e.mode===`silero`?3:1),echoGuard:e.guarded,mode:e.mode,reason:t})}tally(e,t,n){let r=this.window;if(r.ms+=e.ms,r.frames++,r.mode=e.mode,r.floorDb=e.floorDb,r.maxDb=Math.max(r.maxDb,e.db),e.guarded&&(r.guardMs+=e.ms),e.mode===`silero`){let t=Math.min(1,Math.max(0,e.prob??0));r.probFrames++,r.hist[Math.round(t*Ty)]++,r.maxProb=Math.max(r.maxProb,t)}t>=e.startThreshold&&r.aboveStart++,t>=e.speakingThreshold&&r.aboveSpeaking++,t>=n&&(r.close=!0)}summarize(){let e=this.window;this.window=Ey();let t=!e.close&&!e.aboveStart&&!e.aboveSpeaking&&!e.near&&!e.dropped,n=e.floorDb,r=this.quietAt!==void 0&&n!==void 0&&Math.abs(n-this.quietAt)<Sy.dbMargin;if(t&&r)return;this.quietAt=t?n:void 0;let i=e.probFrames>0?{maxProb:wy(e.maxProb,3),p90Prob:wy(Oy(e.hist,e.probFrames,.9),3)}:{};this.onSummary?.({frames:e.frames,...i,...Number.isFinite(e.maxDb)?{maxDb:wy(e.maxDb,1)}:{},...n!==void 0&&Number.isFinite(n)?{noiseFloorDb:wy(n,1)}:{},framesAboveStart:e.aboveStart,framesAboveSpeakingStart:e.aboveSpeaking,msEchoGuard:Math.round(e.guardMs),...e.dropped?{nearDropped:e.dropped}:{},mode:e.mode})}};function Oy(e,t,n){let r=Math.ceil(n*t),i=0;for(let t=0;t<e.length;t++)if(i+=e[t],i>=r)return t/Ty;return 1}var ky=16e3,Ay=512/ky*1e3,jy=Object.freeze({startProb:.6,endProb:.35,speakingStartProb:.85,minSpeechMs:250,endSilenceMs:ry.endSilenceMs,maxSegmentMs:6e4,gateDb:3,energyMarginDb:10,energyMinSpeechMs:ry.minSpeechMs}),My=Object.freeze([`low`,`normal`,`high`]);function Ny(e){return My.includes(e)?e:`normal`}var Py=Object.freeze({low:Object.freeze({...jy,startProb:.75,endProb:.45,speakingStartProb:.92,minSpeechMs:350,gateDb:6,energyMarginDb:13,energyMinSpeechMs:400}),normal:jy,high:Object.freeze({...jy,startProb:.45,endProb:.25,speakingStartProb:.75,minSpeechMs:180,gateDb:0,energyMarginDb:7,energyMinSpeechMs:250})});function Fy(e){return Py[Ny(e)]}var Iy=.75,Ly=class{speaking=!1;segmenter;current;constructor(e,t=ky){this.current=e,this.segmenter=new ly({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}get abandoned(){return this.segmenter.abandoned}reset(){this.segmenter.reset()}process(e,t){let n=this.current;this.segmenter.minSpeechMs=n.minSpeechMs,this.segmenter.minVoicedRatio=Iy;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)}},Ry=class{from;ratio;input=new Float32Array;pos=0;out=new Float32Array(512);filled=0;constructor(e){this.from=e,this.ratio=e/ky}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}},zy=64,By=class{sampleRate=ky;stats={frames:0,avgMs:0,maxMs:0,skipped:0};resampler;meter;vad;onEvents;onLevel;onChunk;warn;now;model;queue=[];inFlight=0;generation=0;warned=new Set;speakingOn=!1;tail=0;capture;constructor({sampleRate:e,params:t=jy,onEvents:n,onLevel:r,onChunk:i,warn:a=e=>console.warn(e),now:o=()=>performance.now(),onNear:s,onSummary:c,onTrace:l}){(s||c||l)&&(this.capture=new Dy({onNear:s,onSummary:c,onTrace:l})),this.resampler=new Ry(e),this.meter=new uy({marginDb:t.energyMarginDb}),this.vad=new Ly(t),this.onEvents=n,this.onLevel=r,this.onChunk=i,this.warn=a,this.now=o}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/Ay)),this.speakingOn=e}get active(){return this.vad.active}reset(){this.generation++,this.queue=[],this.inFlight=0,this.vad.reset(),this.capture?.reset()}push(e){for(let t of this.resampler.push(e))this.chunk(t)}chunk(e){this.onChunk?.(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,Ay,n);this.onLevel?.(a);let s={chunk:e,energyVoiced:o,guarded:t,db:r,floor:i};this.queue.push(s),this.model&&this.inFlight>=zy&&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;let n=this.vad.state;e.push(...t.energy?this.vad.processEnergy(t.chunk,t.energyVoiced):this.vad.process(t.chunk,t.prob)),this.capture&&this.captured(t,n)}e.length&&this.onEvents(e)}captured(e,t){let n=this.vad.params,r=this.vad.abandoned,i={ms:Ay,db:e.db,floorDb:e.floor,guarded:e.guarded,before:t,after:this.vad.state,...r?{abandoned:r}:{}};if(e.energy){let t=Math.max(e.floor+this.meter.marginDb,this.meter.minDb);this.capture.frame({...i,mode:`energy`,startThreshold:t,speakingThreshold:t+this.meter.speakingBoostDb})}else this.capture.frame({...i,mode:`silero`,prob:e.prob??0,startThreshold:n.startProb,speakingThreshold:n.speakingStartProb})}warnOnce(e,t){this.warned.has(e)||(this.warned.add(e),this.warn(t))}},Vy=`voice.speed`,Hy=`voice.cues`,Uy=`voice.background`,Wy=`voice.micDevice`,Gy=`voice.sensitivity`,Ky=`voice.turnDetection`,qy=`voice.front`,Jy,Yy,Xy={get speed(){return Wa(localStorage.getItem(Vy))},set speed(e){localStorage.setItem(Vy,String(Wa(e))),Lv(Qy(),Wa(e))},get cues(){return localStorage.getItem(Hy)!==`0`},set cues(e){localStorage.setItem(Hy,e?`1`:`0`)},get background(){return localStorage.getItem(Uy)===`1`},set background(e){localStorage.setItem(Uy,e?`1`:`0`)},get sensitivity(){return Jy??=Ny(localStorage.getItem(Gy))},set sensitivity(e){Jy=Ny(e),localStorage.setItem(Gy,Jy)},get turnDetection(){return Yy??=C_(localStorage.getItem(Ky))},set turnDetection(e){Yy=C_(e),localStorage.setItem(Ky,Yy)},get front(){return localStorage.getItem(qy)!==`0`},set front(e){localStorage.setItem(qy,e?`1`:`0`)},get smartTurn(){let e=new URLSearchParams(location.search);return k_(t=>e.get(t),e=>localStorage.getItem(e))},setSmartTurnKnob(e,t){let n=O_(e,t);return n===void 0?localStorage.removeItem(e):localStorage.setItem(e,String(n)),n===void 0?``:String(n)}},Zy;function Qy(){return Zy||(Zy=new Audio,Zy.preload=`none`,Zy.volume=1,Lv(Zy,Xy.speed),Zy)}function $y(){let e=Qy();e.paused&&(e.muted=!0,e.play().catch(()=>{}).finally(()=>{e.pause(),e.muted=!1}))}var eb,tb=new Set,nb={get(){return eb??=localStorage.getItem(Wy)??``},set(e){eb=e,localStorage.setItem(Wy,e);for(let t of[...tb])t(e)},subscribe(e){return tb.add(e),()=>{tb.delete(e)}}};async function rb(){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 ib(e,t){let n=await navigator.mediaDevices.getUserMedia(ny(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 ab=6e4;function ob(){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 sb({transcribe:e,deviceId:t=nb.get(),onTick:n}){if(!navigator.mediaDevices?.getUserMedia||!window.MediaRecorder)throw Error(`This browser cannot record here (the microphone needs HTTPS).`);let r;try{r=await navigator.mediaDevices.getUserMedia(ny(t||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 i=ob(),a=new MediaRecorder(r,i?{mimeType:i}:void 0),o=[],s=Date.now();a.ondataavailable=e=>e.data.size&&o.push(e.data);let c=!1,l=new Promise((t,n)=>{a.onstop=async()=>{if(clearInterval(u),clearTimeout(d),r.getTracks().forEach(e=>e.stop()),c)return t(``);let s=new Blob(o,{type:(a.mimeType||i||`audio/webm`).split(`;`)[0]});if(!s.size)return t(``);try{let{text:n}=await e(s);t(String(n??``).trim())}catch(e){let t=e;n(Error(t.status===413?`That recording was too long.`:`Transcription failed: ${t.message}`))}}});a.start();let u=setInterval(()=>n?.(Math.max(0,Math.ceil((ab-(Date.now()-s))/1e3))),1e3),d=setTimeout(()=>a.state===`recording`&&a.stop(),ab);return{finish(){return a.state===`recording`&&a.stop(),l},cancel(){c=!0,a.state===`recording`&&a.stop()}}}var cb=Qy(),[lb,ub]=u(nb.get());function db(e){ub(e),nb.set(e)}function fb(e){return sb({deviceId:lb(),...e?{onTick:e}:{},transcribe:async e=>(await H(`/api/transcribe`,{method:`POST`,body:e,headers:{"content-type":e.type}})).json()})}function pb(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 mb(e){return e.audioState===`suspended`||e.error===`NotAllowedError`&&!e.activated&&e.micPermission!==`denied`}var hb=512,gb=Object.freeze({preMs:3e3,postMs:2e3,gapMs:2e3}),_b=class{sampleRate;buffer;total=0;pending=[];constructor({sampleRate:e=16e3,capacityMs:t}){this.sampleRate=e,this.buffer=new Float32Array(Math.ceil(t/1e3*e))}get position(){return this.total}push(e){for(let t=0;t<e.length;t+=hb)this.write(e,t,Math.min(e.length,t+hb))}write(e,t,n){let r=this.buffer.length;for(let i=t;i<n;i++)this.buffer[(this.total+i-t)%r]=e[i];if(this.total+=n-t,!this.pending.length)return;let i=this.pending.filter(e=>e.to<=this.total);if(i.length){this.pending=this.pending.filter(e=>e.to>this.total);for(let e of i)e.done(this.read(e.from,e.to),{preMs:e.preMs,postMs:e.postMs})}}clip(e,t,n){let r=e=>Math.round(e/this.sampleRate*1e3),i=this.buffer.length,a=Math.min(Math.round(t/1e3*this.sampleRate),i),o=Math.max(0,Math.min(Math.round(e/1e3*this.sampleRate),this.total,i-a-hb));this.pending.push({from:this.total-o,to:this.total+a,preMs:r(o),postMs:r(a),done:n})}reset(){this.pending=[]}read(e,t){let n=this.buffer.length,r=new Float32Array(t-e);for(let i=e;i<t;i++)r[i-e]=this.buffer[i%n];return r}},vb=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(`.`)),yb=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`]),bb=[/^(?:subtitles?|captions?|subtitled|captioned|transcribed|transcription|translated|translation)\b.*\bby\b/,/\bamara\s*\.?\s*org\b/,/^sous-titr/,/^untertitel\b/],xb=/^(?:\[[^\]]*\]|\([^)]*\)|\*[^*]*\*|♪[^♪]*♪|\s)+$/u;function Sb(e){return e.toLowerCase().replace(/[^\p{L}\p{N}'\s]+/gu,` `).replace(/\s+/g,` `).trim()}function Cb(e,{speechMs:t}={}){let n=String(e??``).trim();if(!n)return`empty`;if(!/[\p{L}\p{N}]/u.test(n))return`no words`;if(xb.test(n))return`sound`;let r=Sb(n);if(r.replace(/\s/g,``).length<2)return`too short`;if(yb.has(r)||yb.has(r.replace(/ /g,``))||bb.some(e=>e.test(r)||e.test(n.toLowerCase())))return`noise`;let i=r.split(` `),a=i.some(e=>vb.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 wb=3e4,Tb;function Eb(){return Tb??=Db().catch(e=>{throw Tb=void 0,e}),Tb}function Db(){return new Promise((e,t)=>{let n;try{n=new Worker(new URL(`/assets/silero-worker-CC2etKS3.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(),Tb=void 0,a||t(e)},s=setTimeout(()=>o(Error(`the speech model took too long to load`)),wb);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 Ob=()=>Object.assign(Error(`The download was aborted`),{name:`AbortError`}),kb=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 Ob();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 Ab(e,t){let n=new kb;if(!e)return n.end(),n;let r=e.getReader(),i=()=>{n.fail(Ob()),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?Ob():e)}finally{t?.removeEventListener(`abort`,i)}})(),n}async function jb(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 Mb(e){try{return e.MediaSource?.isTypeSupported?.(`audio/mpeg`)===!0}catch{return!1}}var Nb=24e3,Pb=1,Fb=2;async function Ib(e){let t=globalThis,n=t.OfflineAudioContext||t.webkitOfflineAudioContext;if(!n)throw Error(`No OfflineAudioContext here`);let r=new n(1,1,Nb),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 Lb(e,t){let{samples:n,rate:r}=await Ib(await e.arrayBuffer()),i=yv(n,r,t);return new Blob([bv(i.samples,r)],{type:`audio/wav`})}function Rb(e){try{return Dv(localStorage,e)}catch{return Dv({getItem:()=>null,setItem:()=>{}},e)}}var zb=0,Bb=e=>{let t=globalThis;t.requestIdleCallback?t.requestIdleCallback(e,{timeout:5e3}):setTimeout(e,500)};function Vb(e,t){!t||!e.length||zb>=Fb||(zb++,Bb(()=>{(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 Ib(n.buffer);if(i.length<a*Pb)return;Tv(localStorage,t,hv(i,a))}catch{}finally{zb--}})()}))}var Hb=500,Ub=8e3,Wb=e=>Math.min(Ub,Hb*2**Math.max(0,e)),Gb=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)}},Kb=2500,qb=3e3,Jb=!1,Yb=2,Xb=`Tap to start Voice mode`,Zb=`GestureRequired`,Qb=500,$b=500,ex=3e3,tx=()=>navigator.userActivation?.hasBeenActive??!0;async function nx(){try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return`unknown`}}var rx=`Voice front unavailable, talking to the session directly`,ix={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`},ax=.01,ox=ry.minSpeechMs+ry.preRollMs,sx=50,cx=2e3,lx=gb.preMs+gb.postMs+1e3,ux=()=>new URL(`/assets/vad-worklet-BfxJhrXy.js`,``+import.meta.url).href,dx=class{sessionID;transport;unsubscribe;player;ui;opts;rec;heldText=``;ring;lastClipAt=-1/0;spoken=[];playingRef;reachedEnd=!1;active=!1;paused=!1;agent;front=!1;frontWanted=!1;frontFallback=!1;inflight=0;sent=new Map;typed=new Set;typing=0;heardAt=0;lastStatus;cuePicker=new $a({ready:e=>this.cuePlayer?.ready(e)??!1});scheduler=new eo({pick:e=>this.cuePicker.pick(e)});cuePlayer;voiceKey;onVisibility;liveness=new Gb({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=Mb(window);says;turns;cueClock;speechEndedAt;silence;silenceURL;wakeLock;warnedAutoplay=!1;state;ignoredTimer;sensitivity=`normal`;cueSpeaking=!1;attempt=0;turnAudio=new A_;smartModel;smartLoading=!1;smartError;warnedSmart=!1;constructor({sessionID:e,transport:t,player:n,ui:r,options:i={}}){this.sessionID=e,this.transport=t,this.player=n,this.ui=r;let{recorder:a,speakable:o,...s}=i;this.says=new my(o?{speakable:o}:{}),this.opts={cues:!0,background:!1,speed:()=>1,title:()=>`OpenCode session`,sensitivity:()=>`normal`,turnDetection:()=>`timers`,smartTurnParams:()=>w_,smartTurn:h_,warn:e=>console.warn(e),front:()=>!0,voiceKey:async()=>void 0,...s},this.rec=a,a&&(this.ring=new _b({capacityMs:lx})),a&&(a.onNote=e=>this.ui.note(e)),a&&(a.onMarked=e=>this.devClip(`mark`,e)),this.turns=new hy({now:a?()=>performance.now():()=>Date.now()}),this.lastStatus=i.status,this.scheduler.enabled=this.opts.cues!==!1,this.scheduler.working(io(i.status),Date.now()),this.cuePlayer=new zv({synthesize:async(e,t)=>F_(await this.transport.speak(e,t?{signal:t}:{})),speed:this.opts.speed,normalize:Lb,target:Rb,onSpeaking:e=>{this.cueSpeaking=e,this.guardEcho(),this.scheduler.cueSpeaking(e,Date.now()),this.cueClock.poke()},...a?{onPlayed:e=>this.rec?.event(`cue.played`,e)}:{}}),this.cueClock=new to({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(()=>{}))},this.follow()}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());follow(){this.unsubscribe??=this.transport.events(e=>this.onEvent(e))}unfollow(){this.unsubscribe?.(),this.unsubscribe=void 0}get working(){return io(this.lastStatus)}get speaking(){return!!this.queue?.speaking}async start(){if(this.active)return!0;this.follow();let e=this.attempt+1,t=await this.begin();return!t&&!this.active&&e===this.attempt&&this.unfollow(),t}async begin(){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(ny(this.opts.deviceId))}catch(e){if(t())return!1;let n=e;return mb({error:n.name,micPermission:await nx(),activated:tx()})?this.ui.note(Xb,`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;let i;try{this.frontWanted=this.opts.front();let e;({agent:e,front:i}=await this.transport.conversation(!0,{front:this.frontWanted})),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.transport.conversation(!1).catch(()=>{}),!1;this.active=!0,typeof i!=`boolean`&&(this.frontWanted=!1),this.setFront(i===!0),this.rec?.start(this.sessionID,{detector:`energy`,sensitivity:this.opts.sensitivity(),cues:this.opts.cues!==!1,background:!!this.opts.background,streaming:this.streaming,timings:{...ry,...this.smartTimings()}}),this.prefetchCues();try{await this.listen()}catch(e){return t()||(e.name===Zb?this.ui.note(Xb,`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(),$b),this.cueClock.poke(),this.refresh(),!0)}prefetchCues(){this.opts.cues!==!1&&this.scheduler.enabled&&this.scheduler.phrases&&this.cuePlayer.prefetch(Qa(),this.voiceKey=this.cueKey())}async cueKey(){try{return await this.opts.voiceKey()}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,Qb))]),mb({audioState:n.state,activated:tx()}))throw Object.assign(Error(Xb),{name:Zb});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(this.opts.workletURL??ux());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 By({sampleRate:n.sampleRate,params:Fy(this.sensitivity),onEvents:e=>this.vadEvents(e),onLevel:e=>this.ui.level(e),onChunk:e=>{this.turnAudio.push(e),this.ring?.push(e)},...this.rec?{onNear:e=>{let t=this.rec?.event(`vad.near`,{...e});typeof t==`number`&&this.devClip(`vad.near`,t)},onSummary:e=>this.rec?.event(`vad.summary`,{...e,sensitivity:this.sensitivity}),onTrace:e=>{this.rec?.developer&&this.rec.event(`vad.trace`,{...e,values:[...e.values]})}}:{}});this.detected({mode:`energy`}),this.wantSmartTurn(),Eb().then(e=>{this.vad===r&&(e.reset(),r.classifier=t=>e.classify(t),this.detected({mode:`silero`}))},e=>{Jb||console.warn(`Voice: on-device speech detection unavailable (${e?.message??e}); using the energy detector`),Jb=!0}),this.endpointer=new dy({send:e=>void this.deliver(e),onHeld:e=>{this.ui.held?.(e),e&&e!==this.heldText&&this.rec?.event(`utterance.held`,{text:e}),this.heldText=e},onSend:e=>{this.turnAudio.reset(),this.rec?.event(`utterance.sent`,{text:e.text,segments:[...e.segments],reason:e.reason,holdMs:Math.round(e.holdMs)})},...this.rec?{onMerge:e=>this.rec?.event(`utterance.merged`,{segments:[...e.segments],pauseMs:Math.round(e.pauseMs)})}:{},smart:()=>this.opts.turnDetection()===`smart`?this.opts.smartTurnParams():void 0,predict:()=>this.predictTurn(),onPredict:e=>this.turnPredicted(e),mark:()=>this.rec?.marks===!0}),this.queue=new py({synth:(e,t,n)=>this.synth(e,t,n),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`),this.rec?.event(`error`,{where:`tts`,message:String(e?.message??e)}))},...this.rec?{now:()=>performance.now(),onPlay:e=>this.playingRef=e.ref,onEnd:(e,t)=>this.sentenceEnded(e,t)}:{}})}wantSmartTurn(){this.smartModel||this.smartLoading||this.smartError||this.opts.turnDetection()!==`smart`||(this.smartLoading=!0,this.opts.smartTurn().then(e=>{this.smartLoading=!1,this.active&&(this.smartModel=e)},e=>{this.smartLoading=!1,this.smartError=String(e?.message??e),this.warnSmart(`Voice: Smart Turn unavailable (${this.smartError}); using the timers`)}))}predictTurn(){if(!this.smartModel)return Promise.reject(Error(this.smartError??`loading`));let e=this.turnAudio.snapshot(),t=0;for(let n=0;n<e.length;n++)t=Math.max(t,Math.abs(e[n]));return t<ax?Promise.reject(Error(`no speech`)):this.smartModel.predict(e)}turnPredicted(e){this.ui.turn?.(j_(e)),this.rec?.event(`turn.predict`,{...e.p===void 0?{}:{p:Math.round(e.p*1e3)/1e3},ms:Math.round(e.ms),silenceMs:Math.round(e.silenceMs),decision:e.decision,...e.error===void 0?{}:{error:e.error}}),e.decision===`timer-fallback`&&e.error&&e.error!==`loading`&&e.error!==`no speech`&&this.warnSmart(`Voice: Smart Turn fell back to the timers (${e.error})`)}warnSmart(e){this.warnedSmart||(this.warnedSmart=!0,this.opts.warn(e))}smartTimings(){if(this.opts.turnDetection()!==`smart`)return{};let e=this.opts.smartTurnParams();return{smartTurn:1,smartThreshold:e.threshold,smartGraceMs:e.graceMs,smartRecheckMs:e.recheckMs,smartFallbackMs:e.fallbackMs,smartSlowMs:e.slowMs}}devClip(e,t){let n=this.rec;if(!n?.developer||!n.clip||!this.ring)return;let r=Date.now();r-this.lastClipAt<gb.gapMs||(this.lastClipAt=r,this.ring.clip(gb.preMs,gb.postMs,(r,i)=>{this.active&&n.clip?.(e,t,ty(r,this.ring.sampleRate),i)}))}detected(e){this.ui.detector?.(e),this.rec?.event(`detector`,e.avgMs===void 0?{mode:e.mode}:{mode:e.mode,avgMs:Math.round(e.avgMs*10)/10})}playerMs(e){let t=this.player.currentTime;return Number.isFinite(t)&&t>0?t*1e3:e}playerDuration(){let e=this.player.duration;return Number.isFinite(e)&&e>0?Math.round(e*1e3):void 0}sentenceEnded(e,t){if(this.playingRef===e.ref&&(this.playingRef=void 0),!e.ref)return;let n=this.playerDuration(),r=t.completed&&this.reachedEnd;this.rec?.event(`tts.sentence.ended`,{ref:e.ref,playedMs:Math.round(this.playerMs(t.playedMs)),...n===void 0?{}:{durationMs:n},completed:r}),r&&(this.spoken.push({ref:e.ref,text:e.text}),this.spoken.length>sx&&this.spoken.shift())}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;this.wantSmartTurn();let t=this.opts.sensitivity();t!==this.sensitivity&&(this.sensitivity=t,this.vad.params=Fy(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.busy||this.turnAudio.keepLast(ox),this.rec?.event(`speech.start`,{bargeIn:!!this.queue?.speaking||this.cueSpeaking}),this.endpointer.speechStarted(),this.scheduler.userTalking(!0,Date.now()),this.cuePlayer.stop(),this.queue.speaking?this.hushReplies(`speech`):this.recordBarge(`speech`,void 0,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),r={segment:e,durationMs:Math.round(n.durationMs),speechMs:Math.round(n.speechMs),forced:n.forced};this.rec?.event(`speech.end`,r);let i=ty(n.samples,t.sampleRate);this.rec?.event(`segment.closed`,{...r,bytes:i.byteLength}),this.transcribe(e,i,n.speechMs),this.detected({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=``,i,a;this.rec?.event(`stt.sent`,{segment:e,bytes:t.byteLength});let o=Date.now(),s=this.rec?setTimeout(()=>this.rec?.event(`stt.slow`,{segment:e,ms:Date.now()-o}),cx):void 0;try{let n=this.rec?.transcribeHeaders(e),i=await this.transport.transcribe(new Blob([t],{type:`audio/wav`}),n?{headers:n}:{});a=this.rec?.audioResult(i.headers),r=i.text??``}catch(e){i=e.message,this.active&&this.ui.note(`Transcription failed: ${i}`,`err`),this.rec?.event(`error`,{where:`stt`,message:String(i)})}finally{clearTimeout(s),this.inflight--}if(!this.active)return;let c=r,l=Cb(r,{speechMs:n});l&&(r.trim()&&this.showIgnored(r.trim()),r=``),this.rec&&(this.rec.event(`stt.received`,{segment:e,text:c,...l&&c.trim()?{junk:!0}:{},...!c.trim()&&i===void 0?{empty:!0}:{},...i===void 0?{}:{failed:i},...a?{audio:a}:{},...l&&c.trim()?{junkReason:l}:{},...this.endpointer?.held?{held:this.endpointer.held}:{},speechMs:Math.round(n)}),this.rec.segmentAudio(e,a,t)),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?.(``),qb)}async deliver(e,t=!1){let n=Gv(e,{mark:this.rec?.marks===!0});if(n&&this.rec?.event(`utterance.command`,{command:n,text:e}),n===`mark`){this.rec?.mark?.(`voice`);return}if(n===`pause`)return this.ui.note(`Paused listening.`),this.stop();if(n===`interrupt`){this.hushReplies(`command`),this.ui.note(`“${e}” — interrupting.`);try{await this.transport.interrupt()}catch(e){this.ui.note(`Could not interrupt: ${e.message}`,`err`),this.rec?.event(`error`,{where:`send`,message:e.message})}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 this.transport.utterance(e);this.markTurn(`accepted`),typeof n==`string`&&this.rec?.event(`utterance.accepted`,{inboxID:n}),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.rec?.event(`utterance.failed`,{...typeof t.status==`number`?{status:t.status}:{},message:String(t.message)}),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(`typed`),this.rec?.event(`utterance.sent`,{text:e,segments:[],reason:`typed`,holdMs:0}),this.deliver(e,!0)}hushReplies(e){let t=this.queue?.clear();this.recordBarge(e,t,this.says.mute())}recordBarge(e,t,n){if(!this.rec)return;let r=t?.playing?.ref?{ref:t.playing.ref,text:t.playing.text,playedMs:this.playerMs(t.playing.playedMs),durationMs:this.playerDuration()}:void 0;this.rec.barge({cause:e,completed:this.spoken,...r?{playing:r.durationMs===void 0?{ref:r.ref,text:r.text,playedMs:r.playedMs}:r}:{},unplayed:(t?.dropped??[]).flatMap(e=>e.ref?[{ref:e.ref,text:e.text}]:[]),mutedMessages:n,turnRunning:io(this.lastStatus)}),this.spoken=[]}onEvent(e){if(e.type===`reset`)return this.reset();if(e.sessionID===this.sessionID){if(e.type===`status`&&typeof e.state==`string`)return this.onStatus([{id:this.sessionID,state:e.state}]);if(e.type===`heard`){typeof e.inboxID==`string`&&this.rec?.event(`heard`,{inboxID:e.inboxID});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.take(e);if(!t)return;if(this.rec){this.rec.event(`say.received`,{messageID:String(e.messageID??``),ordinal:typeof e.ordinal==`number`?e.ordinal:0,chars:String(e.text??``).length,sentences:t.muted?this.says.split(String(e.text??``)).length:t.items.length,muted:t.muted});for(let e of t.items)this.rec.event(`tts.sentence.queued`,{ref:e.ref,text:e.text})}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.items)}else e.type===`conversation`&&e.on&&this.active?typeof e.front==`boolean`&&this.setFront(e.front):e.type===`conversation`&&!e.on&&this.active&&(this.ui.note(`Voice mode was turned off.`),this.stop({post:!1}))}}reset(){this.active&&(this.queue?.clear(),this.cuePlayer.stop(),this.cueClock.poke(),this.refresh())}setFront(e){let t=this.frontWanted&&!e,n=e!==this.front||t!==this.frontFallback;this.front=e,this.frontFallback=t,this.scheduler.phrases=!e,n&&(this.ui.front?.({on:e,fallback:t}),t&&this.ui.note(rx),!e&&this.active&&this.prefetchCues(),this.cueClock.poke())}onStatus(e){let t=Date.now(),{started:n,finished:r}=ro(this.lastStatus,e,this.sessionID);if(this.lastStatus=e,this.scheduler.working(io(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.rec?.event(`control`,{action:`cues`,on:e}),this.scheduler.enabled=e,e?this.active&&this.prefetchCues():this.cuePlayer.stop(),this.cueClock.poke()}setBackground(e){this.opts.background=e,this.active&&(this.rec?.event(`control`,{action:`background`,on:e}),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.rec?.event(`control`,{action:`pause`}),this.cueClock.stop(),this.hushReplies(`pause`),this.cuePlayer.stop(),this.endpointer?.reset(),this.vad?.reset(),this.turnAudio.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.rec?.event(`control`,{action:`resume`}),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];if(t)try{this.rec?.micTrack?.({...t.getSettings?.()??{}},t.label)}catch{}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<ex)&&(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&&(this.rec?.event(`mic`,t?{live:e,reason:t}:{live:e}),e?(clearTimeout(this.recoverTimer),this.recoverTimer=void 0,this.recoverAttempt=0,this.cuePlayer.earcon(`resumed`),this.cueClock.poke()):(this.vad?.reset(),this.turnAudio.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()},Wb(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,Qb))])}async reacquire(){let e;try{e=await navigator.mediaDevices.getUserMedia(ny(this.opts.deviceId))}catch(e){if(!this.active)return;mb({error:e.name,micPermission:await nx(),activated:tx()})&&this.ui.note(Xb,`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([ty(new Float32Array(16e3*Yb),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.rec?.event(`control`,{action:`hush`}),this.hushReplies(`hush`),this.cuePlayer.stop()}async synth(e,t,n){let r=this.rec?.speakHeaders(n);n&&this.rec?.event(`tts.request`,{ref:n});let i=Ab(await this.transport.speak(e,{signal:t,...r&&Object.keys(r).length?{headers:r}:{}})??null,t);return i.firstByte.then(()=>{this.markTurn(`firstByte`),n&&this.rec?.event(`tts.first.byte`,{ref:n})},()=>{}),i.whole().then(async e=>Vb(e,await(this.voiceKey??=this.cueKey()))).catch(()=>{}),i}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}this.reachedEnd=!1;let i=new Promise(e=>{t.onended=()=>{this.reachedEnd=!0,e()},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.playingRef&&this.rec?.event(`tts.sentence.played`,{ref:this.playingRef}),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 jb(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))return;try{performance.mark(ix[e])}catch{}let t=e===`firstAudio`?_y(this.turns.last):void 0;t&&this.ui.timing?.(t);let n=this.turns.last;if(e===`firstAudio`&&n?.firstAudio!==void 0&&this.rec){let e=e=>n[e]===void 0?{}:{[e]:Math.round(n[e]*10)/10};this.rec.event(`turn.timing`,{...e(`speechEnd`),...e(`transcript`),...e(`accepted`),...e(`firstSay`),...e(`firstByte`),firstAudio:Math.round(n.firstAudio*10)/10})}}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<Kb?`sent`:`listening`:`suspended`;e!==this.state&&(this.state=e,this.ui.state(e),this.rec?.event(`state`,{state:e}))}async lockScreen(){if(`wakeLock`in navigator&&document.visibilityState===`visible`&&(!this.wakeLock||this.wakeLock.released))try{this.wakeLock=await navigator.wakeLock.request(`screen`),this.rec?.wakeLock?.(!0)}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++,this.unfollow();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.hushReplies(`stop`),this.endpointer?.reset(),this.vad?.reset(),this.turnAudio.reset(),(this.front||this.frontFallback)&&this.ui.front?.({on:!1,fallback:!1}),this.front=this.frontWanted=this.frontFallback=!1,this.scheduler.phrases=!0,this.smartModel=void 0,this.smartError=void 0,this.warnedSmart=!1;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&&this.rec?.wakeLock?.(!1),this.wakeLock?.release().catch(()=>{}),this.wakeLock=void 0,this.ring?.reset(),this.ui.level(0),this.ui.held?.(``),this.ui.turn?.(``),clearTimeout(this.ignoredTimer),this.ui.ignored?.(``),this.ui.state(`off`),this.ui.ended(),this.rec&&(this.rec.event(`state`,{state:`off`}),this.rec.stop({keepalive:t,reason:e?`stopped`:`conversation_off`})),e&&n&&await this.transport.conversation(!1,t?{keepalive:t}:void 0).catch(()=>{})}};function fx({api:e,sessionID:t,events:n}){let r=`/api/sessions/${encodeURIComponent(t)}`;return{async conversation(t,n){let i=n?.front===void 0?{on:t}:{on:t,front:n.front},a=await e(`${r}/conversation`,{method:`POST`,json:i,...n?.keepalive===void 0?{}:{keepalive:n.keepalive}});return t?a.json():{on:t}},async utterance(t){return(await e(`${r}/utterance`,{method:`POST`,json:{text:t}})).json()},async interrupt(){await e(`${r}/interrupt`,{method:`POST`,json:{}})},async transcribe(t,n){let r=await e(`/api/transcribe`,{method:`POST`,body:t,headers:{"content-type":t.type||`audio/wav`,...n?.headers},...n?.signal?{signal:n.signal}:{}}),{text:i}=await r.json();return{text:i??``,headers:r.headers}},async speak(t,n){let r=n?.headers;return(await e(`/api/speak`,{method:`POST`,json:{text:t},...n?.signal?{signal:n.signal}:{},...r&&Object.keys(r).length?{headers:{...r}}:{}})).body},events:n??(()=>()=>{})}}async function px(e){try{let{tts:t}=await(await e(`/api/settings/speech`)).json();return t?.voice?[t.provider,t.model,t.voice,t.speed??``,t.baseURL??``].join(`|`):void 0}catch{return}}function mx(e,t){return n=>e.subscribe(e=>`sessionID`in e&&e.sessionID===t&&n(e))}var hx=class extends dx{constructor({sessionID:e,api:t,events:n,player:r,ui:i,options:a={}}){super({sessionID:e,transport:fx({api:t,sessionID:e,...n?{events:n}:{}}),player:r,ui:i,options:{speakable:zn,voiceKey:()=>px(t),workletURL:`/vad-worklet.js`,...a}})}},[gx,_x]=u(Date.now());setInterval(()=>Cu()&&_x(Date.now()),1e3);var[vx,yx]=u(!1),bx=e=>yx(e),xx=()=>Us(lu(),Cu(),Math.max(gx(),Date.now())),Sx=(e,t)=>lu().find(t=>t.id===e)?.options.find(e=>e.id===t)?.label??t;async function Cx(e,t,n){let r=Sx(e,t);try{let{decision:i}=await(await H(`/api/decisions/${q(e)}/answer`,{method:`POST`,json:{option:t,...n?{via:n}:{}}})).json().catch(()=>({}));i?Ad(i):jd(e),J(`Answered “${r}”${n?` by ${n}`:``}`)}catch(t){throw t instanceof G&&t.status===409&&t.code===`gone`?(jd(e),new G(409,`Already answered or expired`)):t}}function wx(e){return nc(H,{sessionID:e,current:()=>gu()?.sessionID,armed:()=>xx(),present:()=>vx()&&document.visibilityState===`visible`,answer:async(e,t)=>{try{await Cx(e,t,`voice`),Jl(`decision.voice`,{decisionID:e,option:t,outcome:`answered`})}catch(n){let r=n instanceof G&&n.status===403;throw Jl(`decision.voice`,{decisionID:e,option:t,outcome:r?`refused`:`failed`}),Object.assign(Error(r?`Not answered by voice: ${n.message}. Tap an option on the card.`:`Not answered: ${n instanceof Error?n.message:String(n)}`),{status:409})}}})}var Tx=new P_,Ex=new i_({async expose(e){let t=()=>Lu(e)?.session.exposed!==!1;if(t())return!0;if(!await Ud(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 hx({sessionID:e,api:wx(e),events:mx(Tx,e),player:cb,ui:t,options:{cues:Xy.cues,background:Xy.background,speed:()=>Xy.speed,sensitivity:()=>Xy.sensitivity,turnDetection:()=>Xy.turnDetection,smartTurnParams:()=>Xy.smartTurn,front:()=>Xy.front,title:()=>Lu(e)?.session.title||`OpenCode session`,status:Lu(e)?.session.status,deviceId:lb()||void 0,recorder:new Yl}}),stopPlayback:()=>{cb.paused||cb.pause()},notify:(e,t)=>J(e,t===`err`?`err`:``)}),[Dx,Ox]=u(0);Ex.subscribe(()=>Ox(e=>e+1)),N_({mode:Xy.turnDetection,load:h_});var kx=`voice-mode`,Ax=Promise.resolve(),jx=e=>{Ax=Ax.then(async()=>{let t=`serviceWorker`in navigator?await navigator.serviceWorker.getRegistration(`/`):void 0;t&&await e(t)}).catch(()=>{})},Mx={allowed:()=>`Notification`in window&&Notification.permission===`granted`&&`serviceWorker`in navigator,show:e=>jx(t=>t.showNotification(e.title,{body:e.body,tag:kx,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:()=>jx(async e=>(await e.getNotifications({tag:kx})).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{}}},Nx=new u_(Ex,Mx,{title:e=>Lu(e)?.session.title||`OpenCode session`,suffix:()=>Il(Pl.get())});Pl.subscribe(()=>Nx.refresh()),hp(e=>{e?.type===`voice-end`&&typeof e.sessionID==`string`&&Nx.endFromNotification(e.sessionID)});function Px(){return Dx(),Nx.needsPermission()}async function Fx(){try{await cp()}catch(e){J(e instanceof Error?e.message:String(e),`err`)}Nx.refresh(),Ox(e=>e+1)}function Ix(){return Dx(),Ex.state}var Lx=()=>{let e=Ix().sessionID;return e?Lu(e)?.session.title||`Session`:``};Fu(e=>{e.type===`say`||e.type===`heard`||e.type===`conversation`?Tx.emit(e):e.type===`status`&&typeof e.sessionID==`string`&&Array.isArray(e.sessions)&&Ex.onStatus(e.sessionID,e.sessions)}),window.addEventListener(`pagehide`,()=>{Ex.stop({keepalive:!0}),Mx.close()});var Rx=new ev,zx=new n_({record:e=>fb(e),deliver:(e,t)=>void Rx.append(e,t),notify:(e,t)=>J(e,t),hold:()=>Ex.hold()}),[Bx,Vx]=u(0);zx.subscribe(()=>Vx(e=>e+1));function Hx(e){return Bx(),zx.forSession(e)}var Ux=I(`<div class=banner><span></span><a class="btn small"href=/settings/machines>Review`),Wx=I(`<div class=banner><span><strong>Set up speech</strong> · </span><a class="btn small"href=/settings/voice#speech>Set up`),Gx=I(`<section class=decisions aria-label=Decisions><h2 class=section-title>`),Kx=I(`<select aria-label=Server><option value>All servers`),qx=I(`<select class=chip-window aria-label="Touched within">`),Jx=I(`<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`),Yx=I(`<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.`),Xx=I(`<ul class=home-list>`),Zx=I(`<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><button type=button class=chip data-chip=touched title="Sessions you prompted, spoke to, answered or opened">Touched by me</button></div><p class="count muted"role=status>`),Qx=I(`<option>`),$x=I(`<button type=button class=chip>`),eS=I(`<p class="muted small offline-line"><strong></strong> · offline · seen `),tS=I(`<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">`),nS=I(`<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>`),rS=I(`<th><button type=button class=th-btn><span class=sort-mark aria-hidden=true>`),iS=I(`<tr><td colspan=11 class="muted empty-cell">No sessions match.`),aS=I(`<span class=jobs-badge>`),oS=I(`<a>`),sS=I(`<span class=unread-dot role=img aria-label=Unread>`),cS=I(`<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-busy></td><td class=col-touched></td><td class=col-activity></td><td></td><td class=col-actions>`),lS=I(`<span class=row-sub data-row-sub>`),uS=I(`<span class=waiting-since>`),dS=I(`<a class=home-item-link><span class=home-item-text><span class=home-item-title></span><span>`),fS=I(`<li>`),pS=I(`<span class=home-item-link>`),mS=I(`<span class="home-item-sub muted"data-row-sub>`),hS=`hub.table`;function gS(e){tu();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=Ql.has(e.id)?Ql.feed(e.id):void 0,r=n?.pulse(),i=e.jobs?` · ${Yi(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: ${Yi(e.jobs)}`:`Working`}var _S=[[`status`,`Status`],[`title`,`Title`],[`project`,`Project`],[`server`,`Server`],[`source`,`Open in`],[`busy`,`24 h`],[`touched`,`Last touched`],[`activity`,`Last activity`]],vS={busy:`Activity in the last 24 h (sort: most active). Upper bars: the agent; lower marks: you`,touched:`When you last prompted, spoke to, answered or opened the session`},yS={"1h":`1 h`,"24h":`24 h`,"7d":`7 days`},bS=[[`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}]],xS={touched:`24h`};function SS(){let[e,t]=u(Aa(localStorage.getItem(hS))),[i,a]=u(``),o=e=>{t(e),localStorage.setItem(hS,ja(e))},c=C(()=>Oa(Iu(),{...e(),query:i()},N())),[d,f]=u(new Set),p=C(()=>c().filter(e=>d().has(e.id))),h=(e,t)=>{let n=new Set(d());t?n.add(e):n.delete(e),f(n)},g=e=>f(e?new Set(c().map(e=>e.id)):new Set),_=()=>{Wh(p(),!e().filters.archived),f(new Set)},[v,x]=u(!1),S=()=>X.machines??[],w=t=>Object.keys(t).every(n=>e().filters[n]===t[n]),T=t=>{let n=e().filters,r=Object.fromEntries(Object.keys(t).map(e=>[e,va.filters[e]]));o({...e(),filters:w(t)?{...n,...r}:{...n,...t}})},E=t=>{let n=e().sort;o({...e(),sort:{key:t,dir:n.key===t?n.dir===`asc`?`desc`:`asc`:t===`activity`||t===`touched`||t===`busy`?`desc`:`asc`}})},D=()=>mo(au()??void 0,Z()?.publicURL);return(()=>{var t=Zx(),u=t.firstChild,f=u.firstChild.nextSibling,C=f.firstChild,O=u.nextSibling,k=O.firstChild,A=k.firstChild,j=k.nextSibling,M=O.nextSibling,ee=M.firstChild,P=M.nextSibling;return y(f,n(L,{name:`plus`}),C),y(t,n(l,{get when(){return su().length},get children(){var e=Ux(),t=e.firstChild;return y(t,(()=>{var e=r(()=>su().length===1);return()=>e()?`${su()[0].machineName} wants to connect.`:`${su().length} machines want to connect.`})()),e}}),O),y(t,n(l,{get when(){return D()},get children(){var e=Wx(),t=e.firstChild;return t.firstChild.nextSibling,y(t,()=>D().reason,null),e}}),O),y(t,n(l,{get when(){return lu().length},get children(){var e=Gx(),t=e.firstChild;return y(t,(()=>{var e=r(()=>lu().length===1);return()=>e()?`A decision waits for you`:`${lu().length} decisions wait for you`})()),y(e,n(Jg,{get decisions(){return lu()},showSession:!0}),null),e}}),O),y(k,n(L,{name:`search`}),A),A.$$input=e=>a(e.currentTarget.value),j.$$click=()=>x(!0),y(O,n(l,{get when(){return S().length>1},get children(){var t=Kx();return t.firstChild,t.addEventListener(`change`,t=>o({...e(),filters:{...e().filters,machine:t.currentTarget.value}})),y(t,n(m,{get each(){return S()},children:e=>(()=>{var t=Qx();return y(t,()=>e.name),s(()=>t.value=e.id),t})()}),null),s(()=>t.value=e().filters.machine),t}}),null),ee.$$click=()=>o({...e(),filters:{...e().filters,touched:e().filters.touched?``:xS.touched}}),y(M,n(l,{get when(){return e().filters.touched},get children(){var t=qx();return t.addEventListener(`change`,t=>o({...e(),filters:{...e().filters,touched:t.currentTarget.value}})),y(t,n(m,{each:ga,children:e=>(()=>{var t=Qx();return t.value=e,y(t,()=>`within ${yS[e]}`),t})()})),s(()=>t.value=e().filters.touched),t}}),null),y(M,n(m,{each:bS,children:([e,t,n])=>(()=>{var r=$x();return r.$$click=()=>T(n),b(r,`data-chip`,e),y(r,t),s(()=>b(r,`aria-pressed`,w(n))),r})()}),null),y(t,n(l,{get when(){return p().length},get children(){var t=Jx(),n=t.firstChild,r=n.firstChild,i=n.nextSibling,a=i.nextSibling;return y(n,()=>p().length,r),i.$$click=_,y(i,()=>e().filters.archived?`Unarchive`:`Archive`),a.$$click=()=>g(!1),t}}),P),y(P,(()=>{var t=r(()=>X.machines===void 0);return()=>t()?`Loading…`:La(c().length,Iu().filter(e=>!e.hidden).length,lu().length,e().filters.status===`needs`)})()),y(t,n(l,{get when(){return r(()=>!!X.machines)()&&X.machines.length===0},get children(){return Yx()}}),null),y(t,n(l,{get when(){return Q()},get fallback(){return n(TS,{get rows(){return c()},get table(){return e()},sortBy:E,get picked(){return d()},pick:h,pickAll:g})},get children(){var e=Xx();return y(e,n(m,{get each(){return c()},children:e=>n(ES,{row:e})})),e}}),null),y(t,n(m,{get each(){return S().filter(e=>!e.online)},children:e=>(()=>{var t=eS(),n=t.firstChild;return n.nextSibling,y(n,()=>e.name),y(t,()=>z(e.lastSeen,N()),null),t})()}),null),y(t,n(wS,{get open(){return v()},get rows(){return Iu()},onClose:()=>x(!1)}),null),s(()=>b(ee,`aria-pressed`,e().filters.touched!==``)),s(()=>A.value=i()),t})()}var CS=30;function wS(e){let[t,i]=u(String(CS)),a=C(()=>e.open?Fa(e.rows,Number(t()),N()):[]),o=()=>a().length,c=()=>{Wh(a(),!0),e.onClose()};return n(de,{get open(){return e.open},title:`Archive inactive sessions`,get onClose(){return e.onClose},get children(){var n=tS(),a=n.firstChild,l=a.firstChild.nextSibling,u=a.nextSibling,d=u.firstChild,f=d.nextSibling;f.nextSibling;var p=u.nextSibling.firstChild,m=p.nextSibling;return n.addEventListener(`submit`,e=>{e.preventDefault(),o()&&c()}),l.$$input=e=>i(e.currentTarget.value),y(u,(()=>{var e=r(()=>o()===1);return()=>e()?`1 session`:`${o()} sessions`})(),d),y(u,(()=>{var e=r(()=>Number(t())===1);return()=>e()?`1 day`:`${t()||`?`} days`})(),f),V(p,`click`,e.onClose,!0),y(m,(()=>{var e=r(()=>o()===1);return()=>e()?`Archive 1 session`:`Archive ${o()} sessions`})()),s(()=>m.disabled=!o()),s(()=>l.value=t()),n}})}function TS(e){let t=()=>e.rows.length>0&&e.rows.every(t=>e.picked.has(t.id)),i=t=>e.table.sort.key===t?e.table.sort.dir===`asc`?`ascending`:`descending`:`none`;return(()=>{var a=nS(),o=a.firstChild,c=o.firstChild,u=c.firstChild,d=u.firstChild,f=u.nextSibling,p=o.nextSibling;return d.addEventListener(`change`,t=>e.pickAll(t.currentTarget.checked)),y(c,n(m,{each:_S,children:([t,n])=>(()=>{var a=rS(),o=a.firstChild,c=o.firstChild;return k(a,`col-${t}`),o.$$click=()=>e.sortBy(t),y(o,n,c),y(c,(()=>{var n=r(()=>e.table.sort.key===t);return()=>n()?e.table.sort.dir===`asc`?`↑`:`↓`:``})()),s(e=>{var n=i(t),r=vS[t];return n!==e.e&&b(a,`aria-sort`,e.e=n),r!==e.t&&b(o,`title`,e.t=r),e},{e:void 0,t:void 0}),a})()}),f),y(p,n(m,{get each(){return e.rows},get fallback(){return iS()},children:t=>(()=>{var i=cS(),a=i.firstChild,o=a.firstChild,c=a.nextSibling,u=c.firstChild,d=c.nextSibling,f=d.nextSibling,p=f.nextSibling,m=p.firstChild,h=p.nextSibling,g=h.nextSibling,_=g.nextSibling,v=_.nextSibling,x=v.nextSibling,S=x.nextSibling;return i.$$click=e=>!e.target.closest(`button,a,select,input`)&&Bt(Dt(t.id)),o.addEventListener(`change`,n=>e.pick(t.id,n.currentTarget.checked)),y(c,n(A,{get state(){return t.state}}),u),y(u,()=>ue[t.state]),y(c,n(l,{get when(){return t.error},children:e=>n(ie,{get text(){return e()}})}),null),y(c,n(l,{get when(){return t.jobs},get children(){var e=aS();return y(e,()=>t.jobs),s(n=>{var r=Yi(t.jobs),i=Yi(t.jobs);return r!==n.e&&b(e,`title`,n.e=r),i!==n.t&&b(e,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),e}}),null),y(d,n(l,{get when(){return Ia(t,Ix())},get children(){return n(ne,{})}}),null),y(d,n($g,{get id(){return t.id},get title(){return t.title},place:`table`,get children(){var e=oS();return y(e,()=>t.title),s(()=>b(e,`href`,Dt(t.id))),e}}),null),y(d,n(e_,{get id(){return t.id}}),null),y(d,n(l,{get when(){return t.unread},get children(){return sS()}}),null),y(d,n(l,{get when(){return Ba(t)},children:e=>(()=>{var t=lS();return y(t,e),s(()=>b(t,`title`,e())),t})()}),null),y(f,()=>t.where),y(m,()=>t.machineName),y(h,()=>oe[t.source]),y(g,n(Jf,{get buckets(){return t.meter},get now(){return N()}})),y(_,(()=>{var e=r(()=>!!t.touchedKindAt);return()=>e()?pa(t.touchedKind,t.touchedKindAt,N()):``})()),y(v,()=>z(t.updated,N())),y(x,n(l,{get when(){return Va(t,N())},children:e=>(()=>{var t=uS();return y(t,e),s(()=>b(t,`title`,`Waiting for you for ${e()}`)),t})()}),null),y(x,()=>gS(t),null),y(S,n(O,{get label(){return`More actions for ${t.title}`},class:`icon-btn small`,items:()=>Gh(t,{place:`table`})})),s(e=>{var n=`${t.unread?`unread`:``}`,r=`Select ${t.title}`,a=t.directory,s=t.machineOnline?``:`muted`,c=t.touchedKindAt?fa(t.touchedKind,t.touchedKindAt,N()):`Not touched by you in 30 days`,l=`col-now ${t.error?`error`:`muted`}`,u=t.error;return n!==e.e&&k(i,e.e=n),r!==e.t&&b(o,`aria-label`,e.t=r),a!==e.a&&b(f,`title`,e.a=a),s!==e.o&&k(m,e.o=s),c!==e.i&&b(_,`title`,e.i=c),l!==e.n&&k(x,e.n=l),u!==e.s&&b(x,`title`,e.s=u),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),s(()=>o.checked=e.picked.has(t.id)),i})()})),s(()=>d.checked=t()),a})()}function ES(e){let t=()=>e.row;return(()=>{var e=fS();return y(e,n(l,{get when(){return!Uh(t().id,`phone`)},get fallback(){return(()=>{var e=pS();return y(e,n(A,{get state(){return t().state}}),null),y(e,n($g,{get id(){return t().id},get title(){return t().title},place:`phone`,children:null}),null),e})()},get children(){var e=dS(),r=e.firstChild,i=r.firstChild,a=i.nextSibling;return y(e,n(A,{get state(){return t().state}}),r),y(e,n(l,{get when(){return t().error},children:e=>n(ie,{get text(){return e()}})}),r),y(i,n(l,{get when(){return Ia(t(),Ix())},get children(){return n(ne,{})}}),null),y(i,()=>t().title,null),y(i,n(e_,{get id(){return t().id}}),null),y(i,n(l,{get when(){return t().unread},get children(){return sS()}}),null),y(r,n(l,{get when(){return Ba(t())},children:e=>(()=>{var t=mS();return y(t,e),t})()}),a),y(a,n(l,{get when(){return Va(t(),N())},children:e=>(()=>{var t=uS();return y(t,e),t})()}),null),y(a,()=>gS(t())||`${t().where} · ${t().machineName} · ${t().touchedKindAt?fa(t().touchedKind,t().touchedKindAt,N()):z(t().updated,N())}`,null),s(n=>{var r=Dt(t().id),i=`home-item-meta ${t().error?`error`:`muted`}`;return r!==n.e&&b(e,`href`,n.e=r),i!==n.t&&k(a,n.t=i),n},{e:void 0,t:void 0}),e}}),null),y(e,n(O,{get label(){return`More actions for ${t().title}`},class:`icon-btn small`,items:()=>Gh(t(),{place:`phone`})}),null),s(()=>k(e,`home-item${t().unread?` unread`:``}`)),e})()}B([`input`,`click`]);var DS=I(`<div role=separator aria-orientation=vertical tabindex=0>`);function OS(e){let t=0,n=0,r=0,i,a=()=>im()[e.panel],o=()=>am(e.panel),c=()=>{r=0,i!==void 0&&om(e.panel,i,!1)},l=()=>{r&&cancelAnimationFrame(r),r=0,i=void 0,tm(void 0),document.documentElement.classList.remove(`resizing`)},u=(t,n,r)=>{t.hasPointerCapture(n)&&t.releasePointerCapture(n),l(),om(e.panel,r)};return R(()=>e.panel===`rail`&&$p(!0)),M(()=>{e.panel===`rail`&&$p(!1),em()===e.panel&&l()}),(()=>{var l=DS();return l.$$keydown=t=>{let n=kp(e.panel,a(),t.key,t.shiftKey,o());n!==void 0&&(t.preventDefault(),om(e.panel,n))},l.$$dblclick=()=>om(e.panel,Cp[e.panel].default),l.addEventListener(`pointercancel`,t=>em()===e.panel&&u(t.currentTarget,t.pointerId,i??a())),l.$$pointerup=t=>em()===e.panel&&u(t.currentTarget,t.pointerId,i??a()),l.$$pointermove=a=>{if(em()!==e.panel)return;let s=Ap(e.panel,t,a.clientX-n,o());`collapse`in s?(u(a.currentTarget,a.pointerId,t),Gp(!0)):(i=s.width,r||=requestAnimationFrame(c))},l.$$pointerdown=r=>{r.button===0&&(r.preventDefault(),r.currentTarget.setPointerCapture(r.pointerId),t=a(),n=r.clientX,tm(e.panel),document.documentElement.classList.add(`resizing`))},s(t=>{var n=`panel-handle${em()===e.panel?` dragging`:``}`,r=e.panel,i=e.label,s=a(),c=o().min,u=o().max;return n!==t.e&&k(l,t.e=n),r!==t.t&&b(l,`data-panel`,t.t=r),i!==t.a&&b(l,`aria-label`,t.a=i),s!==t.o&&b(l,`aria-valuenow`,t.o=s),c!==t.i&&b(l,`aria-valuemin`,t.i=c),u!==t.n&&b(l,`aria-valuemax`,t.n=u),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),l})()}B([`pointerdown`,`pointermove`,`pointerup`,`dblclick`,`keydown`]);var kS={service:`background service`,standalone:`standalone`};function AS(e){return(e??[]).map(e=>{let t=!!e.online,n=e.processes.find(e=>e.kind===`service`)??e.processes[0],r=t?n?[kS[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 jS(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 MS(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=(t,n)=>t.directories.length?t.directories.includes(n):e.some(e=>e.kind===`folder`&&e.directories.includes(n));return r(t.key,t.dir)??(t=>{let n=t?e.find(e=>e.key===t.key):void 0;return n&&t&&i(n,t.dir)?{key:n.key,dir:t.dir}:void 0})(n)}function NS(e,t,n){let{chosen:r,linked:i,remembered:a}=n;if(t===void 0)return;if(r&&r.machine===t)return e.some(e=>e.key===r.key)?{key:r.key,dir:r.dir}:void 0;let o=e.length===1&&e[0].directories.length<=1?{key:e[0].key,dir:e[0].directories[0]??``}:void 0;return n.switched?o:MS(e,i?.machine===t?{key:i.key,dir:i.dir}:{},a?.machine===t?a:void 0)??o}function PS(e,t){let n=Gr(t).split(/\s+/).filter(Boolean);return n.length?e.filter(e=>{let t=[e.label,...e.directories].map(Gr);return n.every(e=>t.some(t=>t.includes(e)))}):[...e]}var FS=`hub.newSession`;function IS(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 LS(e,t){try{e.setItem(FS,JSON.stringify({machine:t.machine,key:t.key,dir:t.dir}))}catch{}}var RS=`hub.railCollapsed`;function zS(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 BS(e,t){let n=zS(e);n.has(t)?n.delete(t):n.add(t);try{e.setItem(RS,JSON.stringify([...n]))}catch{}return n}var VS=0,HS=e=>e.reduce((e,t)=>e+t.data.length,0);async function US(e,t){let n=U_(t.length,e.type);if(n)throw Error(n);let r=await WS(e);try{let n=e.type!==`image/jpeg`&&KS(r),{blob:i,request:a}=await q_({width:r.width,height:r.height,keepPng:n},W_(HS(t)),e=>qS(r,e)),o=await JS(i);return{id:`img${++VS}`,mime:a.type,data:o.slice(o.indexOf(`,`)+1),name:K_(e.name||`image`,a.type),preview:URL.createObjectURL(i)}}finally{`close`in r&&r.close()}}async function WS(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 GS(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 KS(e){let t=Math.max(1,Math.min(64,e.width)),n=Math.max(1,Math.min(64,e.height)),[,r]=GS(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 qS(e,t){let[n,r]=GS(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 JS(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 YS(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 XS=new Map;function ZS(e,t){XS.set(e,t)}function QS(e){let t=XS.get(e);return XS.delete(e),t}var $S=I(`<li class="attachment busy"aria-label="Preparing image"><span class="spinner small">`),eC=I(`<ul class=attachments aria-label="Attached images">`),tC=I(`<span class="spinner small">`),nC=I(`<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">`),rC=I(`<span class="meta-chip readonly"title="Branch of this folder"><span class="chip-text mono">`),iC=I(`<label class="meta-chip toggle-chip"><input type=checkbox><span class=chip-text>Open in Herdr tab`),aC=I(`<div class=env-meta role=group aria-label="Where the session runs">`),oC=I(`<p data-new-dir>`),sC=I(`<p class="small new-need-project"role=alert data-need-project>Choose a project first: the session starts in one of <!>'s folders.`),cC=I('<p class="small warn"> has no background service connected; start `opencode serve --service` there to create sessions.'),lC=I(`<p class=error role=alert>`),uC=I(`<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?`),dC=I(`<p class=muted>No machine is connected to this hub yet.`),fC=I(`<li class=attachment><img><button type=button class=attachment-remove>`),pC=I(`<span aria-hidden=true>`),mC=I(`<span class=chip-text>`),hC=I(`<button type=button aria-haspopup=dialog aria-label="Choose project folder"><span class=chip-text>`),gC=I(`<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>`),_C=I(`<p class="muted small pad">No folder matches.`),vC=I(`<div class=menu-section> · Herdr`),yC=I(`<button type=button role=option class=menu-item><span class=menu-check></span><span class=menu-label></span><span class="menu-hint mono">`);function bC(e){let i=IS(localStorage),a=()=>X.machines??[],o=C(()=>AS(a())),[c,f]=u(),p=()=>{let t=c();return t&&o().some(e=>e.id===t&&e.online)?t:jS(o(),e.machine,i?.machine)},h=()=>o().find(e=>e.id===p()),g=()=>a().find(e=>e.id===p()),_=C(()=>{let t=g();if(!t)return[];let n=ki(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:j(e.dir),directories:[e.dir]}),n}),[v,x]=u(),[S,w]=u(!1),T=()=>NS(_(),p(),{...v()?{chosen:v()}:{},switched:S(),linked:{machine:e.machine,key:e.key,dir:e.dir},...i?{remembered:i}:{}}),E=()=>_().find(e=>e.key===T()?.key),D=e=>e.directories.length?e.directories:_().filter(e=>e.kind===`folder`).flatMap(e=>e.directories),A=()=>{let e=T(),t=E();return!e||!t?``:e.dir&&D(t).includes(e.dir)?e.dir:D(t)[0]??``},M=(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],[N]=d(()=>{let e=M(g(),A());return e?e.id:void 0},async e=>(await K(`${U(e)}/summary`).catch(()=>({}))).branch),[ee,P]=u(!0),te=()=>!!h()?.herdr&&E()?.kind===`herdr`&&ee(),[I,ne]=u(``),[re,ie]=u([]),[ae,oe]=u(!1),[se,ce]=u(``),[le,ue]=u(!1),de=Promise.resolve(),z=e=>{de=de.then(async()=>{oe(!0);try{for(let t of e)try{let e=await US(t,re());ie(t=>[...t,e])}catch(e){ce(W(e))}}finally{oe(!1)}})},fe=()=>!le()&&!ae()&&!!h()?.canCreate&&!!A()&&(!!I().trim()||re().length>0),[pe,B]=u(!1),V,me=async()=>{let e=h(),t=E(),n=A();if(!n&&e&&!le()&&(I().trim()||re().length>0))B(!0),V?.focus();else if(fe()&&e&&t){ue(!0),ce(``);try{let r=Ai({target:t,directory:n,openInHerdr:te()}),i=await(await H(`/api/machines/${q(e.id)}/sessions`,{method:`POST`,json:r})).json();LS(localStorage,{machine:e.id,key:t.key,dir:n}),ZS(i.sessionID,{text:I().trim(),images:re()}),Bt(Dt(i.sessionID),{replace:!0}),i.warning?J(`Session created, but Herdr didn't open it: ${i.warning}`,`warn`):i.openedIn===`herdr`&&J(`Opened in Herdr · ${t.label}`)}catch(t){ce(t instanceof G&&t.status===409?`The background service on ${e.name} isn't connected. Start it, then try again.`:`Could not create the session: ${W(t)}`),ue(!1)}}},he=()=>[{section:`Choose environment`},...o().map(e=>({label:e.name,hint:e.online?e.canCreate?e.detail:`${e.detail} · no background service`:`offline`,checked:e.id===p(),disabled:e.disabled,run:()=>{e.id!==p()&&(w(!0),x(void 0),f(e.id))}}))],ge,_e;R(()=>ge?.focus());let ve=()=>{ge.style.height=`auto`,ge.style.height=`${Math.min(ge.scrollHeight,320)}px`};return(()=>{var e=uC(),i=e.firstChild,a=i.firstChild,c=i.nextSibling;return c.firstChild,y(i,n(l,{get when(){return Q()},get children(){return n(F,{icon:`menu`,label:`Open sidebar`,onClick:qp})}}),a),y(c,n(l,{get when(){return o().length},get fallback(){return dC()},get children(){return[(()=>{var e=nC(),r=e.firstChild,i=r.firstChild,a=i.nextSibling,o=a.nextSibling.firstChild,c=o.nextSibling.nextSibling;e.addEventListener(`drop`,e=>{let t=YS(e.dataTransfer);t.length&&(e.preventDefault(),z(t))}),e.addEventListener(`dragover`,e=>[...e.dataTransfer?.types??[]].includes(`Files`)&&e.preventDefault()),e.addEventListener(`submit`,e=>{e.preventDefault(),me()}),y(r,n(l,{get when(){return re().length||ae()},get children(){var e=eC();return y(e,n(m,{get each(){return re()},children:e=>(()=>{var t=fC(),r=t.firstChild,i=r.nextSibling;return i.$$click=()=>ie(t=>t.filter(t=>t.id!==e.id)),y(i,n(L,{name:`close`})),s(t=>{var n=e.preview,a=e.name,o=e.name,s=`Remove ${e.name}`;return n!==t.e&&b(r,`src`,t.e=n),a!==t.t&&b(r,`alt`,t.t=a),o!==t.a&&b(r,`title`,t.a=o),s!==t.o&&b(i,`aria-label`,t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),null),y(e,n(l,{get when(){return ae()},get children(){return $S()}}),null),e}}),i),i.$$keydown=e=>{e.key===`Enter`&&!e.shiftKey&&!e.isComposing&&!(matchMedia(`(max-width: 760px)`).matches&&`ontouchstart`in window)&&(e.preventDefault(),me())},i.addEventListener(`paste`,e=>{let t=YS(e.clipboardData);t.length&&(e.preventDefault(),z(t))}),i.$$input=e=>{ne(e.currentTarget.value),ve()};var u=ge;typeof u==`function`?t(u,i):ge=i,a.addEventListener(`change`,e=>{let t=[...e.currentTarget.files??[]];e.currentTarget.value=``,t.length&&z(t)});var d=_e;return typeof d==`function`?t(d,a):_e=a,o.$$click=()=>_e.click(),y(o,n(L,{name:`plus`})),y(c,n(l,{get when(){return le()},get fallback(){return n(L,{name:`send`})},get children(){return tC()}})),s(e=>{var t=I_.join(`,`),n=re().length>=L_.maxImages||ae(),r=fe()||A()?`Start session`:`Choose a project first`,i=!fe(),s=!fe();return t!==e.e&&b(a,`accept`,e.e=t),n!==e.t&&(o.disabled=e.t=n),r!==e.a&&b(c,`title`,e.a=r),i!==e.o&&(c.disabled=e.o=i),s!==e.i&&b(c,`aria-disabled`,e.i=s),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),s(()=>i.value=I()),e})(),(()=>{var e=aC();return y(e,n(O,{label:`Choose environment`,class:`meta-chip env-chip`,align:`left`,items:he,get text(){return[n(L,{name:`cloud`}),(()=>{var e=pC();return s(()=>k(e,`online-dot${h()?.online?` on`:``}`)),e})(),(()=>{var e=mC();return y(e,()=>h()?.name??`No environment`),e})(),n(L,{name:`down`,class:`chip-caret`})]}}),null),y(e,n(xC,{get targets(){return _()},get current(){return T()},get dir(){return A()},get disabled(){return!h()},get asked(){return r(()=>!!pe())()&&!A()},buttonRef:e=>V=e,foldersOf:D,onPick:(e,t)=>x({machine:p(),key:e,dir:t})}),null),y(e,n(l,{get when(){return r(()=>!!A())()&&N()},get children(){var e=rC(),t=e.firstChild;return y(e,n(L,{name:`branch`}),t),y(t,N),e}}),null),y(e,n(l,{get when(){return r(()=>!!h()?.herdr)()&&E()?.kind===`herdr`},get children(){var e=iC(),t=e.firstChild;return t.addEventListener(`change`,e=>P(e.currentTarget.checked)),s(()=>b(e,`title`,`Open the new session in a new tab of the Herdr workspace ${E().label}`)),s(()=>t.checked=ee()),e}}),null),e})(),(()=>{var e=oC();return y(e,(()=>{var e=r(()=>!!A());return()=>e()?A():r(()=>!!h())()?`Choose one of ${h().name}'s projects`:``})()),s(t=>{var n=`small muted new-dir${A()?` mono`:``}`,r=A()||void 0;return n!==t.e&&k(e,t.e=n),r!==t.t&&b(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e})(),n(l,{get when(){return r(()=>!(!pe()||A()))()&&h()},get children(){var e=sC(),t=e.firstChild.nextSibling;return t.nextSibling,y(e,()=>h().name,t),e}}),n(l,{get when(){return r(()=>!!h())()&&!h().canCreate},get children(){var e=cC(),t=e.firstChild;return y(e,()=>h().name,t),e}}),n(l,{get when(){return se()},get children(){var e=lC();return y(e,se),e}})]}}),null),e})()}function xC(e){let[i,o]=u(!1),[c,d]=u(``),[f,p]=u({top:0,left:0}),h,g,_,v=()=>PS(e.targets,c()),x=()=>e.targets.some(t=>t.key===e.current?.key),S=()=>{let t=e.targets.find(t=>t.key===e.current?.key);return t?t.kind===`herdr`&&e.dir?`${t.label} · ${j(e.dir)}`:t.label:e.targets.length?`Choose a project`:`No folder`},C=()=>{let e=h.getBoundingClientRect();p({top:e.bottom+4,left:e.left}),d(``),o(!i()),i()&&queueMicrotask(()=>_?.focus())},w=e=>{i()&&!h.contains(e.target)&&!g?.contains(e.target)&&o(!1)},T=e=>{i()&&e.key===`Escape`&&!ee(g)&&(o(!1),h.focus())};R(()=>{document.addEventListener(`mousedown`,w),document.addEventListener(`keydown`,T)}),M(()=>{document.removeEventListener(`mousedown`,w),document.removeEventListener(`keydown`,T)});let E=(t,n)=>{e.onPick(t,n),o(!1)};return[(()=>{var r=hC(),a=r.firstChild;return r.$$click=C,t(t=>{h=t,e.buttonRef?.(t)},r),y(r,n(L,{name:`folder`}),a),y(a,S),y(r,n(L,{name:`down`,class:`chip-caret`}),null),s(t=>{var n=`meta-chip folder-chip${x()?``:` unset`}${e.asked?` asked`:``}`,a=i(),o=e.dir||`Choose a folder`,s=e.disabled;return n!==t.e&&k(r,t.e=n),a!==t.t&&b(r,`aria-expanded`,t.t=a),o!==t.a&&b(r,`title`,t.a=o),s!==t.o&&(r.disabled=t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),r})(),n(l,{get when(){return i()},get children(){return n(fe,{get children(){var i=gC(),o=i.firstChild,u=o.nextSibling,p=g;typeof p==`function`?t(p,i):g=i,o.$$keydown=t=>{let n=v()[0];t.key===`Enter`&&n&&(t.preventDefault(),E(n.key,e.foldersOf(n)[0]??``))},o.$$input=e=>d(e.currentTarget.value);var h=_;return typeof h==`function`?t(h,o):_=o,y(u,n(l,{get when(){return v().length},get fallback(){return _C()},get children(){return n(m,{get each(){return v()},children:t=>n(l,{get when(){return r(()=>t.kind===`herdr`)()&&e.foldersOf(t).length>1},get fallback(){return(()=>{var n=yC(),i=n.firstChild,a=i.nextSibling,o=a.nextSibling;return n.$$click=()=>E(t.key,e.foldersOf(t)[0]??``),y(i,()=>e.current?.key===t.key?`✓`:``),y(a,()=>t.label),y(o,(()=>{var n=r(()=>t.kind===`herdr`);return()=>n()?`Herdr`:e.foldersOf(t)[0]??``})()),s(r=>{var i=e.current?.key===t.key,a=e.foldersOf(t)[0];return i!==r.e&&b(n,`aria-selected`,r.e=i),a!==r.t&&b(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()},get children(){return[(()=>{var e=vC(),n=e.firstChild;return y(e,()=>t.label,n),e})(),n(m,{get each(){return e.foldersOf(t)},children:n=>(()=>{var r=yC(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling;return r.$$click=()=>E(t.key,n),b(r,`title`,n),y(i,()=>e.current?.key===t.key&&e.dir===n?`✓`:``),y(a,()=>j(n)),y(o,n),s(()=>b(r,`aria-selected`,e.current?.key===t.key&&e.dir===n)),r})()})]}})})}})),s(e=>{var t=`${f().top}px`,n=`${f().left}px`;return t!==e.e&&a(i,`top`,e.e=t),n!==e.t&&a(i,`left`,e.t=n),e},{e:void 0,t:void 0}),s(()=>o.value=c()),i}})}})]}B([`input`,`keydown`,`click`]);var SC={name:`home`},CC=ce(()=>C(()=>{let e=ut();return e.name===`concierge`?Q()?e:SC:SC=e})),wC=e=>String(e??``).normalize(`NFD`).replace(/[\u0300-\u036f]/g,``).toLowerCase();function TC(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 EC(e){let t=e?.note;return!Array.isArray(e)&&typeof t==`string`&&t.trim()?t.trim():void 0}var DC=e=>e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;function OC(e,t,{current:n=``,limit:r=200,grouped:i=!1}={}){let a=String(t??``).trim(),o=wC(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=wC(e.id),r=`${n} ${wC(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(DC(t.option.id))||e.set(DC(t.option.id),e.size);u.sort((t,n)=>e.get(DC(t.option.id))-e.get(DC(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 kC(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 AC=I(`<input type=search class=picker-search autofocus>`),jC=I(`<button type=button class="btn small">Retry`),MC=I(`<p class="muted small"role=status>`),NC=I(`<p class="muted small picker-note">`),PC=I(`<li><button type=button><span class=po-name>Use “<!>”</span><span class="po-id muted">as a custom `),FC=I(`<ul class=picker-list role=listbox>`),IC=I(`<div class="picker-group muted small">`),LC=I(`<span class="po-id muted">`),RC=I(`<span class=po-mark>✓ Current`),zC=I(`<li><button type=button><span class=po-name>`);function BC(t){let[i,a]=u(``),[o,c]=u(),[d,f]=u(``),[p,h]=u(``),[g,_]=u(0),v=()=>{let e=t.request;e&&(c(void 0),f(``),h(``),e.load().then(e=>{if(Array.isArray(e))return c(e);h(e.note??``),c(e.options)},e=>f(W(e))))};x(e(()=>t.request,e=>{e&&(a(``),_(0),v())}));let S=C(()=>OC(o()??[],i(),{current:t.request?.current,grouped:t.request?.grouped})),w=()=>[...S().items.map(e=>e.id),...S().custom?[S().custom]:[]],T=e=>{let n=t.request;t.onClose(),n?.onPick(e)},E=()=>t.request?.noun??`option`;return n(de,{get open(){return!!t.request},get title(){return t.request?.title??``},get onClose(){return t.onClose},class:`picker`,get children(){return[(()=>{var e=AC();return e.$$keydown=e=>{let t={ArrowDown:1,ArrowUp:-1};if(e.key in t)e.preventDefault(),_(kC(g(),t[e.key],w().length));else if(e.key===`Enter`){e.preventDefault();let t=w()[g()];t&&T(t)}},e.$$input=e=>{a(e.currentTarget.value),_(0)},s(t=>{var n=`Search or type a ${E()}`,r=`Search ${E()}s`;return n!==t.e&&b(e,`placeholder`,t.e=n),r!==t.t&&b(e,`aria-label`,t.t=r),t},{e:void 0,t:void 0}),s(()=>e.value=i()),e})(),(()=>{var e=MC();return y(e,(()=>{var e=r(()=>!!d());return()=>e()?`Couldn't load the ${E()} list: ${d()}. Type any ${E()}.`:r(()=>o()===void 0)()?`Loading ${E()}s…`:r(()=>!o().length)()?`No suggestions. Type any ${E()}.`:`${S().total} ${S().total===1?E():`${E()}s`}`})(),null),y(e,n(l,{get when(){return d()},get children(){return[` `,(()=>{var e=jC();return e.$$click=v,e})()]}}),null),e})(),n(l,{get when(){return p()},get children(){var e=NC();return y(e,p),e}}),(()=>{var e=FC();return y(e,n(m,{get each(){return S().items},children:(e,i)=>(()=>{var a=zC(),o=a.firstChild,c=o.firstChild;return y(a,n(l,{get when(){return r(()=>!!t.request?.grouped)()&&(i()===0||DC(S().items[i()-1].id)!==DC(e.id))},get children(){var t=IC();return y(t,()=>DC(e.id)||`Other`),t}}),o),o.$$click=()=>T(e.id),y(c,()=>e.id),y(o,n(l,{get when(){return e.name},get children(){var t=LC();return y(t,()=>e.name),t}}),null),y(o,n(l,{get when(){return e.current},get children(){return RC()}}),null),s(t=>{var n=`picker-opt${g()===i()?` active`:``}`,r=!!e.current;return n!==t.e&&k(o,t.e=n),r!==t.t&&b(o,`aria-selected`,t.t=r),t},{e:void 0,t:void 0}),a})()}),null),y(e,n(l,{get when(){return S().custom},get children(){var e=PC(),t=e.firstChild,n=t.firstChild,r=n.firstChild.nextSibling;r.nextSibling;var i=n.nextSibling;return i.firstChild,t.$$click=()=>T(S().custom),y(n,()=>S().custom,r),y(i,E,null),s(()=>k(t,`picker-opt${g()===S().items.length?` active`:``}`)),e}}),null),e})()]}})}B([`input`,`keydown`,`click`]);var VC=I(`<div class=chips role=group aria-label="Which speech settings"><button type=button class=chip>Yours</button><button type=button class=chip>Server default`),HC=I(`<div class="speech-panel stack">`),UC=I(`<p class=error>`),WC=I(`<p class=muted>Loading…`),GC=I(`<p class="small inherit">`),KC=I(`<p class="small muted">`),qC=I(`<p class=field-error>`),JC=I(`<div class=field><label>`),YC=I(`<input type=text autocomplete=off autocapitalize=off>`),XC=I(`<div class=row><button type=button class="btn small">Browse…`),ZC=I(`<input type=password autocomplete=new-password placeholder="Paste the new key"aria-label="New API key">`),QC=I(`<div class=row><button type=button class="btn small">Cancel`),$C=I(`<div class="field key-field"><span class=field-label>API key`),ew=I(`<p>`),tw=I(`<button type=button class="btn small">Undo`),nw=I(`<button type=button class="btn small danger">Clear`),rw=I(`<div class=row><button type=button class="btn small">`),iw=I(`<fieldset class="card speech-card"><legend>`),aw=I(`<div class="row reset-row"><span class="small muted grow"></span><button type=button class="btn small">Reset to server default`),ow=I(`<option>`),sw=I(`<select>`),cw=I(`<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.`),lw=I(`<button type=button class=btn>Preview voice`),uw=I(`<form class=stack novalidate><div class=row><button type=submit class="btn primary">Save</button></div><p role=status>`),dw=I(`<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.`),fw=[[`openrouter`,`OpenRouter`],[`openai-compatible`,`OpenAI-compatible`]],pw={settings:`from settings`,config:`from hub.json`,env:`from env`,user:`yours`},mw={user:`/api/settings/speech`,default:`/api/settings/speech/default`},hw={stt:`Speech-to-text`,tts:`Text-to-speech`};function gw(){let[e,t]=u(`user`),[r,i]=u(!1),[a,o]=u(),[c,d]=u(``),f=async t=>{o(void 0),d(``);try{let n=await K(mw[t]);t===`user`&&i(Xn(Z(),n).length>1),e()===t&&o(n)}catch(e){d(e instanceof G&&e.status===403?t==="default"?`Only admins can change the server default.`:`This account cannot change speech settings.`:e instanceof G&&e.status===404?`This hub does not support speech settings.`:`Could not load speech settings: ${W(e)}`)}};R(()=>void f(`user`));let p=n=>{n!==e()&&(t(n),f(n))};return(()=>{var t=HC();return y(t,n(l,{get when(){return r()},get children(){var t=VC(),n=t.firstChild,r=n.nextSibling;return n.$$click=()=>p(`user`),r.$$click=()=>p(`default`),s(t=>{var i=e()===`user`,a=e()==="default";return i!==t.e&&b(n,`aria-pressed`,t.e=i),a!==t.t&&b(r,`aria-pressed`,t.t=a),t},{e:void 0,t:void 0}),t}}),null),y(t,n(l,{get when(){return!c()},get fallback(){return(()=>{var e=UC();return y(e,c),e})()},get children(){return n(l,{get when(){return a()},get fallback(){return WC()},keyed:!0,children:t=>n(_w,{settings:t,get scope(){return e()},onSaved:e=>o(e)})})}}),null),t})()}function _w(e){let[t,a]=Ar(co(e.settings)),[o,c]=u({}),[d,f]=u({text:``,kind:``}),[p,h]=u(!1),[g,v]=u(),x=()=>e.scope===`user`?tr(e.settings):void 0,S=()=>e.scope===`user`?mo(e.settings.ready,Z()?.publicURL):void 0,C=()=>Object.keys(lo(e.settings,vr(t))).length>0,w={},T=e=>(w[e]??=K(`/api/settings/speech/models?kind=${e}`).then(e=>({options:TC(e),note:EC(e)})),w[e].catch(()=>delete w[e]),w[e]),E=(e,t,r,i,a)=>{let s=()=>x()?.[e]?.[t];return(()=>{var c=JC(),u=c.firstChild;return b(u,`for`,`sp-${e}-${t}`),y(u,r),y(c,i,null),y(c,n(l,{get when(){return s()?.inherited},get children(){var e=GC();return y(e,()=>s().note),e}}),null),y(c,n(l,{when:a,get children(){var e=KC();return y(e,a),e}}),null),y(c,n(l,{get when(){return o()[`${e}.${t}`]},get children(){var n=qC();return y(n,()=>o()[`${e}.${t}`]),n}}),null),c})()},D=(e,n,r={})=>(()=>{var s=YC();return b(s,`id`,`sp-${e}-${n}`),b(s,`spellcheck`,!1),i(s,_(r,{get value(){return t[e][n]},get"aria-invalid"(){return!!o()[`${e}.${n}`]},onInput:t=>a(e,n,t.currentTarget.value)}),!1,!1),s})(),O=(e,n,r,i,o)=>(()=>{var s=XC(),c=s.firstChild;return y(s,()=>D(e,n,{placeholder:`Choose or type a ${i}`}),c),c.$$click=()=>v({title:r,noun:i,current:t[e][n]??``,load:o,grouped:n===`model`,onPick:t=>a(e,n,t)}),s})(),A=i=>{let c=e.settings[i].apiKey??{set:!1,source:`none`},u=()=>x()?.[i].apiKey,d=()=>t[i].apiKey,f=()=>x()?!u()?.inherited&&c.set:c.set&&c.source===`settings`;return(()=>{var e=$C();return e.firstChild,y(e,n(l,{get when(){return d().action===`set`},get fallback(){return[(()=>{var e=ew();return y(e,(()=>{var e=r(()=>d().action===`clear`);return()=>e()?`Key will be removed when you save.`:r(()=>!!u()?.inherited)()?u().note:r(()=>!!c.set)()?`Key set${c.last4?` ••••${c.last4}`:``} (${pw[c.source]??c.source})`:`No key set`})()),s(()=>k(e,`key-summary${u()?.inherited&&d().action!==`clear`?` inherit`:``}`)),e})(),(()=>{var e=rw(),t=e.firstChild;return t.$$click=()=>a(i,`apiKey`,{action:`set`,value:``}),y(t,(()=>{var e=r(()=>!!u()?.inherited);return()=>e()?`Use your own key`:c.set?`Replace`:`Add key`})()),y(e,n(l,{get when(){return d().action===`clear`},get children(){var e=tw();return e.$$click=()=>a(i,`apiKey`,{action:`keep`,value:``}),e}}),null),y(e,n(l,{get when(){return r(()=>d().action!==`clear`)()&&f()},get children(){var e=nw();return e.$$click=()=>a(i,`apiKey`,{action:`clear`,value:``}),e}}),null),e})()]},get children(){return[(()=>{var e=ZC();return e.$$input=e=>a(i,`apiKey`,`value`,e.currentTarget.value),b(e,`id`,`sp-${i}-apiKey`),s(()=>e.value=d().value),e})(),(()=>{var e=QC(),t=e.firstChild;return t.$$click=()=>a(i,`apiKey`,{action:`keep`,value:``}),e})()]}}),null),y(e,n(l,{get when(){return o()[`${i}.apiKey`]},get children(){var e=qC();return y(e,()=>o()[`${i}.apiKey`]),e}}),null),e})()},j=async t=>{if(await P(`Reset ${hw[t].toLowerCase()} to the server default? Your own ${hw[t].toLowerCase()} settings are removed.`,`Reset`,{danger:!0}))try{let n=await(await H(mw.user,{method:`PUT`,json:nr(t)})).json().catch(()=>({})),r=n?.stt&&n?.tts?n:await K(mw.user);ou(r.ready??null),e.onSaved(r),J(`${hw[t]} reset to the server default`)}catch(e){J(`Could not reset: ${W(e)}`,`err`)}},M=i=>(()=>{var o=iw(),c=o.firstChild;return y(c,()=>hw[i]),y(o,n(l,{get when(){return x()},children:e=>(()=>{var t=aw(),n=t.firstChild,a=n.nextSibling;return y(n,(()=>{var t=r(()=>!!e().own[i]);return()=>t()?`${e().own[i]} of your own setting${e().own[i]===1?``:`s`}`:`All from the server default`})()),a.$$click=()=>void j(i),s(()=>a.disabled=!e().own[i]),t})()}),null),y(o,()=>E(i,`provider`,`Provider`,(()=>{var e=sw();return e.addEventListener(`change`,e=>a(i,`provider`,e.currentTarget.value)),b(e,`id`,`sp-${i}-provider`),y(e,n(m,{each:fw,children:([e,t])=>(()=>{var n=ow();return n.value=e,y(n,t),n})()}),null),y(e,n(l,{get when(){return!fw.some(([e])=>e===t[i].provider)},get children(){var e=ow();return y(e,()=>t[i].provider||`—`),s(()=>e.value=t[i].provider),e}}),null),s(()=>e.value=t[i].provider),e})()),null),y(o,n(l,{get when(){return t[i].provider===`openai-compatible`},get children(){return E(i,`baseURL`,`Base URL`,D(i,`baseURL`,{inputmode:`url`,placeholder:`http://host:port/v1`}))}}),null),y(o,()=>E(i,`model`,`Model`,O(i,`model`,i===`stt`?`Speech-to-text model`:`Text-to-speech model`,`model`,()=>T(i))),null),y(o,n(l,{when:i===`tts`,get fallback(){return E(i,`language`,`Language (optional)`,D(i,`language`,{placeholder:`auto, e.g. en`}))},get children(){return[r(()=>E(i,`voice`,`Voice`,O(i,`voice`,`Voice`,`voice`,async()=>TC(fo(e.settings.voiceHints,t.tts.model))))),r(()=>E(i,`speed`,`Server-side speed (optional)`,D(i,`speed`,{inputmode:`decimal`,placeholder:`default`}),`0.25–4, applied by the TTS provider. Your device's voice speed is separate.`))]}}),null),y(o,()=>A(i),null),o})(),N=async n=>{n.preventDefault();let r=vr(t),i=uo(r);if(c(i),Object.keys(i).length)return f({text:`Fix the highlighted fields.`,kind:`error`});let o=lo(e.settings,r);if(!Object.keys(o).length)return f({text:`Nothing to save.`,kind:`muted`});h(!0),f({text:`Saving…`,kind:`muted`});try{let t=await(await H(mw[e.scope],{method:`PUT`,json:o})).json().catch(()=>({})),n=t?.stt&&t?.tts?t:await K(mw[e.scope]);e.scope===`user`?ou(n.ready??null):Nd(),a(Pr(co(n))),e.onSaved(n),J(e.scope==="default"?`Server default saved`:`Speech settings saved`)}catch(e){let t=e.field;t&&c({[t]:W(e)}),f({text:`Could not save: ${W(e)}`,kind:`error`})}finally{h(!1)}},ee=async()=>{f({text:C()?`Previewing the saved voice (save to hear your changes)…`:`Previewing…`,kind:`muted`});let e;try{let t=await(await H(`/api/settings/speech/test`,{method:`POST`,json:{kind:`tts`,text:`Hi! This is how replies will sound.`}})).blob();if(e=URL.createObjectURL(t),cb.src=e,Lv(cb,Xy.speed),!await cb.play().then(()=>!0,()=>!1))throw Error(`the browser blocked playback`);f({text:`Playing preview.`,kind:`muted`}),await new Promise(e=>cb.onended=cb.onpause=cb.onerror=()=>e()),f({text:``,kind:``})}catch(e){f({text:`Preview failed: ${W(e)}`,kind:`error`})}finally{cb.onended=cb.onpause=cb.onerror=null,e&&URL.revokeObjectURL(e)}};return(()=>{var t=uw(),r=t.firstChild,i=r.firstChild,a=r.nextSibling;return t.$$input=()=>f({text:C()?`Unsaved changes.`:``,kind:`muted`}),t.addEventListener(`submit`,N),y(t,n(l,{get when(){return e.scope==="default"},get children(){return cw()}}),r),y(t,n(l,{get when(){return S()},children:e=>(()=>{var t=dw(),r=t.firstChild,i=r.firstChild.nextSibling;return i.nextSibling,y(i,()=>e().reason),y(r,n(l,{get when(){return e().storage},get children(){var t=KC();return y(t,()=>e().storage),t}}),null),t})()}),r),y(t,()=>M(`stt`),r),y(t,()=>M(`tts`),r),y(r,n(l,{get when(){return e.scope===`user`},get children(){var e=lw();return e.$$click=()=>void ee(),e}}),null),y(a,()=>d().text),y(t,n(BC,{get request(){return g()},onClose:()=>v(void 0)}),null),s(e=>{var t=p(),n=`small ${d().kind}`;return t!==e.e&&(i.disabled=e.e=t),n!==e.t&&k(a,e.t=n),e},{e:void 0,t:void 0}),t})()}B([`click`,`input`]);var vw=I(`<p class="small muted">This hub does not record voice conversations.`),yw=I(`<ul class=switches><li id=set-recording><label class=switch><span class=notify-kind><span></span><span class="small muted"></span></span><input type=checkbox role=switch data-recording-switch></label><ul class="recording-details small muted"></ul></li><li id=set-developer><label class=switch><span class=notify-kind><span></span><span class="small muted"></span></span><input type=checkbox role=switch data-developer-switch></label><ul class="recording-details small muted">`),bw=I(`<div class=recording-head><span class=grow></span><a class="btn small"href=/api/recordings/export download>Export all</a><button type=button class="btn small danger">Delete all`),xw=I(`<p class="small muted recording-empty">No recordings.`),Sw=I(`<button type=button class="btn small recording-more-page">Show more`),Cw=I(`<div class=recording-pane data-recording-pane role=region aria-label="Your recordings"tabindex=0>`),ww=I(`<details class="notify-group recording-fold"id=recordings data-recording-fold><summary><h4>Recordings</h4><span class="small muted notify-group-summary"data-recording-summary data-recording-usage></span></summary><div class=recording-fold-body>`),Tw=I(`<section class=settings-section id=recording aria-labelledby=h-recording><h3 class=section-title id=h-recording>Recording`),Ew=I(`<li>`),Dw=I(`<div class=recording-day><h5 class=recording-day-title></h5><ul class=recording-list>`),Ow=I(`<span class=recording-name>`),kw=I(`<select class=recording-segment aria-label=Segment title="Segment to play">`),Aw=I(`<button type=button class="btn small recording-play"aria-label="Play segment">▶ Play`),jw=I(`<li><div class=recording-main><div class=recording-title><span class=recording-kind></span></div><div class="small muted recording-meta"> · <!> · <span></span> · <!> · <!> · </div></div><div class=recording-actions>`),Mw=I(`<option>/`),Nw=I(`<a class="btn small"download>Export`),Pw=I(`<button type=button class="btn small danger"data-recording-focus>Delete`),Fw=50,Iw=200;function Lw(e){let t=Lu(e)?.session,n=Hu(e);return El({...n.startsWith(`@`)?{name:n}:{},...typeof t?.project==`string`&&t.project||t?.directory?{directory:typeof t?.project==`string`&&t.project||t.directory}:{}})}var Rw=e=>Dl(e,N(),void 0,Lw);function zw(){let[e,i]=u(void 0),[a,o]=u(),[c,d]=u(),[f,p]=u([]),[h,g]=u(),[_,v]=u(!1),[x,S]=u(!1),[w,T]=u(!1);async function E(){try{let e=await(await H(`/api/settings/recording`)).json();i(!0),o(e.settings),d(e.usage),Ll.set({supported:!0,settings:e.settings})}catch(e){e instanceof G&&(e.status===404||e.status===405)?(i(!1),Ll.set({supported:!1})):J(`Could not load the recording setting: ${W(e)}`,`err`)}}async function D(e=!1){try{let t=e?h():void 0,n=e?Fw:Math.min(Iw,Math.max(Fw,f().length)),r=await(await H(`/api/recordings?limit=${n}${t?`&cursor=${q(t)}`:``}`)).json();p(e?[...f(),...r.recordings]:r.recordings),d(r.usage),g(r.next)}catch(e){e instanceof G&&e.status===404||J(`Could not list the recordings: ${W(e)}`,`err`)}finally{S(!0)}}R(async()=>{await E(),e()&&await D()});let O;M(Fu(e=>{e.type===`recording`&&(e.settings&&typeof e.settings.enabled==`boolean`&&o(e.settings),clearTimeout(O),O=setTimeout(()=>void D(),300))})),M(()=>clearTimeout(O));async function k(e,t=`enabled`){let n=a();if(!n)return;let r=e.checked;v(!0);try{let e=await(await H(`/api/settings/recording`,{method:`PUT`,json:{[t]:r,expectedRevision:n.revision}})).json();o(e.settings),Gl(e.settings),J(t===`developer`?r?`Developer mode on from the next Voice start (recording too)`:`Developer mode off: the extras stop now`:r?`Recording on from the next Voice start`:`Recording off`)}catch(r){e.checked=t===`developer`?n.developer===!0:n.enabled,r instanceof G&&r.status===409?(J(`The setting changed on another device; it is reloaded. Try again.`,`err`),await E()):J(`Could not change the recording setting: ${W(r)}`,`err`)}finally{v(!1)}}async function A(e){let t=Rw(e);if(await P(`Delete this recording? ${t.kind} · ${t.title}, ${t.started}: its audio and events are deleted now.`,`Delete`,{danger:!0}))try{await H(`/api/recordings/${q(e.id)}`,{method:`DELETE`});let t=f().findIndex(t=>t.id===e.id),n=f()[t+1]??f()[t-1];p(f().filter(t=>t.id!==e.id)),c()&&d({...c(),bytes:Math.max(0,c().bytes-e.bytes)}),J(`Recording deleted`),ee(n?.id),D()}catch(e){J(`Could not delete the recording: ${W(e)}`,`err`)}}let j;function ee(e){requestAnimationFrame(()=>{((e?document.querySelector(`[data-recording-row="${CSS.escape(e)}"] [data-recording-focus], [data-recording-row="${CSS.escape(e)}"] [aria-haspopup="menu"]`):null)??j)?.focus()})}let F=C(()=>new Map(f().map(e=>[e.id,e]))),te=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),I=C(()=>[...new Set(f().map(e=>kl(e.startedAt)))],[],{equals:te});async function ne(){let e=f().length;if(await P(`Delete all ${e} recording${e===1?``:`s`}${h()?` (and the ones not listed yet)`:``}? Their audio and events are deleted now.`,`Delete all`,{danger:!0}))try{let{deleted:t}=await(await H(`/api/recordings`,{method:`DELETE`})).json();p([]),g(void 0),J(`${t??e} recording${(t??e)===1?``:`s`} deleted`),D()}catch(e){J(`Could not delete the recordings: ${W(e)}`,`err`)}}return(()=>{var i=Tw();return i.firstChild,y(i,n(l,{get when(){return e()===!1},get children(){return vw()}}),null),y(i,n(l,{get when(){return r(()=>!!e())()&&a()},get children(){return[(()=>{var e=yw(),t=e.firstChild,r=t.firstChild,i=r.firstChild,o=i.firstChild,c=o.nextSibling,l=i.nextSibling,u=r.nextSibling,d=t.nextSibling.firstChild,f=d.firstChild,p=f.firstChild,h=p.nextSibling,g=f.nextSibling,v=d.nextSibling;return y(o,()=>bl.label),y(c,()=>bl.description),l.addEventListener(`change`,e=>void k(e.currentTarget)),y(u,n(m,{get each(){return bl.details},children:e=>(()=>{var t=Ew();return y(t,e),t})()})),y(p,()=>xl.label),y(h,()=>xl.description),g.addEventListener(`change`,e=>void k(e.currentTarget,`developer`)),y(v,n(m,{get each(){return xl.details},children:e=>(()=>{var t=Ew();return y(t,e),t})()})),s(e=>{var t=_(),n=_();return t!==e.e&&(l.disabled=e.e=t),n!==e.t&&(g.disabled=e.t=n),e},{e:void 0,t:void 0}),s(()=>l.checked=a().enabled),s(()=>g.checked=a().developer===!0),e})(),(()=>{var e=ww(),i=e.firstChild,a=i.firstChild.nextSibling,o=i.nextSibling;return e.addEventListener(`toggle`,e=>T(e.currentTarget.open)),y(a,()=>Ol(f().length,!!h(),c())),y(o,n(l,{get when(){return f().length},get children(){var e=bw(),t=e.firstChild.nextSibling.nextSibling;return t.$$click=()=>void ne(),e}}),null),y(o,n(l,{get when(){return r(()=>!!x())()&&!f().length},get children(){return xw()}}),null),y(o,n(l,{get when(){return f().length},get children(){var e=Cw(),r=j;return typeof r==`function`?t(r,e):j=e,y(e,n(m,{get each(){return I()},children:e=>{let t=C(()=>f().filter(t=>kl(t.startedAt)===e).map(e=>e.id),[],{equals:te}),r=()=>{let e=F().get(t()[0]??``);return e?Al(e.startedAt,N()):``};return(()=>{var i=Dw(),a=i.firstChild,o=a.nextSibling;return b(i,`data-recording-day`,e),y(a,r),y(o,n(m,{get each(){return t()},children:e=>n(l,{get when(){return F().get(e)},children:e=>n(Bw,{get recording(){return e()},onDelete:()=>void A(e())})})})),i})()}}),null),y(e,n(l,{get when(){return h()},get children(){var e=Sw();return e.$$click=()=>void D(!0),e}}),null),e}}),null),s(()=>e.open=w()),e})()]}}),null),i})()}function Bw(e){let t=()=>Rw(e.recording),[i,a]=u(1),[o,c]=u(!1),d=()=>e.recording.segments;async function f(){c(!0);try{await Xl(e.recording.id,i())}catch(e){J(`Could not play segment ${i()}: ${W(e)}`,`err`)}finally{c(!1)}}let p=()=>`/api/recordings/${q(e.recording.id)}/export`,h=()=>{let e=document.createElement(`a`);e.href=p(),e.download=``,document.body.append(e),e.click(),e.remove()},g=()=>jl(t());return(()=>{var c=jw(),u=c.firstChild,_=u.firstChild,v=_.firstChild,x=_.nextSibling,S=x.firstChild,C=S.nextSibling,w=C.nextSibling.nextSibling,T=w.nextSibling.nextSibling,E=T.nextSibling.nextSibling;E.nextSibling;var D=u.nextSibling;return y(v,()=>g().kind),y(_,n(l,{get when(){return g().title},get children(){var e=Ow();return y(e,()=>g().title),e}}),null),y(x,()=>t().time,S),y(x,()=>t().device,C),y(w,()=>t().length),y(x,()=>t().segments,T),y(x,()=>t().size,E),y(x,()=>t().expires,null),y(x,n(l,{get when(){return t().note},get children(){return[` · `,r(()=>t().note)]}}),null),y(D,n(l,{get when(){return d()>0},get children(){return[n(l,{get when(){return d()>1},get children(){var e=kw();return e.addEventListener(`change`,e=>a(Number(e.currentTarget.value)||1)),y(e,n(m,{get each(){return Array.from({length:d()},(e,t)=>t+1)},children:e=>(()=>{var t=Mw(),n=t.firstChild;return y(t,e,n),y(t,d,null),s(()=>t.value=String(e)),t})()})),s(()=>e.value=String(i())),e}}),(()=>{var e=Aw();return e.$$click=()=>void f(),s(t=>{var n=o(),r=`Play segment ${i()}`;return n!==t.e&&(e.disabled=t.e=n),r!==t.t&&b(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e})()]}}),null),y(D,n(l,{get when(){return Q()},get fallback(){return[(()=>{var e=Nw();return s(()=>b(e,`href`,p())),e})(),(()=>{var t=Pw();return t.$$click=()=>e.onDelete(),t})()]},get children(){return n(O,{label:`Recording actions`,class:`btn small recording-menu`,text:`⋯`,items:()=>[{label:`Export (zip)`,run:h},{label:`Delete…`,danger:!0,run:()=>e.onDelete()}]})}}),null),s(n=>{var r=`recording-row${d()>0?` has-play`:``}`,i=e.recording.id,a=`${t().kind} · ${t().title}\nSession ${e.recording.sessionID} · recording ${e.recording.id}`,o=!!t().active;return r!==n.e&&k(c,n.e=r),i!==n.t&&b(c,`data-recording-row`,n.t=i),a!==n.a&&b(_,`title`,n.a=a),o!==n.o&&w.classList.toggle(`recording-live`,n.o=o),n},{e:void 0,t:void 0,a:void 0,o:void 0}),c})()}B([`click`]);var Vw={entries:100,chars:253},Hw=new Set([...[`co`,`org`,`ac`,`gov`,`net`,`me`,`ltd`,`plc`,`sch`,`nhs`].map(e=>`${e}.uk`),...[`com`,`net`,`org`,`edu`,`gov`,`id`,`asn`].map(e=>`${e}.au`),...[`co`,`ne`,`or`,`ac`,`go`,`gr`,`ed`,`ad`,`lg`].map(e=>`${e}.jp`),...[`co`,`org`,`net`,`ac`,`govt`,`school`,`geek`,`gen`,`kiwi`,`maori`].map(e=>`${e}.nz`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.br`),...[`com`,`net`,`org`,`gov`,`edu`,`ac`].map(e=>`${e}.cn`),...[`com`,`net`,`org`,`gob`,`edu`].map(e=>`${e}.mx`),...[`co`,`net`,`org`,`firm`,`gen`,`ind`,`ac`,`edu`,`gov`,`res`].map(e=>`${e}.in`),...[`co`,`org`,`net`,`ac`,`gov`,`web`].map(e=>`${e}.za`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.tr`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.sg`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.hk`),...[`co`,`or`,`ne`,`go`,`ac`,`re`].map(e=>`${e}.kr`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.tw`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.ar`),...[`co`,`or`,`ac`,`go`].map(e=>`${e}.id`),...[`co`,`or`,`ac`,`go`].map(e=>`${e}.th`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.my`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.ph`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.pk`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.ua`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.pl`),...[`co`,`or`,`ac`].map(e=>`${e}.at`),...[`co`,`org`,`ac`].map(e=>`${e}.il`),`com.es`,`org.es`,`co.it`,`com.ru`,`co.ca`,`eu.org`,`github.io`,`githubpreview.dev`,`gitlab.io`,`pages.dev`,`workers.dev`,`netlify.app`,`vercel.app`,`herokuapp.com`,`appspot.com`,`blogspot.com`,`cloudfront.net`,`azurewebsites.net`,`web.app`,`firebaseapp.com`,`s3.amazonaws.com`,`ngrok.io`,`ngrok-free.app`,`glitch.me`,`repl.co`,`fly.dev`,`onrender.com`]),Uw=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function Ww(e){if(typeof e!=`string`)return{ok:!1,reason:`Expected a hostname`};let t=e.trim();if(!t)return{ok:!1,reason:`Expected a hostname`};if(t.length>Vw.chars)return{ok:!1,reason:`${Gw(t)}: at most ${Vw.chars} characters`};if(/[\s/\\:@?#[\]%]/.test(t))return{ok:!1,reason:`${Gw(t)}: a hostname only (no scheme, port, path or address)`};let n=t.startsWith(`*.`),r=n?t.slice(2):t;if(r.includes(`*`))return{ok:!1,reason:`${Gw(t)}: a wildcard only as a leading "*."`};let i=Kw(r.replace(/\.$/,``));if(i===void 0)return{ok:!1,reason:`${Gw(t)}: not a hostname`};let a=i.split(`.`);if(a.some(e=>!Uw.test(e)))return{ok:!1,reason:`${Gw(t)}: not a hostname`};if(/^\d+$/.test(a[a.length-1]))return{ok:!1,reason:`${Gw(t)}: an IP address or numeric domain is not allowed`};if(a.length<2)return{ok:!1,reason:n?`${Gw(t)}: too broad (name at least two labels after "*.")`:`${Gw(t)}: name a full hostname (like github.com)`};if(Hw.has(i))return{ok:!1,reason:`${Gw(t)}: too broad (a public suffix: name the site itself)`};let o=n?`*.${i}`:i;return o.length>Vw.chars?{ok:!1,reason:`${Gw(t)}: at most ${Vw.chars} characters`}:{ok:!0,entry:o}}var Gw=e=>e.length>60?`${e.slice(0,57)}…`:e;function Kw(e){if(e)try{let t=new URL(`http://${e}/`);return t.hostname&&t.hostname===t.host?t.hostname:void 0}catch{return}}function qw(e){let t;try{t=new URL(e)}catch{return}if((t.protocol===`http:`||t.protocol===`https:`)&&!(t.port&&t.port!==`80`&&t.port!==`443`))return t.hostname.replace(/\.$/,``)||void 0}function Jw(e,t){let n=t.toLowerCase().replace(/\.$/,``);return n?e.some(e=>e.startsWith(`*.`)?n.endsWith(e.slice(1))&&n.length>e.length-1:n===e):!1}function Yw(e){return e.split(`.`).map(e=>e.toLowerCase().startsWith(`xn--`)?Xw(e.slice(4))??e:e).join(`.`)}function Xw(e){let t=128,n=0,r=72,i=e.lastIndexOf(`-`),a=[];for(let t=0;t<Math.max(i,0);t++){let n=e.charCodeAt(t);if(n>=128)return;a.push(n)}let o=(e,t,n)=>{e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t);let r=0;for(;e>455;)e=Math.floor(e/35),r+=36;return r+Math.floor(36*e/(e+38))},s=e=>e>=48&&e<=57?e-22:e>=65&&e<=90?e-65:e>=97&&e<=122?e-97:36;for(let c=i>0?i+1:0;c<e.length;){let i=n;for(let t=1,i=36;;i+=36){if(c>=e.length)return;let a=s(e.charCodeAt(c++));if(a>=36)return;n+=a*t;let o=i<=r?1:i>=r+26?26:i-r;if(a<o)break;t*=36-o}if(r=o(n-i,a.length+1,i===0),t+=Math.floor(n/(a.length+1)),n%=a.length+1,t>1114111)return;a.splice(n++,0,t)}try{return String.fromCodePoint(...a)}catch{return}}var Zw=`/api/settings/media`,[Qw,$w]=u(),eT;function tT(){let e=Qw();return!e&&!eT&&nT(),e}function nT(e=!1){if(eT&&!e)return eT;let t=H(Zw).then(e=>e.json()).then(e=>($w(e),e),()=>{eT===t&&(eT=void 0)});return eT=t,t}async function rT(e){let t=await(await H(Zw,{method:`PUT`,json:{allowlist:e}})).json();return $w(t),t}async function iT(e){let t=Qw()??await nT(),n=t?.allowlist??[];return t&&n.includes(e)?t:rT([...n,e])}var[aT,oT]=u(new Map),sT=e=>aT().get(e)??[];function cT(e,t){let n=aT().get(e)??[];if(n.includes(t))return;let r=new Map(aT());r.set(e,[...n,t]),oT(r)}var lT=I(`<p class="small media-off"role=status>Web images are turned off on this hub (HUB_REMOTE_FETCH=off): images from other sites are not loaded, allowed or not.`),uT=I(`<p class="small media-allowlist-error">`),dT=I(`<ul class=media-allowlist aria-label="Allowed sites">`),fT=I(`<p class="small media-allowlist-error"role=alert>`),pT=I(`<div class=media-settings><p class="small muted">Images in replies from these sites load at once, through this hub. Images from other sites show their address and wait for you to load them. Add a site (github.com) or every subdomain of one (*.githubusercontent.com).</p><p class="small media-warning">An allowed site that hosts other people's content (for example a file host) can still receive data an agent puts in an image URL.</p><form class=media-allowlist-add><input type=text aria-label=Site placeholder="github.com or *.githubusercontent.com"autocomplete=off autocapitalize=none><button type=submit class="btn small">Add`),mT=I(`<p class="small muted">No sites allowed yet.`),hT=I(`<span class=muted> (<!>)`),gT=I(`<li><span class=grow></span><button type=button class="btn small">Remove`);function _T(){let[e,t]=u(``),[r,i]=u(``),[a,o]=u(!1),[c,d]=u(``);R(async()=>{await nT(!0)||d(`Could not load the media settings.`)});let f=()=>tT()?.allowlist??[],p=async(e,t)=>{o(!0);try{return await rT(e),J(t),!0}catch(e){return i(W(e)),!1}finally{o(!1)}},h=async n=>{n?.preventDefault(),i(``);let r=Ww(e());if(!r.ok)return void i(r.reason);if(f().includes(r.entry))return void(t(``),i(`${r.entry} is already allowed`));if(f().length>=Vw.entries)return void i(`At most ${Vw.entries} allowed sites`);await p([...f(),r.entry],`Images from ${r.entry} now load at once`)&&t(``)},g=e=>{i(``),p(f().filter(t=>t!==e),`${e} removed`)};return(()=>{var o=pT(),u=o.firstChild.nextSibling.nextSibling,d=u.firstChild,p=d.nextSibling;return y(o,n(l,{get when(){return tT()?.remoteFetch===!1},get children(){return lT()}}),u),y(o,n(l,{get when(){return c()},get children(){var e=uT();return y(e,c),e}}),u),y(o,n(l,{get when(){return f().length},get fallback(){return mT()},get children(){var e=dT();return y(e,n(m,{get each(){return f()},children:e=>(()=>{var t=gT(),r=t.firstChild,i=r.nextSibling;return y(r,e,null),y(r,n(l,{get when(){return Yw(e)!==e},get children(){var t=hT(),n=t.firstChild.nextSibling;return n.nextSibling,y(t,()=>Yw(e),n),t}}),null),i.$$click=()=>g(e),b(i,`aria-label`,`Remove ${e}`),s(()=>i.disabled=a()),t})()})),e}}),u),u.addEventListener(`submit`,e=>void h(e)),d.$$input=e=>(t(e.currentTarget.value),i(``)),b(d,`spellcheck`,!1),y(o,n(l,{get when(){return r()},get children(){var e=fT();return y(e,r),e}}),null),s(()=>p.disabled=a()||!e().trim()),s(()=>d.value=e()),o})()}B([`input`,`click`]);var vT=[`queued`,`placing`,`provisioning`,`running`],yT=e=>typeof e==`object`&&!!e&&!Array.isArray(e),bT=e=>typeof e==`string`,xT=e=>typeof e==`number`&&Number.isFinite(e);function ST(e){if(!yT(e)||!bT(e.id)||!bT(e.state)||!yT(e.spec)||!yT(e.spec.workspace)||!bT(e.spec.workspace.repo))return;let t=e.spec.workspace,n=e.waiting;return{id:e.id,state:e.state,reason:bT(e.reason)?e.reason:``,repo:t.repo,...bT(t.branch)?{branch:t.branch}:{},...bT(e.by)?{by:e.by}:{},...bT(e.byLabel)?{byLabel:e.byLabel}:{},launcherRevoked:e.launcherRevoked===!0,...yT(n)&&bT(n.wait)&&bT(n.reason)&&xT(n.since)?{waiting:{wait:n.wait,reason:n.reason,since:n.since}}:{},...bT(e.name)?{name:e.name}:{},...bT(e.sessionID)?{sessionID:e.sessionID}:{},...bT(e.machineID)?{machineID:e.machineID}:{},concierge:e.by===`app:concierge`&&yT(e.spec.labels)&&e.spec.labels[`hub/system`]===`concierge`,created:xT(e.created)?e.created:0}}function CT(e){return!yT(e)||!Array.isArray(e.launches)?[]:e.launches.map(ST).filter(e=>e!==void 0)}function wT(e,t){if(!yT(t)||t.type!==`launch`)return e;let n=ST(t.launch);return n?vT.includes(n.state)?e.some(e=>e.id===n.id)?e.map(e=>e.id===n.id?{...n,launcherRevoked:n.launcherRevoked||e.launcherRevoked}:e):[...e,n]:e.filter(e=>e.id!==n.id):e}function TT(e){let{by:t,byLabel:n}=e;return t===void 0||t===`user`?`you`:t===`app:concierge`?`the Concierge`:t.startsWith(`app:`)?n?`app ${JSON.stringify(n)}`:`app ${t.slice(4)}`:n??`session ${t}`}var ET={queued:`Queued`,placing:`Placing`,provisioning:`Starting`,running:`Running`,ended:`Ended`},DT=e=>{let t=Math.floor(Math.max(0,e)/6e4);return t<1?`just now`:t<60?`for ${t} min`:`for ${Math.floor(t/60)} h`};function OT(e,t){let n=e.name?`@${e.name.replace(/^@+/,``)}`:`${e.repo}${e.branch?` (${e.branch})`:``}`;return{title:n,status:`${ET[e.state]??e.state} · by ${TT(e)}`,detail:e.state===`queued`&&e.waiting?`${e.waiting.reason} · ${DT(t-e.waiting.since)}`:e.reason,...e.launcherRevoked?{flag:`Its app token was revoked: it ${e.state===`queued`?`waits`:`keeps running`} and counts toward your launch limit until you stop it.`}:{},...e.concierge?{managed:`Managed by the Concierge — turn it off in Settings → Concierge`}:{stopLabel:`Stop launch ${n}`}}}function kT(e,t){if(e.state!==`ready`&&e.state!==`refreshing`)return;let n=e.latest();return n?wT(n,t):void 0}var AT=e=>e.normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase(),jT=e=>!!e&&/[a-z0-9]/.test(e),MT=(e,t)=>t===0||!jT(e[t-1]);function NT(e,t){let n;for(let r=t.indexOf(e);r>=0;r=t.indexOf(e,r+1)){let i=100+e.length*2+(r===0?40:MT(t,r)?20:0)-r*.01;(n===void 0||i>n)&&(n=i)}if(n!==void 0)return n;let r=10,i=-1;for(let n of e){let e=t.indexOf(n,i+1);if(e<0)return;r+=1+(e===i+1?4:0)+(MT(t,e)?6:0)-(i>=0?(e-i-1)*.2:0),i=e}return Math.min(99,r)}function PT(e,t){let n=AT(e).split(/\s+/).filter(Boolean);if(!n.length)return 0;let r=AT(t),i=0;for(let e of n){let t=NT(e,r);if(t===void 0)return;i+=t}return i}var FT=e=>[e.value,e.label,e.detail,e.keywords].filter(Boolean).join(` `);function IT(e,t,{exclude:n=[],limit:r=100}={}){let i=new Set(n),a=new Map,o=[];if(e.forEach((e,n)=>{let r=e.group??``;if(a.has(r)||a.set(r,a.size),i.has(e.value))return;let s=PT(t,FT(e));s!==void 0&&o.push({option:e,score:s,index:n,group:a.get(r)})}),t.trim()){let e=new Map;for(let t of o)e.set(t.group,Math.max(e.get(t.group)??-1/0,t.score));let t=[...e].sort((e,t)=>t[1]-e[1]||e[0]-t[0]).map(([e])=>e);for(let e of o)e.group=t.indexOf(e.group)}return o.sort((e,t)=>e.group-t.group||t.score-e.score||e.index-t.index),o.slice(0,r).map(e=>e.option)}function LT(e,t,n,r=[]){let i=e.trim();if(!i||r.includes(i)||t.some(e=>e.value===i))return;let a=n?.(i);return a?{value:i,problem:a}:{value:i}}function RT(e,t){let n=AT(t).split(/\s+/).filter(Boolean);return n.length?e.some(e=>{let t=AT(FT(e));return n.every(e=>t.includes(e))}):!1}var zT=8,BT=120;function VT({below:e,above:t,want:n}){if(n+zT<=e)return{up:!1,maxHeight:n};let r=t>e,i=Math.max(0,Math.min(n,(r?t:e)-zT));return i<Math.min(n,BT)?{up:r,maxHeight:i,cramped:!0}:{up:r,maxHeight:i}}function HT(e){let t=[];return e.forEach((e,n)=>{let r=t.at(-1);r&&r.group===e.group?r.items.push({option:e,index:n}):t.push({group:e.group,items:[{option:e,index:n}]})}),t}var UT=I(`<div role=option>`),WT=I(`<span role=img>`),GT=I(`<span class="po-id muted combo-detail">`),KT=I(`<span class=combo-text><span class="po-name combo-label">`),qT=I(`<span class=combo-text><span class="po-name combo-label">Use “<!>”</span><span class="po-id muted combo-detail">as typed`),JT=I(`<p class="combo-empty muted small">`),YT=I(`<div><div class="combo-list picker-list"role=listbox>`),XT=I(`<div class=combo><input type=text role=combobox class=combo-input aria-autocomplete=list autocomplete=off autocapitalize=off><p class="combo-problem small"aria-live=polite>`),ZT=I(`<div role=group class=combo-section><div class="picker-group combo-group muted small">`),QT=I(`<span class=pick-chip-kind>`),$T=I(`<span class="pick-chip-detail muted">`),eE=I(`<button type=button class=pick-chip-x>×`),tE=I(`<li class=pick-chip><span class=pick-chip-text><span class=pick-chip-label>`),nE=I(`<ul class=pick-chips>`),rE=I(`<div>`);function iE(e){for(let t=e.parentElement;t;t=t.parentElement){let e=getComputedStyle(t).overflowY;if(e===`auto`||e===`scroll`)return t}}var aE=264;function oE(e){let i=T(),o=`combo-${i}`,c=`combo-problem-${i}`,d,f,[p,h]=u(!1),[g,_]=u(0),[v,S]=u({up:!1,maxHeight:aE}),w=C(()=>IT(e.options,e.query,{exclude:e.exclude,limit:e.limit??60})),E=C(()=>HT(w())),D=C(()=>e.noCustom?void 0:LT(e.query,e.options,e.problem,e.exclude)),O=()=>D()?.problem,A=()=>D()&&!D().problem?D().value:void 0,j=C(()=>!!A()&&!RT(w(),e.query)),M=()=>{let e=A(),t=w().map(e=>e.value);return e===void 0?t:j()?[e,...t]:[...t,e]},N=e=>j()?e+1:e,ee=()=>j()?0:w().length,P=e=>`${o}-${e}`,F=()=>p()&&g()>=0&&g()<M().length?P(g()):void 0,te=t=>{e.onPick(t),e.onQuery(``),_(0),h(!1)},I=(e=!0)=>{if(!d||!f)return;let t=Math.min(aE,f.scrollHeight+2),n=iE(d)?.getBoundingClientRect(),r=Math.max(n?.top??0,0),i=Math.min(n?.bottom??window.innerHeight,window.innerHeight),a=d.getBoundingClientRect(),o=VT({below:i-a.bottom,above:a.top-r,want:t});if(o.cramped&&e)return d.scrollIntoView({block:`start`}),I(!1);S({up:o.up,maxHeight:o.maxHeight})};x(()=>{p()&&(w(),D(),I(),requestAnimationFrame(()=>p()&&I()))}),x(()=>{let e=F();e&&queueMicrotask(()=>document.getElementById(e)?.scrollIntoView({block:`nearest`}))});let ne=t=>{let n=M().length;if(t.key===`ArrowDown`||t.key===`ArrowUp`){if(t.preventDefault(),!p())return void(h(!0),_(t.key===`ArrowDown`?0:Math.max(0,n-1)));_(kC(g(),t.key===`ArrowDown`?1:-1,n))}else t.key===`Home`&&p()&&!e.query?(t.preventDefault(),_(0)):t.key===`End`&&p()&&!e.query?(t.preventDefault(),_(Math.max(0,n-1))):t.key===`Enter`?p()&&n&&g()>=0&&g()<n?(t.preventDefault(),te(M()[g()])):e.query.trim()&&t.preventDefault():t.key===`Escape`&&p()?(t.preventDefault(),t.stopPropagation(),h(!1)):t.key===`Tab`&&h(!1)},re=e=>(()=>{var t=UT();return t.$$click=()=>te(e.value),t.addEventListener(`pointerenter`,()=>_(e.index)),t.$$mousedown=e=>e.preventDefault(),y(t,()=>e.children),s(n=>{var r=P(e.index),i=`picker-opt combo-opt${e.class?` ${e.class}`:``}${g()===e.index?` active`:``}`,a=g()===e.index,o=e.value;return r!==n.e&&b(t,`id`,n.e=r),i!==n.t&&k(t,n.t=i),a!==n.a&&b(t,`aria-selected`,n.a=a),o!==n.o&&b(t,`data-value`,n.o=o),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t})(),ie=e=>n(re,{get index(){return N(e.index)},get value(){return e.row.value},get children(){return[n(l,{get when(){return e.row.online!==void 0},get children(){var t=WT();return s(n=>{var r=`combo-dot${e.row.online?` on`:``}`,i=e.row.online?`online`:`offline`;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),t}}),(()=>{var t=KT(),r=t.firstChild;return y(r,()=>e.row.label??e.row.value),y(t,n(l,{get when(){return e.row.detail},get children(){var t=GT();return y(t,()=>e.row.detail),t}}),null),t})()]}}),ae=()=>n(l,{get when(){return A()},children:e=>n(re,{get index(){return ee()},get value(){return e()},class:`combo-custom`,get children(){var t=qT(),n=t.firstChild,r=n.firstChild.nextSibling;return r.nextSibling,y(n,e,r),t}})}),oe=()=>[e.describedBy,O()?c:``].filter(Boolean).join(` `)||void 0;return(()=>{var i=XT(),u=i.firstChild,g=u.nextSibling,x=d;return typeof x==`function`?t(x,i):d=i,u.$$keydown=ne,u.addEventListener(`blur`,()=>h(!1)),u.$$click=()=>h(!0),u.addEventListener(`focus`,()=>h(!0)),u.$$input=t=>{e.onQuery(t.currentTarget.value),h(!0),_(0)},b(u,`aria-controls`,o),b(u,`spellcheck`,!1),b(g,`id`,c),y(g,()=>O()??``),y(i,n(l,{get when(){return p()},get children(){var i=YT(),c=i.firstChild,u=f;return typeof u==`function`?t(u,c):f=c,b(c,`id`,o),y(c,n(l,{get when(){return j()},get children(){return ae()}}),null),y(c,n(m,{get each(){return E()},children:e=>n(l,{get when(){return e.group},get fallback(){return n(m,{get each(){return e.items},children:e=>n(ie,{get row(){return e.option},get index(){return e.index}})})},children:t=>{let r=`${o}-g-${e.items[0].index}`;return(()=>{var i=ZT(),a=i.firstChild;return b(i,`aria-labelledby`,r),b(a,`id`,r),y(a,t),y(i,n(m,{get each(){return e.items},children:e=>n(ie,{get row(){return e.option},get index(){return e.index}})}),null),i})()}})}),null),y(c,n(l,{get when(){return!j()},get children(){return ae()}}),null),y(i,n(l,{get when(){return r(()=>!w().length)()&&!A()},get children(){var t=JT();return y(t,()=>e.query.trim()?`No matches`:`Nothing to suggest: type a value`),t}}),null),s(t=>{var n=`combo-pop${v().up?` up`:``}`,r=e.label,o=`${v().maxHeight}px`;return n!==t.e&&k(i,t.e=n),r!==t.t&&b(c,`aria-label`,t.t=r),o!==t.a&&a(c,`max-height`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),i}}),null),s(t=>{var n=e.label,r=p(),i=F(),a=oe(),o=e.invalid||!!O()||void 0,s=e.placeholder??``,c=e.autofocus;return n!==t.e&&b(u,`aria-label`,t.e=n),r!==t.t&&b(u,`aria-expanded`,t.t=r),i!==t.a&&b(u,`aria-activedescendant`,t.a=i),a!==t.o&&b(u,`aria-describedby`,t.o=a),o!==t.i&&b(u,`aria-invalid`,t.i=o),s!==t.n&&b(u,`placeholder`,t.n=s),c!==t.s&&(u.autofocus=t.s=c),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),s(()=>u.value=e.query),i})()}function sE(e){return(()=>{var t=tE(),r=t.firstChild,i=r.firstChild;return y(t,n(l,{get when(){return e.kind},get children(){var t=QT();return y(t,()=>e.kind),t}}),r),y(i,()=>e.label),y(r,n(l,{get when(){return e.detail},get children(){var t=$T();return y(t,()=>e.detail),t}}),null),y(t,n(l,{get when(){return e.onRemove},get children(){var t=eE();return t.$$click=()=>e.onRemove(),s(()=>b(t,`aria-label`,e.removeLabel??`Remove ${e.label}`)),t}}),null),s(()=>b(t,`title`,e.title)),t})()}function cE(e){let t=C(()=>new Map(e.options.map(e=>[e.value,e]))),r=n=>{if(e.chip)return e.chip(n);let r=t().get(n);return{label:r?.label??n,detail:r?.detail&&r.detail!==r.label?r.detail:void 0}};return(()=>{var t=rE();return y(t,n(l,{get when(){return e.values.length},get children(){var t=nE();return y(t,n(m,{get each(){return e.values},children:t=>n(sE,_(()=>r(t),{title:t,removeLabel:`Remove ${t}`,onRemove:()=>e.onRemove(t)}))})),s(()=>b(t,`aria-label`,`${e.label}: chosen`)),t}}),null),y(t,n(oE,_(e,{get exclude(){return e.values},onPick:t=>e.onAdd(t)})),null),s(()=>k(t,`chip-picker${e.mono?` mono-chips`:``}`)),t})()}B([`mousedown`,`click`,`input`,`keydown`]);var lE=/^[a-z0-9-]{2,40}$/,uE=e=>lE.test(e),dE=/^([a-z0-9-]{2,40})(?:\.([^./\s#]+))?$/i;function fE(e){if(e.startsWith(`ses_`))return/^ses_[A-Za-z0-9]+$/.test(e)?{kind:`id`,id:e}:void 0;let t=e.startsWith(`@@`);if(!t&&!e.startsWith(`@`))return;let n=dE.exec(e.slice(t?2:1));if(!n||!uE(n[1]))return;let r=n[2]?.toLowerCase(),i=r?{project:r}:{};return t?{kind:`role`,role:n[1],...i}:{kind:`name`,name:n[1],...i}}var pE=e=>!!e&&typeof e==`object`&&!Array.isArray(e),mE=e=>typeof e==`string`&&e?e:void 0;function hE(e){return(pE(e)&&Array.isArray(e.sessions)?e.sessions:[]).flatMap(e=>{if(!pE(e)||typeof e.sessionID!=`string`||!e.sessionID)return[];let t=Array.isArray(e.roles)?e.roles.flatMap(e=>pE(e)&&typeof e.role==`string`?[e.role]:[]):[];return[{sessionID:e.sessionID,...mE(e.name)?{name:mE(e.name)}:{},...mE(e.title)?{title:mE(e.title)}:{},...mE(e.project)?{project:mE(e.project)}:{},online:e.online===!0,...e.archived===!0?{archived:!0}:{},...e.concierge===!0?{concierge:!0}:{},roles:t}]})}var gE=/^orchestrator/,_E=e=>gE.test(e)||e.startsWith(`concierge`),vE=`holder is @@role, @name, ses_… or app:<token id>`,yE=/^app:[0-9a-f]{16}$/,bE={role:`Reserved roles`,session:`Sessions`,app:`Apps`},xE={role:`Reserved role`,session:`Session`,app:`App`},SE=e=>e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()||e,CE=e=>typeof e.project==`string`&&e.project||e.directory||``;function wE({who:e,sessions:t,tokens:n,hidden:r=new Set}){let i=new Map(t.map(e=>[e.id,e])),a=e=>r.has(e),o=new Map([[`orchestrator`,[]]]);for(let t of e)if(!(t.concierge||t.archived||a(t.sessionID)))for(let e of t.roles){if(!gE.test(e))continue;let n=o.get(e)??[];n.push(t.name?`@${t.name}`:t.sessionID),o.set(e,n)}let s=[...o].map(([e,t])=>({value:`@@${e}`,label:`@@${e}`,kind:`role`,group:bE.role,detail:t.length?`Held by ${t.join(`, `)} · follows whoever holds it`:`Follows whoever holds it when the grant is used`})),c=[],l=new Set,u=(e,t)=>{let n=i.get(e);return n&&(n.projectName||CE(n)&&SE(CE(n)))||t||``};for(let t of e){if(t.concierge||t.archived||a(t.sessionID))continue;l.add(t.sessionID);let e=t.title||i.get(t.sessionID)?.title||``,n=u(t.sessionID,t.project);c.push({value:t.name?`@${t.name}`:t.sessionID,label:t.name?`@${t.name}`:e||t.sessionID,kind:`session`,group:bE.session,online:t.online,detail:[t.name?e:t.sessionID,n,t.name?t.sessionID:``].filter(Boolean).join(` · `)})}for(let e of t){if(l.has(e.id)||e.archived||a(e.id))continue;l.add(e.id);let t=u(e.id);c.push({value:e.id,label:e.title||e.id,kind:`session`,group:bE.session,online:!!e.machineOnline,detail:[e.id,t,e.machineName].filter(Boolean).join(` · `)})}let d=c.filter(e=>e.online),f=c.filter(e=>!e.online),p=n.map(e=>({value:`app:${e.id}`,label:e.label||`Unnamed app`,kind:`app`,group:bE.app,detail:`app:${e.id}${e.scopes.length?` · ${e.scopes.join(`, `)}`:``}`}));return[...s,...d,...f,...p]}function TE(e,t){let n=t.find(t=>t.value===e);if(n)return{kind:n.kind,kindLabel:xE[n.kind],label:n.label,detail:n.detail??``};let r=e.startsWith(`@@`)?`role`:e.startsWith(`app:`)?`app`:`session`,i=r===`role`?`Follows whoever holds it when the grant is used`:r===`app`?`One of your app tokens`:`Pinned to that session when the grant is created`;return{kind:r,kindLabel:xE[r],label:e,detail:i}}function EE(e){if(yE.test(e))return;let t=fE(e);if(!t||t.kind===`name`&&t.name===`me`)return vE;if(t.kind===`role`&&!_E(t.role))return`A role holder must be a reserved role (such as @@orchestrator)`}var DE=e=>/^([A-Za-z]:)?[\\/]/.test(e),OE=e=>e.length>1?e.replace(/[\\/]+$/,``):e;function kE(e){let t=e.trim();return t?DE(t)?void 0:`${t} is not an absolute directory`:`A project directory`}function AE({sessions:e,grants:t}){let n=new Map,r=e=>{let t=OE(e.trim());t&&DE(t)&&n.set(t,(n.get(t)??0)+1)};for(let t of e)r(CE(t));for(let e of t)for(let t of e.scope.projects)n.has(OE(t))||r(t);return[...n.keys()].map(e=>({value:e,label:SE(e),detail:e}))}var jE=/^[A-Za-z0-9_.*?-]{1,80}$/,ME=1e3;function NE(e){let t=`${e} is not an action[:glob] pattern (e.g. shell:bun test *)`;if(!e||e!==e.trim())return t;let n=e.indexOf(`:`),r=n<0?e:e.slice(0,n),i=n<0?`*`:e.slice(n+1);return jE.test(r)&&i!==``&&i.length<=ME?void 0:t}var PE=[[`edit`,`Edit any file`],[`write`,`Write any file`],[`read`,`Read any file`],[`glob`,`Find files`],[`grep`,`Search files`],[`list`,`List folders`],[`webfetch`,`Fetch web pages`],[`websearch`,`Search the web`],[`task`,`Start subagents`],[`external_directory`,`Work outside the project folder`],[`shell`,`Run any shell command`]],FE=[[`shell:bun test *`,`Run the tests (bun)`],[`shell:npm test *`,`Run the tests (npm)`],[`shell:npm run *`,`Run package scripts`],[`shell:git status *`,`git status`],[`shell:git diff *`,`git diff`],[`shell:git log *`,`git log`],[`shell:ls *`,`List files`],[`edit:src/*`,`Edit files under src/`]],IE=[[`shell:rm *`,`Delete files`],[`shell:git push *`,`Push commits`],[`shell:git reset --hard *`,`Discard work`],[`shell:sudo *`,`Run as root`],[`shell:curl *`,`Download or upload`],[`edit:.env*`,`Edit secrets files`],[`external_directory`,`Work outside the project folder`]];function LE(e,t){let n=new Map,r=(e,t,r)=>{!n.has(e)&&!NE(e)&&n.set(e,{value:e,label:e,detail:t,group:r})};for(let n of t)for(let t of e===`permit`?n.permissions.allow:n.permissions.never)r(t,`From your grants`,`Used before`);for(let[t,n]of e===`permit`?FE:IE)r(t,n,`Common`);if(e===`permit`)for(let[e,t]of PE)r(e,t,`Every resource of an action`);return[...n.values()]}var RE=e=>e.split(`
|
|
10
|
+
`).map(e=>e.trim()).filter(Boolean);function zE(e,t){let n=RE(e),r=t.trim();return(r&&!n.includes(r)?[...n,r]:n).join(`
|
|
11
|
+
`)}var BE=(e,t)=>RE(e).filter(e=>e!==t).join(`
|
|
12
|
+
`),VE={approve:`Approve permission requests that pass the patterns below`,deny:`Deny permission requests`,answer:`Answer questions and forms (also lets an app with decisions:answer answer its sessions' confirm-tier Decisions)`,prompt:`Send a prompt to a session (also lets an app follow and talk in its conversation)`,stop:`Stop a session's turn`,roles:`Claim and release roles of sessions (apps)`,launch:`Start new sessions in these projects`},HE=[`30m`,`8h`,`1d`,`7d`,`30d`],UE=60,WE=1,GE=1e3;function KE(e,t){let n=e.trim();return/^\d+$/.test(n)?String(Math.min(GE,Math.max(WE,Number(n)+t))):String(UE)}var qE=(e,t)=>e.allow.includes(`approve`)||!!e.permit.trim()||!!e.never.trim()||e.allowAlways||!!t?.permit.trim()||!!t?.never.trim(),JE={projects:kE,permit:NE,never:NE};function YE(e,t){let n={},r=[],i=e,a=t.holder.trim();!i.holder.trim()&&a&&(i={...i,holder:a},r.push(`holder`));for(let e of[`projects`,`permit`,`never`]){let a=t[e].trim();if(!a)continue;let o=JE[e](a);o?n[e]=o:(i={...i,[e]:zE(i[e],a)},r.push(e))}let o=i.holder.trim(),s=o?EE(o):void 0;s&&(n.holder=s);let c=bt(i);return Object.keys(n).length?{draft:e,cleared:[],result:{ok:!1,errors:{...c.ok?{}:c.errors,...n}}}:{draft:i,cleared:r,result:c}}var XE=I(`<div id=agent-activity>`),ZE=I(`<section class=settings-section id=agents aria-label=Agents><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"id=grants><button type=button class=chip>Grants</button><button type=button class=chip>Activity`),QE=I(`<ul class=list>`),$E=I(`<div class="stack connected-apps"id=connected-apps><div class=row><div class=grow><h3>Connected apps</h3><p class="small muted">Apps you let use this hub as you, through their consent page. Each keeps only the scopes you approved; acting still needs a grant.</p></div><button type=button class="btn small">Refresh`),eD=I(`<p class="small muted">`),tD=I(`<p class="small muted">No connected apps.`),nD=I(`<li class=row><div class=grow><div class=name></div><div class="small muted mono"></div><div class=small data-connection-scopes></div><div class="small muted"></div></div><button type=button class="btn small danger">Revoke`),rD=I(`<div class="stack app-clients"id=app-clients><div class=row><div class=grow><h3>App clients</h3><p class="small muted">Apps that may ask you (and <!>) to connect. Register the app's exact redirect URIs and the most it may ask for; its server keeps the secret.</p></div><button type=button class="btn small primary">Register app`),iD=I(`<p class="small muted">No app clients registered.`),aD=I(`<span class="badge-pill off">`),oD=I(`<button type=button class="btn small">Edit`),sD=I(`<button type=button class="btn small">Rotate secret`),cD=I(`<button type=button class="btn small">`),lD=I(`<button type=button class="btn small danger">Delete`),uD=I(`<li class=row><div class=grow><div class=name><span class=badge-pill></span></div><div class="small muted mono"></div><div class="small muted">Returns to </div><div class=small>At most: `),dD=I(`<p role=alert>`),fD=I(`<div class=text-field><span class=field-title id=app-client-audience>Who may connect</span><div class=chips role=group aria-labelledby=app-client-audience><button type=button class=chip>Everyone on this hub</button><button type=button class=chip>Only me`),pD=I(`<form class=grant-form novalidate><label class=text-field><span class=field-title>Name</span><span class="field-desc muted small">Shown on the consent page.</span><input type=text maxlength=100></label><label class=text-field><span class=field-title>Redirect URIs</span><span class="field-desc muted small">One per line, matched exactly: https, or http on 127.0.0.1, [::1] or localhost.</span><textarea rows=3 placeholder=https://app.example.com/hub/callback></textarea></label><fieldset class=grant-verbs><legend class=field-title>Scopes it may ask for</legend></fieldset><div class=dialog-actions><button type=button class=btn>Cancel</button><button type=submit class="btn primary">`),mD=I(`<label class=check><input type=checkbox><span>`),hD=I(`<div class=stack><p class=warn><strong>Copy the secret now.</strong> It will not be shown again. Keep it on the app's server only.</p><div class=dialog-actions><button type=button class="btn primary">Done`),gD=I(`<div class="stack app-tokens"id=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`),_D=I(`<p class="small muted">No app tokens yet.`),vD=I(`<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`),yD=I(`<div class="stack launches"id=launches><div class=row><div class=grow><h3>Launches</h3><p class="small muted">Sessions started on your machines by you, apps and sessions. A queued one says why it waits.</p></div><button type=button class="btn small">Refresh`),bD=I(`<p class="small muted">No live launches.`),xD=I(`<div class="small warn"data-launcher-revoked>`),SD=I(`<div class="small muted"data-launch-managed>`),CD=I(`<button type=button class="btn small danger">Stop`),wD=I(`<li class=row><div class=grow><div class=name></div><div class="small muted"></div><div class=small data-launch-reason>`),TD=I(`<span class="field-desc muted small">`),ED=I(`<div class=copy-field><span class=field-title></span><div class=copy-row><div class="copy-value mono"role=textbox aria-readonly=true tabindex=0></div><button type=button class="btn small">Copy`),DD=I(`<div class=stack><p class=warn><strong>Copy this token now.</strong> It will not be shown again.</p><div class=dialog-actions><button type=button class="btn primary">Done`),OD=I(`<p class=error role=alert>`),kD=I(`<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 type=text 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=dialog-actions><button type=button class=btn>Cancel</button><button type=submit class="btn primary">Create token`),AD=I(`<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>`),jD=I(`<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>`),MD=I(`<p class="small warn"role=status data-acting-note>`),ND=I(`<ul class="list grants">`),PD=I(`<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`),FD=I(`<p class="small muted">No grants. Agents can still ask you (Decisions).`),ID=I(`<dt>Permissions`),LD=I(`<dd class=mono>`),RD=I(`<dt>Never`),zD=I(`<button type=button class="btn small danger">Revoke`),BD=I(`<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>`),VD=I(`<p class="field-error small"role=alert>`),HD=I(`<div class="text-field grant-field"><span class=field-title></span><span class="field-desc muted small">`),UD=I(`<ul class="pick-chips holder-chip"aria-label="Holder: chosen">`),WD=I(`<p class="small warn"data-approve-note>These only apply to approve: tick approve, or remove them.`),GD=I(`<fieldset aria-label=Approving><label class=check><input type=checkbox aria-label="May allow always"><span>May answer “Always allow” (still only for patterns it may approve)`),KD=I(`<p class=error role=alert data-error=form>`),qD=I(`<form class=grant-form novalidate><div class="text-field grant-field"data-field=holder><span class=field-title>Holder</span><span class="field-desc muted small"id=grant-hint-holder></span></div><fieldset class=grant-verbs aria-label=Actions><legend class=field-title>May</legend><div class=verb-grid></div></fieldset><div class=grant-limits><div class="text-field grant-field"data-field=expires><span class=field-title id=grant-expires-title>Expires after</span><span class="field-desc muted small"></span><div class=expiry-row><div class=chips role=group aria-labelledby=grant-expires-title></div><input type=text class=expiry-input aria-label="Expires after"placeholder="e.g. 12h"></div></div><div class="text-field grant-field"data-field=maxActionsPerHour><span class=field-title>Actions per hour</span><span class="field-desc muted small">1–1000</span><div class=stepper><button type=button class="btn small"aria-label="Fewer actions per hour">−</button><input type=number inputmode=numeric min=1 max=1000 step=1 aria-label="Actions per hour"><button type=button class="btn small"aria-label="More actions per hour">+</button></div></div></div><div class=dialog-actions><button type=button class=btn>Cancel</button><button type=submit class="btn primary">`),JD=I(`<label><input type=checkbox><span class=verb-text><span class=verb-name></span><span class="verb-help muted small">`),YD=I(`<button type=button class=chip>`),XD=I(`<ol class="list audit agent-audit">`),ZD=I(`<p class="small muted">Loading…`),QD=I(`<button type=button class="btn small">Load older`),$D=I(`<div class=stack>`),eO=I(`<p class="small err">Could not load: `),tO=I(`<p class="small muted">No agent actions yet.`),nO=I(`<span>`),rO=I(`<li class=audit-row><div class=grow><div class=name><span></span> <span class=muted></span></div><div class="small muted"><span></span></div></div><time class="small muted">`),iO=50,aO=`/api/agent/grants`,oO=`/api/agent/app-tokens`,sO=`/api/agent/launches`,cO=`/api/agent/connections`,lO=`/api/agent/app-clients`,[uO,dO]=u(0);function fO(){let e=d(()=>K(oO).then(qe)),t=d(()=>K(cO).then(Ut)),r=C(()=>[...e[0]()??[],...(t[0]()??[]).map(e=>({id:e.id,label:`${e.clientName} (connected app)`,scopes:e.scopes,created:e.created}))]),[i,a]=u(`grants`);return x(()=>{let e=Nt().hash;e===`#agent-activity`?a(`activity`):e===`#grants`&&a(`grants`)}),(()=>{var o=ZE(),c=o.firstChild.nextSibling,u=c.firstChild,d=u.nextSibling;return y(o,n(xO,{}),c),y(o,n(pO,{connections:t}),c),y(o,n(mO,{onChanged:()=>void t[1].refetch()}),c),y(o,n(_O,{tokens:e}),c),y(o,n(vO,{}),c),u.$$click=()=>a(`grants`),d.$$click=()=>a(`activity`),y(o,n(l,{get when(){return i()===`grants`},get children(){return n(SO,{tokens:r})}}),null),y(o,n(l,{get when(){return i()===`activity`},get children(){var e=XE();return y(e,n(wO,{})),e}}),null),s(e=>{var t=i()===`grants`,n=i()===`activity`;return t!==e.e&&b(u,`aria-pressed`,e.e=t),n!==e.t&&b(d,`aria-pressed`,e.t=n),e},{e:void 0,t:void 0}),o})()}function pO(e){let[t,{mutate:i,refetch:a}]=e.connections,o=async e=>{if(await P(`Revoke ${e.clientName}? Its tokens stop working at once and its grants and webhooks are deleted. Sessions it launched keep running until you stop them under Launches.`,`Revoke`,{danger:!0}))try{await H(`${cO}/${q(e.id)}`,{method:`DELETE`}),i(t=>(t??[]).filter(t=>t.id!==e.id)),dO(e=>e+1),J(`${e.clientName} revoked`)}catch(e){J(W(e),`err`),a()}};return(()=>{var e=$E(),i=e.firstChild.firstChild.nextSibling;return i.$$click=()=>void a(),y(e,n(l,{get when(){return t()},get fallback(){return(()=>{var e=eD();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${W(t.error)}`:`Loading…`})()),e})()},get children(){return n(l,{get when(){return t().length},get fallback(){return tD()},get children(){var e=QE();return y(e,n(m,{get each(){return t()},children:e=>{let t=()=>nt(e,N());return(()=>{var n=nD(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,c=a.nextSibling,l=c.nextSibling,u=r.nextSibling;return y(i,()=>t().title),y(a,()=>t().holder),y(c,()=>t().scopes),y(l,()=>t().detail),u.$$click=()=>void o(e),s(t=>{var r=e.id,i=`Revoke ${e.clientName}`;return r!==t.e&&b(n,`data-connection`,t.e=r),i!==t.t&&b(u,`aria-label`,t.t=i),t},{e:void 0,t:void 0}),n})()}})),e}})}}),null),e})()}function mO(e){let[t,{mutate:i,refetch:a}]=d(()=>K(lO).then(he)),[o,c]=u(),[f,p]=u(),h=e=>e.audience===`user`||Kn(Z()),g=e=>i(t=>[e,...(t??[]).filter(t=>t.id!==e.id)].sort((e,t)=>t.created-e.created)),_=async t=>{let n=!t.disabled;if(!n||await P(`Disable ${t.name}? Every account connected to it is disconnected at once.`,`Disable`,{danger:!0}))try{let r=We((await(await H(`${lO}/${q(t.id)}`,{method:`PATCH`,json:{disabled:n}})).json())?.client);r?g(r):a(),J(n?`${t.name} disabled`:`${t.name} enabled`),e.onChanged()}catch(e){J(W(e),`err`)}},v=async e=>{if(await P(`Rotate the secret of ${e.name}? The old secret stops working at once: update the app's server first.`,`Rotate`,{danger:!0}))try{let t=await(await H(`${lO}/${q(e.id)}/secret`,{method:`POST`,json:{}})).json(),n=We(t?.client);if(!n||typeof t?.secret!=`string`)throw Error(`The hub did not return the new secret`);g(n),p({client:n,secret:t.secret})}catch(e){J(W(e),`err`)}},x=async t=>{if(await P(`Delete ${t.name}? Every account connected to it is disconnected and the app can no longer connect.`,`Delete`,{danger:!0}))try{await H(`${lO}/${q(t.id)}`,{method:`DELETE`}),i(e=>(e??[]).filter(e=>e.id!==t.id)),J(`${t.name} deleted`),e.onChanged()}catch(e){J(W(e),`err`),a()}};return(()=>{var i=rD(),a=i.firstChild.firstChild,u=a.firstChild.nextSibling,d=u.firstChild.nextSibling;d.nextSibling;var S=a.nextSibling;return y(u,()=>Kn(Z())?`everyone on this hub, for hub-wide ones`:`only you`,d),S.$$click=()=>c(`new`),y(i,n(l,{get when(){return o()},keyed:!0,children:t=>n(hO,{client:t===`new`?void 0:t,onClose:()=>c(void 0),onSaved:(t,n)=>{g(t),c(void 0),n&&p(n),e.onChanged()}})}),null),y(i,n(l,{get when(){return f()},keyed:!0,children:e=>n(gO,{get client(){return e.client},get secret(){return e.secret},onClose:()=>p(void 0)})}),null),y(i,n(l,{get when(){return t()},get fallback(){return(()=>{var e=eD();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${W(t.error)}`:`Loading…`})()),e})()},get children(){return n(l,{get when(){return t().length},get fallback(){return iD()},get children(){var e=QE();return y(e,n(m,{get each(){return t()},children:e=>{let t=()=>Ae(e);return(()=>{var r=uD(),i=r.firstChild.firstChild,a=i.firstChild,o=i.nextSibling,u=o.nextSibling;u.firstChild;var d=u.nextSibling;return d.firstChild,y(i,()=>e.name,a),y(a,()=>t().badge),y(i,n(l,{get when(){return t().state},get children(){var e=aD();return y(e,()=>t().state),e}}),null),y(o,()=>e.id),y(u,()=>t().redirects,null),y(d,()=>t().scopes,null),y(r,n(l,{get when(){return h(e)},get children(){return[(()=>{var t=oD();return t.$$click=()=>c(e),s(()=>b(t,`aria-label`,`Edit ${e.name}`)),t})(),(()=>{var t=sD();return t.$$click=()=>void v(e),s(()=>b(t,`aria-label`,`Rotate the secret of ${e.name}`)),t})(),(()=>{var t=cD();return t.$$click=()=>void _(e),y(t,()=>e.disabled?`Enable`:`Disable`),s(()=>b(t,`aria-label`,`${e.disabled?`Enable`:`Disable`} ${e.name}`)),t})(),(()=>{var t=lD();return t.$$click=()=>void x(e),s(()=>b(t,`aria-label`,`Delete ${e.name}`)),t})()]}}),null),s(()=>b(r,`data-app-client`,e.id)),r})()}})),e}})}}),null),i})()}function hO(e){let[t,i]=u(e.client?.name??``),[a,o]=u((e.client?.redirectURIs??[]).join(`
|
|
13
|
+
`)),[c,d]=u([...e.client?.scopes??[`sessions:read`]]),[f,p]=u(e.client?.audience??(Kn(Z())?`hub`:`user`)),[h,g]=u({}),[_,v]=u(!1),x=async n=>{n.preventDefault();let r=Lt({name:t(),redirects:a(),scopes:c(),...e.client?{}:{audience:f()}});if(!r.ok)return g({[r.field]:r.error});g({}),v(!0);try{let t=await(await H(e.client?`${lO}/${q(e.client.id)}`:lO,{method:e.client?`PATCH`:`POST`,json:r.body})).json(),n=We(t?.client);if(!n)throw Error(`The hub did not return the client`);J(e.client?`${n.name} updated`:`${n.name} registered`),e.onSaved(n,!e.client&&typeof t?.secret==`string`?{client:n,secret:t.secret}:void 0)}catch(e){g({form:W(e)})}finally{v(!1)}},S=e=>n(l,{get when(){return h()[e.field]},get children(){var t=dD();return y(t,()=>h()[e.field]),s(n=>{var r=e.field===`form`?`error`:`field-error small`,i=e.field;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`data-error`,n.t=i),n},{e:void 0,t:void 0}),t}});return n(de,{open:!0,get title(){return r(()=>!!e.client)()?`Edit ${e.client.name}`:`Register an app`},get onClose(){return e.onClose},class:`app-client-dialog`,get children(){var u=pD(),h=u.firstChild,g=h.firstChild.nextSibling.nextSibling,v=h.nextSibling,C=v.firstChild.nextSibling.nextSibling,w=v.nextSibling;w.firstChild;var T=w.nextSibling,E=T.firstChild,D=E.nextSibling;return u.addEventListener(`submit`,e=>void x(e)),g.$$input=e=>i(e.currentTarget.value),y(u,n(S,{field:`name`}),v),C.$$input=e=>o(e.currentTarget.value),y(u,n(S,{field:`redirects`}),w),y(w,n(m,{each:Mt,children:e=>(()=>{var t=mD(),n=t.firstChild,r=n.nextSibling;return n.addEventListener(`change`,t=>d(t.currentTarget.checked?[...c(),e]:c().filter(t=>t!==e))),y(r,e),s(()=>n.checked=c().includes(e)),t})()}),null),y(u,n(S,{field:`scopes`}),T),y(u,n(l,{get when(){return r(()=>!e.client)()&&Kn(Z())},get children(){var e=fD(),t=e.firstChild.nextSibling.firstChild,n=t.nextSibling;return t.$$click=()=>p(`hub`),n.$$click=()=>p(`user`),s(e=>{var r=f()===`hub`,i=f()===`user`;return r!==e.e&&b(t,`aria-pressed`,e.e=r),i!==e.t&&b(n,`aria-pressed`,e.t=i),e},{e:void 0,t:void 0}),e}}),T),y(u,n(S,{field:`form`}),T),V(E,`click`,e.onClose,!0),y(D,()=>e.client?`Save`:`Register`),s(()=>D.disabled=_()),s(()=>g.value=t()),s(()=>C.value=a()),u}})}function gO(e){let t=async(e,t)=>{try{await navigator.clipboard.writeText(e),J(`${t} copied`)}catch{J(`Could not copy ${t.toLowerCase()}`,`err`)}};return n(de,{open:!0,get title(){return`Save the secret of ${e.client.name}`},get onClose(){return e.onClose},class:`app-token-dialog`,get children(){var r=hD(),i=r.firstChild.nextSibling,a=i.firstChild;return y(r,n(yO,{field:`client-id`,title:`Client ID`,get value(){return e.client.id},onCopy:()=>void t(e.client.id,`Client ID`)}),i),y(r,n(yO,{field:`client-secret`,title:`Client secret`,get value(){return e.secret},onCopy:()=>void t(e.secret,`Secret`)}),i),y(r,n(yO,{field:`issuer`,title:`Hub (issuer)`,desc:`The app reads the endpoints from /.well-known/oauth-authorization-server.`,get value(){return Z()?.publicURL??location.origin},onCopy:()=>void t(Z()?.publicURL??location.origin,`Issuer`)}),i),V(a,`click`,e.onClose,!0),r}})}function _O(e){let[t,{mutate:i,refetch:a}]=e.tokens,[o,c]=u(!1),d=async e=>{if(await P(`Revoke ${e.label||e.id}? Apps using it will stop working immediately. Sessions it launched keep running until you stop them under Launches.`,`Revoke`,{danger:!0}))try{await H(`${oO}/${q(e.id)}`,{method:`DELETE`}),i(t=>(t??[]).filter(t=>t.id!==e.id)),dO(e=>e+1),J(`App token revoked`)}catch(e){J(W(e),`err`),a()}};return(()=>{var e=gD(),a=e.firstChild.firstChild.nextSibling;return a.$$click=()=>c(!0),y(e,n(l,{get when(){return o()},get children(){return n(bO,{onClose:()=>c(!1),onCreated:e=>i(t=>[e,...(t??[]).filter(t=>t.id!==e.id)])})}}),null),y(e,n(l,{get when(){return t()},get fallback(){return(()=>{var e=eD();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${W(t.error)}`:`Loading…`})()),e})()},get children(){return n(l,{get when(){return t().length},get fallback(){return _D()},get children(){var e=QE();return y(e,n(m,{get each(){return t()},children:e=>(()=>{var t=vD(),n=t.firstChild,i=n.firstChild,a=i.nextSibling;a.firstChild;var o=a.nextSibling,c=n.nextSibling;return y(i,()=>e.label||`Unnamed app`),y(a,()=>e.id,null),y(o,()=>e.scopes.join(`, `)||`No scopes`,null),y(o,(()=>{var t=r(()=>!!e.created);return()=>t()?` · created ${z(e.created,N())}`:``})(),null),c.$$click=()=>void d(e),s(()=>b(t,`data-app-token`,e.id)),t})()})),e}})}}),null),e})()}function vO(){let[e,{refetch:t,mutate:i}]=d(uO,()=>K(`${sO}?state=${vT.join(`,`)}`).then(e=>CT(e)));M(Fu(t=>{let n=kT({state:e.state,latest:()=>e.latest},t);n&&i(n)}));let[a,o]=u(),c=async e=>{if(await P(`Stop ${OT(e,N()).title}? Its session is stopped and its workspace cleaned up by its policy.`,`Stop`,{danger:!0})){o(e.id);try{await H(`${sO}/${q(e.id)}`,{method:`DELETE`}),J(`Launch stopped`)}catch(e){J(W(e),`err`)}finally{o(void 0),t()}}};return(()=>{var i=yD(),o=i.firstChild.firstChild.nextSibling;return o.$$click=()=>void t(),y(i,n(l,{get when(){return e()},get fallback(){return(()=>{var t=eD();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?`Could not load: ${W(e.error)}`:`Loading…`})()),t})()},get children(){return n(l,{get when(){return e().length},get fallback(){return bD()},get children(){var t=QE();return y(t,n(m,{get each(){return e()},children:e=>{let t=()=>OT(e,N());return(()=>{var r=wD(),i=r.firstChild,o=i.firstChild,u=o.nextSibling,d=u.nextSibling;return y(o,()=>t().title),y(u,()=>t().status),y(d,()=>t().detail),y(i,n(l,{get when(){return t().flag},get children(){var e=xD();return y(e,()=>t().flag),e}}),null),y(i,n(l,{get when(){return t().managed},get children(){var e=SD();return y(e,()=>t().managed),e}}),null),y(r,n(l,{get when(){return t().stopLabel},get children(){var n=CD();return n.$$click=()=>void c(e),s(r=>{var i=t().stopLabel,o=a()===e.id;return i!==r.e&&b(n,`aria-label`,r.e=i),o!==r.t&&(n.disabled=r.t=o),r},{e:void 0,t:void 0}),n}}),null),s(()=>b(r,`data-launch`,e.id)),r})()}})),t}})}}),null),i})()}function yO(e){let t=`copy-field-${e.field}`;return(()=>{var r=ED(),i=r.firstChild,a=i.nextSibling,o=a.firstChild,c=o.nextSibling;return b(i,`id`,t),y(i,()=>e.title),y(r,n(l,{get when(){return e.desc},get children(){var t=TD();return y(t,()=>e.desc),t}}),a),b(o,`aria-labelledby`,t),y(o,()=>e.value),c.$$click=()=>e.onCopy(),s(t=>{var n=e.field,i=`Copy ${e.title.toLowerCase()}`;return n!==t.e&&b(r,`data-copy-field`,t.e=n),i!==t.t&&b(c,`aria-label`,t.t=i),t},{e:void 0,t:void 0}),r})()}function bO(e){let[t,r]=u(`MCP Gateway`),[i,a]=u([`sessions:read`,`messages:send`,`messages:read`]),[o,c]=u(``),[d,f]=u(``),[p,h]=u(``),[g,_]=u(!1),v=async n=>{n.preventDefault();let r=Pt(t(),i());if(!r.ok)return h(r.error);_(!0),h(``);try{let t=await(await H(oO,{method:`POST`,json:r.body})).json(),n=Zt(t);if(!n||typeof t?.token!=`string`)throw Error(`The hub did not return the new token`);e.onCreated(n),c(t.token),f(`app:${n.id}`)}catch(e){h(W(e))}finally{_(!1)}},b=async(e,t)=>{try{await navigator.clipboard.writeText(e),J(`${t} copied`)}catch{J(`Could not copy ${t.toLowerCase()}`,`err`)}};return n(de,{open:!0,get title(){return o()?`Save your app token`:`New app token`},get onClose(){return e.onClose},class:`app-token-dialog`,get children(){return n(l,{get when(){return o()},get fallback(){return(()=>{var o=kD(),c=o.firstChild,u=c.firstChild.nextSibling.nextSibling,d=c.nextSibling;d.firstChild;var f=d.nextSibling.nextSibling,h=f.firstChild,_=h.nextSibling;return o.addEventListener(`submit`,e=>void v(e)),u.$$input=e=>r(e.currentTarget.value),y(d,n(m,{each:Mt,children:e=>(()=>{var t=mD(),n=t.firstChild,r=n.nextSibling;return n.addEventListener(`change`,t=>a(t.currentTarget.checked?[...i(),e]:i().filter(t=>t!==e))),y(r,e),s(()=>n.checked=i().includes(e)),t})()}),null),y(o,n(l,{get when(){return p()},get children(){var e=OD();return y(e,p),e}}),f),V(h,`click`,e.onClose,!0),s(()=>_.disabled=g()),s(()=>u.value=t()),o})()},get children(){var t=DD(),r=t.firstChild.nextSibling,i=r.firstChild;return y(t,n(yO,{field:`token`,title:`Bearer token`,get value(){return o()},onCopy:()=>void b(o(),`Token`)}),r),y(t,n(yO,{field:`holder`,title:`Grant holder`,desc:`Use this non-secret value if you later create an acting or launch grant.`,get value(){return d()},onCopy:()=>void b(d(),`Holder`)}),r),V(i,`click`,e.onClose,!0),t}})}})}function xO(){let[e,{mutate:t}]=d(()=>K(`/api/agent/acting`).then(St)),[i,a]=d(()=>Kn(Z())||void 0,()=>K(`/api/admin/agents/acting`).then(e=>e?.enabled!==!1)),[o,c]=u(!1),f=async e=>{let n=e.checked;c(!0);try{t(St(await(await H(`/api/agent/acting`,{method:`PUT`,json:{enabled:n}})).json())),J(n?`Agent actions are on for you`:`Agent actions are off for you`)}catch(t){e.checked=!n,J(W(t),`err`)}finally{c(!1)}},p=async e=>{let n=e.checked;if(!n&&!await P(`Turn agent actions off for everyone on this hub? No agent can act until an admin turns them on again.`,`Turn off`,{danger:!0}))e.checked=!0;else{c(!0);try{let e=await(await H(`/api/admin/agents/acting`,{method:`PUT`,json:{enabled:n}})).json();a.mutate(e?.enabled!==!1),J(n?`Agent actions are on for this hub`:`Agent actions are off for this hub`);let r=await K(`/api/agent/acting`).catch(()=>void 0);r&&t(St(r))}catch(t){e.checked=!n,J(W(t),`err`)}finally{c(!1)}}};return n(l,{get when(){return e()},get fallback(){return(()=>{var t=eD();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?`Could not load: ${W(e.error)}`:`Loading…`})()),t})()},children:e=>[(()=>{var t=jD(),a=t.firstChild.firstChild.firstChild.nextSibling;return a.addEventListener(`change`,e=>void f(e.currentTarget)),y(t,n(l,{get when(){return r(()=>!!Kn(Z()))()&&i()!==void 0},get children(){var e=AD(),t=e.firstChild.firstChild.nextSibling;return t.addEventListener(`change`,e=>void p(e.currentTarget)),s(()=>t.disabled=o()),s(()=>t.checked=i()),e}}),null),s(()=>a.disabled=o()),s(()=>a.checked=e().on),t})(),n(l,{get when(){return e().note},get children(){var t=MD();return y(t,()=>e().note),t}})]})}function SO(e){let[t,{refetch:i,mutate:a}]=d(()=>K(aO).then(Se)),[o,c]=u(),[f,p]=u(Date.now()),h=setInterval(()=>p(Date.now()),1e3);M(()=>clearInterval(h));let g=async e=>{if(await P(`Revoke the grant of ${e.holder}? It stops at once.`,`Revoke`,{danger:!0}))try{let t=await(await H(`${aO}/${q(e.id)}`,{method:`DELETE`})).json(),n=we(t?.grant);n?a(e=>(e??[]).map(e=>e.id===n.id?n:e)):i(),J(`Grant of ${e.holder} revoked`)}catch(e){J(W(e),`err`),i()}},_=e=>{a(t=>[e,...(t??[]).filter(t=>t.id!==e.id)].sort((e,t)=>t.created-e.created)),c(void 0)};return(()=>{var i=PD(),a=i.firstChild.firstChild.nextSibling;return a.$$click=()=>c(`new`),y(i,n(l,{get when(){return o()},keyed:!0,children:r=>n(CO,{grant:r===`new`?void 0:r,get grants(){return t()??[]},get tokens(){return e.tokens()??[]},onSaved:_,onClose:()=>c(void 0)})}),null),y(i,n(l,{get when(){return t()},get fallback(){return(()=>{var e=eD();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${W(t.error)}`:`Loading…`})()),e})()},get children(){return n(l,{get when(){return t().length},get fallback(){return FD()},get children(){var e=ND();return y(e,n(m,{get each(){return t()},children:e=>{let t=()=>vt(e,f());return(()=>{var r=BD(),i=r.firstChild.firstChild,a=i.firstChild,o=i.nextSibling,u=o.firstChild.nextSibling,d=u.nextSibling.nextSibling,f=d.nextSibling,p=f.nextSibling,m=o.nextSibling;return y(i,()=>t().holder,a),y(a,()=>t().stateLabel),y(u,()=>t().projects),y(d,()=>t().verbs),y(o,n(l,{get when(){return t().permit},get children(){return[ID(),(()=>{var e=LD();return y(e,()=>t().permit),e})()]}}),f),y(o,n(l,{get when(){return t().never},get children(){return[RD(),(()=>{var e=LD();return y(e,()=>t().never),e})()]}}),f),y(p,()=>t().limits),y(m,()=>t().expiry),y(r,n(l,{get when(){return t().editable},get children(){return[(()=>{var t=oD();return t.$$click=()=>c(e),s(()=>b(t,`aria-label`,`Edit grant of ${e.holder}`)),t})(),(()=>{var t=zD();return t.$$click=()=>void g(e),s(()=>b(t,`aria-label`,`Revoke grant of ${e.holder}`)),t})()]}}),null),s(n=>{var i=`grant-row${t().editable?``:` ended`}`,o=e.id,s=`badge-pill ${t().state}`;return i!==n.e&&k(r,n.e=i),o!==n.t&&b(r,`data-grant`,n.t=o),s!==n.a&&k(a,n.a=s),n},{e:void 0,t:void 0,a:void 0}),r})()}})),e}})}}),null),i})()}function CO(e){let[t,i]=u(It(e.grant)),[a,o]=u({}),[c,f]=u(``),[p,h]=u(!1),[g,_]=u({holder:``,projects:``,permit:``,never:``}),v=(e,t)=>{_(n=>({...n,[e]:t})),a()[e]&&o(t=>({...t,[e]:void 0}))},[x]=d(()=>K(`/api/agent/who`).then(hE,()=>[])),S=C(()=>wE({who:x()??[],sessions:Iu(),tokens:e.tokens,hidden:Eu()})),w=C(()=>AE({sessions:Iu(),grants:e.grants})),T=C(()=>LE(`permit`,e.grants)),E=C(()=>LE(`never`,e.grants)),D=(e,t)=>{i(n=>({...n,[e]:t})),a()[e]&&o(t=>({...t,[e]:void 0}))},O=async n=>{n.preventDefault(),f(``);let r=YE(t(),g());i(r.draft);for(let e of r.cleared)_(t=>({...t,[e]:``}));let a=r.result;if(!a.ok)o(a.errors);else{o({}),h(!0);try{let t=e.grant?`${aO}/${q(e.grant.id)}`:aO,n=await(await H(t,{method:e.grant?`PUT`:`POST`,json:a.body})).json(),r=we(n?.grant);J(e.grant?`Grant updated`:`Grant created`),r?e.onSaved(r):e.onClose()}catch(e){let t=W(e),n=e instanceof G&&(e.status===400||e.status===404)?qt(t):void 0;n?o({[n]:t}):f(e instanceof G&&e.hint?`${t} (${e.hint})`:t)}finally{h(!1)}}},A=e=>n(l,{get when(){return a()[e.field]},get children(){var t=VD();return y(t,()=>a()[e.field]),s(n=>{var r=e.field,i=`grant-error-${e.field}`;return r!==n.e&&b(t,`data-error`,n.e=r),i!==n.t&&b(t,`id`,n.t=i),n},{e:void 0,t:void 0}),t}}),j=e=>(()=>{var r=HD(),i=r.firstChild,o=i.nextSibling;return y(i,()=>e.label),y(o,()=>e.hint),y(r,n(cE,{get label(){return e.label},get placeholder(){return e.placeholder},get options(){return e.options},get values(){return RE(t()[e.field])},onAdd:n=>D(e.field,zE(t()[e.field],n)),onRemove:n=>D(e.field,BE(t()[e.field],n)),get query(){return g()[e.field]},onQuery:t=>v(e.field,t),get problem(){return e.check},get mono(){return e.mono},get chip(){return e.chip},get invalid(){return!!a()[e.field]},get describedBy(){return`grant-hint-${e.field}${a()[e.field]?` grant-error-${e.field}`:``}`}}),null),y(r,n(A,{get field(){return e.field}}),null),s(t=>{var n=e.field,i=`grant-hint-${e.field}`;return n!==t.e&&b(r,`data-field`,t.e=n),i!==t.t&&b(o,`id`,t.t=i),t},{e:void 0,t:void 0}),r})(),M=e=>({label:e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()||e,detail:e}),N=()=>TE(t().holder,S()),ee=()=>t().allow.includes(`approve`);return n(de,{open:!0,get title(){return r(()=>!!e.grant)()?`Edit grant of ${e.grant.holder}`:`New grant`},get onClose(){return e.onClose},wide:!0,class:`grant-dialog`,get children(){var i=qD(),o=i.firstChild,u=o.firstChild.nextSibling,d=o.nextSibling,f=d.firstChild.nextSibling,h=d.nextSibling,_=h.firstChild,x=_.firstChild.nextSibling,C=x.nextSibling.firstChild,P=C.nextSibling,F=_.nextSibling,te=F.firstChild.nextSibling.nextSibling.firstChild,I=te.nextSibling,ne=I.nextSibling,re=h.nextSibling,ie=re.firstChild,ae=ie.nextSibling;return i.addEventListener(`submit`,e=>void O(e)),y(u,()=>e.grant?`A grant's holder cannot change: revoke it and create another.`:`Search, or type @@role, @name, ses_… or app:<token id>. A role follows whoever holds it; a session is pinned to that session.`),y(o,n(l,{get when(){return t().holder},get fallback(){return n(oE,{label:`Holder`,placeholder:`Search roles, sessions and apps…`,get options(){return S()},get query(){return g().holder},onQuery:e=>v(`holder`,e),onPick:e=>D(`holder`,e),problem:EE,get invalid(){return!!a().holder},get describedBy(){return`grant-hint-holder${a().holder?` grant-error-holder`:``}`}})},get children(){var i=UD();return y(i,n(sE,{get kind(){return N().kindLabel},get label(){return N().label},get detail(){return r(()=>N().label===t().holder)()?N().detail:`${t().holder} · ${N().detail}`},get title(){return t().holder},removeLabel:`Change holder`,get onRemove(){return e.grant?void 0:()=>D(`holder`,``)}})),s(()=>b(i,`data-holder`,t().holder)),i}}),null),y(o,n(A,{field:`holder`}),null),y(i,n(j,{field:`projects`,label:`Projects`,hint:`Where it may act: project directories (subdirectories and worktrees included).`,placeholder:`Search projects or type an absolute path…`,get options(){return w()},check:kE,chip:M}),d),y(f,n(m,{each:zt,children:e=>(()=>{var n=JD(),r=n.firstChild,i=r.nextSibling.firstChild,a=i.nextSibling;return r.addEventListener(`change`,n=>D(`allow`,n.currentTarget.checked?[...t().allow,e]:t().allow.filter(t=>t!==e))),b(r,`aria-label`,e),y(i,e),y(a,()=>VE[e]),s(()=>k(n,`verb-option${t().allow.includes(e)?` on`:``}`)),s(()=>r.checked=t().allow.includes(e)),n})()})),y(d,n(A,{field:`allow`}),null),y(i,n(l,{get when(){return qE(t(),g())},get children(){var e=GD(),r=e.firstChild,i=r.firstChild;return y(e,n(l,{get when(){return!ee()},get children(){return WD()}}),r),y(e,n(j,{field:`permit`,label:`Permissions it may approve`,hint:`Patterns action[:glob]: the action alone covers every resource (e.g. shell:bun test *).`,placeholder:`Search patterns or type one`,get options(){return T()},check:NE,mono:!0}),r),y(e,n(j,{field:`never`,label:`Never`,hint:`Patterns it may never approve; never wins over every allow.`,placeholder:`Search patterns or type one, e.g. shell:rm *`,get options(){return E()},check:NE,mono:!0}),r),i.addEventListener(`change`,e=>D(`allowAlways`,e.currentTarget.checked)),y(e,n(A,{field:`allowAlways`}),null),s(()=>k(e,`grant-approve${ee()?``:` idle`}`)),s(()=>i.checked=t().allowAlways),e}}),h),y(x,()=>e.grant?`From now: saving restarts the countdown.`:`At most 30 days.`),y(C,n(m,{each:HE,children:e=>(()=>{var n=YD();return n.$$click=()=>D(`expires`,e),y(n,e),s(()=>b(n,`aria-pressed`,t().expires.trim()===e)),n})()})),P.$$input=e=>D(`expires`,e.currentTarget.value),y(_,n(A,{field:`expires`}),null),te.$$click=()=>D(`maxActionsPerHour`,KE(t().maxActionsPerHour,-1)),I.$$input=e=>D(`maxActionsPerHour`,e.currentTarget.value),ne.$$click=()=>D(`maxActionsPerHour`,KE(t().maxActionsPerHour,1)),y(F,n(A,{field:`maxActionsPerHour`}),null),y(i,n(l,{get when(){return c()},get children(){var e=KD();return y(e,c),e}}),re),V(ie,`click`,e.onClose,!0),y(ae,()=>e.grant?`Save`:`Create grant`),s(()=>ae.disabled=p()),s(()=>P.value=t().expires),s(()=>I.value=t().maxActionsPerHour),i}})}function wO(){let[e,t]=u([]),[i,a]=u(),[o,c]=u(`loading`),[f,p]=u(``),h=async e=>{c(`loading`);try{let n=Yt(await K(`/api/agent/audit?limit=${iO}${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))]}),a(n.next),c(`ready`)}catch(e){p(W(e)),c(`failed`)}};h();let[g]=d(async()=>{try{let{decisions:e}=await K(`/api/decisions`);return(e??[]).map(Ne).filter(e=>!!e)}catch{return[]}}),_=()=>{let e=new Map((g()??[]).map(e=>[e.id,e]));for(let t of pu().values())e.set(t.id,t);return[...e.values()]},v=()=>{let t=e()[0]?.seq??0;return[...Du().filter(e=>e.seq>t),...e()]};return(()=>{var e=$D();return y(e,n(l,{get when(){return o()!==`failed`},get fallback(){return(()=>{var e=eO();return e.firstChild,y(e,f,null),e})()},get children(){return[n(l,{get when(){return v().length||o()!==`ready`},get fallback(){return tO()},get children(){var e=XD();return y(e,n(m,{get each(){return v()},children:e=>{let t=()=>Ot(e,dt(e,_()),Hu);return(()=>{var i=rO(),a=i.firstChild,o=a.firstChild,c=o.firstChild,u=c.nextSibling.nextSibling,d=o.nextSibling,f=d.firstChild,p=a.nextSibling;return y(c,()=>t().who),y(u,()=>t().what),y(f,()=>t().result),y(d,n(l,{get when(){return t().grant},get children(){return[` · `,(()=>{var e=nO();return y(e,()=>t().grant),s(()=>b(e,`title`,t().grantTitle)),e})()]}}),null),y(d,(()=>{var e=r(()=>!!t().reason);return()=>e()?` · ${t().reason}`:``})(),null),y(p,()=>z(e.at,N())),s(n=>{var r=e.seq,a=e.actor.kind===`session`?e.actor.sessionID:void 0,o=t().whatTitle,s=`audit-result ${t().tone}`,l=new Date(e.at).toISOString(),d=new Date(e.at).toLocaleString();return r!==n.e&&b(i,`data-seq`,n.e=r),a!==n.t&&b(c,`title`,n.t=a),o!==n.a&&b(u,`title`,n.a=o),s!==n.o&&k(f,n.o=s),l!==n.i&&b(p,`datetime`,n.i=l),d!==n.n&&b(p,`title`,n.n=d),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),i})()}})),e}}),n(l,{get when(){return o()===`loading`},get children(){return ZD()}}),n(l,{get when(){return r(()=>o()===`ready`)()&&i()!==void 0},get children(){var e=QD();return e.$$click=()=>void h(i()),e}})]}})),e})()}B([`click`,`input`]);var TO=I(`<fieldset class=stack id=concierge-watchlist><legend class=field-title>Watchlist`),EO=I(`<p class="small muted">`),DO=I(`<span class="field-desc muted small"data-watchlist-count>Watching <!> session<!> now.`),OO=I(`<label class=check><input type=checkbox><span>Sessions that are working, blocked or failed, have a Decision open, or were active in the last <!> h<span class=muted data-watch-active-count> (<!> now)`),kO=I(`<label class=text-field><span class=small>Watch sessions active in the last (hours)</span><input type=number min=1 max=24 aria-label="Watch sessions active in the last (hours)">`),AO=I(`<label class=check><input type=checkbox><span>Pinned sessions and workspaces<span class=muted> (<!> now)`),jO=I(`<div class=stack><span class=small>Also watch</span><ul class=list></ul><form class=row><input class="mono grow"aria-label="Session to watch"placeholder="@name or ses_… (pick from the list)"list=concierge-sessions><button type=submit class="btn small">Watch`),MO=I(`<div class=stack><span class=small>Muted for the Concierge (beats everything above; your notifications are not affected)</span><ul class=list></ul><form class=row><input class="mono grow"aria-label="Session to mute"placeholder="@name or ses_… (pick from the list)"list=concierge-sessions><button type=submit class="btn small">Mute`),NO=I(`<label class=text-field><span class=small>Projects to watch (one directory per line)</span><textarea class=mono rows=2 aria-label="Projects to watch">`),PO=I(`<datalist id=concierge-sessions>`),FO=I(`<label class=text-field><span class=small>Projects to mute (one directory per line)</span><textarea class=mono rows=2 aria-label="Projects to mute">`),IO=I(`<li class="small muted">No sessions added.`),LO=I(`<li class=row><span class="small grow"></span><button type=button class="btn small">Remove`),RO=I(`<li class="small muted">Nothing muted.`),zO=I(`<li class=row><span class="small grow"></span><button type=button class="btn small">Unmute`),BO=I(`<option>`),VO=`/api/agent/concierge/watchlist`,HO=e=>Hu(e),UO=(e,t)=>e.filter(e=>e.reasons.includes(t)).length,WO=e=>[...new Set(e.split(`
|
|
14
|
+
`).map(e=>e.trim()).filter(Boolean))];function GO(){let[e,{refetch:t,mutate:i}]=d(()=>K(VO)),[a,o]=u(!1),[c,f]=u(``),[p,h]=u(``),g=async(n,r)=>{o(!0);try{let t=await(await n()).json(),a=e();return a&&t.config&&i({...a,config:t.config}),J(r),!0}catch(e){return J(e instanceof G&&e.status===409?`The watchlist changed elsewhere: reloaded`:`Could not save the watchlist: ${W(e)}`,`err`),!1}finally{o(!1),t()}},_=t=>g(()=>H(VO,{method:`PUT`,json:{...t,expectedRevision:e().config.revision}}),`Watchlist saved`),v=(e,t)=>g(()=>H(`${VO}/${e}`,{method:`POST`,json:{session:t}}),e===`watch`?`Watching ${HO(t)}`:e===`mute`?`Muted ${HO(t)} for the Concierge`:`Watchlist saved`);return(()=>{var t=TO();return t.firstChild,y(t,n(l,{get when(){return e()},get fallback(){return(()=>{var t=EO();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?`Could not load the watchlist: ${W(e.error)}`:`Loading…`})()),t})()},children:e=>{let t=()=>e().config;return[(()=>{var t=DO(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(t,()=>e().entries.length,n),y(t,()=>e().truncated?`+`:``,n),y(t,()=>e().entries.length===1?``:`s`,r),t})(),(()=>{var n=OO(),r=n.firstChild,i=r.nextSibling,o=i.firstChild.nextSibling,c=o.nextSibling.nextSibling,l=c.firstChild.nextSibling;return l.nextSibling,r.addEventListener(`change`,e=>void _({autoActive:e.currentTarget.checked})),y(i,()=>t().activeWithinHours,o),y(c,()=>UO(e().entries,`active`),l),s(()=>r.disabled=a()),s(()=>r.checked=t().autoActive),n})(),(()=>{var e=kO(),n=e.firstChild.nextSibling;return n.addEventListener(`change`,e=>{let n=Math.round(Number(e.currentTarget.value));n>=1&&n<=24&&n!==t().activeWithinHours?_({activeWithinHours:n}):e.currentTarget.value=String(t().activeWithinHours)}),s(()=>n.disabled=a()||!t().autoActive),s(()=>n.value=t().activeWithinHours),e})(),(()=>{var n=AO(),r=n.firstChild,i=r.nextSibling.firstChild.nextSibling,o=i.firstChild.nextSibling;return o.nextSibling,r.addEventListener(`change`,e=>void _({usePins:e.currentTarget.checked})),y(i,()=>UO(e().entries,`pinned`)+UO(e().entries,`pinned_project`),o),s(()=>r.disabled=a()),s(()=>r.checked=t().usePins),n})(),(()=>{var e=jO(),r=e.firstChild.nextSibling,i=r.nextSibling,o=i.firstChild,l=o.nextSibling;return y(r,n(m,{get each(){return t().sessions},get fallback(){return IO()},children:e=>(()=>{var t=LO(),n=t.firstChild,r=n.nextSibling;return b(t,`data-watch-session`,e),b(n,`title`,e),b(n,`data-session-id`,e),y(n,()=>HO(e)),r.$$click=()=>void v(`unwatch`,e),s(t=>{var n=a(),i=`Stop watching ${HO(e)}`;return n!==t.e&&(r.disabled=t.e=n),i!==t.t&&b(r,`aria-label`,t.t=i),t},{e:void 0,t:void 0}),t})()})),i.addEventListener(`submit`,e=>(e.preventDefault(),c().trim()&&void v(`watch`,c().trim()).then(e=>e&&f(``)))),o.$$input=e=>f(e.currentTarget.value),s(()=>l.disabled=a()||!c().trim()),s(()=>o.value=c()),e})(),(()=>{var e=MO(),r=e.firstChild.nextSibling,i=r.nextSibling,o=i.firstChild,c=o.nextSibling;return y(r,n(m,{get each(){return t().muted},get fallback(){return RO()},children:e=>(()=>{var t=zO(),n=t.firstChild,r=n.nextSibling;return b(t,`data-muted-session`,e),b(n,`title`,e),b(n,`data-session-id`,e),y(n,()=>HO(e)),r.$$click=()=>void v(`unmute`,e),s(t=>{var n=a(),i=`Unmute ${HO(e)}`;return n!==t.e&&(r.disabled=t.e=n),i!==t.t&&b(r,`aria-label`,t.t=i),t},{e:void 0,t:void 0}),t})()})),i.addEventListener(`submit`,e=>(e.preventDefault(),p().trim()&&void v(`mute`,p().trim()).then(e=>e&&h(``)))),o.$$input=e=>h(e.currentTarget.value),s(()=>c.disabled=a()||!p().trim()),s(()=>o.value=p()),e})(),(()=>{var e=NO(),n=e.firstChild.nextSibling;return n.addEventListener(`change`,e=>void _({projects:WO(e.currentTarget.value)})),s(()=>n.disabled=a()),s(()=>n.value=t().projects.join(`
|
|
15
|
+
`)),e})(),(()=>{var e=PO();return y(e,n(m,{get each(){return Iu().filter(e=>!e.hidden).slice(0,200)},children:e=>(()=>{var t=BO();return s(()=>b(t,`label`,e.title)),s(()=>t.value=e.id),t})()})),e})(),(()=>{var e=FO(),n=e.firstChild.nextSibling;return n.addEventListener(`change`,e=>void _({mutedProjects:WO(e.currentTarget.value)})),s(()=>n.disabled=a()),s(()=>n.value=t().mutedProjects.join(`
|
|
16
|
+
`)),e})()]}}),null),t})()}B([`input`,`click`]);var KO=I(`<section class=settings-section id=concierge aria-label=Concierge><p class="small muted">A hub-managed assistant that watches your sessions, tells you what needs you and answers status questions. It runs as a hidden session on one of your machines and acts only inside the grant you give it; everything else comes to you as a Decision.`),qO=I(`<button type=button class="btn small">Retry`),JO=I(`<p class="small muted"data-concierge-load>`),YO=I(`<button type=button class="btn small">Restart`),XO=I(`<button type=button class="btn small danger">Turn off`),ZO=I(`<button type=button class="btn small primary">Turn on`),QO=I(`<p class="small muted"data-concierge-problem>`),$O=I(`<p class="small muted"data-concierge-hint>After turning it on, open it from <strong>✨ Concierge</strong> at the top of the sidebar (on a phone, the ✨ in the top bar).`),ek=I(`<div class="row concierge-notice err"role=alert data-concierge-suspended><span class=grow>Stopped: </span><button type=button class="btn small">Restart`),tk=I(`<div class=stack><div class=row><div class=grow><div class=name>Status</div><div class="small muted"data-concierge-status></div></div></div><fieldset class=stack id=concierge-machine><legend class=field-title>Machine</legend><span class="field-desc muted small">It needs \`hub node\` with a workspace root and the hub plugin's OpenCode service.</span><ul class=list></ul></fieldset><div class=row id=concierge-brain data-unsupported=brain><div class=grow><div class=field-title>Brain</div><div class="small muted">Not available yet: the Concierge's tools are an exact allow-list (hub, read, glob, grep, question), and Brain's MCP tools cannot be pinned by name.</div></div></div><label class=text-field id=concierge-time-zone><span class=field-title>Time zone</span><input></label><div class=stack id=concierge-grant><div class=field-title>Grant`),nk=I(`<li class="small muted">No machines yet.`),rk=I(`<li class=row><label class="check grow"><input type=radio name=concierge-machine><span><span class="small muted"> · `),ik=I(`<div class=row><p class="small muted grow">No grant: the Concierge reads and notifies; an approve it tries becomes a Decision for you, other actions are proposals you answer.</p><button type=button class="btn small">Use the safe preset</button><button type=button class="btn small">Write a grant…`),ak=I(`<button type=button class="btn small">Renew`),ok=I(`<div class=row data-concierge-grant><div class=grow><div class=small></div><div class=small data-concierge-grant-permissions></div><div class="small muted"> actions/hour</div></div><button type=button class="btn small">Edit</button><button type=button class="btn small danger">Remove`),sk=I(`<optgroup label=Projects>`),ck=I(`<optgroup label="Workspace roots">`),lk=I(`<input class=mono aria-describedby=concierge-directory-hint>`),uk=I(`<div class=stack id=concierge-directory><label class=text-field><span class=field-title>Directory</span><select class=mono aria-describedby=concierge-directory-hint><option value>Choose a directory</option><option>Other folder…</option></select></label><span class="field-desc muted small"id=concierge-directory-hint data-concierge-directory-hint>`),dk=I(`<option>`),fk=I(`<input class=mono aria-label="Other model (provider/model)"aria-describedby=concierge-model-hint placeholder=provider/model>`),pk=I(`<div class=stack id=concierge-model><label class=text-field><span class=field-title>Model</span><select class=mono aria-describedby="concierge-model-hint concierge-model-state"><option value>Machine default</option><option>Other model…</option></select></label><span class="field-desc muted small"id=concierge-model-hint>The machine default, or one of its OpenCode models (provider/model).</span><p class="small muted"id=concierge-model-state role=status data-concierge-models-state>`),mk=I(`<optgroup>`),hk=I(`<p class="field-error small"role=alert>`),gk=I(`<label class=text-field><span class=field-title></span><span class="field-desc muted small"></span><textarea rows=2>`),_k=I(`<p class="small warn"role=note data-shell-warning>`),vk=I(`<p class=error role=alert data-error=form>`),yk=I(`<form class="grant-form card"data-concierge-grant-editor novalidate><fieldset class=stack aria-label=Projects><span class=field-title>Projects</span><span class="field-desc muted small">Where it may act (subdirectories and worktrees included).</span><div class=row><input class="mono grow"aria-label="Another project directory"placeholder=/path/to/project><button type=button class="btn small">Add</button></div></fieldset><fieldset class=grant-verbs aria-label=Actions><span class=field-title>May</span></fieldset><div class=row><label class="text-field grow"><span class=field-title>Expires after</span><span class="field-desc muted small">1h to 30d; saving restarts it</span><input type=text aria-label="Expires after"></label><label class="text-field grow"><span class=field-title>Actions per hour</span><span class="field-desc muted small">1–1000</span><input type=text aria-label="Actions per hour"></label></div><div class=row><button type=submit class="btn small primary">Save grant</button><button type=button class="btn small">Cancel`),bk=I(`<label class=check><input type=checkbox><span class="mono small">`),xk=I(`<label class=check><input type=checkbox><span>`),Sk=I(`<button type=button class="btn small">Turn off quiet hours`),Ck=I(`<fieldset class=stack id=concierge-quiet><legend class=field-title>Quiet hours</legend><span class="field-desc muted small"> Held news arrives as one update when they end.</span><div class=row><label class=text-field><span class=small>Quiet from</span><input type=time aria-label="Quiet from"></label><label class=text-field><span class=small>Quiet until</span><input type=time aria-label="Quiet until"></label><button type=button class="btn small"></button></div><label class=check><input type=checkbox><span>Urgent news (a blocked or failed session, a Decision) still wakes it`),wk=I(`<fieldset class=stack id=concierge-digests><legend class=field-title>Digests</legend><span class="field-desc muted small">At these times (<!>) the Concierge sums up what changed and tells you if it matters.</span><ul class=list></ul><div><button type=button class="btn small">Add a digest`),Tk=I(`<li class="small muted">No digests.`),Ek=I(`<li class=row><input type=time><span class=digest-days></span><button type=button class="btn small danger">Remove`),Dk=I(`<label class="check small"><input type=checkbox><span>`),Ok=`/api/agent/concierge`;async function kk(){let e=es(await K(Ok));if(!e)throw Error(`The hub answered an unexpected Concierge view`);return e}async function Ak(e){if(!e)return;let{grants:t}=await K(`/api/agent/grants`);return t?.find(t=>t.id===e)}function jk(){let[t,{refetch:i,mutate:a}]=d(kk),o=()=>t.error?void 0:t(),[c,{refetch:f}]=d(()=>o()?.settings.grantID,Ak),[p,h]=u(!1),[g,_]=u(!1),[v,S]=u({}),[C,w]=u(),T=()=>gu()??o()?.status,E=0,D;x(e(()=>t.error,e=>{if(clearTimeout(D),!e)return void(E=0);E>=4||(D=setTimeout(()=>void i(),1e3*2**E++))})),x(e(()=>gu()?.state,()=>t.error&&void i(),{defer:!0})),M(()=>clearTimeout(D));let O=async(e,t)=>{h(!0);try{let n=await(await t()).json(),r=o();r&&n.settings&&a({...r,settings:n.settings}),J(e)}catch(e){J(W(e),`err`)}finally{h(!1),i(),f()}},k=(e,t=`Saved`,n={})=>{let r=o().settings;return O(t,()=>H(`${Ok}/settings`,{method:`PUT`,json:{...Es(r,e),...n}}))},A=()=>O(`Concierge on`,()=>H(`${Ok}/enable`,{method:`POST`,json:{expectedRevision:o().settings.revision,timeZone:Xt()}})),j=async()=>{if(await P(`Turn the Concierge off? Its session stops and its grant is revoked; notes and watchlist are kept.`,`Turn off`,{danger:!0}))return O(`Concierge off`,()=>H(`${Ok}/disable`,{method:`POST`,json:{expectedRevision:o().settings.revision}}))},ee=()=>O(`Restarting the Concierge`,()=>H(`${Ok}/restart`,{method:`POST`,json:{}}));return(()=>{var e=KO();return e.firstChild,y(e,n(l,{get when(){return o()},get fallback(){return(()=>{var e=JO();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${W(t.error)} `:`Loading…`})(),null),y(e,n(l,{get when(){return t.error},get children(){var e=qO();return e.$$click=()=>(E=0,void i()),e}}),null),e})()},children:e=>{let t=()=>e().settings,u=()=>ds(e().machines),d=()=>ps(t(),e().machines),h=()=>e().machines.find(e=>e.id===t().machineID);return(()=>{var x=tk(),E=x.firstChild,D=E.firstChild.firstChild.nextSibling,O=E.nextSibling,M=O.firstChild.nextSibling.nextSibling,P=O.nextSibling,F=P.nextSibling,te=F.firstChild.nextSibling,I=F.nextSibling;return I.firstChild,y(D,()=>us(T(),e().machines,N())),y(E,n(l,{get when(){return t().enabled},get children(){return[(()=>{var e=YO();return e.$$click=()=>void ee(),s(()=>e.disabled=p()),e})(),(()=>{var e=XO();return e.$$click=()=>void j(),s(()=>e.disabled=p()),e})()]}}),null),y(E,n(l,{get when(){return!t().enabled},get children(){var e=ZO();return e.$$click=()=>void A(),s(t=>{var n=p()||d()!==void 0,r=d()??``;return n!==t.e&&(e.disabled=t.e=n),r!==t.t&&b(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e}}),null),y(x,n(l,{get when(){return r(()=>!t().enabled)()&&d()},get children(){var e=QO();return y(e,d),e}}),O),y(x,n(l,{get when(){return!t().enabled},get children(){return $O()}}),O),y(x,n(l,{get when(){return r(()=>!!(t().enabled&&T()?.state===`failed`))()&&T()?.reason},get children(){var e=ek(),t=e.firstChild;t.firstChild;var n=t.nextSibling;return y(t,()=>T().reason,null),n.$$click=()=>void ee(),s(()=>n.disabled=p()),e}}),O),y(M,n(m,{get each(){return u()},get fallback(){return nk()},children:e=>(()=>{var n=rk(),r=n.firstChild.firstChild,i=r.nextSibling,a=i.firstChild;return a.firstChild,r.addEventListener(`change`,()=>{let n=v()[e.id];w(n===void 0&&t().model!==void 0?e.id:void 0),k(Ms(t(),e,X.machines,n))}),y(i,()=>e.name,a),y(a,()=>e.note,null),s(t=>{var i=e.id,a=e.eligible?`yes`:`no`,o=!e.selectable||p();return i!==t.e&&b(n,`data-concierge-machine`,t.e=i),a!==t.t&&b(n,`data-eligible`,t.t=a),o!==t.a&&(r.disabled=t.a=o),t},{e:void 0,t:void 0,a:void 0}),s(()=>r.checked=t().machineID===e.id),n})()})),y(x,n(Mk,{get settings(){return t()},get machine(){return h()},get busy(){return p()},save:k}),P),y(x,n(Nk,{get settings(){return t()},get machine(){return h()},get busy(){return p()},save:k,onModels:(e,n)=>{if(S({...v(),[e]:n}),C()!==e||t().machineID!==e)return;w(void 0);let r=Ns(t(),n);r!==t()&&k(r,`Model back to ${h()?.name??`the machine`}'s default`)}}),P),te.addEventListener(`change`,e=>{let n=e.currentTarget.value.trim()||Xt(),r=t().quietHours;k({...t(),timeZone:n,...r?{quietHours:{...r,timeZone:n}}:{}})}),y(x,n(Fk,{get settings(){return t()},get busy(){return p()},save:k}),I),y(x,n(Ik,{get settings(){return t()},get busy(){return p()},save:k}),I),y(x,n(GO,{}),I),y(I,n(l,{get when(){return t().grant},get fallback(){return(()=>{var e=ik(),n=e.firstChild.nextSibling,r=n.nextSibling;return n.$$click=()=>void k({...t(),grant:ms([t().directory])},`Grant set`),r.$$click=()=>_(!0),s(e=>{var i=p()||!t().directory,a=p()||g();return i!==e.e&&(n.disabled=e.e=i),a!==e.t&&(r.disabled=e.t=a),e},{e:void 0,t:void 0}),e})()},children:e=>(()=>{var i=ok(),a=i.firstChild,o=a.firstChild,u=o.nextSibling,d=u.nextSibling,f=d.firstChild,m=a.nextSibling,h=m.nextSibling;return y(o,()=>Cs(e()).head),y(u,()=>Cs(e()).permissions),y(d,()=>e().maxActionsPerHour,f),y(d,(()=>{var e=r(()=>!!c());return()=>e()?` · ${c().state===`active`?ws(c().expiresAt,N()):c().state}`:t().enabled?``:` · created when you turn it on`})(),null),m.$$click=()=>_(!0),y(i,n(l,{get when(){return t().enabled},get children(){var n=ak();return n.$$click=()=>void k(t(),`Grant renewed`,{grant:e()}),s(()=>n.disabled=p()),n}}),h),h.$$click=()=>void k({...t(),grant:void 0},`Grant removed`),s(e=>{var t=p()||g(),n=p();return t!==e.e&&(m.disabled=e.e=t),n!==e.t&&(h.disabled=e.t=n),e},{e:void 0,t:void 0}),i})()}),null),y(I,n(l,{get when(){return g()},get children(){return n(Pk,{get spec(){return t().grant},get directory(){return t().directory},get machineID(){return t().machineID},get revision(){return t().revision},onClose:()=>_(!1),onSaved:e=>{let t=o();t&&a({...t,settings:e}),_(!1),J(`Grant saved`),i(),f()}})}}),null),s(()=>b(x,`data-concierge-state`,T()?.state??`disabled`)),s(()=>te.value=t().timeZone),x})()}}),null),e})()}function Mk(t){let r=()=>ks(t.machine,X.machines),i=()=>[...r().projects,...r().roots],[a,o]=u(!1);x(e(()=>t.machine?.id,()=>o(!1),{defer:!0}));let c=()=>a()?Ds:js(t.settings.directory,i()),d=e=>{e!==t.settings.directory&&t.save({...t.settings,directory:e})},f=()=>r().roots,p=()=>As(t.machine,r());return(()=>{var e=uk(),i=e.firstChild,a=i.firstChild.nextSibling,u=a.firstChild.nextSibling,h=i.nextSibling;return a.addEventListener(`change`,e=>{let t=e.currentTarget.value;if(t===`__other__`)return o(!0);o(!1),d(t||void 0)}),y(a,n(l,{get when(){return r().projects.length},get children(){var e=sk();return y(e,n(m,{get each(){return r().projects},children:e=>(()=>{var t=dk();return t.value=e,y(t,e),t})()})),e}}),u),y(a,n(l,{get when(){return f().length},get children(){var e=ck();return y(e,n(m,{get each(){return f()},children:e=>(()=>{var t=dk();return t.value=e,y(t,e),t})()})),e}}),u),u.value=Ds,y(h,p),y(e,n(l,{get when(){return c()===Ds},get children(){var e=lk();return e.addEventListener(`change`,e=>d(e.currentTarget.value.trim()||void 0)),s(n=>{var r=`Other folder on ${t.machine?.name??`the machine`}`,i=t.machine?.roots[0]?`${t.machine.roots[0].replace(/\/+$/,``)}/…`:`/path/to/repo`,a=t.busy;return r!==n.e&&b(e,`aria-label`,n.e=r),i!==n.t&&b(e,`placeholder`,n.t=i),a!==n.a&&(e.disabled=n.a=a),n},{e:void 0,t:void 0,a:void 0}),s(()=>e.value=t.settings.directory??``),e}}),null),s(()=>a.disabled=!t.machine||t.busy),s(()=>a.value=c()),e})()}function Nk(t){let r=()=>Is(t.machine),[i,{refetch:a}]=d(()=>t.machine&&!r()?t.machine.id:void 0,async e=>({id:e,options:Fs(await K(`${Ok}/machines/${encodeURIComponent(e)}/models`))})),o=()=>i.error||i.loading?void 0:i()?.id===t.machine?.id?i():void 0;x(e(o,e=>e&&t.onModels(e.id,e.options.map(e=>e.value))));let c=()=>o()?.options??[],f=()=>[...new Set(c().map(e=>e.provider))],[p,h]=u(!1);x(e(()=>t.machine?.id,()=>h(!1),{defer:!0}));let g=()=>!o()&&!i.error&&t.settings.model?t.settings.model:void 0,_=()=>p()?Ds:g()??js(t.settings.model,c().map(e=>e.value)),v=e=>{e!==t.settings.model&&t.save({...t.settings,model:e})},S=()=>r()?r():i.loading?`Loading ${t.machine?.name??`the machine`}'s models…`:i.error?`Could not load the models: ${W(i.error)}`:!o()||c().length?``:`Its OpenCode reports no models: type one, or keep the machine default.`;return(()=>{var e=pk(),r=e.firstChild,o=r.firstChild.nextSibling,u=o.firstChild.nextSibling,d=r.nextSibling.nextSibling;return o.addEventListener(`change`,e=>{let t=e.currentTarget.value;if(t===`__other__`)return h(!0);h(!1),v(t||void 0)}),y(o,n(l,{get when(){return g()},children:e=>(()=>{var t=dk();return y(t,e),s(()=>t.value=e()),t})()}),u),y(o,n(m,{get each(){return f()},children:e=>(()=>{var t=mk();return b(t,`label`,e),y(t,n(m,{get each(){return c().filter(t=>t.provider===e)},children:e=>(()=>{var t=dk();return y(t,()=>e.label),s(()=>t.value=e.value),t})()})),t})()}),u),u.value=Ds,y(d,S,null),y(d,n(l,{get when(){return i.error},get children(){return[` `,(()=>{var e=qO();return e.$$click=()=>void a(),e})()]}}),null),y(e,n(l,{get when(){return _()===Ds},get children(){var e=fk();return e.addEventListener(`change`,e=>v(e.currentTarget.value.trim()||void 0)),s(()=>e.disabled=t.busy),s(()=>e.value=t.settings.model??``),e}}),null),s(e=>{var n=t.busy,r=i.loading?`true`:`false`;return n!==e.e&&(o.disabled=e.e=n),r!==e.t&&b(o,`aria-busy`,e.t=r),e},{e:void 0,t:void 0}),s(()=>o.value=_()),e})()}function Pk(e){let[t,r]=u(gs(e.spec,e.directory)),[i,a]=u({}),[o,c]=u(``),[d,f]=u(!1),[p,h]=u(``),g=(e,n)=>r({...t(),[e]:n}),_=()=>(X.machines??[]).find(t=>t.id===e.machineID),v=()=>Ss(_(),e.directory,t().projects),x=async n=>{n.preventDefault(),c(``);let r=ys(t());if(!r.ok)return a(r.errors);a({}),f(!0);try{let t=await(await H(`${Ok}/settings`,{method:`PUT`,json:{grant:r.body,expectedRevision:e.revision}})).json();e.onSaved(t.settings)}catch(e){let t=W(e),n=e instanceof G&&e.status===400?xs(t):void 0;n?a({[n]:t}):c(t)}finally{f(!1)}},S=e=>n(l,{get when(){return i()[e.field]},get children(){var t=hk();return y(t,()=>i()[e.field]),s(()=>b(t,`data-error`,e.field)),t}}),C=e=>(()=>{var r=gk(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling;return y(i,()=>e.label),y(a,()=>e.hint),o.$$input=t=>g(e.field,t.currentTarget.value),y(r,n(S,{get field(){return e.field}}),null),s(t=>{var n=e.label,r=e.placeholder??``;return n!==t.e&&b(o,`aria-label`,t.e=n),r!==t.t&&b(o,`placeholder`,t.t=r),t},{e:void 0,t:void 0}),s(()=>o.value=t()[e.field]),r})();return(()=>{var r=yk(),i=r.firstChild,a=i.firstChild.nextSibling.nextSibling,c=a.firstChild,u=c.nextSibling,f=i.nextSibling;f.firstChild;var _=f.nextSibling,w=_.firstChild,T=w.firstChild.nextSibling.nextSibling,E=w.nextSibling,D=E.firstChild.nextSibling.nextSibling,O=_.nextSibling,k=O.firstChild,A=k.nextSibling;return r.addEventListener(`submit`,e=>void x(e)),y(i,n(m,{get each(){return v()},children:e=>(()=>{var n=bk(),r=n.firstChild,i=r.nextSibling;return r.addEventListener(`change`,n=>g(`projects`,n.currentTarget.checked?[...t().projects,e]:t().projects.filter(t=>t!==e))),b(r,`aria-label`,e),y(i,e),s(()=>r.checked=t().projects.includes(e)),n})()}),a),c.$$input=e=>h(e.currentTarget.value),u.$$click=()=>(g(`projects`,[...t().projects,p().trim()]),h(``)),y(i,n(S,{field:`projects`}),null),y(f,n(m,{each:hs,children:e=>(()=>{var n=xk(),r=n.firstChild,i=r.nextSibling;return r.addEventListener(`change`,n=>g(`allow`,n.currentTarget.checked?[...t().allow,e]:t().allow.filter(t=>t!==e))),b(r,`aria-label`,e),y(i,e),s(()=>r.checked=t().allow.includes(e)),n})()}),null),y(r,n(S,{field:`allow`}),_),y(r,n(C,{field:`permit`,label:`Permissions it may approve`,hint:`Patterns action[:glob], one per line, for example read or edit. Shell, outside folders and tools always need your tap.`,placeholder:`read`}),_),y(r,n(l,{get when(){return bs(t().permit)},get children(){var e=_k();return y(e,()=>bs(t().permit)),e}}),_),y(r,n(C,{field:`never`,label:`Never`,hint:`Patterns it may never approve, one per line; never wins.`,placeholder:`shell:rm *`}),_),T.$$input=e=>g(`expires`,e.currentTarget.value),y(w,n(S,{field:`expires`}),null),D.$$input=e=>g(`maxActionsPerHour`,e.currentTarget.value),y(E,n(S,{field:`maxActionsPerHour`}),null),y(r,n(l,{get when(){return o()},get children(){var e=vk();return y(e,o),e}}),O),V(A,`click`,e.onClose,!0),s(e=>{var t=!p().trim(),n=d();return t!==e.e&&(u.disabled=e.e=t),n!==e.t&&(k.disabled=e.t=n),e},{e:void 0,t:void 0}),s(()=>c.value=p()),s(()=>T.value=t().expires),s(()=>D.value=t().maxActionsPerHour),r})()}function Fk(e){let[t,i]=u(e.settings.quietHours?.start??``),[a,o]=u(e.settings.quietHours?.end??``);return(()=>{var c=Ck(),u=c.firstChild.nextSibling,d=u.firstChild,f=u.nextSibling,p=f.firstChild,m=p.firstChild.nextSibling,h=p.nextSibling,g=h.firstChild.nextSibling,_=h.nextSibling,v=f.nextSibling.firstChild;return y(u,(()=>{var t=r(()=>!!e.settings.quietHours);return()=>t()?`Quiet ${e.settings.quietHours.start}–${e.settings.quietHours.end} (${e.settings.quietHours.timeZone}).`:`Off: news wakes the Concierge any time.`})(),d),m.$$input=e=>i(e.currentTarget.value),g.$$input=e=>o(e.currentTarget.value),_.$$click=()=>void e.save({...e.settings,quietHours:{start:t(),end:a(),timeZone:e.settings.timeZone}},`Quiet hours saved`),y(_,()=>e.settings.quietHours?`Save quiet hours`:`Turn on quiet hours`),y(f,n(l,{get when(){return e.settings.quietHours},get children(){var t=Sk();return t.$$click=()=>void e.save({...e.settings,quietHours:void 0},`Quiet hours off`),s(()=>t.disabled=e.busy),t}}),null),v.addEventListener(`change`,t=>void e.save({...e.settings,quietAllowsUrgent:t.currentTarget.checked})),s(n=>{var r=e.busy||!t()||!a(),i=e.busy;return r!==n.e&&(_.disabled=n.e=r),i!==n.t&&(v.disabled=n.t=i),n},{e:void 0,t:void 0}),s(()=>m.value=t()),s(()=>g.value=a()),s(()=>v.checked=e.settings.quietAllowsUrgent),c})()}function Ik(e){let t=()=>e.settings.digests,r=(t,n=`Digests saved`)=>void e.save({...e.settings,digests:t},n),i=(e,n)=>{let i=t().map((t,r)=>r===e?{at:n.at??t.at,...`days`in n?n.days?{days:n.days}:{}:t.days?{days:t.days}:{}}:t);JSON.stringify(i)!==JSON.stringify(t())&&r(i)};return(()=>{var a=wk(),o=a.firstChild.nextSibling,c=o.firstChild.nextSibling;c.nextSibling;var l=o.nextSibling,u=l.nextSibling.firstChild;return y(o,()=>e.settings.timeZone,c),y(l,n(m,{get each(){return t()},get fallback(){return Tk()},children:(a,o)=>(()=>{var c=Ek(),l=c.firstChild,u=l.nextSibling,d=u.nextSibling;return l.addEventListener(`change`,e=>e.currentTarget.value&&i(o(),{at:e.currentTarget.value})),y(u,n(m,{each:rc,children:(t,n)=>(()=>{var r=Dk(),c=r.firstChild,l=c.nextSibling;return c.addEventListener(`change`,e=>{let t=ic(a.days,n(),e.currentTarget.checked);JSON.stringify(t)===JSON.stringify(a.days)?e.currentTarget.checked=!0:i(o(),{days:t})}),y(l,t),s(n=>{var r=`Digest ${o()+1} on ${t}`,i=e.busy;return r!==n.e&&b(c,`aria-label`,n.e=r),i!==n.t&&(c.disabled=n.t=i),n},{e:void 0,t:void 0}),s(()=>c.checked=!a.days||a.days.includes(n())),r})()})),d.$$click=()=>r(t().filter((e,t)=>t!==o()),`Digest removed`),s(t=>{var n=o(),r=`Digest ${o()+1} time`,i=e.busy,a=e.busy,s=`Remove digest ${o()+1}`;return n!==t.e&&b(c,`data-digest`,t.e=n),r!==t.t&&b(l,`aria-label`,t.t=r),i!==t.a&&(l.disabled=t.a=i),a!==t.o&&(d.disabled=t.o=a),s!==t.i&&b(d,`aria-label`,t.i=s),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),s(()=>l.value=a.at),c})()})),u.$$click=()=>r([...t(),{at:`08:00`}],`Digest added`),s(()=>u.disabled=e.busy||t().length>=4),a})()}B([`click`,`input`]);var Lk=e=>`/api/sessions/${encodeURIComponent(e)}/context-cards`,Rk=(e,t)=>`${Lk(e)}/${encodeURIComponent(t)}/refresh`,zk=e=>`/api/context-cards/primary?sessions=${encodeURIComponent(e.join(`,`))}`,Bk=`/api/settings/context-cards`,Vk=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:void 0,Hk=e=>typeof e==`string`,Uk=e=>typeof e==`number`&&Number.isFinite(e);function Wk(e){if(!Array.isArray(e))return;let t=e.map(Vk).filter(e=>!!e&&Hk(e.label)&&Hk(e.value)).map(e=>({label:e.label,value:e.value}));return t.length===e.length&&t.length?t:void 0}function Gk(e){let t=Vk(e);if(!t||!Hk(t.provider)||!Hk(t.sessionID)||!Hk(t.title)||!Hk(t.headline)||!Uk(t.generatedAt))return;let n=Wk(t.fields);return{provider:t.provider,sessionID:t.sessionID,title:t.title,headline:t.headline,body:Hk(t.body)?t.body:``,...n?{fields:n}:{},generatedAt:t.generatedAt,...Hk(t.model)?{model:t.model}:{},inputsHash:Hk(t.inputsHash)?t.inputsHash:``,version:Uk(t.version)?t.version:0,trigger:Hk(t.trigger)?t.trigger:`manual`,...t.primary===!0?{primary:!0}:{}}}function Kk(e){let t=Vk(e)??{};return{cards:(Array.isArray(t.cards)?t.cards:[]).map(Gk).filter(e=>!!e),providers:(Array.isArray(t.providers)?t.providers:[]).map(Vk).filter(e=>!!e&&Hk(e.id)&&Hk(e.label)).map(e=>({id:e.id,label:e.label,primary:e.primary===!0,usesModel:e.usesModel===!0})),enabled:t.enabled===!0,configured:t.configured===!0}}function qk(e){return e<6e4?`just now`:e<36e5?`${Math.floor(e/6e4)}m ago`:e<864e5?`${Math.floor(e/36e5)}h ago`:`${Math.floor(e/864e5)}d ago`}var Jk=(e,t)=>`updated ${qk(Math.max(0,t-e.generatedAt))}${e.model?` · ${e.model}`:``}`,Yk={disabled:`Context cards are off. Turn them on in Settings › Concierge.`,unchanged:`Up to date: nothing changed since this card.`,rate_limited:`Refreshed a moment ago. Try again shortly.`,backoff:`The model failed several times. Cards pause for a while.`,circuit:`The model is failing for this hub. Cards pause for a few minutes.`,weaker:`The session is unreachable now. The last card stays.`,"no-model":`No model is configured for context cards.`,budget:`Today's context card budget is used up.`,empty:`Nothing to summarise yet.`,unknown:`This card is not available.`,gone:`The session is gone.`};function Xk(e){let t=Vk(e)??{};if(t.outcome!==`generated`)return t.outcome===`skipped`?Yk[String(t.reason)]??`No new card this time.`:`The card could not be made. Try again later.`}var Zk=(e,t)=>e.type===`contextCard`&&e.sessionID===t;function Qk(e){let t=Vk(e)??{},n=Vk(t.model),r=Vk(t.usage),i=Vk(r?.limits);return{enabled:t.enabled===!0,available:t.available===!0,configured:t.configured===!0,...n&&Hk(n.provider)&&Hk(n.model)?{model:{provider:n.provider,model:n.model,keySource:Hk(n.keySource)?n.keySource:``}}:{},...r&&Uk(r.calls)&&Uk(r.tokens)&&i&&Uk(i.calls)&&Uk(i.tokens)?{usage:{calls:r.calls,tokens:r.tokens,limits:{calls:i.calls,tokens:i.tokens}}}:{}}}var $k=class{options;cards=new Map;requested=new Set;queue=[];scheduled=!1;listeners=new Set;constructor(e){this.options=e}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}line(e){return this.requested.has(e)||this.enqueue(e),this.cards.get(e)?.headline}card(e){return this.cards.get(e)??void 0}message(e){e.type===`contextCard`&&e.primary===!0&&typeof e.sessionID==`string`&&(this.requested.delete(e.sessionID),this.enqueue(e.sessionID))}clear(){let e=[...this.cards].filter(([,e])=>e).map(([e])=>e);this.cards.clear(),this.requested.clear();for(let t of e)for(let e of this.listeners)e(t)}put(e){e.primary&&this.set(e.sessionID,e)}set(e,t){let n=this.cards.get(e)?.headline;if(this.cards.set(e,t),this.requested.add(e),n!==(t?.headline??void 0))for(let t of this.listeners)t(e)}enqueue(e){this.requested.add(e),this.queue.push(e),!this.scheduled&&(this.scheduled=!0,this.options.schedule(()=>void this.flush()))}async flush(){this.scheduled=!1;let e=[...new Set(this.queue)];this.queue=[];let t=[];for(let n=0;n<e.length;n+=200)t.push(e.slice(n,n+200));await Promise.all(t.map(async e=>{try{let t=await this.options.fetch(e);for(let n of e)this.set(n,Gk(t[n])??null)}catch{for(let t of e)this.requested.delete(t)}}))}},[eA,tA]=u(0),nA=new $k({fetch:async e=>(await K(zk(e))).cards??{},schedule:e=>void setTimeout(e,30)});nA.subscribe(()=>tA(e=>e+1)),Fu(e=>nA.message(e));function rA(e){return eA(),nA.line(e)}za(rA);var iA=e=>nA.put(e),aA=()=>nA.clear(),oA=I(`<div class=context-cards-settings data-context-cards-settings><p class="muted small">A short, automatically updated card per session (Details rail, session list, Concierge board) that helps you pick its work back up. Off until you turn it on: nothing is sent to a model before.</p><p class="muted small"data-context-cards-sent>When on, for sessions you used in the last day, the hub sends the model (after a turn ends, when a session gets blocked, when you come back, every 30 minutes, and on Refresh): the title, intent, state, what it waits on, and the newest messages (yours, the agent's and error messages, each cut to 1,200 characters; tools by name only). Known key, token and password formats are redacted first (private keys, API keys and tokens, AWS keys, passwords in URLs, password=/secret=/token= values, Authorization headers); other secrets written in the text may still be sent.`),sA=I(`<p class="muted small">`),cA=I(`<ul class=switches><li><label class=switch><span class=notify-kind><span>Context cards</span><span class="small muted"data-context-cards-delete-note>Pick-up summaries of your sessions (off until you turn it on). Turning this off deletes saved cards.</span></span><input type=checkbox data-context-cards-toggle>`),lA=I(`<p class="muted small">Turned off for this hub (HUB_CONTEXT_CARDS=off or contextCards.enabled false).`),uA=I(`<p class="muted small">No model configured: set an OpenRouter key in Speech, or contextCards.model in hub.json.`),dA=I(`<p class="muted small">Model: <span class=mono></span> (<!>)`),fA=I(`<p class="muted small">Daily budget: <!> / <!> calls · <!> / <!> tokens used today`),pA=I(`<p class=field-error>`);function mA(){let[e,{mutate:t}]=d(async()=>Qk(await K(Bk))),[i,a]=u(``),[o,c]=u(!1),f=async e=>{c(!0),a(``);try{t(Qk(await(await H(Bk,{method:`PUT`,json:{enabled:e}})).json())),e||aA()}catch(e){a(W(e))}finally{c(!1)}};return(()=>{var t=oA();return t.firstChild.nextSibling,y(t,n(l,{get when(){return e()},get fallback(){return(()=>{var t=sA();return y(t,()=>e.error?`Could not load the context card settings.`:`Loading…`),t})()},children:e=>[(()=>{var t=cA(),n=t.firstChild.firstChild.firstChild.nextSibling;return n.addEventListener(`change`,e=>void f(e.currentTarget.checked)),s(()=>n.disabled=o()||!e().available),s(()=>n.checked=e().enabled),t})(),n(l,{get when(){return!e().available},get children(){return lA()}}),n(l,{get when(){return r(()=>!!e().available)()&&!e().configured},get children(){return uA()}}),n(l,{get when(){return e().model},children:e=>(()=>{var t=dA(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(n,()=>e().model),y(t,()=>e().provider,r),y(t,()=>e().keySource===`speech`?`, the speech key`:``,r),t})()}),n(l,{get when(){return e().usage},children:e=>(()=>{var t=fA(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,y(t,()=>e().calls,n),y(t,()=>e().limits.calls,r),y(t,()=>e().tokens.toLocaleString(),i),y(t,()=>e().limits.tokens.toLocaleString(),a),t})()})]}),null),y(t,n(l,{get when(){return i()},children:e=>(()=>{var t=pA();return y(t,e),t})()}),null),t})()}function hA(e,t){let n=Math.max(0,Math.ceil((e-t)/1e3));return`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}`}function gA(e,t){return t.find(t=>!e.has(t.id))}function _A(e,t,n){let r=t?Date.parse(t):NaN;return Number.isFinite(r)?n+Math.max(0,e-r-1e3):e}var vA={L:0,M:1,Q:2,H:3},yA={L:1,M:0,Q:3,H:2},bA=[[-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]],xA=[[-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]],SA=(e,t)=>!!(e>>>t&1);function CA(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 wA(e,t){let n=vA[t];return Math.floor(CA(e)/8)-bA[n][e]*xA[n][e]}function TA(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 EA(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]=TA(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=TA(n,2)}return t}function DA(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]^=TA(t,e))}return n}function OA(e,t,n){let r=vA[n],i=xA[r][t],a=bA[r][t],o=Math.floor(CA(t)/8),s=i-o%i,c=Math.floor(o/i),l=EA(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=DA(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 kA(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=wA(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 AA=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=yA[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,SA(r,e));this.set(8,7,SA(r,6)),this.set(8,8,SA(r,7)),this.set(7,8,SA(r,8));for(let e=9;e<15;e++)this.set(14-e,8,SA(r,e));for(let e=0;e<8;e++)this.set(i-1-e,8,SA(r,e));for(let e=8;e<15;e++)this.set(8,i-15+e,SA(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,SA(t,e)),this.set(r,n,SA(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]=SA(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 jA(e,t={}){let n=t.ecc??`M`,r=new TextEncoder().encode(e),i=1;for(;4+(i<=9?8:16)+r.length*8>wA(i,n)*8;)if(++i>40)throw Error(`Text too long for a QR code`);let a=new AA(i,n);a.codewords(OA(kA(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 MA(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 NA=.8,PA=1.8,FA=.05,IA=`hub.fontScale`,LA=e=>Math.min(PA,Math.max(NA,e)),RA=(e,t)=>Number((Math.round(e/t)*t).toFixed(2));function zA(e){return Number.isFinite(e)?RA(LA(e),FA):1}function BA(e){return e?zA(Number(e)):1}function VA(e,t,n){return zA(!(t>0)||!(n>0)?e:n/t*e)}function HA(e,t){let n=LA((Number.isFinite(e)?e:1)*Math.exp(-t*.01));return Number(n.toFixed(3))}var UA=e=>`${Math.round(e*100)}%`;function WA(e){try{return BA(e.getItem(IA))}catch{return 1}}function GA(e,t){let n=zA(t);try{n===1?e.removeItem(IA):e.setItem(IA,String(n))}catch{}return n}var KA=()=>typeof localStorage>`u`?void 0:localStorage,[qA,JA]=u(KA()?WA(KA()):1),YA=qA;function XA(e){document.documentElement.style.setProperty(`--font-scale`,String(e))}var ZA;function QA(e,t={}){let n=t.settle===!1?e:zA(e);JA(n),XA(n),clearTimeout(ZA);let r=()=>{let e=KA();if(!e)return;let t=GA(e,n);t!==qA()&&(JA(t),XA(t))};t.settle===!1?ZA=setTimeout(r,250):r()}var $A=`.scroller, .home-scroll`,ej=e=>e instanceof Element&&e.closest($A)!==null;function tj(e=document){XA(qA());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`&&ej(e.target)&&(t.set(e.pointerId,{x:e.clientX,y:e.clientY}),t.size===2&&(n={scale:qA(),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=VA(n.scale,n.distance,r());e!==qA()&&QA(e,{settle:!1})}},o=e=>{t.delete(e.pointerId)&&t.size<2&&n&&(n=void 0,QA(qA()))},s=e=>{e.touches.length>=2&&ej(e.target)&&e.preventDefault()},c=e=>{e.ctrlKey&&ej(e.target)&&(e.preventDefault(),QA(HA(qA(),e.deltaMode===1?e.deltaY*16:e.deltaY),{settle:!1}))},l,u=e=>{ej(e.target)&&(e.preventDefault(),e.type===`gesturestart`?l=qA():e.type===`gesturechange`&&l!==void 0&&e.scale?QA(VA(l,1,e.scale),{settle:!1}):e.type===`gestureend`&&(l=void 0,QA(qA())))},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 nj=[`light`,`system`,`dark`],rj=`hub.theme`;function ij(e){return e===`light`||e===`dark`||e===`system`?e:`system`}function aj(e){return e===`system`?void 0:e}function oj(){try{return ij(localStorage.getItem(rj))}catch{return`system`}}var[sj,cj]=u(oj());function lj(e){let t=aj(e);t?document.documentElement.dataset.theme=t:delete document.documentElement.dataset.theme;try{e===`system`?localStorage.removeItem(rj):localStorage.setItem(rj,e)}catch{}cj(e)}var uj=[`macos`,`linux`,`windows`],dj={macos:`macOS`,linux:`Linux`,windows:`Windows`},fj=`~/projects`,pj=200,mj=[{id:`session-only`,label:`OpenCode only`,description:`Connects OpenCode on the machine to this hub; its sessions show up here.`},{id:`launch-node`,label:`+ launch node`,description:`Also runs a launch node, so you can start sessions on the machine from here, in a workspace folder.`},{id:`full-harness`,label:`All harnesses`,description:`OpenCode, Claude Code and Codex with their spokes, and the launch node.`}],hj=new Set([`session-only`,`launch-node`]),gj=e=>uj.includes(e);function _j(e,t){let n=gj(t)?t:`linux`,r=(e.userAgentData?.platform??``).toLowerCase(),i=e.userAgent??``;return r===`android`||r===`ios`||/Android|iPhone|iPad|iPod/.test(i)||/Macintosh/.test(i)&&(e.maxTouchPoints??0)>1?n:r===`windows`?`windows`:r===`macos`?`macos`:r===`linux`||r===`chrome os`||r===`chromeos`?`linux`:/Windows/.test(i)?`windows`:/Macintosh|Mac OS X/.test(i)?`macos`:/Linux|X11|CrOS/.test(i)?`linux`:n}var vj=(e,t)=>e!==`windows`||hj.has(t),yj=e=>mj.map(t=>({...t,comingSoon:!vj(e,t.id)}));function bj(e){let t=e.replace(/\\/g,`/`);return/^[a-z]:\//.test(t)?t[0].toUpperCase()+t.slice(1):t}function xj(e,t=`linux`){let n=t===`windows`;if(!e)return`Give a folder, e.g. ~/projects.`;if(n){if(/^[\\/]{2}/.test(e))return`Network (UNC) folders are not supported: use a folder on a drive, e.g. C:\\Users\\you\\projects.`;e=bj(e)}if(e.length>pj)return`At most ${pj} characters.`;let r=n&&/^[A-Z]:\//.test(e),i=r?e.slice(2):e;if(!/^[A-Za-z0-9._/~-]+$/.test(i))return`Use only letters, digits and . _ - ~ / (no spaces or shell characters).`;if(n){if(!r&&!e.startsWith(`~/`))return`Start with a drive (C:\\) or ~\\.`}else if(!e.startsWith(`/`)&&!e.startsWith(`~/`))return`Start with / or ~/.`;if(e.includes(`//`))return`No empty folder names (//).`;if(e.split(`/`).includes(`..`))return`No .. in the path.`}function Sj(e){try{let t=new URL(e);return t.protocol===`https:`||t.protocol===`http:`?t.origin:void 0}catch{return}}function Cj(e){let t=Sj(e.origin);if(!t)return{ok:!1,error:`This hub has no usable public URL (http or https).`};if(!vj(e.os,e.profile))return{ok:!1,error:`${mj.find(t=>t.id===e.profile)?.label??e.profile} is coming soon on ${dj[e.os]}.`};let n=new URLSearchParams;if(e.profile!==`session-only`&&n.set(`profile`,e.profile),e.profile===`launch-node`){let t=e.root||`~/projects`,r=xj(t,e.os);if(r)return{ok:!1,error:`Workspace folder: ${r}`};let i=e.os===`windows`?bj(t):t;i!==`~/projects`&&n.set(`root`,i)}e.profile!==`session-only`&&e.activate&&n.set(`activate`,`1`);let r=n.toString(),i=`${t}/${e.os===`windows`?`install.ps1`:`install.sh`}${r?`?${r}`:``}`;return i.includes(`'`)?{ok:!1,error:`The command would contain a quote.`}:{ok:!0,command:e.os===`windows`?`irm '${i}' | iex`:`curl -fsSL '${i}' | sh`}}var wj=/^(\s{0,3})(`{3,}|~{3,})\s*([^\s`]*)/,Tj=/^\s{0,3}(#{1,6})(?:\s+(.*))?$/,Ej=/^\s{0,3}(={2,}|-{3,})\s*$/,Dj=/^\s{0,3}>\s?(.*)$/,Oj=/^(\s*)([-*+]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/,kj=/^\[([ xX])\](?:\s+(.*))?$/,Aj=/^:?-+:?$/,jj=e=>e.length-e.trimStart().length,Mj=(e,t)=>e.slice(Math.min(t,jj(e))),Nj=e=>wj.test(e);function Pj(e){let t=0;for(;t<e.length&&/\s/.test(e[t]);)t++;let n=e[t];if(t>3||n!==`-`&&n!==`*`&&n!==`_`)return!1;let r=0;for(;t<e.length;t++)if(e[t]===n)r++;else if(!/\s/.test(e[t]))return!1;return r>=3}var Fj=e=>Nj(e)||Tj.test(e)||Pj(e)||Dj.test(e)||Oj.test(e),Ij=32,Lj=20;function Rj(e,t={}){let n=String(e??``).replace(/\r\n?/g,`
|
|
17
|
+
`).split(`
|
|
18
|
+
`).map(e=>e.replace(/^[ \t]+/,e=>e.replace(/\t/g,` `))),r=!!t.streaming,i=zj(n,{streaming:r},!0,0).blocks;return Yj(i,r?Jj(i):void 0)}function zj(e,t,n,r){if(r>Ij)return Bj(e);let i=[],a=[],o=!1,s=!1,c=!1,l=()=>{o&&s&&(c=!0),o=!1,s=!0},u=()=>{a.length&&i.push({type:`paragraph`,text:a.join(`
|
|
19
|
+
`)}),a=[]};for(let s=0;s<e.length;s++){let c=e[s];if(!c.trim()){u(),o=!0;continue}let d=wj.exec(c);if(d){u(),l();let[,t,n]=d,r=[];for(s++;s<e.length;s++){let i=/^\s*(`{3,}|~{3,})\s*$/.exec(e[s]);if(i&&i[1][0]===n[0]&&i[1].length>=n.length)break;r.push(Mj(e[s],t.length))}i.push({type:`code`,lang:d[3]??``,text:r.join(`
|
|
20
|
+
`)});continue}if(a.length){let e=Ej.exec(c);if(e){i.push({type:`heading`,level:e[1][0]===`=`?1:2,text:a.join(`
|
|
21
|
+
`)}),a=[];continue}}let f=Tj.exec(c);if(f){u(),l(),i.push({type:`heading`,level:f[1].length,text:Hj(f[2]??``).trim()});continue}if(Pj(c)){u(),l(),i.push({type:`rule`});continue}let p=qj(e,s,t.streaming&&n);if(p){u(),l(),i.push(p.block),s=p.end-1;continue}if(Dj.test(c)){u(),l();let a=[],o=s;for(;o<e.length;o++){let t=Dj.exec(e[o]);if(t)a.push(t[1]);else if(e[o].trim()&&a.at(-1)?.trim()&&!Fj(e[o]))a.push(e[o]);else break}i.push({type:`quote`,blocks:zj(a,t,n&&o===e.length,r+1).blocks}),s=o-1;continue}let m=Oj.exec(c);if(m&&(!a.length||Uj(m[2]))){u(),l();let a=Wj(e,s,t,n,r);i.push(a.block),s=a.end-1,a.trailingBlank&&(o=!0)}else a.length||l(),a.push(c.trim())}return u(),{blocks:i,loose:c,trailingBlank:o}}function Bj(e){let t=[],n=[];for(let r of e)r.trim()?n.push(r.trim()):n.length&&(t.push({type:`paragraph`,text:n.join(`
|
|
22
|
+
`)}),n=[]);return n.length&&t.push({type:`paragraph`,text:n.join(`
|
|
23
|
+
`)}),{blocks:t,loose:!1,trailingBlank:!e.at(-1)?.trim()}}var Vj=e=>e!==void 0&&Qj.test(e);function Hj(e){let t=e.length;for(;Vj(e[t-1]);)t--;let n=t;for(;e[n-1]===`#`;)n--;if(n===t||n>0&&!Vj(e[n-1]))return e;for(;Vj(e[n-1]);)n--;return e.slice(0,n)}var Uj=e=>!/\d/.test(e)||/^0*1[.)]$/.test(e);function Wj(e,t,n,r,i){let a=Oj.exec(e[t]),o=/\d/.test(a[2]),s=a[2].slice(-1),c=[],l=!1,u=!1,d=t;for(;d<e.length;){let t=Oj.exec(e[d]);if(!t||/\d/.test(t[2])!==o||t[2].slice(-1)!==s)break;c.length&&u&&(l=!0);let a=t[1].length,f=t[3]?.replace(/\t/g,` `).length??0,p=a+t[2].length+(f>=1&&f<=4?f:1),m=[f>4?`${` `.repeat(f-1)}${t[4]??``}`.trim():t[4]??``],h,g=e=>{if(h){let t=/^\s*(`{3,}|~{3,})\s*$/.exec(e);t&&t[1][0]===h[0]&&t[1].length>=h.length&&(h=void 0)}else{let t=wj.exec(e);t&&(h=t[2])}};g(m[0]);let _=d+1,v=0;for(;_<e.length;_++){let t=e[_];if(!t.trim()){v++;continue}let n=jj(t),r;if(r=h?!0:v?n>=Math.min(p,a+2):n>=p?!0:Oj.test(t)?n>=a+2:n>a||!Fj(t)&&!Nj(m.at(-1)),!r)break;for(;v;v--)m.push(``);let i=Mj(t,p);m.push(i),g(i)}u=v>0;let y=kj.exec(m[0]),b=zj(y?[y[2]??``,...m.slice(1)]:m,n,r&&_===e.length,i+1);b.loose&&(l=!0),c.push({...y?{checked:y[1]!==` `}:{},blocks:b.blocks}),d=_}let f=o?Number(a[2].slice(0,-1)):void 0;return{block:{type:`list`,ordered:o,...o?{start:f}:{},loose:l,items:c},end:d,trailingBlank:u}}function Gj(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 Kj=e=>{let t=e.trim(),n=t.startsWith(`:`),r=t.length>1&&t.endsWith(`:`);return n&&r?`center`:r?`right`:n?`left`:null};function qj(e,t,n){let r=e[t];if(!r.includes(`|`))return;let i=Gj(r),a=e[t+1],o;if(a!==void 0){let r=Gj(a),s=t+1===e.length-1;r.length===i.length&&r.every(e=>Aj.test(e))?o=r.map(Kj):s&&/^[\s|:-]*$/.test(a)&&(a.includes(`-`)||n)&&a.includes(`|`)&&r.length<=i.length&&(o=i.map((e,t)=>r[t]&&Aj.test(r[t])?Kj(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(`|`)||Nj(t)||Dj.test(t)||Tj.test(t))break;s.push(Gj(t).slice(0,i.length))}return{block:{type:`table`,align:o,head:i,rows:s},end:Math.min(c,e.length)}}function Jj(e){let t=e.at(-1);if(t){if(t.type===`paragraph`||t.type===`heading`)return{node:t};if(t.type===`quote`)return Jj(t.blocks);if(t.type===`list`)return Jj(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 Yj(e,t){let n=e=>t?.node===e;return e.map(e=>{switch(e.type){case`paragraph`:return{type:`paragraph`,children:hM(e.text,{streaming:n(e)})};case`heading`:return{type:`heading`,level:e.level,children:hM(e.text,{streaming:n(e)})};case`quote`:return{type:`quote`,blocks:Yj(e.blocks,t)};case`list`:return{...e,items:e.items.map(e=>({...e.checked===void 0?{}:{checked:e.checked},blocks:Yj(e.blocks,t)}))};case`table`:{let r=(r,i,a)=>hM(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 Xj(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 Zj=/[!-/:-@[-`{-~]/,Qj=/\s/,$j=/[\p{L}\p{N}_]/u,eM={"**":`strong`,__:`strong`,"~~":`del`,"==":`mark`},tM=(e,t,n)=>{let r=0;for(;e[t+r]===n;)r++;return r},nM=0,rM=e=>({s:e,closers:new Map}),iM=e=>new Int32Array(e.s.length+2);function aM(e,t,n){if(!e.runs){e.runs=new Map;let t=e.s;for(let n=t.indexOf("`");n>=0;n=t.indexOf("`",n)){let r=tM(t,n,"`"),i=e.runs.get(r);i?i.push(n):e.runs.set(r,[n]),n+=r}}let r=e.runs.get(n);if(!r)return-1;let i=0,a=r.length;for(;i<a;){let e=i+a>>1;r[e]<t?i=e+1:a=e}return i<r.length?r[i]:-1}function oM(e,t){let n=e.s[t];if(n===`\\`)return t+2;if(n==="`"){let n=tM(e.s,t,"`"),r=aM(e,t+n,n);return(r>=0?r:t)+n}return t+1}function sM(e,t,n,r,i){let a=e.s,o=e.closers.get(t);o||e.closers.set(t,o=iM(e));let s=a.length-r.length,c=[],l=-1;for(let t=n;t<=s;){if(o[t]!==nM){l=o[t]-2;break}c.push(t);let n=a[t];if(n!==`\\`&&n!=="`"&&a.startsWith(r,t)&&i(t)){l=t;break}t=oM(e,t)}for(let e of c)o[e]=l+2;return l}function cM(e,t,n,r){let i=n=>n>=t?-1:e[n]===nM?void 0:e[n]-2,a=[n];for(;a.length;){let t=a[a.length-1];if(i(t)!==void 0){a.pop();continue}let n=r(t),o;if(typeof n==`number`)o=n;else if(n===`open`){let e=i(t+1);e===void 0?a.push(t+1):e<0?o=-1:(o=i(e+1))===void 0&&a.push(e+1)}else(o=i(n.next))===void 0&&a.push(n.next);o!==void 0&&(e[t]=o+2,a.pop())}return i(n)}function lM(e,t){let n=e.s;return cM(e.brackets??=iM(e),n.length,t+1,t=>{let r=n[t];return r===`]`?t:r===`[`?`open`:{next:oM(e,t)}})}function uM(e,t){let n=e.s;return cM(e.parens??=iM(e),n.length,t,e=>{let t=n[e];return t===`)`?e:t===`
|
|
24
|
+
`?-1:t===`(`?`open`:{next:e+1}})}function dM(e,t){let n=e.newline;return(!n||t<n.from||n.at>=0&&t>n.at)&&(e.newline={from:t,at:e.s.indexOf(`
|
|
25
|
+
`,t)}),e.newline.at>=0}function fM(e){let t=e.trim();return t.startsWith(`<`)?t.slice(1,t.indexOf(`>`)>0?t.indexOf(`>`):void 0):t.split(/\s+/)[0]??``}var pM=e=>e.map(e=>e.type===`text`||e.type===`code`?e.text:e.type===`image`?e.alt:e.type===`br`?` `:pM(e.children)).join(``);function mM(e,t){let n=/^https?:\/\/[^\s<>]+/i.exec(e.slice(t,t+2048));if(!n)return;let r=n[0],i=e=>r.split(e).length-1,a=i(`(`),o=i(`)`),s=i(`[`),c=i(`]`),l=r.length;for(;;){let e=r[l-1];if(/[.,:;!?'"*_~]/.test(e))l--;else if(e===`)`&&a<o)o--,l--;else if(e===`]`&&s<c)c--,l--;else break}return/^https?:\/\/[^/]/i.test(r.slice(0,l))?r.slice(0,l):void 0}function hM(e,t={}){let n=String(e??``),r=!!t.streaming,i=t.depth??0;if(i>Lj)return n?[{type:`text`,text:n}]:[];let a=rM(n),o=(e,n,r=t.inLink)=>hM(e,{inLink:r,streaming:n,depth:i+1}),s=[],c=``,l=(...e)=>{c&&s.push({type:`text`,text:c}),c=``,s.push(...e)},u=0;for(;u<n.length;){let e=n[u],i=n[u+1];if(e===`\\`){if(i===`
|
|
26
|
+
`){l({type:`br`}),u+=2;continue}if(i!==void 0&&Zj.test(i)){c+=i,u+=2;continue}}if(e===`
|
|
27
|
+
`){let e=c.length;for(;c[e-1]===` `;)e--;c=c.slice(0,e),l({type:`br`}),u++;continue}if(e==="`"){let e=tM(n,u,"`"),t=aM(a,u+e,e);if(t>=0||r){let r=n.slice(u+e,t>=0?t:void 0);r.length>2&&r.startsWith(` `)&&r.endsWith(` `)&&r.trim()&&(r=r.slice(1,-1)),l({type:`code`,text:r}),u=t>=0?t+e:n.length;continue}c+=n.slice(u,u+e),u+=e;continue}let s=n.slice(u,u+2),d=eM[s];if(d&&i!==void 0&&n[u+2]!==void 0&&!Qj.test(n[u+2])&&n[u+2]!==e&&(e!==`_`||u===0||!$j.test(n[u-1]))){let t=sM(a,s,u+3,s,t=>!Qj.test(n[t-1])&&(e!==`_`||!$j.test(n[t+2]??``)));if(t>0||r){l({type:d,children:o(n.slice(u+2,t>0?t:void 0),t<0)}),u=t>0?t+2:n.length;continue}}if((e===`*`||e===`_`)&&i!==void 0&&i!==e&&!Qj.test(i)&&(e===`*`||u===0||!$j.test(n[u-1]))){let t=sM(a,e,u+1,e,t=>n[t+1]===e||n[t-1]===e?!1:!Qj.test(n[t-1])&&(e!==`_`||!$j.test(n[t+1]??``)));if(t>u+1||r){l({type:`em`,children:o(n.slice(u+1,t>u?t:void 0),t<0)}),u=t>u?t+1:n.length;continue}}let f=e===`!`&&i===`[`;if(e===`[`||f){let e=f?u+1:u,i=lM(a,e);if(i>0&&n[i+1]===`(`){let s=uM(a,i+2),c=()=>o(n.slice(e+1,i),!1,!0);if(s>0){let e=fM(n.slice(i+2,s)),r=Xj(e);f?l({type:`image`,alt:pM(c()),...r?{href:r}:{},src:e}):r&&!t.inLink?l({type:`link`,href:r,children:c()}):!r&&!t.inLink&&e?l({type:`label`,target:e,children:c()}):l(...c()),u=s+1;continue}if(r&&!dM(a,i)){l(...f?[{type:`text`,text:pM(c())}]:c()),u=n.length;continue}}}if(e===`<`&&!t.inLink){let e=/^<([a-zA-Z][a-zA-Z0-9+.-]{1,31}:[^\s<>]*)>/.exec(n.slice(u,u+2048)),t=/^<([^\s<>@\\]+@[^\s<>@\\]+\.[^\s<>@\\]+)>/.exec(n.slice(u,u+512)),r=e??t;if(r){let t=Xj(e?r[1]:`mailto:${r[1]}`);t?l({type:`link`,href:t,children:[{type:`text`,text:r[1]}]}):c+=r[0],u+=r[0].length;continue}}if((e===`h`||e===`H`)&&!t.inLink&&(u===0||!/[\p{L}\p{N}_/]/u.test(n[u-1]))&&n.slice(u-2,u)!==`](`){let e=mM(n,u),t=e&&Xj(e);if(e&&t){l({type:`link`,href:t,children:[{type:`text`,text:e}]}),u+=e.length;continue}}c+=e,u++}return c&&s.push({type:`text`,text:c}),s}var gM={files:200,fileBytes:5242880,totalBytes:20971520,chunkBytes:524288,inlineBytes:393216,bundlePathMax:200,pathMax:4096,refMax:300,skipped:200};new Set(Object.values({html:`text/html`,htm:`text/html`,css:`text/css`,js:`text/javascript`,mjs:`text/javascript`,json:`application/json`,txt:`text/plain`,csv:`text/csv`,md:`text/markdown`,pdf:`application/pdf`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`}));var _M=e=>typeof e==`string`&&e.length>0&&e.length<=gM.pathMax&&!/[\u0000\r\n]/.test(e);function vM(e){return!_M(e)||e.startsWith(`~`)||/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e)&&!/^file:/i.test(e)?!1:/\.html?$/i.test(e)}var yM=new Set([`html`,`htm`]),bM=e=>yM.has(e.toLowerCase());function xM(e){let t=[],n=e=>{for(let r of e)if(r.type===`code`&&bM(r.lang))t.push(r);else if(r.type===`quote`)n(r.blocks);else if(r.type===`list`)for(let e of r.items)n(e.blocks)};return n(e),t}var SM=new Map,CM=256;function wM(e){let t=SM.get(e);if(t!==void 0)return t;let n=e.includes("```")||e.includes(`~~~`)?xM(Rj(e)).length:0;return SM.size>=CM&&SM.delete(SM.keys().next().value),SM.set(e,n),n}function TM(e,t){let n=new Set(t?[t]:[]);for(let t of e)t.type===`assistant`&&t.messageID&&t.live&&t.key===`${t.messageID}:text`&&n.add(t.messageID);let r=new Map,i=new Map;for(let t of e){if(t.type!==`assistant`||!t.messageID||n.has(t.messageID))continue;let e=r.get(t.messageID)??0;i.set(t.key,{messageID:t.messageID,base:e}),r.set(t.messageID,e+wM(t.text))}return i}function EM(e){let t=e?.status,n=e?.code,r=e instanceof Error?e.message:String(e);return e instanceof Error&&e.name===`NetworkError`?r:typeof t==`number`?t===404?n===`too_old`?`Can't preview this message (it's too far back or no longer available)`:`This HTML block isn't available to preview yet — try again in a moment.`:t===409?`The session's machine is offline. Try again when it's back.`:t===413?`This HTML block is too large to preview (over 2 MiB).`:t===422?`This hub can't store previews.`:t===400?`This block can't be previewed.`:t===429?`Too many previews right now. Try again in a moment.`:`Couldn't open the preview: ${r}`:`Couldn't open the preview: ${r}`}function DM(e){let t=e.type===`code`?e.text:e.type===`link`?e.href:e.type===`label`?e.target:void 0;return t!==void 0&&vM(t)?t:void 0}var OM=Math.round(gM.fileBytes/1048576);function kM(e){let t=e?.status,n=e?.code,r=e instanceof Error?e.message:String(e);return e instanceof Error&&e.name===`NetworkError`?r:t===404?n===`refused`?`This page isn't one of this session's files, so it can't be previewed.`:`This message isn't available to preview anymore.`:t===409?n===`changed`?`The page kept changing while it was read. Try again.`:`The session's machine is offline. Try again when it's back.`:t===413?`This page is too large to preview (over ${OM} MiB).`:t===422?/previewBundle/.test(r)?`The session's machine can't preview local pages yet (update Hub there).`:`This hub can't store previews.`:t===502?`The session's machine sent a broken preview.`:t===429?`Too many previews right now. Try again in a moment.`:t===400?`This page can't be previewed.`:`Couldn't open the preview: ${r}`}var AM={missing:`not found`,refused:`not one of this session's files`,too_large:`over ${OM} MiB`,limit:`over the preview's size or file limit`,name:`a file name previews can't hold`,type:`a type previews can't hold`};function jM(e,t=0){let n=e??[],r=n.length+t;if(r!==0)return{title:`${r} ${r===1?`file`:`files`} not included`,items:n.map(e=>`${e.path} — ${AM[e.reason]??e.reason}`),...t>0?{more:`and ${t} more`}:{}}}var[MM,NM]=u(new Map),PM=e=>MM().get(e);function FM(e,t){let n=Array.isArray(t.skipped)?t.skipped.filter(e=>e&&typeof e.path==`string`&&typeof e.reason==`string`):[],r=typeof t.skippedMore==`number`&&t.skippedMore>0?t.skippedMore:0;NM(t=>new Map(t).set(e,{skipped:n,more:r}))}var IM=I(`<span role=alert>`),LM=I(`<button type=button>`);async function RM(e){let{sessionID:t,messageID:n}=e,r=`path`in e?{messageID:n,path:e.path}:{messageID:n,block:e.block},i=await Qe(`${U(t)}/previews`,r),a=i?.artifact?.id;if(typeof a!=`string`||!a)throw Error(`The hub's answer wasn't a preview.`);return`path`in e&&FM(a,i),a}function zM(e){let[t,r]=u(!1),[i,a]=u(),o=()=>`path`in e.target,c=async()=>{if(!(t()||e.waiting)){r(!0),a(void 0);try{let t=await RM(e.target);xn(t)||a(_n)}catch(e){a(e instanceof Error&&e.message===`The hub's answer wasn't a preview.`?e.message:o()?kM(e):EM(e))}finally{r(!1)}}},d=()=>e.waiting?`Load earlier messages to preview`:o()?`Preview this page and its files in an isolated frame beside the session`:`Preview this HTML in an isolated frame beside the session`;return[n(l,{get when(){return i()},get children(){var t=IM();return y(t,i),s(()=>k(t,e.inline?`md-preview-err`:`code-preview-err`)),t}}),(()=>{var n=LM();return n.$$click=()=>void c(),y(n,()=>t()?`Opening…`:`Preview`),s(r=>{var i=e.inline?`md-preview`:`code-btn code-preview`,a=t(),s=t()||e.waiting,c=d(),l=o()?`Preview ${e.target.path}`:void 0;return i!==r.e&&k(n,r.e=i),a!==r.t&&b(n,`aria-busy`,r.t=a),s!==r.a&&(n.disabled=r.a=s),c!==r.o&&b(n,`title`,r.o=c),l!==r.i&&b(n,`aria-label`,r.i=l),r},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),n})()]}B([`click`]);var BM=`/api/agent/artifacts`,VM={textBytes:2097152,imageBytes:10485760,editBytes:1048576,revisionsPage:20},HM=encodeURIComponent,UM=e=>`${BM}/${HM(e)}`,WM=(e,t)=>`${UM(e)}/revisions?limit=${VM.revisionsPage}${t?`&cursor=${HM(t)}`:``}`,GM=(e,t)=>`${UM(e)}/revisions/${HM(t)}`,KM=(e,t,n)=>`${GM(e,t)}/blobs/${HM(n)}`,qM=e=>typeof e==`object`&&!!e&&!Array.isArray(e),JM=e=>typeof e==`string`&&e.length>0,YM=e=>typeof e==`number`&&Number.isFinite(e),XM=e=>typeof e==`string`&&wn.includes(e),ZM=(e,t)=>qM(e)&&qM(e[t])?e[t]:e;function QM(e){let t=ZM(e,`artifact`);if(!qM(t)||!JM(t.id)||typeof t.title!=`string`||!XM(t.kind)||!JM(t.latestRevisionID)||!YM(t.revision))return;let n=Array.isArray(t.tags)?t.tags.filter(e=>typeof e==`string`):void 0;return{v:1,id:t.id,title:t.title,kind:t.kind,state:t.state===`archived`?`archived`:`active`,visibility:t.visibility===`workspace`?`workspace`:`private`,latestRevisionID:t.latestRevisionID,revision:t.revision,createdAt:YM(t.createdAt)?t.createdAt:0,updatedAt:YM(t.updatedAt)?t.updatedAt:0,...JM(t.description)?{description:t.description}:{},...JM(t.workspaceID)?{workspaceID:t.workspaceID}:{},...JM(t.createdBySessionID)?{createdBySessionID:t.createdBySessionID}:{},...n?.length?{tags:n}:{},...t.origin===`preview`?{origin:`preview`}:{},...$M(t.provenance)??{}}}function $M(e){if(qM(e)&&JM(e.sessionID)&&JM(e.messageID)){if(JM(e.path))return{provenance:{sessionID:e.sessionID,messageID:e.messageID,path:e.path}};if(YM(e.block))return{provenance:{sessionID:e.sessionID,messageID:e.messageID,block:e.block}}}}function eN(e){if(qM(e)){if(e.kind===`user`)return{kind:`user`};if(e.kind===`session`&&JM(e.sessionID))return{kind:`session`,sessionID:e.sessionID};if(e.kind===`ai_job`&&JM(e.jobID))return{kind:`ai_job`,jobID:e.jobID}}}function tN(e){let t=ZM(e,`revision`);if(!qM(t)||!JM(t.id)||!JM(t.artifactID)||!YM(t.number)||!Array.isArray(t.blobs))return;let n=eN(t.author);if(!n)return;let r=t.blobs.filter(e=>yn(e)===void 0);return{v:1,id:t.id,artifactID:t.artifactID,number:t.number,blobs:r.map(e=>({hash:e.hash,bytes:e.bytes,mediaType:e.mediaType,...e.path===void 0?{}:{path:e.path}})),author:n,createdAt:YM(t.createdAt)?t.createdAt:0,...JM(t.baseRevisionID)?{baseRevisionID:t.baseRevisionID}:{},...JM(t.entry)?{entry:t.entry}:{}}}function nN(e){let t=qM(e)?e:{};return{items:Array.isArray(t.items)?t.items.flatMap(e=>tN(e)??[]):[],...JM(t.cursor)?{cursor:t.cursor}:{}}}function rN(e){return e.kind===`user`?`You`:e.kind===`session`?`Session ${e.sessionID.slice(0,12)}…`:`AI job`}var iN=[`text/markdown`,`text/plain`,`text/csv`,`text/html`,`text/css`,`text/javascript`,`application/json`],aN=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`],oN={markdown:{"text/markdown":`markdown`,"text/plain":`markdown`},code:Object.fromEntries(iN.map(e=>[e,`code`])),image:Object.fromEntries(aN.map(e=>[e,`image`])),table:{"text/csv":`table`,"application/json":`table`},chart:{"application/json":`chart`},dashboard:{"application/json":`dashboard`},file:{...Object.fromEntries(aN.map(e=>[e,`image`])),"text/plain":`text`,"text/markdown":`text`}},sN={ts:`ts`,tsx:`tsx`,js:`js`,jsx:`jsx`,mjs:`js`,cjs:`js`,py:`python`,go:`go`,rs:`rust`,sh:`bash`,bash:`bash`,json:`json`,css:`css`,html:`html`,htm:`html`,md:`markdown`,yaml:`yaml`,yml:`yaml`,toml:`toml`,sql:`sql`,java:`java`,c:`c`,h:`c`,cpp:`cpp`,rb:`ruby`,swift:`swift`,kt:`kotlin`,diff:`diff`,csv:`csv`,txt:``},cN={"text/javascript":`js`,"text/css":`css`,"application/json":`json`,"text/html":`html`,"text/markdown":`markdown`,"text/csv":`csv`};function lN(e){let t=e.path?.split(`/`).pop()?.split(`.`).slice(1).pop()?.toLowerCase();return t!==void 0&&t in sN?sN[t]:cN[e.mediaType]??``}function uN(e,t){let n=t.blobs;if(Sn.includes(e))return{mode:`isolated`,files:n,...n[0]?{file:dN(t)??n[0]}:{}};if(!n.length)return{mode:`empty`,files:n};let r=oN[e],i=dN(t)??n.find(e=>r[e.mediaType])??n[0],a=r[i.mediaType];if(!a)return{mode:`download`,file:i,files:n,note:`A ${i.mediaType} file can't be shown as ${e===`image`?`an`:`a`} ${e} here.`};let o=a===`image`?VM.imageBytes:VM.textBytes;return i.bytes>o?{mode:`download`,file:i,files:n,note:`This file is too large to preview (${Math.ceil(i.bytes/1024)} KiB).`}:{mode:a,file:i,files:n,...a===`code`?{lang:lN(i)}:{}}}function dN(e){return e.entry===void 0?void 0:e.blobs.find(t=>t.path===e.entry)}var fN=class extends Error{limit;name=`TooLargeError`;code=`too_large`;constructor(e){super(`A file here is at most ${Math.round(e/1024)} KiB`),this.limit=e}};async function pN(e,t){let n=Number(e.headers.get(`content-length`)??``);if(Number.isFinite(n)&&n>t)throw await e.body?.cancel().catch(()=>{}),new fN(t);if(!e.body)return new Uint8Array;let r=e.body.getReader(),i=[],a=0;for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw await r.cancel().catch(()=>{}),new fN(t);i.push(n)}let o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.byteLength;return o}function mN(e){let t=e&&typeof e==`object`?e:{},n=typeof t.status==`number`?t.status:0,r=typeof t.message==`string`?t.message:``;return t.name===`NetworkError`||n===503?{kind:`offline`,text:`Can't reach the hub right now. Nothing was lost; try again when it's back.`}:t.name===`TooLargeError`||t.code===`too_large`?{kind:`too_large`,text:r||`The file is too large.`}:n===404||n===403?{kind:`not_found`,text:`This artifact doesn't exist or you can't see it.`}:n===401?{kind:`forbidden`,text:`This device isn't signed in to the hub.`}:n===422||t.code===`unsupported`?{kind:`unsupported`,text:`Artifacts aren't supported on this hub yet.`}:n===409||t.code===`conflict`?{kind:`conflict`,text:`The artifact changed since you opened it.`}:n===429||t.code===`rate_limited`?{kind:`rate_limited`,text:r?`Limit reached: ${r}`:`A limit was reached; try again later.`}:n===400?{kind:`invalid`,text:r||`The hub refused the change.`}:{kind:`error`,text:r?`Something went wrong: ${r}`:`Something went wrong (HTTP ${n}).`}}var hN=e=>new TextEncoder().encode(e).byteLength;function gN(e,t){if(e.state!==`active`||t.id!==e.latestRevisionID||Sn.includes(e.kind)||t.blobs.length!==1)return!1;let n=t.blobs[0];return iN.includes(n.mediaType)&&n.bytes<=VM.editBytes}function _N(e,t,n){if(hN(n)>VM.editBytes)throw new fN(VM.editBytes);return{baseRevisionID:e,upload:[{mediaType:t.mediaType,data:n,encoding:`utf8`,...t.path===void 0?{}:{path:t.path}}]}}var vN=e=>`hub.artifactDraft.v1.${e}`;function yN(e,t){try{let n=e?.getItem(vN(t)),r=n?JSON.parse(n):void 0;return qM(r)&&r.v===1&&JM(r.base)&&typeof r.text==`string`?{v:1,base:r.base,text:r.text}:void 0}catch{return}}function bN(e,t){let n=yN(t.storage,e.artifactID),r=n?n.base===e.baseRevisionID?{status:`editing`,draft:n.text,baseRevisionID:n.base,restored:!0}:{status:`conflict`,draft:n.text,baseRevisionID:n.base,latestRevisionID:e.baseRevisionID,restored:!0}:{status:`editing`,draft:e.original,baseRevisionID:e.baseRevisionID},i=e.original,a,o=e=>{r=e,t.onChange()},s=()=>{try{r.draft===i&&r.baseRevisionID===e.baseRevisionID?t.storage?.removeItem(vN(e.artifactID)):hN(r.draft)<=VM.editBytes&&t.storage?.setItem(vN(e.artifactID),JSON.stringify({v:1,base:r.baseRevisionID,text:r.draft}))}catch{}};return{state:()=>r,setDraft(e){o({...r,draft:e,status:r.status===`conflict`?`conflict`:`editing`}),s()},async save(){if(r.status===`saving`||r.status===`conflict`||r.draft===i&&r.baseRevisionID===e.baseRevisionID)return;let n;try{n=_N(r.baseRevisionID,e.file,r.draft)}catch(e){o({...r,status:`error`,error:{kind:`too_large`,text:`${e.message}; shorten the draft to save it.`}});return}let c=`${r.baseRevisionID}\n${r.draft}`,l=a?.sig===c?a.key:t.newKey();a={sig:c,key:l};let u=r;o({...r,status:`saving`});try{let r=await t.revise(e.artifactID,n,l);return i=u.draft,t.storage?.removeItem(vN(e.artifactID)),o({status:`saved`,draft:u.draft,baseRevisionID:r.id}),r}catch(e){let t=mN(e),n=e.details;t.kind===`conflict`?o({...u,status:`conflict`,error:t,...JM(n?.latestRevisionID)?{latestRevisionID:n.latestRevisionID}:{}}):o({...u,status:`error`,error:t}),s();return}},rebase(e){let{latestRevisionID:t,error:n,...i}=r;o({...i,status:`editing`,baseRevisionID:e}),s()},discard(){t.storage?.removeItem(vN(e.artifactID)),a=void 0,o({status:`editing`,draft:i,baseRevisionID:e.baseRevisionID})}}}var xN=/^\/artifacts\/([^/?#]+)(?:\/revisions\/([^/?#]+))?$/;function SN(e){let t=xN.exec(e);if(!t)return;let[,n,r]=t;if(ge(`artifact`,n)&&(r===void 0||ge(`revision`,r)))return r===void 0?{id:n}:{id:n,rev:r}}var CN=e=>({ok:!1,reason:e});function wN(e){let t=e?.status;return CN(t===404||t===403?`not_found`:`error`)}async function TN(e,t){let n;try{n=await t.artifact(e.id)}catch(e){return wN(e)}if(n.id!==e.id)return CN(`not_found`);if(n.kind!==`image`&&n.kind!==`file`)return CN(`not_image`);let r=e.rev??n.latestRevisionID,i;try{i=await t.revision(n.id,r)}catch(e){return wN(e)}if(i.id!==r||i.artifactID!==n.id)return CN(`not_found`);let a=EN(n,i);return a?a.bytes>Mn.maxBytes?CN(`too_large`):{ok:!0,artifactID:n.id,revisionID:r,title:n.title,file:a,src:KM(n.id,r,a.hash),page:`/artifacts/${encodeURIComponent(n.id)}`}:CN(`not_image`)}function EN(e,t){let n=uN(e.kind,t),r=n.file;if(r&&jn.includes(r.mediaType))return n.mode===`image`||n.mode===`download`?r:void 0}function DN(e){let t=e.now??Date.now,n=e.ttlMs??3e4,r=An(e.limit??3),i=new Map;return{resolve(a){let o=`${a.id}/${a.rev??``}`,s=i.get(o);if(s&&t()-s.at<=n)return s.answer;let c=r.acquire().then(async t=>{try{return await TN(a,e.reader)}finally{t()}});return i.set(o,{at:t(),answer:c}),c}}}var ON={text:`No longer available from this artifact`,retry:!1},kN={text:`Artifacts aren't available on this hub`,retry:!1};function AN(e,t){return t===`not_found`||t===void 0&&e===404?{...ON}:t===`unsupported`||t===void 0&&e===422?{...kN}:In(e,t)}var jN=I(`<a class=md-image target=_blank rel="noopener noreferrer">`),MN=I(`<span class=md-artifact><a class=md-artifact-link title="Open the artifact">`),NN=()=>new G(404,`No such artifact`),PN=DN({reader:{async artifact(e){let t=QM(await K(UM(e)));if(!t)throw NN();return t},async revision(e,t){let n=tN(await K(GM(e,t)));if(!n)throw NN();return n}}}),FN={not_found:`Image (artifact not found)`,not_image:`Artifact (not an image)`,too_large:`Image (too large to show inline)`,error:`Image (couldn't load the artifact)`};function IN(e){let[t]=d(()=>SN(e.href),e=>PN.resolve(e)),r=()=>{let e=t.state===`ready`?t():void 0;return e?.ok?e:void 0},i=t=>({key:`artifact:${t.artifactID}:${t.revisionID}:${t.file.hash}`,name:e.alt||t.title||`image`,mime:t.file.mediaType,src:t.src,bytes:t.file.bytes,download:t.src}),a=t=>(()=>{var n=jN();return b(n,`title`,t),y(n,()=>e.alt||`image`),s(()=>b(n,`href`,e.href)),n})();return n(v,{get fallback(){return a(t.state===`ready`&&!t().ok?FN[t().reason]:`Image (opens in a new tab)`)},get children(){return n(o,{get when(){return r()},children:e=>{let t=C(()=>i(e()));return(()=>{var r=MN(),i=r.firstChild;return y(r,n(Rn,{get images(){return[t()]},children:e=>n(Pn,{get image(){return t()},class:`md-media`,explain:AN,onOpen:()=>e(t().key)})}),i),y(i,()=>e().title||`Artifact`),s(t=>{var n=e().artifactID,a=e().page;return n!==t.e&&b(r,`data-artifact`,t.e=n),a!==t.t&&b(i,`href`,t.t=a),t},{e:void 0,t:void 0}),r})()}})}})}var LN=e=>`/api/media/remote?url=${encodeURIComponent(e)}`;function RN(e,t){let n;try{n=new URL(e,t.origin)}catch{return{kind:`invalid`}}if(n.origin===new URL(t.origin).origin)return{kind:`same-origin`};if(n.protocol!==`http:`&&n.protocol!==`https:`)return{kind:`invalid`};let r=qw(n.href),i=r??n.host.replace(/\.(?=:|$)/,``),a=Yw(i);if(!t.enabled)return{kind:`off`,host:i,unicode:a,url:e};let o=n.username!==``||n.password!==``;return r&&!o&&(Jw(t.allowlist,r)||t.sessionHosts.includes(r))?{kind:`auto`,host:r,src:LN(e)}:{kind:`card`,host:i,unicode:a,src:LN(e),url:e}}var zN=I(`<span class=remote-image>`),BN=I(`<span class=remote-card-unicode>(<!>)`),VN=I(`<span class=remote-card-alt>`),HN=I(`<button type=button class="btn small">Always allow `),UN=I(`<span class=remote-card-actions><button type=button class="btn small">Load image`),WN=I(`<button type=button class=remote-card-session>Load all from this domain in this session`),GN=I(`<span class=remote-card><span class=remote-card-head><span class=remote-card-domain></span></span><button type=button class=remote-card-url>`),KN=I(`<span class=remote-card-off>Web images are turned off on this hub`),qN=c(``),JN=e=>RN(e,{origin:location.origin,allowlist:[],sessionHosts:[],enabled:!0}).kind!==`same-origin`,YN=(e,t=64)=>{let n=e.replace(/^https?:\/\//i,``);return n.length>t?`${n.slice(0,t-21)}…${n.slice(-20)}`:n};function XN(e){let t=le(qN),[i,a]=u(!1),[c,d]=u(!1),[f,p]=u(!1),m=C(()=>{let n=tT();return RN(e.href,{origin:location.origin,allowlist:n?.allowlist??[],sessionHosts:sT(t),enabled:n?.remoteFetch!==!1})}),h=()=>{let e=m();return e.kind===`card`||e.kind===`off`?e:void 0},g=()=>{let e=m();return e.kind===`auto`||e.kind===`card`&&i()?e.src:void 0},_=()=>e.alt||h()?.host||`image`,x=async e=>{p(!0);try{await iT(e),J(`Images from ${e} now load at once`)}catch(t){J(`Could not allow ${e}: ${W(t)}`,`err`)}finally{p(!1)}};return(()=>{var i=zN();return y(i,n(v,{get children(){return[n(o,{get when(){return g()},children:e=>{let t={key:e(),name:_(),mime:`image/*`,src:e()};return n(Rn,{images:[t],children:e=>n(Pn,{image:t,class:`md-media`,onOpen:()=>e(t.key)})})}}),n(o,{get when(){return h()},children:i=>(()=>{var o=GN(),u=o.firstChild,p=u.firstChild,m=u.nextSibling;return y(u,n(L,{name:`image`}),p),y(p,()=>i().host),y(u,n(l,{get when(){return i().unicode!==i().host},get children(){var e=BN(),t=e.firstChild.nextSibling;return t.nextSibling,y(e,()=>i().unicode,t),e}}),null),m.$$click=()=>d(!c()),y(m,(()=>{var e=r(()=>!!c());return()=>e()?i().url:YN(i().url)})()),y(o,n(l,{get when(){return e.alt},get children(){var t=VN();return y(t,()=>e.alt),t}}),null),y(o,n(l,{get when(){return i().kind===`card`},get fallback(){return KN()},get children(){return[(()=>{var e=UN(),t=e.firstChild;return t.$$click=()=>a(!0),y(e,n(l,{get when(){return!i().host.includes(`:`)},get children(){var e=HN();return e.firstChild,e.$$click=()=>void x(i().host),y(e,()=>i().host,null),s(()=>e.disabled=f()),e}}),null),e})(),n(l,{get when(){return!i().host.includes(`:`)},get children(){var e=WN();return e.$$click=()=>cT(t,i().host),e}})]}}),null),s(e=>{var t=i().url,n=i().kind,r=c(),a=`Web address: ${i().url}`;return t!==e.e&&b(o,`title`,e.e=t),n!==e.t&&b(o,`data-state`,e.t=n),r!==e.a&&b(m,`aria-expanded`,e.a=r),a!==e.o&&b(m,`aria-label`,e.o=a),e},{e:void 0,t:void 0,a:void 0,o:void 0}),o})()})]}})),s(t=>{var n=e.alt,r=m().host;return n!==t.e&&b(i,`data-alt`,t.e=n),r!==t.t&&b(i,`data-host`,t.t=r),t},{e:void 0,t:void 0}),i})()}B([`click`]);var ZN=e=>`/api/media/unfurl?url=${encodeURIComponent(e)}`;function QN(e,t){if(!t.enabled)return{kind:`none`};let n;try{n=new URL(e,t.origin)}catch{return{kind:`none`}}if(n.protocol!==`http:`&&n.protocol!==`https:`||n.origin===new URL(t.origin).origin||n.username!==``||n.password!==``)return{kind:`none`};let r=qw(n.href);return r?{kind:Jw(t.allowlist,r)?`auto`:`tap`,host:r,url:n.href}:{kind:`none`}}function $N(e,t){for(let n of e)n.type===`link`?t.push(n.href):(n.type===`strong`||n.type===`em`||n.type===`del`||n.type===`mark`)&&$N(n.children,t)}function eP(e,t,n={}){let r=new Set,i=new Set,a=new Map;if(n.streaming||!t.enabled)return{auto:r,tap:i,cards:a};let o=(e,n)=>{for(let o of n){let n=QN(o,t);if(n.kind===`none`||r.has(n.url)||i.has(n.url))continue;n.kind===`auto`&&r.size<3?r.add(n.url):i.add(n.url);let s=a.get(e)??[];s.push(n.url),a.set(e,s)}},s=e=>{for(let t of e){let e=[];if(t.type===`paragraph`||t.type===`heading`)$N(t.children,e);else if(t.type===`table`)for(let n of[t.head,...t.rows])for(let t of n)$N(t,e);else if(t.type===`list`)for(let e of t.items)s(e.blocks);else t.type===`quote`&&s(t.blocks);e.length&&o(t,e)}};return s(e),{auto:r,tap:i,cards:a}}function tP(e,t){if(typeof e!=`string`||!e)return;let n=RN(e,{origin:t.origin,allowlist:t.allowlist,sessionHosts:[],enabled:t.enabled});return n.kind===`auto`?n.src:void 0}function nP(e,t){return t===`not_html`||e===415?{text:`No preview: not a web page`,retry:!1}:t===`disabled`?{text:`Link previews are turned off on this hub`,retry:!1}:t===`bad_url`||e===400?{text:`This link can't be previewed`,retry:!1}:t===`refused`||e===403?{text:`No preview: that address is not allowed`,retry:!1}:t===`rate_limited`||e===429?{text:`Too many previews right now: try again`,retry:!0}:t===`timeout`||e===504?{text:`No preview: the site didn't answer in time`,retry:!0}:t===`upstream`||e===502?{text:`No preview: couldn't reach the site`,retry:!0}:e===0?{text:`Couldn't load the preview (offline?)`,retry:!0}:{text:`Couldn't load the preview`,retry:!0}}var rP=class extends Error{reason;status;code;constructor(e,t=0,n){super(e.text),this.reason=e,this.status=t,this.code=n}},iP=256,aP={title:200,description:300,siteName:100},oP=(e,t)=>new rP(nP(e,t),e,t),sP=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;function cP(e,t){if(typeof e!=`string`)return;let n=e.replace(sP,``).trim();return n?n.length>t?`${n.slice(0,t-1)}…`:n:void 0}function lP(e,t){let n=e&&typeof e==`object`?e:{},r=typeof n.url==`string`&&/^https?:\/\//i.test(n.url)?n.url:t,i=cP(n.title,aP.title),a=cP(n.description,aP.description),o=cP(n.siteName,aP.siteName),s=typeof n.image==`string`&&/^https?:\/\//i.test(n.image)?n.image:void 0;return{url:r,...i?{title:i}:{},...a?{description:a}:{},...o?{siteName:o}:{},...s?{image:s}:{}}}function uP(e={}){let t=e.fetch??((...e)=>fetch(...e)),n=e.slots??An(3),r=e.timeoutMs??2e4,i=new Map,a=new Map,o=new Map;async function s(e){let i=await n.acquire(),a=new AbortController,o=!1,s=setTimeout(()=>(o=!0,a.abort()),r);try{let n;try{n=await t(ZN(e),{credentials:`same-origin`,referrerPolicy:`no-referrer`,signal:a.signal})}catch{throw o?oP(504,`timeout`):oP(0)}let r=await n.json().catch(()=>void 0);if(!n.ok)throw oP(n.status,typeof r?.code==`string`?r.code:void 0);if(!r||typeof r!=`object`)throw oP(500);return lP(r,e)}finally{clearTimeout(s),i()}}return{load(e){let t=i.get(e);if(t)return Promise.resolve(t);let n=a.get(e);if(n)return Promise.reject(n);let r=o.get(e);if(r)return r;let c=s(e).then(t=>(o.delete(e),i.set(e,t),i.size>iP&&i.delete(i.keys().next().value),t),t=>{o.delete(e);let n=t instanceof rP?t:oP(0);throw a.set(e,n),n});return o.set(e,c),c},forget(e){a.delete(e)}}}var dP=I(`<button type=button class=link-preview-btn>`),fP=I(`<div class=link-cards>`),pP=I(`<div class=link-card>`),mP=I(`<span class=link-card-loading>Loading a preview of <!>…`),hP=I(`<span class=link-card-title>`),gP=I(`<span class=link-card-desc>`),_P=I(`<a class=link-card-link target=_blank rel="noopener noreferrer"><span class=link-card-site>`),vP=I(`<button type=button class="btn small">Retry`),yP=I(`<span class=link-card-failed><span class=link-card-note>`),bP=uP({slots:Dn}),xP=c(()=>void 0);function SP(e){let t=le(xP),r=C(()=>{let n=t();if(!n)return;let r=QN(e.href,n.context);return r.kind!==`none`&&n.plan.tap.has(r.url)&&!n.tapped.has(r.url)?r:void 0});return n(l,{get when(){return r()},children:e=>(()=>{var r=dP();return r.$$click=()=>t()?.tap(e().url),y(r,n(L,{name:`search`})),s(t=>{var n=`Preview ${e().host}`,i=`Preview ${e().host}`;return n!==t.e&&b(r,`aria-label`,t.e=n),i!==t.t&&b(r,`title`,t.t=i),t},{e:void 0,t:void 0}),r})()})}function CP(e){let t=le(xP),r=C(()=>{let n=t();return(n?.plan.cards.get(e.block)??[]).filter(e=>n.plan.auto.has(e)||n.tapped.has(e))});return n(l,{get when(){return r().length},get children(){var e=fP();return y(e,n(m,{get each(){return r()},children:e=>n(wP,{url:e,get auto(){return t()?.plan.auto.has(e)===!0},context:()=>t()?.context})})),e}})}function wP(e){let[r,i]=u({at:`waiting`}),[a,c]=u(!e.auto),d,f=!0;M(()=>f=!1);let p=()=>{try{return new URL(e.url).hostname}catch{return e.url}};R(()=>{if(a())return;if(typeof IntersectionObserver>`u`)return void c(!0);let e=new IntersectionObserver(e=>e.some(e=>e.isIntersecting)&&c(!0),{rootMargin:`300px 0px`});e.observe(d),M(()=>e.disconnect())});let m=()=>{i({at:`loading`}),bP.load(e.url).then(e=>f&&i({at:`shown`,preview:e}),e=>{if(!f)return;let t=e instanceof rP?e.reason:{text:`Couldn't load the preview`,retry:!0};i({at:`failed`,...t})})};x(()=>{a()&&r().at===`waiting`&&m()});let h=()=>{bP.forget(e.url),m()},g=()=>{let e=r();return e.at===`shown`?e.preview:void 0},_=()=>{let e=r();return e.at===`failed`?e:void 0},S=C(()=>{let t=g(),n=e.context();return t&&n?tP(t.image,n):void 0});return(()=>{var i=pP(),a=d;return typeof a==`function`?t(a,i):d=i,y(i,n(v,{get fallback(){return(()=>{var e=mP(),t=e.firstChild.nextSibling;return t.nextSibling,y(e,p,t),e})()},get children(){return[n(o,{get when(){return g()},children:t=>[(()=>{var r=_P(),i=r.firstChild;return y(i,()=>t().siteName??p()),y(r,n(l,{get when(){return t().title},get children(){var e=hP();return y(e,()=>t().title),e}}),null),y(r,n(l,{get when(){return t().description},get children(){var e=gP();return y(e,()=>t().description),e}}),null),s(t=>{var n=e.url,i=e.url;return n!==t.e&&b(r,`href`,t.e=n),i!==t.t&&b(r,`title`,t.t=i),t},{e:void 0,t:void 0}),r})(),n(l,{get when(){return S()},children:e=>n(Pn,{get image(){return{key:e(),name:t().title??p(),mime:`image/*`,src:e()}},class:`link-card-image`})})]}),n(o,{get when(){return _()},children:e=>(()=>{var t=yP(),r=t.firstChild;return y(r,()=>e().text),y(t,n(l,{get when(){return e().retry},get children(){var e=vP();return e.$$click=h,e}}),null),t})()})]}})),s(t=>{var n=e.url,a=r().at;return n!==t.e&&b(i,`data-url`,t.e=n),a!==t.t&&b(i,`data-state`,t.t=a),t},{e:void 0,t:void 0}),i})()}B([`click`]);var TP=I(`<span class=md-image>`),EP=I(`<a class=md-image target=_blank rel="noopener noreferrer"title="Image (opens in a new tab)">`),DP=I(`<br>`),OP=I(`<code class=inline-code>`),kP=I(`<a rel="noopener noreferrer">`),AP=I(`<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>`),jP=I(`<span>`),MP=I(`<hr>`),NP=I(`<p>`),PP=I(`<input type=checkbox disabled>`),FP=I(`<li>`),IP=I(`<blockquote>`),LP=I(`<div class=table-wrap><table><thead><tr></tr></thead><tbody>`),RP=I(`<th>`),zP=I(`<tr>`),BP=I(`<td>`),VP=I(`<div class=md>`),[HP,UP]=u(),WP=!1;function GP(){WP||(WP=!0,Vn(()=>import(`./highlight-y4rJE6Tt.js`).then(e=>UP({run:e.highlight,languageOf:e.languageOf}),()=>WP=!1),[]))}var KP=65536;function qP(e,t){GP();let n=HP();return!n||!e||t.length>KP||!n.languageOf(e)?[{text:t}]:n.run(t,e)}function JP(e){let t=le(nF),r=C(()=>{let n=t(),r=n&&!n.streaming&&!e.inLink?DM(e.node):void 0;return n&&r!==void 0?{sessionID:n.sessionID,messageID:n.messageID,path:r,waiting:n.waiting}:void 0});return n(l,{get when(){return r()},children:e=>n(zM,{get target(){return e()},get waiting(){return e().waiting},inline:!0})})}var YP=c(()=>void 0);function XP(e){let t=le(YP),i=C(()=>kn(e.node,t()?.images)),a=()=>e.node.alt||`image`;return n(v,{get fallback(){return(()=>{var e=TP();return y(e,a),e})()},get children(){return[n(o,{get when(){return r(()=>!!(i().kind===`remote`&&JN(i().href)))()&&i()},children:t=>n(XN,{get href(){return t().href},get alt(){return e.node.alt}})}),n(o,{get when(){return r(()=>i().kind===`local`)()&&i()},children:r=>n(Pn,{get image(){return{...r().image,name:e.node.alt||r().image.name}},class:`md-media`,onOpen:()=>t()?.open(r().image.key)})}),n(o,{get when(){return r(()=>i().kind===`artifact`)()&&i()},children:t=>n(IN,{get href(){return t().href},get alt(){return e.node.alt}})}),n(o,{get when(){return r(()=>i().kind===`artifact`||i().kind===`remote`)()&&i()},children:e=>(()=>{var t=EP();return y(t,a),s(()=>b(t,`href`,e().href)),t})()})]}})}function ZP(e){return n(g,{get each(){return e.nodes},children:t=>n(v,{get children(){return[n(o,{get when(){return r(()=>t().type===`text`)()&&t()},children:e=>r(()=>e().text)}),n(o,{get when(){return t().type===`br`},get children(){return DP()}}),n(o,{get when(){return r(()=>t().type===`code`)()&&t()},children:r=>[(()=>{var e=OP();return y(e,()=>r().text),e})(),n(JP,{get node(){return t()},get inLink(){return e.inLink}})]}),n(o,{get when(){return r(()=>t().type===`link`)()&&t()},children:r=>[(()=>{var e=kP();return y(e,n(ZP,{get nodes(){return r().children},inLink:!0})),s(t=>{var n=r().href,i=r().href.startsWith(`/`)?void 0:`_blank`;return n!==t.e&&b(e,`href`,t.e=n),i!==t.t&&b(e,`target`,t.t=i),t},{e:void 0,t:void 0}),e})(),n(SP,{get href(){return r().href}}),n(JP,{get node(){return t()},get inLink(){return e.inLink}})]}),n(o,{get when(){return r(()=>t().type===`image`)()&&t()},children:e=>n(XP,{get node(){return e()}})}),n(o,{get when(){return r(()=>`children`in t())()&&t()},children:r=>[n(D,{get component(){return{strong:`strong`,em:`em`,del:`del`,mark:`mark`}[r().type]??`span`},get children(){return n(ZP,{get nodes(){return r().children},get inLink(){return e.inLink}})}}),n(l,{get when(){return r().type===`label`},get children(){return n(JP,{get node(){return t()},get inLink(){return e.inLink}})}})]})]}})})}async function QP(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 $P(e){let[t,r]=u(!1),[i,a]=u(!1),o;M(()=>clearTimeout(o)),GP();let c=C(()=>{let t=HP();return!t||!e.lang||e.text.length>KP||!t.languageOf(e.lang)?[{text:e.text}]:t.run(e.text,e.lang)}),d=()=>e.lang||`text`;return(()=>{var u=AP(),f=u.firstChild,p=f.firstChild,m=p.nextSibling,h=m.nextSibling,_=f.nextSibling,v=_.firstChild;return y(p,d),y(f,()=>e.actions,m),m.$$click=()=>a(!i()),y(m,()=>i()?`No wrap`:`Wrap`),h.$$click=async()=>{await QP(e.text)&&(r(!0),clearTimeout(o),o=setTimeout(()=>r(!1),1500))},y(h,()=>t()?`Copied`:`Copy`),y(v,n(g,{get each(){return c()},children:e=>n(l,{get when(){return e().kind},get fallback(){return e().text},get children(){var t=jP();return y(t,()=>e().text),s(()=>k(t,`tok-${e().kind}`)),t}})})),s(n=>{var r=`code-block${i()?` wrap`:``}`,a=i(),o=i()?`Scroll long lines`:`Wrap long lines`,s=t()?`Copied`:`Copy ${d()} code`,c=e.lang||void 0;return r!==n.e&&k(u,n.e=r),a!==n.t&&b(m,`aria-pressed`,n.t=a),o!==n.a&&b(m,`title`,n.a=o),s!==n.o&&b(h,`aria-label`,n.o=s),c!==n.i&&b(_,`data-lang`,n.i=c),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),u})()}var eF=E(()=>Vn(()=>import(`./Diagram-PvOPetOI.js`),__vite__mapDeps([0,1,2,3,4,5,6]))),tF=c(()=>void 0),nF=c(()=>void 0);function rF(e){let t=e.at(-1);if(t){if(t.type===`code`)return t;if(t.type===`quote`)return rF(t.blocks);if(t.type===`list`)return rF(t.items.at(-1)?.blocks??[])}}function iF(e){let t=le(tF),i=le(nF),a=C(()=>{let n=i(),r=t()===e.block?void 0:n?.number(e.block);return n&&r!==void 0?{sessionID:n.sessionID,messageID:n.messageID,block:r,waiting:n.waiting}:void 0}),o=()=>n($P,{get lang(){return e.block.lang},get text(){return e.block.text},get actions(){return n(l,{get when(){return a()},children:e=>n(zM,{get target(){return e()},get waiting(){return e().waiting}})})}});return n(l,{get when(){return r(()=>!!Bn(e.block.lang))()&&t()!==e.block},get fallback(){return o()},get children(){return n(f,{get fallback(){return o()},get children(){return n(eF,{get lang(){return e.block.lang},get text(){return e.block.text}})}})}})}var aF={left:`left`,center:`center`,right:`right`};function oF(e){return n(g,{get each(){return e.blocks},children:e=>n(v,{get children(){return[n(o,{get when(){return r(()=>e().type===`paragraph`)()&&e()},children:e=>[(()=>{var t=NP();return y(t,n(ZP,{get nodes(){return e().children}})),t})(),n(CP,{get block(){return e()}})]}),n(o,{get when(){return r(()=>e().type===`heading`)()&&e()},children:e=>[n(D,{get component(){return`h${Math.min(6,e().level+2)}`},get children(){return n(ZP,{get nodes(){return e().children}})}}),n(CP,{get block(){return e()}})]}),n(o,{get when(){return r(()=>e().type===`list`)()&&e()},children:e=>n(D,{get component(){return e().ordered?`ol`:`ul`},get start(){return r(()=>!!(e().ordered&&e().start!==1))()?e().start:void 0},get class(){return e().loose?`loose`:void 0},get children(){return n(g,{get each(){return e().items},children:e=>(()=>{var t=FP();return y(t,n(l,{get when(){return e().checked!==void 0},get children(){var t=PP();return s(()=>b(t,`aria-label`,e().checked?`Done`:`Not done`)),s(()=>t.checked=e().checked),t}}),null),y(t,n(oF,{get blocks(){return e().blocks}}),null),s(()=>k(t,e().checked===void 0?void 0:`task`)),t})()})}})}),n(o,{get when(){return r(()=>e().type===`code`)()&&e()},children:e=>n(iF,{get block(){return e()}})}),n(o,{get when(){return r(()=>e().type===`quote`)()&&e()},children:e=>(()=>{var t=IP();return y(t,n(oF,{get blocks(){return e().blocks}})),t})()}),n(o,{get when(){return r(()=>e().type===`table`)()&&e()},children:e=>[(()=>{var t=LP(),r=t.firstChild.firstChild,i=r.firstChild,a=r.nextSibling;return y(i,n(g,{get each(){return e().head},children:(t,r)=>(()=>{var i=RP();return y(i,n(ZP,{get nodes(){return t()}})),s(t=>h(i,e().align[r]?{"text-align":aF[e().align[r]]}:void 0,t)),i})()})),y(a,n(g,{get each(){return e().rows},children:t=>(()=>{var r=zP();return y(r,n(g,{get each(){return t()},children:(t,r)=>(()=>{var i=BP();return y(i,n(ZP,{get nodes(){return t()}})),s(t=>h(i,e().align[r]?{"text-align":aF[e().align[r]]}:void 0,t)),i})()})),r})()})),t})(),n(CP,{get block(){return e()}})]}),n(o,{get when(){return e().type===`rule`},get children(){return MP()}})]}})})}function sF(e){let t=C(()=>Rj(e.text,{streaming:e.streaming})),r=C(()=>e.streaming&&On(e.text)?rF(t()):void 0),i=C(()=>e.preview?new Map(xM(t()).map((e,t)=>[e,t])):void 0),a=C(()=>{let t=e.preview,n=i();if(t&&n)return{sessionID:t.sessionID,messageID:t.messageID,waiting:t.waiting===!0,streaming:e.streaming===!0,number:e=>n.has(e)?t.base+n.get(e):void 0}}),[o,s]=u(new Set),c=C(()=>{if(!e.links)return;let n=tT();if(!n)return;let r={origin:location.origin,allowlist:n.allowlist,enabled:n.remoteFetch!==!1};return{context:r,plan:eP(t(),r,{streaming:e.streaming}),tapped:o(),tap:e=>s(new Set([...o(),e]))}}),d=i=>n(xP.Provider,{value:c,get children(){return n(YP.Provider,{value:()=>i&&e.images?.length?{images:e.images,open:i}:void 0,get children(){return n(tF.Provider,{value:r,get children(){return n(nF.Provider,{value:a,get children(){return n(oF,{get blocks(){return t()}})}})}})}})}}),f=C(()=>Nn(t(),e.images));return(()=>{var t=VP();return y(t,n(l,{get when(){return e.images?.length},get fallback(){return d()},get children(){return n(Rn,{get images(){return f()},children:e=>d(e)})}})),t})()}B([`click`]);var cF=I(`<div class=dialog-head><h2 id=setup-machine-title>Set up Hub on a machine`),lF=I(`<label class="sm-field sm-root"><span class=sm-label>Workspace folder</span><input type=text class=mono autocapitalize=off autocomplete=off aria-describedby=setup-machine-root-hint><span id=setup-machine-root-hint class="small muted">Where sessions started from here run on the machine<!>. Empty: <!>.`),uF=I(`<label class="check sm-activate"><input type=checkbox><span>Start services now<span class="small muted block">Loads the machine's Hub services right away. Off: they are installed, and the installer prints how to start them.`),dF=I(`<div class="dialog-body setup-machine"><p id=setup-machine-intro class="small muted">Run this on the machine. It installs hubctl, then waits for you to approve the machine here (Settings → Machines & devices → Approvals).</p><fieldset class=sm-field><legend>Operating system</legend><div class=sm-seg></div></fieldset><fieldset class=sm-field><legend>What to install</legend><div class=sm-profiles></div></fieldset><div class=sm-command-box><button type=button class="btn primary sm-copy"aria-label="Copy command"> </button></div><p class="small muted"aria-live=polite>`),fF=I(`<dialog class="dialog setup-machine-dialog"aria-labelledby=setup-machine-title aria-describedby=setup-machine-intro data-setup-machine>`),pF=I(`<label class=sm-seg-item><input type=radio name=setup-os>`),mF=I(`<label class=sm-profile><input type=radio name=setup-profile><span class=grow><span class=name></span><span class="small muted">`),hF=I(`<p class="error small"role=alert>`),gF=I(`<code class=sm-command data-setup-command>`),_F=`hub.setupMachine.os`,vF=`button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`,[yF,bF]=u();function xF(e={}){yF()||bF(e)}var SF=()=>{try{return localStorage.getItem(_F)??void 0}catch{return}};function CF(){let e,i,[a,o]=u(`linux`),[c,d]=u(`session-only`),[f,p]=u(``),[h,g]=u(!1),[_,v]=u(!1),S,w=()=>bF(void 0);x(()=>{let t=yF();e&&(t&&!e.open?(i=t.returnTo?.()??document.activeElement,o(_j(navigator,SF())),d(`session-only`),p(``),g(!1),v(!1),e.showModal(),queueMicrotask(()=>e?.querySelector(`input[name=setup-os]:checked`)?.focus())):!t&&e.open&&(e.close(),i?.isConnected&&i.focus(),i=void 0))});let T=e=>{o(e),vj(e,c())||d(`session-only`);try{localStorage.setItem(_F,e)}catch{}},E=()=>Z()?.publicURL??location.origin,D=C(()=>Cj({origin:E(),os:a(),profile:c(),root:f().trim(),activate:h()})),O=()=>a()===`windows`,k=()=>c()===`launch-node`,A=()=>c()!==`session-only`,j=()=>k()&&!D().ok,M=async()=>{let e=D();e.ok&&(await QP(e.command)?(J(`Command copied`),v(!0),clearTimeout(S),S=setTimeout(()=>v(!1),2e3)):J(`Couldn't copy: select the command and copy it`,`err`))};return(()=>{var i=fF();i.$$keydown=t=>{if(t.key!==`Tab`||!e)return;let n=[...e.querySelectorAll(vF)].filter(e=>!(e instanceof HTMLInputElement&&e.type===`radio`&&!e.checked));if(!n.length)return;let r=n[0],i=n[n.length-1];t.shiftKey&&document.activeElement===r?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),r.focus())},i.$$click=t=>t.target===e&&w(),i.addEventListener(`cancel`,e=>{e.preventDefault(),w()});var o=e;return typeof o==`function`?t(o,i):e=i,y(i,n(l,{get when(){return yF()},get children(){return[(()=>{var e=cF();return e.firstChild,y(e,n(F,{icon:`close`,label:`Close`,onClick:w}),null),e})(),(()=>{var e=dF(),t=e.firstChild.nextSibling,i=t.firstChild.nextSibling,o=t.nextSibling,u=o.firstChild.nextSibling,v=o.nextSibling,x=v.firstChild,S=x.firstChild,C=v.nextSibling;return y(i,n(m,{each:uj,children:e=>(()=>{var t=pF(),n=t.firstChild;return n.addEventListener(`change`,()=>T(e)),n.value=e,y(t,()=>dj[e],null),s(()=>t.classList.toggle(`on`,a()===e)),s(()=>n.checked=a()===e),t})()})),y(u,n(m,{get each(){return yj(a())},children:e=>(()=>{var t=mF(),n=t.firstChild,i=n.nextSibling.firstChild,o=i.nextSibling;return n.addEventListener(`change`,()=>d(e.id)),y(i,()=>e.label),y(o,(()=>{var t=r(()=>!!e.comingSoon);return()=>t()?`Coming soon on ${dj[a()]}`:e.description})()),s(r=>{var i=c()===e.id,a=!!e.comingSoon,o=e.comingSoon;return i!==r.e&&t.classList.toggle(`on`,r.e=i),a!==r.t&&t.classList.toggle(`disabled`,r.t=a),o!==r.a&&(n.disabled=r.a=o),r},{e:void 0,t:void 0,a:void 0}),s(()=>n.value=e.id),s(()=>n.checked=c()===e.id),t})()})),y(e,n(l,{get when(){return k()},get children(){var e=lF(),t=e.firstChild.nextSibling,n=t.nextSibling,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,t.$$input=e=>p(e.currentTarget.value),b(t,`placeholder`,fj),b(t,`spellcheck`,!1),y(n,()=>O()?` (C:\\Users\\you\\projects, C:/… or ~/…)`:``,r),y(n,fj,i),s(()=>b(t,`aria-invalid`,j()?`true`:void 0)),s(()=>t.value=f()),e}}),v),y(e,n(l,{get when(){return A()},get children(){var e=uF(),t=e.firstChild;return t.addEventListener(`change`,e=>g(e.currentTarget.checked)),s(()=>t.checked=h()),e}}),v),y(v,n(l,{get when(){return r(()=>!!D().ok)()&&D().command},get fallback(){return(()=>{var e=hF();return y(e,()=>D().error),e})()},children:e=>(()=>{var t=gF();return y(t,e),t})()}),x),x.$$click=()=>void M(),y(x,n(L,{get name(){return _()?`check`:`copy`}}),S),y(x,()=>_()?`Copied`:`Copy`,null),y(C,n(l,{get when(){return _()},get children(){return[`Copied. Paste it into a terminal on the machine`,r(()=>O()?` (PowerShell)`:``),`.`]}})),s(()=>x.disabled=!D().ok),e})()]}})),i})()}B([`click`,`keydown`,`input`]);var wF=I(`<h3 class=section-title>`),TF=I(`<section class=settings-section>`),EF=I(`<div class=settings-search role=search><input type=search placeholder="Search settings"aria-label="Search settings">`),DF=I(`<nav class=settings-nav aria-label="Settings sections">`),OF=I(`<div class=settings><header class=topbar><h1 class=title></h1></header><div class=settings-body><div class=settings-content><p class="small muted settings-footer">Server <!> · v`),kF=I(`<a>`),AF=I(`<ul class=settings-results aria-label="Search results">`),jF=I(`<p class="muted settings-empty">No settings match.`),MF=I(`<li><a><span class=name></span><span class="small muted"> · `),NF=I(`<ul class=settings-list aria-label="Settings sections">`),PF=I(`<li><a><span class=grow><span class=name></span><span class="small muted">`),FF=I(`<div class=settings-page><p class=muted>No such settings section.</p><a class="btn small"href=/settings>All settings`),IF=I(`<div class=settings-page><h2 class=settings-page-title>`),LF=I(`<span class=badge-pill>`),RF=I(`<div class="small muted">`),zF=I(`<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`),BF=I(`<h3>Notify me when`),VF=I(`<p class="small notify-summary"data-notify-summary>`),HF=I(`<p class="small warn">These apply once this device is subscribed.`),UF=I(`<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.`),WF=I(`<h4>When`),GF=I(`<ul class=switches><li id=quiet-hours><label class=switch><span>Quiet hours</span><input type=checkbox>`),KF=I(`<p class="small muted"> muted (⋯ menu of a session → Unmute notifications).`),qF=I(`<p class="small muted">Checking this device…`),JF=I(`<div class=notify-status-row><p role=status></p><details class=notify-details><summary class=small>Details</summary><dl class="notify-facts small muted"><dt>Permission</dt><dd></dd><dt>Service worker</dt><dd></dd><dt>Subscribed on this hub</dt><dd>`),YF=I(`<button type=button class="btn small primary">Enable notifications on this device`),XF=I(`<button type=button class="btn small">Turn off on this device`),ZF=I(`<span class=notify-test id=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`),QF=I(`<div class=row-actions>`),$F=I(`<option>`),eI=I(`<p data-test-result>`),tI=I(`<details class=notify-group><summary><h4></h4><span class="small muted notify-group-summary"data-group-summary></span></summary><ul class=switches>`),nI=I(`<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.`),rI=I(`<li><label class=switch><span class=notify-kind><span></span><span class="small muted"></span></span><input type=checkbox>`),iI=I(`<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.`),aI=I(`<ul class=switches><li class=appearance-theme id=set-theme><span id=color-theme>Color theme</span><div class=theme-toggle role=radiogroup aria-labelledby=color-theme></div></li><li class=speed id=set-text-size><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`),oI=I(`<p class="small muted">On this device. Pinch the conversation or the session list to change it too (a trackpad pinch works on desktop).`),sI=I(`<button type=button role=radio class=theme-choice><span>`),cI=I(`<details class=turn-advanced><summary class=small>Advanced</summary><div class=turn-knobs></div><p class="small muted">Empty: the default. Values outside a field's range are clamped. Slow cap: a score slower than this hands the turn to the timers (it rises to twice the usual score time on a slow device, at most 5 s). A URL query parameter (e.g. ?voiceTurn.threshold=0.6) overrides these until the page reloads without it; “in use” shows what applies.`),lI=I(`<ul class=switches><li class=speed id=set-voice-speed><label for=voice-speed>Voice speed</label><input id=voice-speed type=range><output for=voice-speed></output></li><li id=set-sensitivity><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 id=set-turn-detection><div class=switch><span id=voice-turn-detection>Turn detection</span><div class=chips role=radiogroup aria-labelledby=voice-turn-detection></div></div><p class="small muted">When Voice mode decides you finished speaking. Timers: a fixed wait after you stop (1 s, 1.6 s when the words sound unfinished). Smart Turn: an on-device audio model (Pipecat Smart Turn v3, 8.7 MB, loaded on first use) scores your intonation at each pause; a confident “finished” sends at once, otherwise it waits (at most 3 s). The Voice bar shows its score. On this device; applies at once.</p></li><li id=set-voice-front><label class=switch><span>Voice front</span><input type=checkbox></label><p class="small muted">On (the default): in Voice mode a fast voice agent answers in front of the session. It says what it understood, then passes your request to the session, which keeps its own agent and model. No spoken “On it.” phrases (the tones stay). Off: Voice mode talks to the session directly, with short spoken replies. If the front is not available, Voice mode talks to the session directly too. The front runs on the session's Voice model (else the machine's <code>voiceModel</code>): pick a fast paid model. On this device; applies the next time Voice mode starts.</p></li><li id=set-cues><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 id=set-background><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.`),uI=I(`<button type=button class=chip role=radio>`),dI=I(`<label class=small> <input type=number inputmode=decimal> <output class=muted data-turn-effective>in use: `),fI=I(`<h3>Waiting for approval`),pI=I(`<ul class=list>`),mI=I(`<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`),hI=I(`<div class=row><p class="small muted grow">Computers connected to this hub. Set one up with a one-line installer (macOS, Linux, Windows).</p><button type=button id=setup-machine class="btn small">Set up a machine`),gI=I(`<p class="small muted">None yet.`),_I=I(`<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`),vI=I(`<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`),yI=I(`<p class="small muted">`),bI=I(`<span class=muted> · this device`),xI=I(`<li><div class=grow><div class=name></div><div class="small muted">last seen </div></div><button type=button class="btn small danger">`),SI=I(`<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>`),CI=I(`<p class="small muted">Expires in <span class=add-app-countdown></span> · single use`),wI=I(`<div class=row><code class="add-app-link grow"></code><button type=button class="btn small">Copy</button><a class="btn small">Open`),TI=I(`<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.`),EI=I(`<div class=add-app-expired><p class="small warn">This code expired.</p><button type=button class="btn small primary">New code`),DI=I(`<div class=row><p class="small muted grow">Use Hub from a phone or tablet: scan a code in the Hub app to link it to your account.</p><button type=button class="btn small">Add app`),OI=I(`<p class="small muted">How your <a href=/teams>teams</a> work with the rest of your sessions.`),kI=I(`<ul class=switches><li id=team-isolation><label class=switch><span class=notify-kind><span>Team isolation</span><span class="small muted">On: sessions seated in a team see only their teams' sessions; your other sessions are hidden from them. Off: they also see your sessions in no team. Your own view is unchanged either way.</span></span><input type=checkbox data-team-isolation>`),AI=I(`<div class=chips role=group aria-label="Admin sections">`),jI=I(`<p class=error role=alert>`),MI=I(`<div id=admin-machines>`),NI=I(`<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=…).`),PI=I(`<div id=admin-audit>`),FI=I(`<span class=count>`),II=I(`<button type=button class=chip>`),LI=I(`<p class=muted>No machines are waiting for approval.`),RI=I(`<p role=alert>The saved limits are invalid; saving replaces them.`),zI=I(`<p role=alert class="small warn">`),BI=I(`<form class=stack><h3>Agent limits</h3><p class="small muted">Hub-wide limits guard against runaway agent loops.</p><label>Hop limit (<!>) <input type=number min=1 required></label><label>Hop ceiling, the highest hop limit hubs and teams may use (<!>) <input type=number min=1 max=10000 required></label><p class="small muted">Raising the ceiling asks first. Lowering it never rewrites teams: a team above it is capped by the hub-wide limit. Before rolling the hub back to an older version, lower the hop limit to 100 or less.</p><p class="small muted">Launch limits source: <!>.</p><label>Maximum queued launches <input type=number min=1 max=100000 required></label><label>Maximum active launches <input type=number min=1 max=100000 required></label><label>Launches per hour <input type=number min=1 max=100000 required></label><label>Lost after minutes (blank: default, false: never) <input type=text></label><p class="small muted">Item budget source: <!>. Defaults bound each intake item by agent wakes and hours in progress.</p><label>Item budget wakes <input type=number min=10 max=5000 required></label><label>Item budget hours <input type=number min=1 max=720 required></label><p class="small muted">Loop source: <!>. No-progress messages between the same pair of seats.</p><label>Loop messages <input type=number min=4 max=200 required></label><label>Loop window minutes <input type=number min=5 max=240 required></label><button type=submit class="btn primary">Save limits`),VI=I(`<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">`),HI=I(`<p class=muted>`),UI=I(`<li class=muted>No users match.`),WI=I(`<span class=badge-pill>Admin`),GI=I(`<span class="badge-pill off">Disabled`),KI=I(`<span class=badge-pill>You`),qI=I(`<li><div class=grow><div class=name></div><div class="small muted"> · <!> · seen `),JI=I(`<button type=button>`),YI=I(`<p class=muted>No machines are connected to this hub yet.`),XI=I(`<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`),ZI=I(`<ol class="list audit">`),QI=I(`<p class=muted>Nothing recorded yet.`),$I=I(`<li><div class=grow><div class=name></div><div class="small muted"></div></div><time class="small muted">`);function eL(e){return(()=>{var t=TF();return i(t,_({get id(){return e.id}},()=>e.title?{"aria-labelledby":`h-${e.id}`}:{"aria-label":e.label??e.id}),!1,!0),y(t,n(l,{get when(){return e.title},get children(){var t=wF();return y(t,()=>e.title),s(()=>b(t,`id`,`h-${e.id}`)),t}}),null),y(t,()=>e.children,null),t})()}var tL=2400,nL=3e3;function rL(e){if(!e)return;let t=Date.now()+nL,n=()=>{let r=document.getElementById(e);if(!r)Date.now()<t&&setTimeout(n,60);else{for(let e=r.closest(`details`);e;e=e.parentElement?.closest(`details`)??null)e.open=!0;r.scrollIntoView({block:`center`}),r.classList.add(`settings-hit`),setTimeout(()=>r.classList.remove(`settings-hit`),tL)}};requestAnimationFrame(n)}var iL=e=>_t(!0).find(t=>t.id===e)?.label,aL=!1;function oL(){let t=()=>Kn(Z()),i=()=>{let e=CC();return e.name===`settings`?e.section:void 0},a=()=>ht(i(),{admin:t(),phone:Q()}),[c,d]=u(``),f=()=>Ft(c(),yt(t()));x(e(Nt,e=>rL(kt(decodeURIComponent(e.hash.slice(1))))));let p=()=>{aL?(aL=!1,history.back()):Bt(`/settings`)},h=()=>(()=>{var e=EF(),t=e.firstChild;return t.$$keydown=e=>{e.key===`Escape`&&d(``);let t=f()[0];e.key===`Enter`&&t&&(d(``),Bt(`/settings/${t.section}#${t.id}`))},t.$$input=e=>d(e.currentTarget.value),s(()=>t.value=c()),e})();return(()=>{var e=OF(),i=e.firstChild,u=i.firstChild,g=i.nextSibling,_=g.firstChild,x=_.firstChild,S=x.firstChild.nextSibling;return S.nextSibling,y(i,n(l,{get when(){return Q()},get children(){return n(l,{get when(){return a()!==`list`},get fallback(){return n(F,{icon:`menu`,label:`Open sidebar`,onClick:qp})},get children(){return n(F,{icon:`back`,label:`All settings`,onClick:p})}})}}),u),y(u,(()=>{var e=r(()=>!!(Q()&&a()!==`list`));return()=>e()?iL(a())??`Settings`:`Settings`})()),y(g,n(l,{get when(){return!Q()},get children(){var e=DF();return y(e,h,null),y(e,n(m,{get each(){return _t(t())},children:e=>(()=>{var t=kF();return t.$$click=()=>d(``),y(t,()=>e.label),s(n=>{var r=`/settings/${e.id}`,i=a()===e.id&&!c()?`page`:void 0;return r!==n.e&&b(t,`href`,n.e=r),i!==n.t&&b(t,`aria-current`,n.t=i),n},{e:void 0,t:void 0}),t})()}),null),e}}),_),y(_,n(l,{get when(){return r(()=>!!Q())()&&a()===`list`},get children(){return h()}}),x),y(_,n(l,{get when(){return!c()},get fallback(){return n(sL,{get results(){return f()},onPick:()=>d(``)})},get children(){return n(v,{get fallback(){return n(lL,{})},get children(){return[n(o,{get when(){return a()===`list`},get children(){return n(cL,{onPick:()=>aL=!0})}}),n(o,{get when(){return r(()=>a()!==`list`)()&&a()},keyed:!0,children:e=>n(uL,{id:e})})]}})}}),x),y(x,()=>Z()?.publicURL??location.origin,S),y(x,()=>Z()?.version??`?`,null),e})()}function sL(e){return n(l,{get when(){return e.results.length},get fallback(){return jF()},get children(){var t=AF();return y(t,n(m,{get each(){return e.results},children:t=>(()=>{var n=MF(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild;return V(r,`click`,e.onPick,!0),y(i,()=>t.label),y(a,()=>iL(t.section),o),y(a,()=>t.description,null),s(()=>b(r,`href`,`/settings/${t.section}#${t.id}`)),n})()})),t}})}function cL(e){return(()=>{var t=NF();return y(t,n(m,{get each(){return _t(Kn(Z()))},children:t=>(()=>{var r=PF(),i=r.firstChild,a=i.firstChild.firstChild,o=a.nextSibling;return V(i,`click`,e.onPick,!0),y(a,()=>t.label),y(o,()=>t.description),y(i,n(L,{name:`chevron`}),null),s(()=>b(i,`href`,`/settings/${t.id}`)),r})()})),t})()}function lL(){return FF()}function uL(e){return(()=>{var t=IF(),i=t.firstChild;return y(i,()=>iL(e.id)),y(t,n(v,{get children(){return[n(o,{get when(){return e.id===`general`},get children(){return[n(fL,{}),n(mL,{}),n(EL,{})]}}),n(o,{get when(){return e.id===`notifications`},get children(){return n(pL,{})}}),n(o,{get when(){return e.id===`voice`},get children(){return[n(yL,{}),n(zw,{}),n(eL,{id:`speech`,title:`Speech`,get children(){return n(gw,{})}})]}}),n(o,{get when(){return e.id===`media`},get children(){return n(eL,{id:`media-allowlist`,title:`Web images`,get children(){return n(_T,{})}})}}),n(o,{get when(){return e.id===`machines`},get children(){return[n(SL,{}),n(CL,{})]}}),n(o,{get when(){return e.id===`agents`},get children(){return n(fO,{})}}),n(o,{get when(){return e.id===`concierge`},get children(){return[n(jk,{}),n(eL,{id:`context-cards`,title:`Context cards`,get children(){return n(mA,{})}})]}}),n(o,{get when(){return e.id===`teams`},get children(){return n(OL,{})}}),n(o,{get when(){return r(()=>e.id===`admin`)()&&Kn(Z())},get children(){return n(jL,{})}})]}}),null),s(()=>b(t,`data-settings-section`,e.id)),t})()}async function dL(){if(qn(Z()).mode!==`pairing`||await P(`Sign out this device? You will need a new pairing code.`,`Sign out`,{danger:!0})){await(await ip().catch(()=>void 0))?.unsubscribe().catch(()=>{}),await H(`/api/logout`,{method:`POST`,json:{}}).catch(()=>{});try{ss(localStorage)}catch{}dd(),location.href=`/`}}function fL(){let e=()=>qn(Z());return n(eL,{id:`account`,title:`Account`,get children(){var t=zF(),r=t.firstChild,i=r.nextSibling,a=i.firstChild,o=a.firstChild,c=a.nextSibling;c.firstChild;var u=i.nextSibling;return y(r,()=>e().initial),y(o,()=>e().title),y(a,n(l,{get when(){return e().badge},get children(){var t=LF();return y(t,()=>e().badge),t}}),null),y(i,n(l,{get when(){return e().subtitle},get children(){var t=RF();return y(t,()=>e().subtitle),t}}),c),y(c,()=>Z()?.device?.name??`paired`,null),u.$$click=()=>void dL(),s(()=>k(r,`avatar large${e().badge?` admin`:``}`)),t}})}function pL(){let[e,{refetch:t}]=d(Qf,()=>op()),[i,a]=u(!1),[o,c]=u(),[f,p]=u(``),[h,g]=u(),[_,v]=u(null),[x,S]=u(),C=()=>x()??T()?.activityMinutes??5,w=()=>e()?Ke(e().env):void 0,T=()=>e()?.view,E=()=>h()??T()?.prefs,D=()=>h()?_():T()?.quietHours??null,O=async(e,n)=>{a(!0);try{await e(),n&&J(n)}catch(e){J(W(e),`err`)}finally{a(!1),g(void 0),t()}},A=async e=>{try{let t=await(await H(`/api/push/prefs`,{method:`PUT`,json:e})).json();g(t.prefs),v(t.quietHours??null),t.activityMinutes!==void 0&&S(t.activityMinutes)}catch(e){J(W(e),`err`)}},j=async()=>{c(void 0);try{c(ct(await up(f()||void 0)))}catch(e){c({ok:!1,text:W(e)})}};return n(eL,{id:`notifications`,label:`Notifications`,get children(){return[n(l,{get when(){return w()},get fallback(){return qF()},children:t=>[(()=>{var n=JF(),i=n.firstChild,a=i.nextSibling.firstChild.nextSibling.firstChild.nextSibling,o=a.nextSibling.nextSibling,c=o.nextSibling.nextSibling;return y(i,()=>t().message),y(a,(()=>{var t=r(()=>!!e().env.supported);return()=>t()?e().env.permission:`unsupported`})()),y(o,()=>e().env.worker?`registered`:`not registered`),y(c,()=>e().env.hubSubscribed?`yes`:`no`),s(e=>{var n=t().warn?`notify-status warn`:`notify-status ok`,r=t().state;return n!==e.e&&k(i,e.e=n),r!==e.t&&b(i,`data-state`,e.t=r),e},{e:void 0,t:void 0}),n})(),(()=>{var r=QF();return y(r,n(l,{get when(){return t().action===`enable`},get children(){var e=YF();return e.$$click=()=>void O(cp,`Notifications are on for this device`),s(()=>e.disabled=i()),e}}),null),y(r,n(l,{get when(){return t().action===`disable`},get children(){var e=XF();return e.$$click=()=>void O(lp,`Notifications are off for this device`),s(()=>e.disabled=i()),e}}),null),y(r,n(l,{get when(){return e().env.hubSubscriptions>0},get children(){var e=ZF(),t=e.firstChild;t.firstChild;var r=t.nextSibling;return t.addEventListener(`change`,e=>p(e.currentTarget.value)),y(t,n(m,{each:Qt,children:e=>(()=>{var t=$F();return y(t,()=>e.label),s(()=>t.value=e.key),t})()}),null),r.$$click=()=>void j(),s(()=>t.value=f()),e}}),null),r})(),n(l,{get when(){return o()},children:e=>(()=>{var t=eI();return y(t,()=>e().text),s(()=>k(t,e().ok?`small ok`:`small err`)),t})()})]}),n(l,{get when(){return E()},get children(){return[BF(),(()=>{var e=VF();return y(e,()=>ye(E())),e})(),n(l,{get when(){return r(()=>!!w())()&&w().state!==`on`},get children(){return HF()}}),n(l,{get when(){return r(()=>`activity`in E()&&!E().activity)()&&!E().done},get children(){return UF()}}),n(m,{get each(){return Kt.filter(e=>e.kinds.some(e=>e.key in E()))},children:e=>(()=>{var t=tI(),i=t.firstChild,a=i.firstChild,o=a.nextSibling,c=i.nextSibling;return y(a,()=>e.title),y(o,()=>ft(e.kinds,E())),y(c,n(m,{get each(){return e.kinds.filter(e=>e.key in E())},children:e=>(()=>{var t=rI(),i=t.firstChild.firstChild,a=i.firstChild,o=a.nextSibling,c=i.nextSibling;return y(a,()=>e.label),y(o,()=>e.description),c.addEventListener(`change`,t=>void A({[e.key]:t.currentTarget.checked})),y(t,n(l,{get when(){return r(()=>e.key===`activity`)()&&E().activity},get children(){var e=nI(),t=e.firstChild.firstChild.nextSibling;return t.addEventListener(`change`,e=>void A({activityMinutes:Number(e.currentTarget.value)})),y(t,n(m,{each:at,children:e=>(()=>{var t=$F();return y(t,e===1?`minute`:`${e} minutes`),s(()=>t.value=String(e)),t})()})),s(()=>t.value=String(C())),e}}),null),s(n=>{var r=`pref-${e.key}`,i=e.key;return r!==n.e&&b(t,`id`,n.e=r),i!==n.t&&b(c,`data-pref`,n.t=i),n},{e:void 0,t:void 0}),s(()=>c.checked=!!E()[e.key]),t})()})),s(()=>b(t,`data-notify-group`,e.title)),t})()}),WF(),(()=>{var e=GF(),t=e.firstChild,r=t.firstChild.firstChild.nextSibling;return r.addEventListener(`change`,e=>void A({quietHours:e.currentTarget.checked?{start:`22:00`,end:`07:00`,timeZone:Xt()}:null})),y(t,n(l,{get when(){return D()},children:e=>(()=>{var t=iI(),n=t.firstChild,r=n.firstChild.nextSibling,i=n.nextSibling,a=i.firstChild.nextSibling,o=i.nextSibling,c=o.firstChild;return r.addEventListener(`change`,t=>void A({quietHours:{...e(),start:t.currentTarget.value,timeZone:Xt()}})),a.addEventListener(`change`,t=>void A({quietHours:{...e(),end:t.currentTarget.value,timeZone:Xt()}})),y(o,()=>e().timeZone,c),s(()=>r.value=e().start),s(()=>a.value=e().end),t})()}),null),s(()=>r.checked=!!D()),e})(),n(l,{get when(){return ep().size},get children(){var e=KF(),t=e.firstChild;return y(e,()=>gn(ep().size,`session`),t),e}})]}})]}})}function mL(){return n(eL,{id:`appearance`,title:`Appearance`,get children(){return[(()=>{var e=aI(),t=e.firstChild,r=t.firstChild.nextSibling,i=t.nextSibling.firstChild.nextSibling,a=i.nextSibling,o=a.nextSibling;return y(r,n(m,{each:nj,children:e=>(()=>{var t=sI(),n=t.firstChild;return t.$$click=()=>lj(e),y(t,e===`light`?`☀`:e===`dark`?`☾`:`▣`,n),y(n,()=>e[0].toUpperCase()+e.slice(1)),s(()=>b(t,`aria-checked`,sj()===e)),t})()})),i.$$input=e=>QA(Number(e.currentTarget.value)),b(i,`min`,NA),b(i,`max`,PA),b(i,`step`,FA),y(a,()=>UA(YA())),o.$$click=()=>QA(1),s(e=>{var t=UA(YA()),n=YA()===1;return t!==e.e&&b(i,`aria-valuetext`,e.e=t),n!==e.t&&(o.disabled=e.t=n),e},{e:void 0,t:void 0}),s(()=>i.value=YA()),e})(),oI()]}})}var hL={low:`Low`,normal:`Normal`,high:`High`},gL={timers:`Timers (current)`,smart:`Smart Turn (experimental)`},_L={threshold:{label:`Threshold`,step:`0.05`},graceMs:{label:`Grace (ms)`,step:`50`},fallbackMs:{label:`Fallback (ms)`,step:`100`},slowMs:{label:`Slow cap (ms)`,step:`100`}},vL=D_.flatMap(e=>_L[e.field]?[{...e,..._L[e.field],placeholder:String(w_[e.field])}]:[]);function yL(){let[e,t]=u(Xy.speed),[r,i]=u(Xy.sensitivity),[a,o]=u(Xy.turnDetection),[c,d]=u(Xy.smartTurn);return n(eL,{id:`voice`,title:`Voice`,get children(){var u=lI(),f=u.firstChild,p=f.firstChild.nextSibling,h=p.nextSibling,g=f.nextSibling,_=g.firstChild.firstChild.nextSibling,v=g.nextSibling,x=v.firstChild,S=x.firstChild.nextSibling;x.nextSibling;var C=v.nextSibling,w=C.firstChild.firstChild.nextSibling,T=C.nextSibling,E=T.firstChild.firstChild.nextSibling,D=T.nextSibling.firstChild.firstChild.nextSibling;return p.$$input=e=>{Xy.speed=Number(e.currentTarget.value),t(Xy.speed)},b(p,`min`,Ha),b(p,`max`,2),b(p,`step`,Ua),y(h,()=>Ga(e())),y(_,n(m,{each:My,children:e=>(()=>{var t=uI();return t.$$click=()=>{Xy.sensitivity=e,i(e)},y(t,()=>hL[e]),s(n=>{var i=r()===e,a=r()===e;return i!==n.e&&b(t,`aria-checked`,n.e=i),a!==n.t&&b(t,`aria-pressed`,n.t=a),n},{e:void 0,t:void 0}),t})()})),y(S,n(m,{each:S_,children:e=>(()=>{var t=uI();return t.$$click=()=>{Xy.turnDetection=e,o(e),N_({mode:e,load:h_})},y(t,()=>gL[e]),s(n=>{var r=a()===e,i=a()===e;return r!==n.e&&b(t,`aria-checked`,n.e=r),i!==n.t&&b(t,`aria-pressed`,n.t=i),n},{e:void 0,t:void 0}),t})()})),y(v,n(l,{get when(){return a()===`smart`},get children(){var e=cI(),t=e.firstChild.nextSibling;return y(t,n(m,{each:vL,children:e=>(()=>{var t=dI(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling.nextSibling;return i.firstChild,y(t,()=>e.label,n),r.addEventListener(`change`,t=>{t.currentTarget.value=Xy.setSmartTurnKnob(e.key,t.currentTarget.value),d(Xy.smartTurn)}),y(i,()=>c()[e.field],null),s(n=>{var i=e.key,a=e.min,o=e.max,s=e.step,c=e.placeholder;return i!==n.e&&b(t,`data-turn-knob`,n.e=i),a!==n.t&&b(r,`min`,n.t=a),o!==n.a&&b(r,`max`,n.a=o),s!==n.o&&b(r,`step`,n.o=s),c!==n.i&&b(r,`placeholder`,n.i=c),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),s(()=>r.value=O_(e.key,localStorage.getItem(e.key))??``),t})()})),e}}),null),w.addEventListener(`change`,e=>Xy.front=e.currentTarget.checked),E.addEventListener(`change`,e=>Xy.cues=e.currentTarget.checked),D.addEventListener(`change`,e=>Xy.background=e.currentTarget.checked),s(()=>b(p,`aria-valuetext`,Ga(e()))),s(()=>p.value=e()),s(()=>w.checked=Xy.front),s(()=>E.checked=Xy.cues),s(()=>D.checked=Xy.background),u}})}async function bL(e,t){try{await H(`/api/enrollments/${q(e.userCode)}/${t}`,{method:`POST`,json:{}}),J(t===`approve`?`${e.machineName} approved; it belongs to you`:`Request denied`)}catch(e){J(W(e),`err`)}Md()}function xL(){return n(l,{get when(){return su().length},get children(){return[fI(),(()=>{var e=pI();return y(e,n(m,{get each(){return su()},children:e=>(()=>{var t=mI(),n=t.firstChild,r=n.firstChild,i=r.nextSibling,a=i.firstChild.nextSibling;a.nextSibling;var o=n.nextSibling,s=o.nextSibling;return y(r,()=>e.machineName),y(i,()=>e.userCode,a),y(i,()=>z(e.created,N()),null),o.$$click=()=>void bL(e,`approve`),s.$$click=()=>void bL(e,`deny`),t})()})),e})()]}})}function SL(){let e=async e=>{if(await P(`Revoke ${e.name}? Its OpenCode processes disconnect and it must be connected again.`,`Revoke`,{danger:!0}))try{await H(`/api/machines/${q(e.id)}`,{method:`DELETE`}),J(`${e.name} revoked`)}catch(e){J(W(e),`err`)}};return n(eL,{id:`machines`,title:`Machines`,get children(){return[(()=>{var e=hI(),t=e.firstChild.nextSibling;return t.$$click=()=>xF(),e})(),n(xL,{}),n(l,{get when(){return(X.machines??[]).length},get fallback(){return gI()},get children(){var t=pI();return y(t,n(m,{get each(){return X.machines},children:t=>(()=>{var n=_I(),i=n.firstChild,a=i.firstChild,o=a.firstChild;o.nextSibling;var c=a.nextSibling,l=i.nextSibling;return y(a,()=>t.name,null),y(c,(()=>{var e=r(()=>!!t.online);return()=>e()?`online · ${gn(t.processes.length,`OpenCode process`)}`:`offline · seen ${z(t.lastSeen,N())}`})()),l.$$click=()=>void e(t),s(e=>{var n=`online-dot${t.online?` on`:``}`,r=`Revoke machine ${t.name}`;return n!==e.e&&k(o,e.e=n),r!==e.t&&b(l,`aria-label`,e.t=r),e},{e:void 0,t:void 0}),n})()})),t}})]}})}function CL(){let[e,{refetch:t,mutate:i}]=d(()=>K(`/api/devices`).then(e=>e.devices)),[a,o]=u(!1),s=async e=>{if(e.current)return void dL();if(await P(`Revoke ${e.name}?`,`Revoke`,{danger:!0})){try{await H(`/api/devices/${q(e.id)}`,{method:`DELETE`}),J(`${e.name} revoked`)}catch(e){J(W(e),`err`)}t()}};return n(eL,{id:`devices`,title:`Devices`,get children(){return[(()=>{var e=vI(),t=e.firstChild.nextSibling;return t.$$click=()=>o(!0),e})(),n(l,{get when(){return a()},get children(){return n(TL,{get known(){return new Set((e()??[]).map(e=>e.id))},onLinked:e=>i(e),onClose:()=>{o(!1),t()}})}}),n(l,{get when(){return e()},get fallback(){return(()=>{var t=yI();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?W(e.error):`Loading…`})()),t})()},get children(){var t=pI();return y(t,n(m,{get each(){return e()},children:e=>(()=>{var t=xI(),r=t.firstChild,i=r.firstChild,a=i.nextSibling;a.firstChild;var o=r.nextSibling;return y(i,()=>e.name,null),y(i,n(l,{get when(){return e.current},get children(){return bI()}}),null),y(a,()=>z(e.lastSeen,N()),null),o.$$click=()=>void s(e),y(o,()=>e.current?`Sign out`:`Revoke`),t})()})),t}})]}})}var wL=2e3;function TL(e){let[t,r]=u(),[i,a]=u(``),[o,c]=u(Date.now()),d=async()=>{a(``);try{let e=await H(`/api/devices/link`,{method:`POST`,json:{}}),t=await e.json(),n=Date.now();c(n),r({...t,expiresAt:_A(t.expiresAt,e.headers.get(`date`),n)})}catch(e){a(W(e))}},f=()=>(t()?.expiresAt??0)<=o(),p=()=>{let e=t();return e?jA(e.url,{ecc:`M`}):void 0},m=setInterval(()=>c(Date.now()),1e3),h=!1,g=setInterval(async()=>{if(!(h||!t()||f())){h=!0;try{let t=(await K(`/api/devices`)).devices,n=gA(e.known,t);n&&(e.onLinked(t),J(`${n.name} linked`),e.onClose())}catch{}finally{h=!1}}},wL);return M(()=>{clearInterval(m),clearInterval(g)}),d(),n(de,{open:!0,title:`Add the Hub app`,get onClose(){return e.onClose},class:`add-app`,get children(){return n(l,{get when(){return t()},get fallback(){return(()=>{var e=yI();return y(e,()=>i()||`Creating a link code…`),e})()},children:e=>(()=>{var t=TI(),r=t.firstChild,i=r.firstChild.nextSibling.nextSibling.nextSibling,a=r.nextSibling;return y(i,()=>e().hub),y(t,n(l,{get when(){return!f()},get fallback(){return(()=>{var e=EI(),t=e.firstChild.nextSibling;return t.$$click=()=>void d(),e})()},get children(){return[(()=>{var e=SI(),t=e.firstChild.nextSibling;return s(n=>{var r=`0 0 ${p().size+8} ${p().size+8}`,i=MA(p(),4);return r!==n.e&&b(e,`viewBox`,n.e=r),i!==n.t&&b(t,`d`,n.t=i),n},{e:void 0,t:void 0}),e})(),(()=>{var t=CI(),n=t.firstChild.nextSibling;return y(n,()=>hA(e().expiresAt,o())),t})(),(()=>{var t=wI(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling;return y(n,()=>e().url),r.$$click=()=>void navigator.clipboard?.writeText(e().url).then(()=>J(`Link copied`),()=>J(`Copy failed`,`err`)),s(()=>b(i,`href`,e().url)),t})()]}}),a),t})()})}})}function EL(){let[e,t]=u(),r=async()=>{try{t(new Set((await K(`/api/devices`)).devices.map(e=>e.id)))}catch(e){J(W(e),`err`)}};return n(eL,{id:`add-app`,title:`Add the Hub app`,get children(){return[(()=>{var e=DI(),t=e.firstChild.nextSibling;return t.$$click=()=>void r(),e})(),n(l,{get when(){return e()},children:e=>n(TL,{get known(){return e()},onLinked:()=>{},onClose:()=>t(void 0)})})]}})}var DL=`/api/agent/team-settings`;function OL(){let[e,{mutate:t,refetch:i}]=d(()=>K(DL).then(e=>e.settings)),[a,o]=u(!1),c=async n=>{let r=e();if(!r)return;let a=n.checked;o(!0);try{let e=await(await H(DL,{method:`PUT`,json:{teamIsolation:a,expectedRevision:r.revision}})).json();t(e.settings),J(a?`Team isolation is on`:`Team isolation is off`)}catch(e){n.checked=!a,e instanceof G&&e.status===409?(J(`Team settings changed elsewhere. Showing the current setting; try again.`,`err`),i()):J(W(e),`err`)}finally{o(!1)}};return n(eL,{id:`teams`,label:`Teams`,get children(){return[OI(),n(l,{get when(){return e()},get fallback(){return(()=>{var t=yI();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?`Could not load: ${W(e.error)}`:`Loading…`})()),t})()},children:e=>(()=>{var t=kI(),n=t.firstChild.firstChild.firstChild.nextSibling;return n.addEventListener(`change`,e=>void c(e.currentTarget)),s(()=>n.disabled=a()),s(()=>n.checked=e().teamIsolation),t})()})]}})}var kL=(e,t)=>Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[],AL=e=>e.id===`local`?`Hub owner (pairing)`:e.name||e.email||e.id;function jL(){let e=()=>Yn(Z()),[t,r]=u(e()[0]?.[0]??`machines`),[i,a]=u(``);x(()=>{let t=Nt().hash,n=t===`#admin-machines`?`machines`:t===`#admin-audit`?`audit`:void 0;n&&e().some(([e])=>e===n)&&r(n)});let o=async(e,t)=>{try{return await e(),a(``),J(t),!0}catch(e){return a(cr(e)),J(i(),`err`),!1}};return n(eL,{id:`admin`,label:`Admin`,get children(){return[(()=>{var i=AI();return y(i,n(m,{get each(){return e()},children:([e,i])=>(()=>{var o=II();return o.$$click=()=>(r(e),a(``)),y(o,i,null),y(o,n(l,{get when(){return e===`approvals`&&su().length},get children(){var e=FI();return y(e,()=>su().length),e}}),null),s(()=>b(o,`aria-pressed`,t()===e)),o})()})),i})(),n(l,{get when(){return i()},get children(){var e=jI();return y(e,i),e}}),n(l,{get when(){return t()===`users`},get children(){return n(NL,{change:o})}}),n(l,{get when(){return t()===`machines`},get children(){var e=MI();return y(e,n(PL,{change:o})),e}}),n(l,{get when(){return t()===`approvals`},get children(){return[NI(),n(l,{get when(){return su().length},get fallback(){return LI()},get children(){return n(xL,{})}})]}}),n(l,{get when(){return t()===`audit`},get children(){var e=PI();return y(e,n(FL,{})),e}}),n(l,{get when(){return t()===`agent-limits`},get children(){return n(ML,{change:o})}})]}})}function ML(e){let[t,r]=u(),[i,a]=u(``),[o,c]=u(``),[d,f]=u(),[p,m]=u(``),[h,g]=u(``),[_,v]=u(``),[x,S]=u(``),[C,w]=u(``),[T,E]=u(``),[D,O]=u(``),[k,A]=u(``),j=async()=>{let e=await K(`/api/settings/agent-limits`);r(e),a(String(e.hopLimit)),c(String(e.hopCeiling)),m(String(e.launches.maxQueued)),g(String(e.launches.maxActive)),v(String(e.launches.perHour)),S(e.launches.lostAfterMinutes===!1?`false`:e.launches.lostAfterMinutes===void 0?``:String(e.launches.lostAfterMinutes)),w(String(e.itemBudget.wakes)),E(String(e.itemBudget.hours)),O(String(e.loop.messages)),A(String(e.loop.windowMinutes))};return R(()=>void j()),(()=>{var r=BI(),u=r.firstChild.nextSibling,M=u.nextSibling,N=M.firstChild.nextSibling,ee=N.nextSibling.nextSibling,F=M.nextSibling,te=F.firstChild.nextSibling,I=te.nextSibling.nextSibling,ne=F.nextSibling,re=ne.nextSibling,ie=re.firstChild.nextSibling;ie.nextSibling;var ae=re.nextSibling,oe=ae.firstChild.nextSibling,se=ae.nextSibling,ce=se.firstChild.nextSibling,L=se.nextSibling,le=L.firstChild.nextSibling,ue=L.nextSibling,de=ue.firstChild.nextSibling,R=ue.nextSibling,z=R.firstChild.nextSibling;z.nextSibling;var fe=R.nextSibling,pe=fe.firstChild.nextSibling,B=fe.nextSibling,V=B.firstChild.nextSibling,me=B.nextSibling,he=me.firstChild.nextSibling;he.nextSibling;var ge=me.nextSibling,_e=ge.firstChild.nextSibling,ve=ge.nextSibling,ye=ve.firstChild.nextSibling,be=ve.nextSibling;return r.addEventListener(`submit`,n=>{n.preventDefault();let r=t();if(!r)return;let a=dr({hop:i(),ceiling:o(),maxQueued:p(),maxActive:h(),perHour:_(),lost:x()},r);f(a.ok?void 0:{field:a.field,error:a.error}),a.ok&&(async()=>{(!a.confirm||await P(a.confirm,`Raise the ceiling`,{danger:!0}))&&await e.change(async()=>{await H(`/api/settings/agent-limits`,{method:`PUT`,json:{...a.body,itemBudget:{wakes:Number(C()),hours:Number(T())},loop:{messages:Number(D()),windowMinutes:Number(k())}}}),await j()},`Agent limits saved`)})()}),y(r,n(l,{get when(){return t()?.invalidStored},get children(){return RI()}}),u),y(M,()=>t()?.sources.hopLimit??`loading`,N),ee.$$input=e=>a(e.currentTarget.value),y(r,n(l,{get when(){return d()?.field===`hop`},get children(){var e=zI();return y(e,()=>d().error),e}}),F),y(F,()=>t()?.sources.hopCeiling??`loading`,te),I.$$input=e=>c(e.currentTarget.value),y(r,n(l,{get when(){return d()?.field===`ceiling`},get children(){var e=zI();return y(e,()=>d().error),e}}),ne),y(re,()=>t()?.sources.launches??`loading`,ie),oe.$$input=e=>m(e.currentTarget.value),ce.$$input=e=>g(e.currentTarget.value),le.$$input=e=>v(e.currentTarget.value),de.$$input=e=>S(e.currentTarget.value),y(R,()=>t()?.sources.itemBudget??`loading`,z),pe.$$input=e=>w(e.currentTarget.value),V.$$input=e=>E(e.currentTarget.value),y(me,()=>t()?.sources.loop??`loading`,he),_e.$$input=e=>O(e.currentTarget.value),ye.$$input=e=>A(e.currentTarget.value),s(e=>{var n=o()||`10000`,r=!t();return n!==e.e&&b(ee,`max`,e.e=n),r!==e.t&&(be.disabled=e.t=r),e},{e:void 0,t:void 0}),s(()=>ee.value=i()),s(()=>I.value=o()),s(()=>oe.value=p()),s(()=>ce.value=h()),s(()=>le.value=_()),s(()=>de.value=x()),s(()=>pe.value=C()),s(()=>V.value=T()),s(()=>_e.value=D()),s(()=>ye.value=k()),r})()}function NL(e){let[t,{refetch:i}]=d(()=>K(`/api/admin/users`).then(e=>kL(e,`users`))),[a,o]=u(``),[c,f]=u(`all`),[p,h]=u(`role`),g=async(t,n)=>{await P(n.confirm,n.label,{danger:!!n.danger})&&(await e.change(()=>H(`/api/admin/users/${q(t.id)}`,{method:`PUT`,json:n.change}),`${AL(t)}: ${n.label.toLowerCase()} done`)&&t.id===Z()?.user?.id&&(nu(void 0),await Gu().catch(()=>!1)),i())};return(()=>{var e=VI(),i=e.firstChild.firstChild,u=i.nextSibling,d=u.nextSibling;return i.$$input=e=>o(e.currentTarget.value),u.addEventListener(`change`,e=>f(e.currentTarget.value)),y(u,n(m,{each:Wn,children:([e,t])=>(()=>{var n=$F();return n.value=e,y(n,t),n})()})),d.addEventListener(`change`,e=>h(e.currentTarget.value)),y(d,n(m,{each:Un,children:([e,t])=>(()=>{var n=$F();return n.value=e,y(n,t),n})()})),y(e,n(l,{get when(){return t()},get fallback(){return(()=>{var e=HI();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${cr(t.error)}`:`Loading…`})()),e})()},get children(){var e=pI();return y(e,n(m,{get each(){return or(t(),{query:a(),filter:c(),sort:p()})},get fallback(){return UI()},children:e=>(()=>{var i=qI(),a=i.firstChild,o=a.firstChild,c=o.nextSibling,u=c.firstChild,d=u.nextSibling;return d.nextSibling,y(o,()=>AL(e),null),y(o,n(l,{get when(){return e.role===`admin`},get children(){return WI()}}),null),y(o,n(l,{get when(){return e.disabled},get children(){return GI()}}),null),y(o,n(l,{get when(){return e.id===Z()?.user?.id},get children(){return KI()}}),null),y(a,n(l,{get when(){return r(()=>!!e.name)()&&e.email},get children(){var t=RF();return y(t,()=>e.email),t}}),c),y(c,()=>gn(e.machines??0,`machine`),u),y(c,()=>gn(e.devices??0,`device`),d),y(c,()=>z(e.lastSeen,N())||`never`,null),y(i,n(m,{get each(){return sr(e,t(),Z()?.user?.id)},children:t=>(()=>{var n=JI();return n.$$click=()=>void g(e,t),y(n,()=>t.label),s(()=>k(n,`btn small${t.danger?` danger`:``}`)),n})()}),null),s(()=>k(i,e.disabled?`disabled`:``)),i})()})),e}}),null),s(()=>i.value=a()),s(()=>u.value=c()),s(()=>d.value=p()),e})()}function PL(e){let[t,{refetch:i}]=d(()=>K(`/api/admin/machines`).then(e=>kL(e,`machines`)));return n(l,{get when(){return t()},get fallback(){return(()=>{var e=HI();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${cr(t.error)}`:`Loading…`})()),e})()},get children(){return n(l,{get when(){return t().length},get fallback(){return YI()},get children(){var a=pI();return y(a,n(m,{get each(){return t()},children:t=>{let n=t.ownerEmail??(t.ownerID===`local`?`hub owner`:t.ownerID)??`unknown`;return(()=>{var a=XI(),o=a.firstChild,c=o.firstChild,l=c.firstChild;l.nextSibling;var u=c.nextSibling,d=u.firstChild,f=o.nextSibling;return y(c,()=>t.name,null),y(u,n,d),y(u,()=>t.ownerID===Z()?.user?.id?` (you)`:``,d),y(u,(()=>{var e=r(()=>!!t.online);return()=>e()?`online`:`offline · seen ${z(t.lastSeen,N())}`})(),null),f.$$click=async()=>{await P(`Revoke ${t.name} (${n})? Its OpenCode processes disconnect and it must be connected again.`,`Revoke`,{danger:!0})&&(await e.change(()=>H(`/api/admin/machines/${q(t.id)}`,{method:`DELETE`}),`${t.name} revoked`),i())},s(()=>k(l,`online-dot${t.online?` on`:``}`)),a})()}})),a}})}})}function FL(){let[e]=d(async()=>{let[e,t,n]=await Promise.all([K(`/api/admin/audit`),K(`/api/admin/users`).then(e=>kL(e,`users`),()=>[]),K(`/api/admin/machines`).then(e=>kL(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 ir(kL(e,`audit`).length?kL(e,`audit`):kL(e,`entries`),r)});return n(l,{get when(){return e()},get fallback(){return(()=>{var t=HI();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?`Could not load: ${cr(e.error)}`:`Loading…`})()),t})()},get children(){return n(l,{get when(){return e().length},get fallback(){return QI()},get children(){var t=ZI();return y(t,n(m,{get each(){return e()},children:e=>(()=>{var t=$I(),n=t.firstChild,i=n.firstChild,a=i.nextSibling,o=n.nextSibling;return y(i,()=>e.action),y(a,()=>e.actor,null),y(a,(()=>{var t=r(()=>!!e.target);return()=>t()?` → ${e.target}`:``})(),null),y(a,(()=>{var t=r(()=>!!e.detail);return()=>t()?` · ${e.detail}`:``})(),null),y(o,()=>z(e.at,N())),s(t=>{var n=new Date(e.at).toISOString(),r=new Date(e.at).toLocaleString();return n!==t.e&&b(o,`datetime`,t.e=n),r!==t.t&&b(o,`title`,t.t=r),t},{e:void 0,t:void 0}),t})()})),t}})}})}B([`input`,`keydown`,`click`]);var IL=I(`<a href=/settings/voice#recordings title="This conversation is recorded on this hub (Settings → Voice → Recording)"><span class=recording-dot aria-hidden=true>`),LL=I(`<button type=button class="btn small recording-mark"data-recording-mark title="Bookmark this moment in the recording (or say “mark that”)">Mark`),RL=I(`<span class="recording-note small"data-recording-note>`),zL=I(`<span class=sr-only role=status aria-live=polite data-recording-status>`);function BL(){let[e,t]=u(Pl.get());return M(Pl.subscribe(()=>t(Pl.get()))),e}function VL(e){let t=BL(),i=t=>e.sessionID===void 0||t.sessionID===void 0||t.sessionID===e.sessionID,a=()=>t().on&&i(t()),o=a(),[c,d]=u(``);return M(Pl.subscribe(()=>{let e=Pl.get(),t=e.on&&i(e);t!==o&&(o=t,d(t?`Recording on`:`Recording off`))})),[n(l,{get when(){return a()},get children(){var e=IL();return e.firstChild,y(e,()=>Fl(t()),null),s(n=>{var r=`recording-indicator${t().audio?``:` no-audio`}`,i=t().audio?`on`:`no-audio`,a=`${Fl(t())}: this conversation is recorded on the hub. Open the recording settings`;return r!==n.e&&k(e,n.e=r),i!==n.t&&b(e,`data-recording-indicator`,n.t=i),a!==n.a&&b(e,`aria-label`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),e}}),n(l,{get when(){return r(()=>!!(e.mark&&a()))()&&t().marks},get children(){var e=LL();return e.$$click=()=>Kl(),e}}),n(l,{get when(){return r(()=>!(a()||!t().note))()&&i(t())},get children(){var e=RL();return y(e,()=>t().note),e}}),n(l,{get when(){return e.announce},get children(){var e=zL();return y(e,c),e}})]}B([`click`]);var HL=I(`<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 UL(){let e=()=>Ix().sessionID??``;return(()=>{var t=HL(),r=t.firstChild,i=r.firstChild.nextSibling,a=r.nextSibling;return y(t,n(L,{name:`wave`}),r),y(i,Lx),y(t,n(VL,{announce:!0,get sessionID(){return e()}}),a),a.$$click=()=>void Ex.end(),s(n=>{var i=`voice-pill ${Ix().voice}`,a=`Voice mode is on in ${Lx()}`,o=Dt(e());return i!==n.e&&k(t,n.e=i),a!==n.t&&b(t,`aria-label`,n.t=a),o!==n.a&&b(r,`href`,n.a=o),n},{e:void 0,t:void 0,a:void 0}),t})()}B([`click`]);var WL=`/api/agent/workspaces`,GL=50,KL=4e3,qL=e=>e instanceof G?{status:e.status,...e.code?{code:e.code}:{},message:e.message,...e.details?{details:e.details}:{}}:{status:0,message:e instanceof en||e instanceof Error?e.message:String(e)},JL=e=>Ym(qL(e));function YL(){let[e,t]=u(`loading`),[n,r]=u(),[i,a]=u([]),[o,s]=Ar({}),[c,l]=u(),[d,f]=u(new Set),p=new Map,m=new Map,h=!1;async function g(){try{let e=Fm(await K(`${WL}?state=active&limit=${GL}`));a(e.items),r(void 0),t(`ready`)}catch(e){e instanceof G&&(e.status===404||e.code===`unsupported`)?t(`unavailable`):e instanceof G&&e.status===403?t(`forbidden`):(r(JL(e)),t(`error`))}}async function _(e){p.set(e,Date.now()),s(e,e=>({...e??{},loading:!0}));try{let t=Pm(await K(`${WL}/${q(e)}/board`));if(!t)throw Error(`The hub sent a board this console can't read.`);return s(e,e=>({...e,board:t,loading:!1,error:void 0})),t}catch(t){s(e,e=>({...e,loading:!1,error:JL(t)}));return}}async function v(){try{l(Se(await K(`/api/agent/grants`)))}catch{l(`error`)}}function y(e){if(m.has(e))return;let t=Math.max(0,(p.get(e)??0)+KL-Date.now());m.set(e,setTimeout(()=>{m.delete(e),d().has(e)&&document.visibilityState!==`hidden`&&_(e)},t))}function b(){h||(h=!0,g(),Fu(e=>{if(e.type===`resync`&&g(),e.type===`catalog`||e.type===`resync`)for(let e of d())y(e)}))}function x(e){let t=new Set(d());t.has(e)?t.delete(e):(t.add(e),_(e),c()===void 0&&v()),f(t)}let S=(e,t)=>s(e,e=>({...e??{loading:!1},notice:t}));async function C(e,t){await H(`${WL}/${q(e)}/supervision`,{method:`PUT`,json:t})}async function w(e,t,n){let r=o[e]?.board;if(!r||o[e]?.saving)return;let i=Rm(r,t);if(i)i!==`unchanged`&&S(e,{text:qm(i),kind:`warn`});else{s(e,e=>({...e,saving:!0,notice:{text:`Saving: ${n}…`,kind:``}}));try{await T(e,t,Gm(t,r.revision),n)}finally{s(e,e=>({...e,saving:!1}))}}}async function T(e,t,n,r){try{await C(e,n),await _(e),S(e,{text:`Done: ${r}.`,kind:``});return}catch(t){if(!(t instanceof G&&t.status===409&&t.code===`conflict`)){S(e,{text:JL(t),kind:`err`}),_(e);return}}let i=await _(e);if(!i)return S(e,{text:`The workspace changed elsewhere and could not be reloaded. Your change is kept: ${r}.`,kind:`warn`,pending:t});let a=Jm(t,i);if(a.kind===`done`)return S(e,{text:`Already done elsewhere: ${r}.`,kind:``});if(a.kind===`dropped`)return S(e,{text:a.reason,kind:`warn`});try{await C(e,a.body),await _(e),S(e,{text:`The workspace changed elsewhere; re-applied your change: ${r}.`,kind:``})}catch(n){_(e),n instanceof G&&n.status===409?S(e,{text:`The workspace keeps changing elsewhere. Your change is kept: ${r}.`,kind:`warn`,pending:t}):S(e,{text:JL(n),kind:`err`})}}return{availability:e,listError:n,workspaces:i,boards:o,grants:c,expanded:d,start:b,loadList:g,loadBoard:_,toggle:x,move:w,notify:S}}var XL=ce(YL),ZL=`hub.sidebar.sections.collapsed`;function QL(e){try{let t=JSON.parse(e.getItem(`hub.sidebar.sections.collapsed`)??`[]`);return new Set(Array.isArray(t)?t.filter(e=>typeof e==`string`):[])}catch{return new Set}}function $L(e,t){let n=QL(e);n.has(t)?n.delete(t):n.add(t);try{e.setItem(ZL,JSON.stringify([...n]))}catch{}return n}var eR=e=>e!==`results`;function tR(e,t,n){if(t&&eR(e)){if(e===`needs`)return{text:String(t),label:`${gn(t,`session`)} ${t===1?`needs`:`need`} you`};if(n)return{text:String(t),label:gn(t,e===`workspaces`?`workspace`:`session`)}}}var nR=I(`<button type=button class=side-section-toggle><span class=side-section-title>`),rR=I(`<div class=side-section-head>`),iR=I(`<span class=side-section-title>`),aR=I(`<span aria-hidden=true data-section-count>`),[oR,sR]=u(QL(localStorage)),cR=(e,t)=>eR(t)&&oR().has(e),lR=e=>`side-sec-${e.replace(/[^A-Za-z0-9_-]/g,`-`)}`;function uR(e){let t=()=>cR(e.id,e.kind),r=()=>tR(e.kind,e.count,t());return(()=>{var i=rR();return y(i,n(l,{get when(){return eR(e.kind)},get fallback(){return(()=>{var t=iR();return y(t,()=>e.title),t})()},get children(){var i=nR(),a=i.firstChild;return i.$$click=()=>sR($L(localStorage,e.id)),y(i,n(L,{get name(){return t()?`chevron`:`down`},class:`side-section-caret`}),a),y(a,()=>e.title),y(i,n(l,{get when(){return r()},children:t=>(()=>{var n=aR();return y(n,()=>t().text),s(()=>k(n,`side-count${e.kind===`needs`?` needs`:``}`)),n})()}),null),s(n=>{var a=!t(),o=lR(e.id),s=e.id,c=r()?`${e.title}, ${r().label}`:e.title,l=t()?`Show ${e.title}`:`Hide ${e.title}`;return a!==n.e&&b(i,`aria-expanded`,n.e=a),o!==n.t&&b(i,`aria-controls`,n.t=o),s!==n.a&&b(i,`data-section-toggle`,n.a=s),c!==n.o&&b(i,`aria-label`,n.o=c),l!==n.i&&b(i,`title`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),i}}),null),y(i,()=>e.children,null),i})()}B([`click`]);var dR=I(`<p class=side-empty>Workspaces are not available to this device.`),fR=I(`<p class=side-empty role=alert>Could not load workspaces: <!> <button type=button class=link-btn>Retry`),pR=I(`<ul class=ws-list>`),mR=I(`<section aria-label=Workspaces data-section=workspaces>`),hR=I(`<p class=ws-goal><span class=sr-only>Goal: `),gR=I(`<div class=ws-panel>`),_R=I(`<li><button type=button class=ws-head><span class=ws-title>`),vR=I(`<p class=ws-notice role=status aria-live=polite>`),yR=I(`<p class=side-empty role=alert>Could not load the board: <!> <button type=button class=link-btn>Retry`),bR=I(`<button type=button class=link-btn>Retry`),xR=I(`<p class=side-empty>Loading…`),SR=I(`<p class=side-empty>No members yet.`),CR=I(`<ul role=tree>`),wR=I(`<div>Drop here: no supervisor`),TR=I(`<p class=ws-keys>Drag to change supervision, or Alt+arrows. Supervision grants nothing.`),ER=I(`<p class=ws-keys>`),DR=I(`<span class="ws-rel ws-spawned"title="Native parent session (unchanged by supervision)">spawned by <a tabindex=-1>`),OR=I(`<span class="ws-rel ws-supervised"title="Workspace supervision link">supervised by `),kR=I(`<ul class=ws-assignments>`),AR=I(`<li role=treeitem><div class=ws-row><a class=ws-member tabindex=-1></a></div><p class=ws-meta>`),jR=I(`<span>`),MR=I(`<span class=ws-assignment-stale> · stale`),NR=I(`<li><span class=ws-assignment-title></span> <span class=ws-assignment-status>`),PR=I(`<ul>`),FR=I(`<details class=ws-controls><summary>Delegated controls</summary><p class=muted>Read-only. Grants held by roles or apps are not listed here; dragging never creates one.`),IR=I(`<p>Could not load your grants.`),LR=I(`<p>Loading…`),RR=I(`<p> holds no grant from you. Supervising grants nothing: it can message and ask, and actions on this session come to you as Decisions. <a href=/settings/agents#grants>Grants are in Settings → Agents & access.`),zR=I(`<li> · <!> · <!> <span class=muted>(grant <!>)`),BR=new Set([`idle`,`working`,`blocked`,`error`]),VR={open:`open`,in_progress:`in progress`,blocked:`blocked`},HR={ArrowRight:`indent`,ArrowLeft:`outdent`,ArrowUp:`up`,ArrowDown:`down`};function UR(e){let t=XL;R(()=>t.start());let r=()=>{let e=t.availability();return e===`forbidden`||e===`error`||e===`ready`&&t.workspaces().length>0};return n(l,{get when(){return r()},get children(){var r=mR();return y(r,n(uR,{id:`workspaces`,kind:`workspaces`,title:`Workspaces`,get count(){return t.workspaces().length}}),null),y(r,n(l,{get when(){return t.availability()===`forbidden`},get children(){return dR()}}),null),y(r,n(l,{get when(){return t.availability()===`error`},get children(){var e=fR(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling;return y(e,()=>t.listError(),n),r.$$click=()=>void t.loadList(),e}}),null),y(r,n(l,{get when(){return!cR(`workspaces`,`workspaces`)},get children(){var r=pR();return y(r,n(m,{get each(){return t.workspaces()},children:t=>n(WR,{ws:t,get onPick(){return e.onPick}})})),s(()=>b(r,`id`,lR(`workspaces`))),r}}),null),s(()=>k(r,`side-section ws-section${cR(`workspaces`,`workspaces`)?` collapsed`:``}`)),r}})}function WR(e){let t=XL,r=()=>t.expanded().has(e.ws.id),i=`ws-panel-${e.ws.id}`;return(()=>{var a=_R(),o=a.firstChild,c=o.firstChild;return o.$$click=()=>t.toggle(e.ws.id),b(o,`aria-controls`,i),y(o,n(L,{get name(){return r()?`down`:`chevron`}}),c),y(c,()=>e.ws.title),y(a,n(l,{get when(){return e.ws.goal},get children(){var t=hR();return t.firstChild,y(t,()=>e.ws.goal,null),s(()=>b(t,`title`,e.ws.goal)),t}}),null),y(a,n(l,{get when(){return r()},get children(){var t=gR();return b(t,`id`,i),y(t,n(qR,{get ws(){return e.ws},get onPick(){return e.onPick}})),t}}),null),s(t=>{var n=`ws-item${r()?` open`:``}`,i=e.ws.id,s=r();return n!==t.e&&k(a,t.e=n),i!==t.t&&b(a,`data-workspace`,t.t=i),s!==t.a&&b(o,`aria-expanded`,t.a=s),t},{e:void 0,t:void 0,a:void 0}),a})()}var GR=(e,t)=>{let n=e.members.find(e=>e.memberID===t);if(!n)return`a member`;let r=Zm(X.machines,n.sessionID);return r.found?r.title:n.session?.name??n.sessionID};function KR(e,t,n){let r=GR(e,t.memberID);return t.supervisorMemberID===null?`${r} has no supervisor`:n===`reorder`?`${r} reordered`:`${r} supervised by ${GR(e,t.supervisorMemberID)}`}function qR(e){let i=XL,o=()=>e.ws.id,c=()=>i.boards[o()],d=()=>c()?.board,f=C(()=>d()?Lm(d()):void 0),[p,h]=u(),[g,_]=u(),[v,S]=u(),w,T,E=()=>{let e=f();if(e?.flat.length)return e.flat.some(e=>e.member.memberID===p())?p():e.flat[0].member.memberID},D=e=>{h(e),w?.querySelector(`[data-member="${CSS.escape(e)}"]`)?.focus()};x(()=>{if(f(),T){let e=T;queueMicrotask(()=>{w?.querySelector(`[data-member="${CSS.escape(e)}"]`)&&(T=void 0,D(e))})}});let j=(e,t,n=!1)=>{let r=d();e&&r&&(n&&(T=e.memberID),i.move(o(),e,KR(r,e,t)))},M=(t,n,r)=>{let a=r.flat.indexOf(n);if(t.altKey&&HR[t.key]){t.preventDefault();let e=HR[t.key],a=Wm(r,n.member.memberID,e);return a?j(a,e===`up`||e===`down`?`reorder`:`supervise`,!0):i.notify(o(),{text:`No move that way.`,kind:`warn`})}if(t.altKey||t.ctrlKey||t.metaKey)return;let s=t.key===`ArrowDown`?r.flat[a+1]:t.key===`ArrowUp`?r.flat[a-1]:t.key===`Home`?r.flat[0]:t.key===`End`?r.flat[r.flat.length-1]:void 0;s?(t.preventDefault(),D(s.member.memberID)):t.key===`Enter`&&t.target===t.currentTarget&&(t.preventDefault(),e.onPick?.(),Bt(Dt(n.member.sessionID)))},N=e=>{let t=e.currentTarget.querySelector(`.ws-row`).getBoundingClientRect(),n=e.clientY-t.top;return n<t.height*.25?`before`:n>t.height*.75?`after`:`inside`},ee=(e,t)=>{let n=d(),r=e.member.memberID,i=[];for(let[e,a,o]of[[`indent`,`Supervised by the member above`,`Alt+→`],[`outdent`,`Up one level`,`Alt+←`],[`up`,`Move up`,`Alt+↑`],[`down`,`Move down`,`Alt+↓`],[`detach`,`No supervisor`,``]]){let s=Wm(t,r,e);s&&!Rm(n,s)&&i.push({label:a,hint:o,run:()=>j(s,e===`up`||e===`down`?`reorder`:`supervise`,!0)})}let a=t.flat.filter(e=>e.member.memberID!==r&&!Rm(n,Um(t,r,{memberID:e.member.memberID,position:`inside`})));if(a.length){i.push({section:`Supervised by`});for(let e of a)i.push({label:GR(n,e.member.memberID),run:()=>j(Um(t,r,{memberID:e.member.memberID,position:`inside`}),`supervise`,!0)})}return i.length||i.push({label:n.workspace.state===`active`?e.member.master?`The master is the root`:`No moves`:`Archived: read-only`,disabled:!0,run:()=>{}}),i};return[(()=>{var e=vR();return y(e,()=>c()?.notice?.text??``,null),y(e,n(l,{get when(){return c()?.notice?.pending},children:e=>(()=>{var t=bR();return t.$$click=()=>j(e(),`supervise`),t})()}),null),e})(),n(l,{get when(){return c()?.error},get children(){var e=yR(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return y(e,()=>c().error,t),n.$$click=()=>void i.loadBoard(o()),e}}),n(l,{get when(){return f()},get fallback(){return n(l,{get when(){return!c()?.error},get children(){return xR()}})},children:u=>[n(l,{get when(){return!u().flat.length},get children(){return SR()}}),(()=>{var r=CR(),f=w;return typeof f==`function`?t(f,r):w=r,y(r,n(m,{get each(){return u().flat},children:t=>{let r=()=>Zm(X.machines,t.member.sessionID),c=()=>GR(d(),t.member.memberID),f=()=>t.supervisorMemberID?u().flat.find(e=>e.member.memberID===t.supervisorMemberID)?.children??[]:u().roots,p=()=>Qm(t,d(),X.machines),x=()=>BR.has(t.member.session?.state??``)?t.member.session.state:`idle`,C=()=>d().workspace.state===`active`&&!i.boards[o()]?.saving;return(()=>{var i=AR(),o=i.firstChild,d=o.firstChild,w=o.nextSibling;return i.addEventListener(`drop`,e=>{let n=g();if(!n)return;e.preventDefault(),e.stopPropagation();let r=N(e);_(void 0),S(void 0),j(Um(u(),n,{memberID:t.member.memberID,position:r}),r===`inside`?`supervise`:`reorder`)}),i.addEventListener(`dragleave`,e=>{e.currentTarget.contains(e.relatedTarget)||S(void 0)}),i.addEventListener(`dragover`,e=>{let n=g();n&&n!==t.member.memberID&&(e.preventDefault(),e.stopPropagation(),S(`${t.member.memberID}:${N(e)}`))}),i.addEventListener(`dragend`,()=>{hm(),_(void 0),S(void 0)}),i.addEventListener(`dragstart`,e=>{mm(e,{target:{sessionID:t.member.sessionID},label:c()}),e.dataTransfer?.setData(`text/plain`,t.member.memberID),e.dataTransfer&&(e.dataTransfer.effectAllowed=`move`),_(t.member.memberID)}),i.$$keydown=e=>M(e,t,u()),i.addEventListener(`focus`,e=>e.target===e.currentTarget&&h(t.member.memberID)),y(o,n(A,{get state(){return x()}}),d),d.$$click=()=>e.onPick?.(),b(d,`draggable`,!1),y(d,c),y(o,n(O,{get label(){return`Move ${c()}`},class:`icon-btn small row-more`,items:()=>ee(t,u())}),null),y(w,n(m,{get each(){return eh(t.member,r())},children:e=>(()=>{var t=jR();return y(t,()=>e.label),s(n=>{var r=`ws-badge ${e.kind}`,i=e.title;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),null),y(w,n(l,{get when(){return p().spawnedBy},get children(){var e=DR(),t=e.firstChild.nextSibling;return y(t,()=>p().spawnedBy.title),s(()=>b(t,`href`,Dt(p().spawnedBy.sessionID))),e}}),null),y(w,n(l,{get when(){return p().supervisedBy},get children(){var e=OR();return e.firstChild,y(e,()=>p().supervisedBy.title,null),e}}),null),y(i,n(l,{get when(){return t.assignments.length},get children(){var e=kR();return y(e,n(m,{get each(){return t.assignments},children:e=>(()=>{var t=NR(),r=t.firstChild,i=r.nextSibling.nextSibling;return y(r,()=>e.title),y(i,()=>VR[e.status]??e.status),y(t,n(l,{get when(){return e.stale?.length},get children(){var t=MR();return s(()=>b(t,`title`,e.stale.join(`, `))),t}}),null),s(()=>k(t,`ws-assignment ${e.status}`)),t})()})),s(()=>b(e,`aria-label`,`Assignments of ${c()}`)),e}}),null),y(i,n(l,{get when(){return p().supervisedBy},children:e=>n(JR,{get supervisorSessionID(){return e().sessionID},get supervisorTitle(){return e().title},get memberDirectory(){return r().directory}})}),null),s(e=>{var n=t.depth+1,r=f().length,o=f().indexOf(t)+1,s=E()===t.member.memberID,l=`${c()}${t.member.master?`, master`:``}${p().supervisedBy?`, supervised by ${p().supervisedBy.title}`:``}`,u=E()===t.member.memberID?0:-1,m=t.member.memberID,h=`ws-node${t.member.presence===`online`?``:` away`}${g()===t.member.memberID?` dragged`:``}${v()?.startsWith(`${t.member.memberID}:`)?` drop-${v().split(`:`)[1]}`:``}`,_=String(t.depth),y=C()&&!t.member.master,x=Dt(t.member.sessionID);return n!==e.e&&b(i,`aria-level`,e.e=n),r!==e.t&&b(i,`aria-setsize`,e.t=r),o!==e.a&&b(i,`aria-posinset`,e.a=o),s!==e.o&&b(i,`aria-selected`,e.o=s),l!==e.i&&b(i,`aria-label`,e.i=l),u!==e.n&&b(i,`tabindex`,e.n=u),m!==e.s&&b(i,`data-member`,e.s=m),h!==e.h&&k(i,e.h=h),_!==e.r&&a(i,`--ws-depth`,e.r=_),y!==e.d&&b(i,`draggable`,e.d=y),x!==e.l&&b(d,`href`,e.l=x),e},{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}),i})()}})),s(t=>{var n=`ws-tree${g()?` dragging`:``}`,i=`Supervision in ${e.ws.title}`,a=`ws-keys-${o()}`,s=c()?.saving?`true`:void 0;return n!==t.e&&k(r,t.e=n),i!==t.t&&b(r,`aria-label`,t.t=i),a!==t.a&&b(r,`aria-describedby`,t.a=a),s!==t.o&&b(r,`aria-busy`,t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),r})(),n(l,{get when(){return g()},get children(){var e=wR();return e.addEventListener(`drop`,e=>{e.preventDefault();let t=g();_(void 0),S(void 0),t&&j(Um(u(),t,{root:!0}),`supervise`)}),e.addEventListener(`dragleave`,()=>S(void 0)),e.addEventListener(`dragover`,e=>{e.preventDefault(),S(`root`)}),s(()=>k(e,`ws-root-drop${v()===`root`?` over`:``}`)),e}}),(()=>{var e=TR();return s(()=>b(e,`id`,`ws-keys-${o()}`)),e})(),n(l,{get when(){return u().staleLinks||d().membersTruncated||d().linksTruncated},get children(){var e=ER();return y(e,n(l,{get when(){return u().staleLinks},get children(){return[r(()=>u().staleLinks),` link(s) to departed members not shown. `]}}),null),y(e,n(l,{get when(){return d().membersTruncated||d().linksTruncated},children:`Some members are not shown (limit).`}),null),e}})]})]}function JR(e){let t=XL,i=()=>{let n=t.grants();return Array.isArray(n)?rh(n,e.supervisorSessionID,e.memberDirectory,Date.now()):n};return(()=>{var t=FR(),a=t.firstChild.nextSibling;return y(t,n(l,{get when(){return i()!==`error`},get fallback(){return IR()},get children(){return n(l,{get when(){return Array.isArray(i())},get fallback(){return LR()},get children(){return n(l,{get when(){return i().length},get fallback(){return(()=>{var t=RR(),n=t.firstChild;return y(t,()=>e.supervisorTitle,n),t})()},get children(){var e=PR();return y(e,n(m,{get each(){return i()},children:e=>(()=>{var t=zR(),n=t.firstChild,i=n.nextSibling,a=i.nextSibling.nextSibling,o=a.nextSibling.nextSibling,s=o.firstChild.nextSibling;return s.nextSibling,y(t,()=>e.verbs.join(`, `),n),y(t,(()=>{var t=r(()=>e.covers===void 0);return()=>t()?`folder unknown`:e.covers?`covers this session's folder`:`not this session's folder`})(),i),y(t,()=>ws(e.expiresAt,Date.now()),a),y(o,()=>e.grantID,s),t})()})),e}})}})}}),a),t})()}B([`click`,`keydown`]);var YR=I(`<nav aria-label=Primary><ul>`),XR=I(`<a>`),ZR=I(`<li>`),QR=I(`<a class="side-link nav-link disabled"aria-disabled=true>`),$R=I(`<div class=nav-rail>`),ez=()=>({signedIn:!!Z(),concierge:gu()?.state});function tz(e){let t=()=>Ce(Nt().pathname);return(()=>{var r=YR(),i=r.firstChild;return y(i,n(m,{get each(){return xe(ez())},children:r=>(()=>{var i=ZR();return y(i,n(l,{get when(){return r.enabled},get fallback(){return(()=>{var t=QR();return y(t,n(L,{get name(){return r.dest.icon}}),null),y(t,n(l,{get when(){return!e.compact},get children(){return r.dest.label}}),null),s(n=>{var i=`${r.dest.label} isn't available`,a=e.compact?r.dest.label:void 0;return i!==n.e&&b(t,`title`,n.e=i),a!==n.t&&b(t,`aria-label`,n.t=a),n},{e:void 0,t:void 0}),t})()},get children(){var i=XR();return i.$$click=()=>e.onPick?.(),y(i,n(L,{get name(){return r.dest.icon}}),null),y(i,n(l,{get when(){return!e.compact},get children(){return r.dest.label}}),null),s(n=>{var a=`side-link nav-link${t()===r.dest.id?` active`:``}`,o=r.dest.route,s=t()===r.dest.id?`page`:void 0,c=e.compact?r.dest.label:void 0,l=e.compact?r.dest.label:void 0;return a!==n.e&&k(i,n.e=a),o!==n.t&&b(i,`href`,n.t=o),s!==n.a&&b(i,`aria-current`,n.a=s),c!==n.o&&b(i,`aria-label`,n.o=c),l!==n.i&&b(i,`title`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),i}})),i})()})),s(()=>k(r,e.compact?`nav-rail-links`:`feature-nav`)),r})()}function nz(e){return(()=>{var t=$R();return y(t,n(F,{icon:`sidebar`,label:`Show sidebar (⌘B)`,get onClick(){return e.onExpand}}),null),y(t,n(tz,{compact:!0}),null),t})()}B([`click`]);var rz=I(`<span class=concierge-btn-text>Concierge`),iz=I(`<span aria-hidden=true>`),az=I(`<button type=button>`),oz=I(`<a href=/settings/concierge data-concierge-button=disabled data-indicator=off>`),sz;function cz(){let e=sz;return sz=void 0,e}function lz(e){let t=()=>ut().name===`concierge`,i=()=>e.labelled?rz():null,a=e=>n(l,{get when(){return e.indicator!==`running`},get children(){var t=iz();return y(t,(()=>{var t=r(()=>e.indicator===`attention`);return()=>t()?e.count??`!`:``})()),s(()=>k(t,`concierge-ind ind-${e.indicator}`)),t}});return n(l,{get when(){return gu()},children:r=>{let o=()=>Zs(r(),Cu(),t(),Date.now(),Ws(lu(),r(),{tiers:`all`}).length,new Set(lu().filter(e=>e.state===`open`).map(e=>e.id)));return n(l,{get when(){return Ys(r())===!0},get fallback(){return(()=>{var t=oz();return t.$$click=()=>e.onPick?.(),y(t,n(L,{name:`spark`}),null),y(t,i,null),y(t,()=>a(o()),null),s(n=>{var r=`icon-btn concierge-btn off ind-off${e.labelled?` labelled`:``}`,i=o().label,a=o().title;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`aria-label`,n.t=i),a!==n.a&&b(t,`title`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()},get children(){var c=az();return c.$$click=n=>{if(e.onPick?.(),t())return xt(`/`);sz=n.currentTarget,Bt(`/concierge`)},y(c,n(L,{name:`spark`}),null),y(c,i,null),y(c,()=>a(o()),null),s(n=>{var i=`icon-btn concierge-btn state-${r().state} ind-${o().indicator}${t()?` on`:``}${e.labelled?` labelled`:``}`,a=o().label,s=t(),l=o().title,u=r().state,d=o().indicator;return i!==n.e&&k(c,n.e=i),a!==n.t&&b(c,`aria-label`,n.t=a),s!==n.a&&b(c,`aria-expanded`,n.a=s),l!==n.o&&b(c,`title`,n.o=l),u!==n.i&&b(c,`data-concierge-button`,n.i=u),d!==n.n&&b(c,`data-indicator`,n.n=d),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),c}})}})}B([`click`]);var uz=I(`<section class="side-section side-decisions"aria-label=Decisions><ul class=side-list><li class=side-row><a class=side-row-link data-side-decisions><span class=decision-mark aria-hidden=true>⚑</span><span class=side-title>`),dz=I(`<div class=sidebar><div class=side-top><a class=brand href=/><span class=brand-name>Hub</span></a><div class=side-top-actions></div></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><nav class=side-sessions aria-label=Sessions><div class=side-head><span>Sessions</span></div><div class=side-scroll></div></nav><div class=side-foot>`),fz=I(`<p class=side-empty>`),pz=I(`<a class="icon-btn small">`),mz=I(`<ul class=side-list>`),hz=I(`<section>`),gz=I(`<span aria-hidden=true>`),_z=I(`<span class=account-name>`),vz=I(`<span class=badge title="Machines waiting for approval">`),yz=I(`<span class="terminal-wait small muted"title="Herdr says this session waits for input; answer it in its terminal"data-waiting-in-terminal>waiting in terminal`),bz=I(`<span class=jobs-badge>`),xz=I(`<span class=unread-dot role=img aria-label=Unread>`),Sz=I(`<a class=side-row-link><span class=side-text><span class=side-title>`),Cz=I(`<li>`),wz=I(`<span class=side-row-link>`),Tz=I(`<span class=side-sub data-row-sub>`),Ez=I(`<span class="waiting-since small">`),Dz=`hub.sidebar.groupBy`,Oz=`hub.sidebar.sort`;function kz(e){let[t,i]=u(``),[a,o]=u(localStorage.getItem(Dz)===`machine`?`machine`:`project`),[c,d]=u(localStorage.getItem(Oz)===`title`?`title`:`recent`),f=C(()=>Na(Iu(),{query:t(),groupBy:a(),sortBy:c(),now:N()})),p=()=>{let e=CC();return e.name===`session`?e.id:void 0},h=()=>qn(Z()),g=(e,t)=>{e&&(o(e),localStorage.setItem(Dz,e)),t&&(d(t),localStorage.setItem(Oz,t))};return(()=>{var o=dz(),u=o.firstChild,d=u.firstChild,_=d.firstChild,v=d.nextSibling,x=u.nextSibling,S=x.firstChild,C=x.nextSibling,w=C.firstChild,T=C.nextSibling,E=T.firstChild;E.firstChild;var D=E.nextSibling,A=T.nextSibling;return d.$$click=()=>e.phone&&e.onClose(),y(d,n(ef,{class:`brand-mark`}),_),y(v,n(lz,{labelled:!0,onPick:()=>e.phone&&e.onClose()}),null),y(v,n(l,{get when(){return e.phone},get fallback(){return n(F,{icon:`sidebar`,label:`Collapse sidebar (⌘B)`,get onClick(){return e.onCollapse}})},get children(){return n(F,{icon:`close`,label:`Close sidebar`,get onClick(){return e.onClose}})}}),null),y(x,n(L,{name:`search`}),S),S.$$keydown=e=>e.key===`Escape`&&i(``),S.$$input=e=>i(e.currentTarget.value),C.$$click=()=>e.phone&&e.onClose(),y(C,n(L,{name:`plus`}),w),y(o,n(tz,{onPick:()=>e.phone&&e.onClose()}),T),y(E,n(O,{label:`Group and sort`,items:()=>[{section:`Group by`},{label:`Project`,checked:a()===`project`,run:()=>g(`project`,void 0)},{label:`Server`,checked:a()===`machine`,run:()=>g(`machine`,void 0)},{section:`Sort by`},{label:`Recent activity`,checked:c()===`recent`,run:()=>g(void 0,`recent`)},{label:`Title`,checked:c()===`title`,run:()=>g(void 0,`title`)}]}),null),y(D,n(l,{get when(){return lu().length},get children(){var t=uz(),n=t.firstChild.firstChild.firstChild,i=n.firstChild.nextSibling;return n.$$click=()=>e.phone&&e.onClose(),y(i,(()=>{var e=r(()=>lu().length===1);return()=>e()?`A Decision waits for you`:`${lu().length} Decisions wait for you`})()),s(()=>b(n,`href`,Ws(lu(),gu(),{tiers:`all`}).length===lu().length?`/concierge`:`/`)),t}}),null),y(D,n(l,{get when(){return f().length},get fallback(){return(()=>{var e=fz();return y(e,()=>t()?`No sessions match.`:`No sessions yet.`),e})()},get children(){return n(m,{get each(){return f()},children:t=>(()=>{var i=hz();return y(i,n(uR,{get id(){return t.id},get kind(){return t.kind},get title(){return t.title},get count(){return t.rows.length},get children(){return n(l,{get when(){return r(()=>t.kind===`group`)()&&t.machineID},get children(){var e=pz();return y(e,n(L,{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&&b(e,`aria-label`,n.e=r),i!==n.t&&b(e,`title`,n.t=i),a!==n.a&&b(e,`href`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),e}})}}),null),y(i,n(l,{get when(){return!cR(t.id,t.kind)},get children(){var r=mz();return y(r,n(m,{get each(){return t.rows},children:t=>n(Az,{row:t,get active(){return p()===t.id},onPick:()=>e.phone&&e.onClose()})})),s(()=>b(r,`id`,lR(t.id))),r}}),null),s(e=>{var n=`side-section ${t.kind}${cR(t.id,t.kind)?` collapsed`:``}`,r=t.title,a=t.id;return n!==e.e&&k(i,e.e=n),r!==e.t&&b(i,`aria-label`,e.t=r),a!==e.a&&b(i,`data-section`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),i})()})}}),null),y(D,n(UR,{onPick:()=>e.phone&&e.onClose()}),null),y(A,n(O,{get label(){return`Account and settings (${h().title})`},class:`account`,align:`left`,up:!0,get text(){return[(()=>{var e=gz();return y(e,()=>h().initial),s(()=>k(e,`avatar${h().badge?` admin`:``}`)),e})(),(()=>{var e=_z();return y(e,()=>h().title),e})(),n(l,{get when(){return su().length},get children(){var e=vz();return y(e,()=>su().length),e}}),n(L,{name:`settings`})]},items:()=>[{label:`Settings`,hint:su().length?`${su().length} to approve`:void 0,run:()=>{e.phone&&e.onClose(),Bt(`/settings`)}},{label:`Set up Hub on a machine`,run:()=>{e.phone&&e.onClose(),xF({returnTo:()=>document.querySelector(`.side-foot .account`)})}}]})),s(()=>S.value=t()),o})()}function Az(e){let t=()=>e.row,r=()=>Ix().phase!==`off`&&Ix().sessionID===t().id;return(()=>{var i=Cz();return y(i,n(l,{get when(){return!Uh(t().id,`sidebar`)},get fallback(){return(()=>{var e=wz();return y(e,n(A,{get state(){return t().state}}),null),y(e,n($g,{get id(){return t().id},get title(){return t().title},place:`sidebar`,class:`side-title`,children:null}),null),e})()},get children(){var r=Sz(),i=r.firstChild,a=i.firstChild;return V(r,`dragend`,hm),r.addEventListener(`dragstart`,e=>mm(e,{target:{sessionID:t().id},label:t().title})),V(r,`click`,e.onPick,!0),y(r,n(A,{get state(){return t().state}}),i),y(r,n(l,{get when(){return Ia(t(),Ix())},get children(){return n(ne,{})}}),i),y(a,()=>t().title),y(i,n(l,{get when(){return Ba(t())},children:e=>(()=>{var t=Tz();return y(t,e),t})()}),null),y(r,n(e_,{get id(){return t().id}}),null),y(r,n(l,{get when(){return Va(t(),N())},children:e=>(()=>{var t=Ez();return y(t,e),s(()=>b(t,`title`,`Waiting for you for ${e()}`)),t})()}),null),y(r,n(l,{get when(){return t().error},children:e=>n(ie,{get text(){return e()}})}),null),y(r,n(l,{get when(){return t().waitingInTerminal},get children(){return yz()}}),null),y(r,n(l,{get when(){return t().jobs},get children(){var e=bz();return y(e,()=>t().jobs),s(n=>{var r=Yi(t().jobs),i=Yi(t().jobs);return r!==n.e&&b(e,`title`,n.e=r),i!==n.t&&b(e,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),e}}),null),y(r,n(l,{get when(){return t().unread},get children(){return xz()}}),null),s(n=>{var i=Dt(t().id),a=e.active?`page`:void 0,o=`${t().title} · ${t().where} · ${t().machineName}${t().error?` · ${t().error}`:``}`,s=!Q();return i!==n.e&&b(r,`href`,n.e=i),a!==n.t&&b(r,`aria-current`,n.t=a),o!==n.a&&b(r,`title`,n.a=o),s!==n.o&&b(r,`draggable`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),r}}),null),y(i,n(O,{get label(){return`More actions for ${t().title}`},class:`icon-btn small row-more`,items:()=>Gh(t(),{open:!1,place:`sidebar`})}),null),s(()=>k(i,`side-row${e.active?` active`:``}${t().unread?` unread`:``}${r()?` voice-here`:``}`)),i})()}B([`click`,`input`,`keydown`]);var jz={cycle:`F6`,close:`Control+Alt+W`,moveEarlier:`Control+Alt+Shift+ArrowLeft`,moveLater:`Control+Alt+Shift+ArrowRight`,focus:e=>`Control+Alt+${e}`},Mz=new Set([`ArrowLeft`,`ArrowUp`]),Nz=new Set([`ArrowRight`,`ArrowDown`]);function Pz(e){if(e.metaKey)return;if(e.key===`F6`&&!e.ctrlKey&&!e.altKey)return{type:`cycle`,step:e.shiftKey?-1:1};if(!e.ctrlKey||!e.altKey)return;if(e.shiftKey)return Mz.has(e.key)?{type:`move`,step:-1}:Nz.has(e.key)?{type:`move`,step:1}:void 0;if(e.code===`KeyW`)return{type:`close`};let t=/^Digit([1-9])$/.exec(e.code),n=t?Number(t[1]):0;return n>=1&&n<=hn?{type:`focus`,index:n-1}:void 0}var Fz=`hub.paneSizes.v1`,Iz={cols:280,rows:160},Lz=[`vertical`,`horizontal`,`grid`];function Rz(e,t){return t<=1||e===`single`?{cols:1,rows:1}:e===`vertical`?{cols:t,rows:1}:e===`horizontal`?{cols:1,rows:t}:{cols:Math.min(2,t),rows:Math.ceil(t/2)}}function zz(e,t,n){if(t<=1||e===`single`)return{col:0,row:0,colSpan:1};if(e===`vertical`)return{col:n,row:0,colSpan:1};if(e===`horizontal`)return{col:0,row:n,colSpan:1};let r=t%2==1&&n===t-1;return{col:r?0:n%2,row:Math.floor(n/2),colSpan:r?2:1}}function Bz(e){return e>0?Array.from({length:e},()=>1/e):[]}function Vz(e,t,n,r,i){if(!Number.isInteger(t)||t<0||t>=e.length-1||!(r>0)||!Number.isFinite(n))return e;let a=e[t],o=a+e[t+1],s=Math.min(i/r,o/2),c=Math.min(o-s,Math.max(s,a+n/r));return e.map((e,n)=>n===t?c:n===t+1?o-c:e)}function Hz(e,t,n,r,i,a,o){let s=r?64:16,[c,l]=o===`cols`?[`ArrowRight`,`ArrowLeft`]:[`ArrowDown`,`ArrowUp`];if(n===c)return Vz(e,t,s,i,a);if(n===l)return Vz(e,t,-s,i,a);if(n===`Home`)return Vz(e,t,-2*i,i,a);if(n===`End`)return Vz(e,t,2*i,i,a)}var Uz=(e,t,n)=>`${e}:${t}:${n}`;function Wz(e){let[t,n,r,...i]=e.split(`:`),a=Number(n);if(i.length||!Lz.includes(t)||!Number.isInteger(a)||a<2||a>hn||r!==`cols`&&r!==`rows`)return;let o=Rz(t,a)[r];return o>1?o:void 0}function Gz(e,t){if(!Array.isArray(e)||e.length!==t||!e.every(e=>typeof e==`number`&&Number.isFinite(e)&&e>0))return;let n=e.reduce((e,t)=>e+t,0);return e.map(e=>e/n)}function Kz(e){let t;try{t=JSON.parse(e?.getItem(`hub.paneSizes.v1`)??`null`)}catch{return{}}if(typeof t!=`object`||!t||t.v!==1)return{};let n=t.sizes;if(typeof n!=`object`||!n||Array.isArray(n))return{};let r={};for(let[e,t]of Object.entries(n)){let n=Wz(e),i=n===void 0?void 0:Gz(t,n);i&&(r[e]=i)}return r}function qz(e,t,n,r,i,a){let o=Uz(n,r,i),s=Wz(o),c=s===void 0?void 0:Gz(a,s);if(!c)return t;let l={...t,[o]:c};try{e?.setItem(Fz,JSON.stringify({v:1,sizes:l}))}catch{}return l}function Jz(e,t,n){let r=Rz(t,n),i=i=>{let a=e[Uz(t,n,i)];return a&&a.length===r[i]?a:Bz(r[i])};return{cols:i(`cols`),rows:i(`rows`)}}function Yz(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 Xz=200,Zz=10,Qz=e=>e instanceof Error?e.message:String(e),$z=e=>e&&typeof e==`object`&&typeof e.status==`number`?e.status:void 0,eB=class{timeline;fetch;options;state=`idle`;error;cursor;invalid=!1;generation=0;loading;oldestMessageID;constructor(e,t,n={}){this.timeline=e,this.fetch=t,this.options=n}get hasOlder(){return this.cursor!==void 0}get cutMessageID(){return this.cursor===void 0?void 0:this.oldestMessageID}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.oldestMessageID=tB(n.items),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=Qz(t),this.invalid=$z(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=Qz(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.oldestMessageID=tB(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<Zz;e++){let e=await this.fetch({limit:Xz,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()}};function tB(e){if(!Array.isArray(e))return;let t=e.find(e=>e&&typeof e==`object`&&(e.depth??0)===0);return typeof t?.messageID==`string`&&t.messageID?t.messageID:void 0}var nB=[`native`,`hooks`,`rpc`,`screen`],rB={opencode:`OpenCode`,"claude-code":`Claude Code`,codex:`Codex`},iB=e=>rB[e]??e;function aB(e){let t=e?.harness||`opencode`,n=e?.features?.includes(`setModel`)===!0;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,sessionModel:n,queued:!1};let r=nB.includes(e?.evidence??``)?e.evidence:`unknown`,i=e?.features?new Set(e.features):void 0,a=e=>!i||i.has(e);return{native:!1,harness:t,harnessName:iB(t),evidence:r,turn:a(`turn`),steer:a(`steer`),interrupt:a(`interrupt`),stop:a(`stop`),permission:a(`permission`),form:a(`form`),models:a(`models`),timeline:a(`timeline`),summary:a(`summary`),voice:a(`conversation`)&&a(`steer`),sessionModel:n,queued:r===`hooks`||r===`screen`||r===`unknown`}}var oB={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 sB(e){if(e.native)return;let t=oB[e.evidence];return{level:e.evidence,label:t.label,detail:t.detail(e.harnessName)}}function cB(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 lB(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 uB={queued:`queued`,retained:`held`,pending:`pending`,dropped:`not delivered`};function dB(e){return typeof e==`string`?uB[e]:void 0}function fB(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 pB=/data:([\w.+-]+\/[\w.+-]+)?((?:;[\w.+-]+=[^;,\s"'<>]*)*);base64,([A-Za-z0-9+/_-]+={0,2})/gi,mB=/^[A-Za-z0-9+/_-]+={0,2}$/,hB=[`mime`,`mimeType`,`media_type`,`mediaType`];function gB(e){let t=e.endsWith(`==`)?2:+!!e.endsWith(`=`),n=Math.max(0,Math.floor(e.length*3/4)-t);return n<1024?`${n} B`:n<1048576?`${Math.round(n/1024)} KB`:`${(n/1048576).toFixed(1)} MB`}function _B(e,t){return`[${e||`data`}, ${gB(t)} — not shown]`}function vB(e){return e.includes(`base64,`)?e.replace(pB,(e,t,n,r)=>_B(t?.toLowerCase(),r)):e}function yB(e){if(typeof e.data!=`string`||!mB.test(e.data))return;let t=hB.map(t=>e[t]).find(e=>typeof e==`string`);if(t?.toLowerCase().startsWith(`image/`))return t.toLowerCase();if(e.type===`image`||e.type===`base64`)return t||`image`}function bB(e){return xB(e)}function xB(e){if(typeof e==`string`)return vB(e);if(Array.isArray(e))return e.map(xB);if(!e||typeof e!=`object`)return e;let t=e,n=yB(t),r={};for(let[e,i]of Object.entries(t))r[e]=e===`data`&&n?_B(n,i):xB(i);return r}var SB=(e,t,n)=>`/api/sessions/${encodeURIComponent(e)}/timeline/messages/${encodeURIComponent(t)}/files/${n}`,CB=(e,t,n)=>`/api/sessions/${encodeURIComponent(e)}/timeline/messages/${encodeURIComponent(t)}/media/${encodeURIComponent(n)}`,wB=e=>typeof e==`number`&&Number.isInteger(e)&&e>0,TB=e=>jn.includes(e),EB=(e,t)=>typeof e==`string`&&En(e)?.kind===t;function DB(e,t,n,r){let i=CB(e.sessionID,e.messageID,n.ref);return{key:t,name:r,mime:n.mime,src:i,download:`${i}?download=1`,ref:n.ref,...typeof n.bytes==`number`&&Number.isInteger(n.bytes)&&n.bytes>=0?{bytes:n.bytes}:{},...wB(n.width)&&wB(n.height)?{width:n.width,height:n.height}:{}}}var OB=e=>typeof e.sessionID==`string`&&typeof e.messageID==`string`,kB=(e,t)=>typeof e.name==`string`&&e.name?e.name:t;function AB(e,t,n){let r=n?`tool`:`path`,i=e.media;if(!Array.isArray(i)||!OB(e))return[];let a=[];for(let o of i){if(a.length>=Mn.perRow)break;o&&EB(o.ref,r)&&typeof o.mime==`string`&&TB(o.mime)&&a.push({...DB(e,`${e.key}:${o.ref}`,o,kB(o,t)),...n?{tool:!0}:{}})}return a}function jB(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=`${e.key}:${n.index}`,i=kB(n,n.mime.startsWith(`image/`)?`image`:`file`);if(n.ref!==void 0){EB(n.ref,`file`)&&TB(n.mime)&&OB(e)?t.push(DB(e,r,n,i)):t.push({key:r,name:i,mime:n.mime});continue}let a=H_(n.mime)&&OB(e);t.push({key:r,name:i,mime:n.mime,...a?{src:SB(e.sessionID,e.messageID,n.index)}:{}})}return t}function MB(e,t={}){let n=[];for(let r of e)if(!((r.depth??0)>0))switch(r.kind){case`user`:{let e=jB(r),t=typeof r.messageID==`string`&&r.key===`${r.messageID}:text`?{messageID:r.messageID}:{},i=typeof r.note==`string`&&r.note?{note:r.note}:{};(r.text||e.length)&&n.push({type:`user`,key:r.key,text:r.text??``,...e.length?{images:e}:{},...t,...i});break}case`assistant`:{if(!r.text)break;let e=AB(r,`image`,!1);n.push({type:`assistant`,key:r.key,text:r.text,live:r.live===!0,...typeof r.messageID==`string`&&r.messageID?{messageID:r.messageID}:{},...e.length?{media:e}:{}});break}case`reasoning`:{let e=r.state===`running`,t=!e&&typeof r.at==`number`&&typeof r.completed==`number`?Math.max(0,Math.round((r.completed-r.at)/1e3)):void 0;n.push({type:`thought`,key:r.key,text:r.text??``,running:e,...t===void 0?{}:{seconds:t}});break}case`tool`:{let e=n[n.length-1],t=e?.type===`tools`?e:void 0,i=t??{type:`tools`,key:`tools:${r.key}`,items:[],failed:0,running:0};i.items.push(r);let a=AB(r,`screenshot`,!0);a.length&&(i.media=[...i.media??[],...a]),r.state===`failed`&&i.failed++,r.state===`running`&&i.running++,t||n.push(i);break}case`message`:n.push(IB(r));break;case`error`:n.push(r.declined===!0?{type:`error`,key:r.key,label:`${t.denied?.(r)??`Denied`}: the turn stopped`,denied:!0}:PB(r));break;case`retry`:n.push({type:`retry`,key:r.key,...NB(`attempt`,r.attempt),...NB(`next`,r.next),...typeof r.errorType==`string`?{errorType:r.errorType}:{},...NB(`errorStatus`,r.errorStatus),...typeof r.text==`string`&&r.text?{message:r.text}:{}});break;case`subagent`:r.sessionID&&n.push({type:`subagent`,key:r.key,sessionID:r.sessionID,label:r.label??r.sessionID,state:r.state??`working`})}return n}var NB=(e,t)=>typeof t==`number`&&Number.isFinite(t)?{[e]:t}:{};function PB(e){let t=typeof e.text==`string`&&e.text.trim()?e.text.trim():void 0,n=ji(e.errorType),r=Ni(e.errorStatus);return{type:`error`,key:e.key,label:n??t??`Error`,...n&&t?{message:t}:{},...r?{status:r}:{}}}function FB(e,t){return{text:zi(e,t),waiting:Pi(e.next,t)!==void 0}}function IB(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=dB(e.delivery),s=n===`primer`?`Hub identity note`:r===`out`?`to ${i}${a&&a!==i?` (→ ${a})`:``}`:`from ${String(t.from??`?`)}`,c=typeof t.from==`string`?t.from:void 0;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}:{},...c?{from:c}:{}}}var LB=`The provider returned this thought redacted: an encrypted signature, no readable text.`;function RB(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…`:LB,muted:!0}}function zB(e,t){if(typeof t.at!=`number`)return{};let n=t.at,r;for(let t of e)t.kind===`user`&&(t.depth??0)===0&&typeof t.at==`number`&&t.at>n&&(r===void 0||t.at<r)&&(r=t.at);return r===void 0?{since:n}:{since:n,until:r}}function BB(e,t){return JSON.stringify(bB(e??{summary:t.summary||void 0,error:t.error}),null,2)}var VB=I(`<p class=composer-error role=alert>`),HB=I(`<p class="composer-hint muted small">`),UB=I(`<li class="attachment busy"aria-label="Preparing image"><span class="spinner small">`),WB=I(`<ul class=attachments aria-label="Attached images">`),GB=I(`<div><button type=button class=split-main>`),KB=I(`<button type=button class="btn stop"aria-label="Stop the session and its subagents"> Stop`),qB=I(`<span class=sr-only>`),JB=I(`<button type=button class=model-chip title="Voice model (the voice front you talk to in Voice mode)">Voice: `),YB=I(`<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>`),XB=I(`<li class=attachment><img><button type=button class=attachment-remove title=Remove>`),ZB=I(`<span class="spinner small">`),QB=I(`<button type=button class="session-model pickable"aria-haspopup=dialog><span class=chip-key>Model: `),$B=I(`<span class=session-model><span class=chip-key>Model: `),eV=I(`<button type=button class=split-chev aria-label="Choose microphone"aria-haspopup=dialog>`),tV=I(`<p class="error small pad">`),nV=I(`<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>`),rV=I(`<button type=button class=menu-item role=menuitemradio><span class=menu-check></span><span class=menu-label>`),iV=I(`<span class=muted> · “<!>…”`),aV=I(`<span class=voice-ignored title="Heard as background noise, not sent"> · ignored: “<!>”`),oV=I(`<span class="voice-turn muted"title="Smart Turn (experimental): how sure the model is that you finished your turn"> · `),sV=I(`<span class="chip voice-front"title="Voice front: a fast voice agent answers and relays to the session">front`),cV=I(`<p class="voice-hint voice-front-fallback small"role=status>`),lV=I(`<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`),uV=I(`<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`),dV=I(`<span>`);function fV(e){let r,i,[a,o]=u(!1),c=()=>e.images.length>=L_.maxImages,d=()=>{r.style.height=`auto`,r.style.height=`${Math.min(r.scrollHeight,280)}px`};x(()=>{e.draft,queueMicrotask(d)});let f=()=>e.view.primary===`steer`?`Steer`:`Send`;return(()=>{var u=YB(),d=u.firstChild,p=d.firstChild,h=p.nextSibling,g=h.nextSibling,_=g.firstChild,v=_.nextSibling.nextSibling,x=v.nextSibling,S=d.nextSibling,C=S.firstChild;C.nextSibling,u.addEventListener(`drop`,t=>{let n=YS(t.dataTransfer);o(!1),n.length&&(t.preventDefault(),e.onAttach(n))}),u.addEventListener(`dragleave`,e=>{e.currentTarget.contains(e.relatedTarget)||o(!1)}),u.addEventListener(`dragover`,e=>{[...e.dataTransfer?.types??[]].includes(`Files`)&&(e.preventDefault(),o(!0))}),u.addEventListener(`submit`,t=>{t.preventDefault(),e.view.canSubmit&&!e.attaching&&e.onSubmit()}),y(u,n(l,{get when(){return e.error},get children(){var t=VB();return y(t,()=>e.error),t}}),d),y(u,n(l,{get when(){return e.view.hint},get children(){var t=HB();return y(t,()=>e.view.hint),t}}),d),y(d,n(l,{get when(){return e.images.length||e.attaching},get children(){var t=WB();return y(t,n(m,{get each(){return e.images},children:t=>(()=>{var r=XB(),i=r.firstChild,a=i.nextSibling;return a.$$click=()=>e.onDetach(t.id),y(a,n(L,{name:`close`})),s(e=>{var n=t.preview,r=t.name,o=t.name,s=`Remove ${t.name}`;return n!==e.e&&b(i,`src`,e.e=n),r!==e.t&&b(i,`alt`,e.t=r),o!==e.a&&b(i,`title`,e.a=o),s!==e.o&&b(a,`aria-label`,e.o=s),e},{e:void 0,t:void 0,a:void 0,o:void 0}),r})()}),null),y(t,n(l,{get when(){return e.attaching},get children(){return UB()}}),null),t}}),p),p.$$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())},p.addEventListener(`paste`,t=>{let n=YS(t.clipboardData);n.length&&(t.preventDefault(),e.onAttach(n))}),p.$$input=t=>e.onInput(t.currentTarget.value);var w=r;typeof w==`function`?t(w,p):r=p,h.addEventListener(`change`,t=>{let n=[...t.currentTarget.files??[]];t.currentTarget.value=``,n.length&&e.onAttach(n)});var T=i;return typeof T==`function`?t(T,h):i=h,_.$$click=()=>i.click(),y(_,n(L,{name:`plus`})),V(v,`click`,e.onDictate,!0),y(v,n(l,{get when(){return!e.transcribing},get fallback(){return ZB()},get children(){return n(L,{get name(){return e.dictating===!1?`mic`:`stop`}})}})),y(g,n(l,{get when(){return e.showVoice!==!1},get children(){var t=GB(),r=t.firstChild;return V(r,`click`,e.onVoice,!0),y(r,n(L,{name:`wave`})),y(t,n(pV,{}),null),s(n=>{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!==n.e&&k(t,n.e=i),a!==n.t&&b(r,`aria-pressed`,n.t=a),o!==n.a&&b(r,`aria-label`,n.a=o),s!==n.o&&b(r,`title`,n.o=s),c!==n.i&&(r.disabled=n.i=c),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t}}),x),y(g,n(l,{get when(){return e.view.showStop},get children(){var t=KB(),r=t.firstChild;return V(t,`click`,e.onStop,!0),y(t,n(L,{name:`stop`}),r),s(()=>t.disabled=!e.view.canStop),t}}),x),y(x,n(l,{get when(){return e.view.primary===`send`},get fallback(){return f()},get children(){return[n(L,{name:`send`}),(()=>{var e=qB();return y(e,f),e})()]}})),y(C,()=>e.metaLeft),y(S,n(l,{get when(){return e.sessionModel},children:t=>n(l,{get when(){return e.sessionModelPickable},get fallback(){return(()=>{var e=$B();return e.firstChild,y(e,()=>t().label.replace(/^Model: /,``),null),s(n=>{var r=t().title,i=t().title;return r!==n.e&&b(e,`title`,n.e=r),i!==n.t&&b(e,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),e})()},get children(){var n=QB();return n.firstChild,n.$$click=()=>e.onModel(`session`),y(n,()=>t().label.replace(/^Model: /,``),null),s(e=>{var r=t().title,i=t().title;return r!==e.e&&b(n,`title`,e.e=r),i!==e.t&&b(n,`aria-label`,e.t=i),e},{e:void 0,t:void 0}),n}})}),null),y(S,n(l,{get when(){return e.showModels!==!1},get children(){var t=JB();return t.firstChild,t.$$click=()=>e.onModel(`voice`),y(t,()=>e.voiceModel,null),t}}),null),s(t=>{var n=`composer${a()?` dragging`:``}`,r=e.voiceOn?`Voice mode is on — talk, or type here`:e.view.primary===`steer`?`Steer the running session…`:`Reply…`,i=I_.join(`,`),o=c()?`At most ${L_.maxImages} images per message`:`Attach images (or paste / drop them here)`,s=c()||e.attaching,l=`icon-btn${e.dictating===!1?``:` recording`}`,d=e.dictating===!1?`Dictate`:`Stop dictation`,f=e.voiceBlocked??(e.dictating===!1?`Dictate`:`Stop dictation (${e.dictating}s left)`),m=!!e.voiceBlocked||e.transcribing||e.voiceOn,g=`btn primary send ${e.view.primary}`,y=!e.view.canSubmit||e.attaching;return n!==t.e&&k(u,t.e=n),r!==t.t&&b(p,`placeholder`,t.t=r),i!==t.a&&b(h,`accept`,t.a=i),o!==t.o&&b(_,`title`,t.o=o),s!==t.i&&(_.disabled=t.i=s),l!==t.n&&k(v,t.n=l),d!==t.s&&b(v,`aria-label`,t.s=d),f!==t.h&&b(v,`title`,t.h=f),m!==t.r&&(v.disabled=t.r=m),g!==t.d&&k(x,t.d=g),y!==t.l&&(x.disabled=t.l=y),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(()=>p.value=e.draft),u})()}function pV(){let[e,r]=u(!1),[i,o]=u([]),[c,d]=u(0),[f,p]=u(``),h,g,_,[v,x]=u({right:0,bottom:0}),S=async()=>{_?.(),_=void 0;try{_=await ib(lb(),d),p(``)}catch(e){p(e.name===`NotAllowedError`?`Microphone permission was denied.`:`Microphone: ${e.message}`)}},C=async()=>{let e=h.getBoundingClientRect();if(x({right:window.innerWidth-e.right,bottom:window.innerHeight-e.top+6}),r(!0),!navigator.mediaDevices)return p(`This browser cannot use the microphone here (it needs HTTPS).`);o(await rb().catch(()=>[])),S()},w=()=>{r(!1),_?.(),_=void 0,d(0)},T=t=>e()&&!h.contains(t.target)&&!g?.contains(t.target)&&w(),E=t=>e()&&t.key===`Escape`&&!ee(g)&&w();return document.addEventListener(`mousedown`,T),document.addEventListener(`keydown`,E),M(()=>{document.removeEventListener(`mousedown`,T),document.removeEventListener(`keydown`,E),w()}),[(()=>{var r=eV();r.$$click=()=>e()?w():void C();var i=h;return typeof i==`function`?t(i,r):h=r,y(r,n(L,{name:`down`})),s(()=>b(r,`aria-expanded`,e())),r})(),n(l,{get when(){return e()},get children(){return n(fe,{get children(){var e=nV(),r=e.firstChild.nextSibling,o=r.firstChild,u=g;return typeof u==`function`?t(u,e):g=e,y(e,n(m,{get each(){return[{deviceId:``,label:`System default`},...i().filter(e=>e.deviceId&&e.deviceId!=="default")]},children:(e,t)=>(()=>{var n=rV(),r=n.firstChild,i=r.nextSibling;return n.$$click=()=>{db(e.deviceId),S()},y(r,()=>lb()===e.deviceId?`✓`:``),y(i,()=>e.label||`Microphone ${t()}`),s(()=>b(n,`aria-checked`,lb()===e.deviceId)),n})()}),r),y(e,n(l,{get when(){return f()},get children(){var e=tV();return y(e,f),e}}),null),s(t=>{var n=`${v().right}px`,i=`${v().bottom}px`,s=Math.round(c()*100),l=`${Math.round(c()*100)}%`;return n!==t.e&&a(e,`right`,t.e=n),i!==t.t&&a(e,`bottom`,t.t=i),s!==t.a&&b(r,`aria-valuenow`,t.a=s),l!==t.o&&a(o,`width`,t.o=l),t},{e:void 0,t:void 0,a:void 0,o:void 0}),e}})}})]}var mV={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 hV(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(`
|
|
28
|
+
`):void 0}function gV(e){let t=()=>e.state===`listening`&&e.working?`Thinking`:mV[e.state],r=[.5,.8,1,.7,.45];return(()=>{var i=uV(),o=i.firstChild,c=o.nextSibling,u=c.nextSibling,d=u.nextSibling,f=d.nextSibling,p=f.nextSibling;return y(o,n(m,{each:r,children:t=>(()=>{var n=dV();return s(r=>a(n,`transform`,`scaleY(${Math.max(.15,Math.min(1,(e.state===`speaking`?.6:e.level)*t*1.6))})`)),n})()})),y(c,t,null),y(c,n(l,{get when(){return e.held},get children(){var t=iV(),n=t.firstChild.nextSibling;return n.nextSibling,y(t,()=>e.held,n),t}}),null),y(c,n(l,{get when(){return e.ignored},get children(){var t=aV(),n=t.firstChild.nextSibling;return n.nextSibling,y(t,()=>e.ignored,n),t}}),null),y(c,n(l,{get when(){return e.turn},get children(){var t=oV();return t.firstChild,y(t,()=>e.turn,null),t}}),null),y(i,n(l,{get when(){return e.front?.on},get children(){return sV()}}),u),y(i,n(VL,{announce:!0,mark:!0}),u),V(d,`click`,e.onModel,!0),y(d,()=>e.model),V(f,`click`,e.onMute,!0),y(f,n(L,{get name(){return e.state===`paused`?`muted`:`mic`}})),V(p,`click`,e.onEnd,!0),y(i,n(l,{get when(){return e.front?.fallback},get children(){var e=cV();return y(e,rx),e}}),null),y(i,n(l,{get when(){return e.notifyHint},get children(){var t=lV(),n=t.firstChild.nextSibling;return n.$$click=()=>e.onAllowNotifications?.(),t}}),null),s(t=>{var n=`voice-bar ${e.state}`,r=e.detector?.mode,a=hV(e.timing,e.detector),o=`icon-btn${e.state===`paused`?` on`:``}`,s=e.state===`paused`,l=e.state===`paused`?`Unmute`:`Mute`,u=e.state===`paused`?`Unmute`:`Mute`;return n!==t.e&&k(i,t.e=n),r!==t.t&&b(i,`data-vad`,t.t=r),a!==t.a&&b(c,`title`,t.a=a),o!==t.o&&k(f,t.o=o),s!==t.i&&b(f,`aria-pressed`,t.i=s),l!==t.n&&b(f,`aria-label`,t.n=l),u!==t.s&&b(f,`title`,t.s=u),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),i})()}B([`input`,`keydown`,`click`]);var _V=e=>e===`voice`?`Voice model`:`Session model`,vV=()=>({query:``,active:0}),yV=e=>[void 0,...(e.variants??[]).filter(e=>e!=="default")];function bV(e,t,n=100){if(t.chosen)return{mode:`variants`,model:t.chosen,rows:yV(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 xV=(e,t)=>({...e,query:t,active:0}),SV=(e,t)=>({providerID:e.providerID,modelID:e.modelID,...t?{variant:t}:{}});function CV(e,t,n){let r=bV(e,t);if(r.mode===`variants`)return n<0||n>=r.rows.length?{state:t}:{state:t,pick:SV(r.model,r.rows[n])};let i=r.rows[n];return i?yV(i).length>1?{state:{...t,chosen:i,active:0}}:{state:t,pick:SV(i)}:{state:t}}function wV(e,t,n,{inSearch:r}){let i=bV(e,t).rows.length;if(n===`ArrowDown`||n===`ArrowUp`)return{state:{...t,active:Math.max(0,kC(t.active,n===`ArrowDown`?1:-1,i))},handled:!0};if(n===`Enter`)return{...CV(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}:{...CV(e,t,r),handled:!0}}return{state:t,handled:!1}}var TV=(e,t)=>({[e]:t}),EV={chosen:`chosen for this session`,reply:`the default model (its latest reply ran on it)`,default:`the default model (no reply yet)`},DV=e=>typeof e==`string`&&e.length>0;function OV(e){let t=e;return typeof t==`object`&&!!t&&DV(t.providerID)&&DV(t.modelID)}var kV=`. Click to change the session's model`;function AV(e,t={}){let n=t.pickable?kV:``;if(!OV(e))return{label:`Model: default`,title:`Model: default (not known yet: it shows once the session has run)${n}`};let r=DV(e.variant)?` · ${e.variant}`:``,i=DV(e.name)?e.name:void 0,a=DV(e.source)?EV[e.source]:void 0;return{label:`Model: ${i??e.modelID}${r}`,title:`Model: ${e.providerID}/${e.modelID}${r}${i?` (${i})`:``}${a?`, ${a}`:``}${n}`}}function jV(e){if(OV(e)&&e.source===`chosen`)return{providerID:e.providerID,modelID:e.modelID,...DV(e.variant)?{variant:e.variant}:{}}}var MV=e=>({model:e}),NV=I(`<div>`),PV=I(`<p class="error small"role=alert>Couldn't load models: `),FV=I(`<p class="muted small">Loading models…`),IV=I(`<input type=search class=picker-search placeholder="Search models"aria-label="Search models"autofocus>`),LV=I(`<p class="muted small"role=status>`),RV=I(`<ul class=picker-list role=listbox aria-label=Models>`),zV=I(`<li class="muted small">No models match.`),BV=I(`<div class="picker-group muted small">`),VV=I(`<span class="po-id muted">variants ›`),HV=I(`<span class=po-mark>✓`),UV=I(`<kbd>`),WV=I(`<li><button type=button role=option><span class=po-name></span><span class="po-id muted">`),GV=I(`<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>`),KV=I(`<li><button type=button role=option><span class=po-name></span><kbd>`);function qV(e,t){let n=e?.prefs[t]??e?.defaults[t];return n?`${n.modelID}${n.variant?` · ${n.variant}`:``}`:`default`}function JV(e){let[t,n]=u(),[r,i]=u(``),[a,o]=u();return{prefs:t,error:r,load:async()=>{try{n(await K(`${U(e())}/model-prefs`)),i(``)}catch(e){i(W(e))}},loadCatalog:async()=>{if(a())return a();let{models:t}=await K(`${U(e())}/models`),n=new je(t);return o(n),n},save:async(t,r)=>{try{n(await(await H(`${U(e())}/model-prefs`,{method:`PUT`,json:TV(t,r)})).json()),J(`Voice model applies the next time Voice mode starts.`)}catch(e){J(`Couldn't set the Voice model: ${W(e)}`,`err`)}},saveSession:async t=>{try{let{model:n}=await(await H(`${U(e())}/model`,{method:`PUT`,json:MV(t)})).json();return J(`The session's next turn runs on ${n.name||n.modelID}${n.variant?` · ${n.variant}`:``}.`),n}catch(e){J(`Couldn't set the session's model: ${W(e)}`,`err`);return}}}}function YV(t){let[i,a]=u(vV()),[o,c]=u(),[d,f]=u(``),p=()=>t.kind!==void 0,h=()=>t.kind===`session`?t.sessionCurrent:t.kind?t.models.prefs()?.prefs[t.kind]??t.models.prefs()?.defaults[t.kind]:void 0,g=e=>h()?.providerID===e.providerID&&h()?.modelID===e.modelID,_=()=>{a(vV()),f(``),t.models.loadCatalog().then(c,e=>f(W(e)))},v=C(()=>o()?bV(o(),i()):void 0),S=e=>{if(a(e.state),!e.pick||!t.kind)return;let n=t.kind,r=e.pick;if(t.onClose(),n===`voice`)return void t.models.save(n,r);t.models.saveSession(r).then(e=>e&&t.onSessionModel?.(e))},w=e=>o()&&S(CV(o(),i(),e)),T=e=>{if(!o()||e.altKey||e.ctrlKey||e.metaKey)return;let t=wV(o(),i(),e.key,{inSearch:e.target instanceof HTMLInputElement});if(!t.handled)return;e.preventDefault(),S(t);let n=e.currentTarget;queueMicrotask(()=>n.querySelector(`.picker-opt.active`)?.scrollIntoView({block:`nearest`}))};return x(e(p,e=>e&&_())),n(de,{get open(){return p()},get title(){return _V(t.kind??`voice`)},get onClose(){return t.onClose},class:`picker`,get children(){var e=NV();return e.$$keydown=T,y(e,n(l,{get when(){return!d()},get fallback(){return(()=>{var e=PV();return e.firstChild,y(e,d,null),e})()},get children(){return n(l,{get when(){return v()},get fallback(){return FV()},children:e=>n(l,{get when(){return r(()=>e().mode===`models`)()&&e()},get fallback(){return n(XV,{get view(){return e()},get active(){return i().active},get current(){return h()},onPick:w,onBack:()=>a(e=>({...e,chosen:void 0,active:0}))})},children:e=>[(()=>{var e=IV();return e.$$input=e=>a(t=>xV(t,e.currentTarget.value)),s(()=>e.value=i().query),e})(),(()=>{var t=LV();return y(t,(()=>{var t=r(()=>e().total===1);return()=>t()?`1 model`:`${e().total} models`})(),null),y(t,(()=>{var t=r(()=>!!e().more);return()=>t()?` · showing ${e().rows.length}, search to narrow`:``})(),null),t})(),(()=>{var t=RV();return y(t,n(m,{get each(){return e().rows},get fallback(){return zV()},children:(t,r)=>(()=>{var a=WV(),o=a.firstChild,c=o.firstChild,u=c.nextSibling;return y(a,n(l,{get when(){return r()===0||e().rows[r()-1].group!==t.group},get children(){var e=BV();return y(e,()=>t.group),e}}),o),o.$$click=()=>w(r()),y(c,()=>t.name||t.modelID),y(u,()=>t.modelID),y(o,n(l,{get when(){return(t.variants??[]).some(e=>e!=="default")},get children(){return VV()}}),null),y(o,n(l,{get when(){return g(t)},get children(){return HV()}}),null),y(o,n(l,{get when(){return r()<9},get children(){var e=UV();return y(e,()=>r()+1),e}}),null),s(e=>{var n=`picker-opt${i().active===r()?` active`:``}`,a=g(t);return n!==e.e&&k(o,e.e=n),a!==e.t&&b(o,`aria-selected`,e.t=a),e},{e:void 0,t:void 0}),a})()})),t})()]})})}})),e}})}function XV(e){let i;R(()=>i?.focus());let a=()=>e.current?.providerID===e.view.model.providerID&&e.current?.modelID===e.view.model.modelID;return(()=>{var o=GV(),c=o.firstChild,u=c.firstChild,d=u.nextSibling;d.firstChild;var f=c.nextSibling;return V(u,`click`,e.onBack,!0),y(d,()=>e.view.model.name||e.view.model.modelID,null),y(f,n(m,{get each(){return e.view.rows},children:(o,c)=>(()=>{var u=KV(),d=u.firstChild,f=d.firstChild,p=f.nextSibling;return d.$$click=()=>e.onPick(c()),t(e=>c()===0&&(i=e),d),y(f,o??`Default`),y(d,n(l,{get when(){return r(()=>!!a())()&&e.current?.variant===o},get children(){return HV()}}),p),y(p,()=>c()+1),s(t=>{var n=`picker-opt${e.active===c()?` active`:``}`,r=a()&&e.current?.variant===o;return n!==t.e&&k(d,t.e=n),r!==t.t&&b(d,`aria-selected`,t.t=r),t},{e:void 0,t:void 0}),u})()})),o})()}B([`keydown`,`input`,`click`]);var ZV=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;function QV(e){let t=[],n=0,r=0,i=!1;for(let a of String(e??``).replace(/\r\n?/g,`
|
|
29
|
+
`).split(`
|
|
30
|
+
`)){let e=ZV.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 $V=new Set([`user`,`launch`,`self`,`prompt`,`title`]),eH=e=>`/api/agent/sessions/${encodeURIComponent(e)}/intent`,tH=e=>e.replace(/\s+/g,` `).trim();function nH(e){let t=Array.from(tH(e)).length;if(t===0)return`Say what this session is for, or clear it.`;if(t>280)return`At most 280 characters (${t} now).`}var rH=(e,t)=>({text:e===null?null:tH(e),expectedRevision:t});function iH(e){if(e?.source===`user`)return{text:null,expectedRevision:e.revision};if(e?.source===`prompt`)return{source:`prompt`,text:null,expectedRevision:e.revision}}function aH(e){switch(e.source){case`user`:return e.by?.startsWith(`app:`)?`Set by an app`:`Set by you`;case`launch`:return`From the launch`;case`self`:return`Set by the session`;case`prompt`:return`From the first prompt`;default:return`From the title`}}function oH(e){let t=e&&typeof e==`object`?e.intent:void 0;if(!t||typeof t!=`object`)return null;let n=t;return typeof n.sessionID!=`string`||typeof n.text!=`string`||typeof n.source!=`string`||!$V.has(n.source)||typeof n.revision!=`number`||typeof n.updatedAt!=`number`||n.by!==void 0&&typeof n.by!=`string`?null:{sessionID:n.sessionID,text:n.text,source:n.source,revision:n.revision,updatedAt:n.updatedAt,...typeof n.by==`string`?{by:n.by}:{}}}function sH(e,t={}){return e.status===409||e.code===`conflict`?t.loaded===!1?{text:`The current intent could not be loaded, so nothing was saved: Retry, then edit again.`,reload:!0}:{text:`It changed meanwhile: here is the latest. Edit again to change it.`,reload:!0}:{text:e.message,reload:!1}}function cH(e,t,n){return e.type===`intent`&&e.sessionID===t&&e.revision!==n}var lH=I(`<div class=field><label class=field-label>What is this session for?</label><input type=text><div class=row><button type=button class="btn small primary">Save</button><button type=button class="btn small">Cancel`),uH=I(`<div class=intent-field>`),dH=I(`<button type=button class="btn small">Retry`),fH=I(`<button type=button class="btn small">Clear`),pH=I(`<div class=row><button type=button class="btn small">Edit`),mH=I(`<p class="muted small intent-error">Could not load the intent.`),hH=I(`<p class="muted small">Loading…`),gH=I(`<p class="muted small">No intent yet.`),_H=I(`<p class="small intent-text">`),vH=I(`<p class="muted small">`),yH=I(`<p class=field-error>`);function bH(e){let[i,{refetch:a,mutate:o}]=d(()=>e.sessionID,async e=>oH(await K(eH(e)))),[c,f]=u(!1),[p,m]=u(``),[h,g]=u(!1),[_,v]=u(``),x=()=>nH(p()),S=()=>i.error?void 0:i.loading?i.latest:i();M(Fu(t=>{!c()&&cH(t,e.sessionID,S()?.revision)&&a()}));let C=()=>{m(S()?.source===`title`?``:S()?.text??``),v(``),f(!0)},w=async t=>{if(h()||t!==null&&x())return;let n=t===null?iH(S()):rH(t,S()?.revision??0);if(n){g(!0),v(``);try{let t=oH(await(await H(eH(e.sessionID),{method:`PUT`,json:n})).json());i.error?a():o(t),f(!1)}catch(e){let t=sH(e instanceof G?{status:e.status,...e.code?{code:e.code}:{},message:e.message}:{message:W(e)},{loaded:!i.error});v(t.text),t.reload&&(f(!1),a())}finally{g(!1)}}};return(()=>{var o=uH();return y(o,n(l,{get when(){return c()},get fallback(){return[n(l,{get when(){return!i.error},get fallback(){return mH()},get children(){return n(l,{get when(){return!i.loading||S()},get fallback(){return hH()},get children(){return n(l,{get when(){return S()},get fallback(){return gH()},children:e=>[(()=>{var t=_H();return y(t,()=>e().text),t})(),(()=>{var t=vH();return y(t,()=>aH(e())),t})()]})}})}}),(()=>{var e=pH(),t=e.firstChild;return t.$$click=C,y(e,n(l,{get when(){return i.error},get children(){var e=dH();return e.$$click=()=>void a(),e}}),null),y(e,n(l,{get when(){return iH(S())},get children(){var e=fH();return e.$$click=()=>void w(null),s(t=>{var n=h(),r=S()?.source===`prompt`?`Not what this session is for: clear it (the title shows instead)`:`Clear your intent`;return n!==t.e&&(e.disabled=t.e=n),r!==t.t&&b(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e}}),null),s(()=>t.disabled=i.loading&&!i.error),e})()]},get children(){var i=lH(),a=i.firstChild,o=a.nextSibling,c=o.nextSibling,u=c.firstChild,d=u.nextSibling;return t(e=>queueMicrotask(()=>e.focus()),o),o.$$keydown=e=>{e.key===`Enter`&&w(p()),e.key===`Escape`&&f(!1)},o.$$input=e=>m(e.currentTarget.value),b(o,`maxlength`,560),y(i,n(l,{get when(){return r(()=>!!p())()&&x()},children:e=>(()=>{var t=yH();return y(t,e),t})()}),c),u.$$click=()=>void w(p()),d.$$click=()=>f(!1),s(t=>{var n=`intent-${e.sessionID}`,r=`intent-${e.sessionID}`,i=h()||!!x(),s=h();return n!==t.e&&b(a,`for`,t.e=n),r!==t.t&&b(o,`id`,t.t=r),i!==t.a&&(u.disabled=t.a=i),s!==t.o&&(d.disabled=t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),s(()=>o.value=p()),i}}),null),y(o,n(l,{get when(){return _()},children:e=>(()=>{var t=yH();return y(t,e),t})()}),null),o})()}B([`input`,`keydown`,`click`]);var xH=e=>`/api/agent/subscriptions?session=${encodeURIComponent(e)}`,SH=e=>`/api/agent/subscriptions/${encodeURIComponent(e)}`,CH=e=>typeof e==`string`,wH=e=>typeof e==`number`&&Number.isFinite(e)?e:0;function TH(e){let t=e;if(t&&typeof t==`object`){if(t.kind===`children`)return{kind:`children`};if(t.kind===`session`&&CH(t.sessionID)&&CH(t.addr))return{kind:`session`,sessionID:t.sessionID,addr:t.addr};if((t.kind===`role`||t.kind===`team`)&&CH(t.addr))return{kind:t.kind,addr:t.addr}}}function EH(e){let t=e?.subscriptions;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=e;if(!t||typeof t!=`object`||!CH(t.id)||!CH(t.subscriber)||!Array.isArray(t.targets)||!Array.isArray(t.types))continue;let r=t.stats??{};n.push({id:t.id,subscriber:t.subscriber,targets:t.targets.map(TH).filter(e=>e!==void 0),types:t.types.filter(CH),delivery:CH(t.delivery)?t.delivery:`queue`,batchMs:wH(t.batchMs),expiresAt:wH(t.expiresAt),pending:wH(t.pending),stats:{delivered:wH(r.delivered),dropped:wH(r.dropped),suppressed:wH(r.suppressed)}})}return n}function DH(e,t){return{listensTo:e.filter(e=>e.subscriber===t),listenedBy:e.filter(e=>e.subscriber!==t)}}function OH(e){if(e<=0)return`ending`;let t=Math.round(e/6e4);if(t<60)return`${Math.max(t,1)} min`;let n=Math.round(e/36e5);return n<48?`${n} h`:`${Math.round(e/864e5)} d`}function kH(e,t){let n=e.targets.map(e=>e.kind===`children`?`its subagents`:e.addr).join(`, `)||`—`,r=[e.types.join(`, `),e.delivery,`every ${Math.round(e.batchMs/1e3)} s`,`${e.stats.delivered} sent`];return e.pending&&r.push(`${e.pending} pending`),e.stats.dropped&&r.push(`${e.stats.dropped} dropped`),e.stats.suppressed&&r.push(`${e.stats.suppressed} loop-suppressed`),r.push(`ends in ${OH(e.expiresAt-t)}`),{title:n,detail:r.join(` · `)}}var AH=I(`<ul class=subscription-list>`),jH=I(`<li class=subscription><div class=subscription-text><span class=small></span><span class="muted small"></span></div><button type=button class="btn small">Remove`),MH=I(`<p class="small subscription-head">Listens to`),NH=I(`<p class="small subscription-head">Listened to by`),PH=I(`<div class=subscriptions-field><div class=row><button type=button class="btn small">Refresh`),FH=I(`<p class="muted small">Could not load the subscriptions.`),IH=I(`<p class="muted small">Loading…`),LH=I(`<p class="muted small">None. An agent follows other sessions with hub subscribe.`);function RH(e){let[t,{refetch:r}]=d(()=>e.sessionID,async e=>EH(await K(xH(e)))),[i,a]=u(``),o=()=>DH(t.error?[]:t.latest??[],e.sessionID),c=async e=>{if(!i()){a(e.id);try{await H(SH(e.id),{method:`DELETE`}),J(`Subscription removed`),r()}catch(e){J(`Could not remove the subscription: ${W(e)}`,`err`)}finally{a(``)}}},f=e=>(()=>{var t=AH();return y(t,n(m,{get each(){return e.items},children:t=>{let n=()=>kH(t,Date.now());return(()=>{var r=jH(),a=r.firstChild,o=a.firstChild,l=o.nextSibling,u=a.nextSibling;return y(o,()=>e.who(t)),y(l,()=>n().detail),u.$$click=()=>void c(t),s(e=>{var n=t.id,a=i()===t.id,o=`Remove subscription ${t.id}`;return n!==e.e&&b(r,`data-subscription`,e.e=n),a!==e.t&&(u.disabled=e.t=a),o!==e.a&&b(u,`aria-label`,e.a=o),e},{e:void 0,t:void 0,a:void 0}),r})()}})),t})();return(()=>{var e=PH(),i=e.firstChild,a=i.firstChild;return y(e,n(l,{get when(){return!t.error},get fallback(){return FH()},get children(){return n(l,{get when(){return!t.loading||t.latest},get fallback(){return IH()},get children(){return n(l,{get when(){return o().listensTo.length||o().listenedBy.length},get fallback(){return LH()},get children(){return[n(l,{get when(){return o().listensTo.length},get children(){return[MH(),n(f,{get items(){return o().listensTo},who:e=>kH(e,Date.now()).title})]}}),n(l,{get when(){return o().listenedBy.length},get children(){return[NH(),n(f,{get items(){return o().listenedBy},who:e=>e.subscriber})]}})]}})}})}}),i),a.$$click=()=>void r(),s(()=>a.disabled=t.loading),e})()}B([`click`]);var zH=I(`<div class=context-cards>`),BH=I(`<p class="muted small">Could not load the context cards. <button type=button class="btn small">Retry`),VH=I(`<p class="muted small">Loading…`),HH=I(`<p class="muted small context-cards-off">`),UH=I(`<article><header class=context-card-head><span class=context-card-title></span><button type=button class="btn small">`),WH=I(`<p class="muted small">No card yet.`),GH=I(`<p class=context-card-headline>`),KH=I(`<p class="small context-card-body">`),qH=I(`<dl class="kv context-card-fields">`),JH=I(`<p class="muted small context-card-meta">`),YH=I(`<dt>`),XH=I(`<dd>`),ZH=I(`<p class="muted small context-card-note">`);function QH(e){let[t,{refetch:r}]=d(()=>e.sessionID,async e=>{let t=Kk(await K(Lk(e)));for(let e of t.cards)iA(e);return t}),[i,a]=u(),[o,s]=u({});M(Fu(t=>{Zk(t,e.sessionID)&&r()}));let c=()=>t.error?void 0:t.loading?t.latest:t(),f=e=>c()?.cards.find(t=>t.provider===e),p=async t=>{if(!i()){a(t),s(e=>({...e,[t]:``}));try{let n=await H(Rk(e.sessionID,t),{method:`POST`}).catch(e=>{if(!(e instanceof G&&e.status===429))throw e}),i=n?await n.json():{outcome:`skipped`,reason:`rate_limited`},a=Xk(i),o=Gk(i.card);o&&iA(o),s(e=>({...e,[t]:a??``})),await r()}catch(e){s(n=>({...n,[t]:W(e)}))}finally{a(void 0)}}};return(()=>{var e=zH();return y(e,n(l,{get when(){return!t.error},get fallback(){return(()=>{var e=BH(),t=e.firstChild.nextSibling;return t.$$click=()=>void r(),e})()},get children(){return n(l,{get when(){return c()},get fallback(){return VH()},children:e=>[n(l,{get when(){return!e().enabled},get children(){var t=HH();return y(t,()=>e().configured?`Context cards are off. Turn them on in Settings › Concierge (nothing is sent to a model until you do).`:`No model is configured for context cards (see docs/context-cards.md).`),t}}),n(m,{get each(){return e().providers},children:e=>n($H,{provider:e,get card(){return f(e.id)},get busy(){return i()===e.id},get disabled(){return!!i()},get note(){return o()[e.id]},onRefresh:()=>void p(e.id)})})]})}})),e})()}function $H(e){return(()=>{var t=UH(),r=t.firstChild.firstChild,i=r.nextSibling;return y(r,()=>e.card?.title??e.provider.label),i.$$click=()=>e.onRefresh(),y(i,()=>e.busy?`Refreshing…`:`Refresh`),y(t,n(l,{get when(){return e.card},get fallback(){return WH()},children:e=>[(()=>{var t=GH();return y(t,()=>e().headline),t})(),n(l,{get when(){return e().body},get children(){var t=KH();return y(t,()=>e().body),t}}),n(l,{get when(){return e().fields?.length},get children(){var t=qH();return y(t,n(m,{get each(){return e().fields},children:e=>[(()=>{var t=YH();return y(t,()=>e.label),t})(),(()=>{var t=XH();return y(t,()=>e.value),t})()]})),t}}),(()=>{var t=JH();return y(t,()=>Jk(e(),N())),t})()]}),null),y(t,n(l,{get when(){return e.note},children:e=>(()=>{var t=ZH();return y(t,e),t})()}),null),s(n=>{var r=`context-card${e.provider.primary?` primary`:``}`,a=e.provider.id,o=e.busy,s=e.disabled,c=`Refresh ${e.provider.label}`;return r!==n.e&&k(t,n.e=r),a!==n.t&&b(t,`data-context-card`,n.t=a),o!==n.a&&b(t,`aria-busy`,n.a=o),s!==n.o&&(i.disabled=n.o=s),c!==n.i&&b(i,`title`,n.i=c),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t})()}B([`click`]);var eU=e=>Array.isArray(e)?e.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`string`):[],tU=e=>typeof e==`string`?e:``,nU=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,rU=new Set([`working`,`blocked`]),iU=e=>Rr[tU(e.state)]??Rr.idle;function aU(e){let t=new Map,n=[];for(let r of e){let e=t.get(r.id);e===void 0?(t.set(r.id,n.length),n.push(r)):iU(r)<iU(n[e])&&(n[e]=r)}return n}function oU(e,t,n){let r=aU(eU(t)),i=e=>{let t=[],n=new Set([e]);for(let e=!0;e;){e=!1;for(let i of r)n.has(tU(i.parentID))&&!n.has(i.id)&&(n.add(i.id),t.push(i),e=!0)}return t},a=new Map;for(let e of eU(n)){let t=nU(e.updated);t!==void 0&&a.set(e.id,Math.max(t,a.get(e.id)??-1/0))}let o=[];for(let t of r){if(t.parentID!==e||t.id===e)continue;let n=i(t.id),r=[t,...n].map(e=>tU(e.state)),a=r.includes(`blocked`)?`blocked`:t.state===`error`?`error`:r.includes(`working`)?`working`:`idle`,s=[t,...n].filter(e=>e.state===`working`).map(e=>nU(e.since)).filter(e=>e!==void 0);o.push({id:t.id,title:tU(t.title)||`Subagent`,state:a,...a===`working`&&s.length?{since:Math.min(...s)}:{},nested:n.length,order:o.length})}let s=new Set(o.map(e=>e.id));for(let t of eU(n)){if(t.parentID!==e||s.has(t.id))continue;s.add(t.id);let n=tU(t.state),r=n===`working`||n===`blocked`||n===`error`?n:`idle`;o.push({id:t.id,title:tU(t.title)||`Subagent`,state:r,nested:0,order:o.length})}let c=({order:e,...t})=>t,l=o.filter(e=>rU.has(e.state)).sort((e,t)=>(e.state===t.state?0:e.state===`blocked`?-1:+(t.state===`blocked`))||(e.since??1/0)-(t.since??1/0)||e.order-t.order),u=o.filter(e=>!rU.has(e.state)).sort((e,t)=>Number(t.state===`error`)-Number(e.state===`error`)||(a.get(t.id)??-1/0)-(a.get(e.id)??-1/0)||t.order-e.order);return{running:l.map(c),finished:u.map(c)}}function sU(e){let t=e.finished.filter(e=>e.state===`error`).length;return[`Subagents`,e.running.length?`${e.running.length} running`:e.finished.length?`${e.finished.length} finished`:``,t?`${t} failed`:``].filter(Boolean).join(` · `)}var cU={working:`Running`,blocked:`Needs you`,error:`Error`,idle:`Done`};function lU(e,t){let n=[cU[e.state]];return e.state===`working`&&e.since!==void 0&&n.push(qi(t-e.since)),e.nested&&n.push(`${e.nested} subagent${e.nested===1?``:`s`}`),n.join(` · `)}var uU=I(`<section><h3><button type=button class=card-toggle><span>`),dU=I(`<li><a><span class=subagent-text><span class=subagent-title></span><span class="muted small">`),fU=I(`<ul class=job-list>`),pU=I(`<ul class=subagent-list>`),mU=I(`<button type=button class="subagents-more small">`),hU=I(`<ul class=mcp-list>`),gU=I(`<aside class=rail aria-label="Session details"><div class=rail-head><span class=rail-title>Details`),_U=I(`<p class="rail-error small"><strong>`),vU=I(`<p class="muted small">`),yU=I(`<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>Directory</dt><dd class=kv-path data-session-directory><span class="mono path-tail"><bdi></bdi></span></dd><dt>Branch</dt><dd class=mono></dd><dt>Open in</dt><dd>`),bU=I(`<span class=muted>`),xU=I(`<p class="small retry-note">`),SU=I(`<li><span aria-hidden=true></span><span class="job-command mono"></span><span class="muted small">`),CU=I(`<div class=meter role=meter aria-valuemin=0 aria-valuemax=100 aria-label="Context used"><span>`),wU=I(`<p class=small><strong></strong><span class=muted> `),TU=I(`<li><span aria-hidden=true></span><span class=mcp-name></span><span class="muted small">`),EU=I(`<span class=diffstat><span class=add>+</span> <span class=del>−`),DU=I(`<ul class=file-list>`),OU=I(`<p class="muted small">No changes.`),kU=I(`<li><button type=button class=file><span></span><span class=file-name><bdi></bdi></span><span class="diffstat small"><span class=add>+</span> <span class=del>−`),AU=I(`<p class="muted small more-files">+<!> more <!> (only the most-changed files are listed)`),jU=I(`<table class=diff><tbody>`),MU=I(`<p class="muted small pad">The diff is too large to show completely (512 KB).`),NU=I(`<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>`),PU=I(`<option>`),FU=I(`<p class="muted small pad">Loading diff…`),IU=I(`<p class="muted small pad">`),LU=I(`<p class="muted small pad">No textual changes (binary file, or a rename).`),RU=I(`<tr><td class=ln></td><td class=ln></td><td class=code-line><span class=sign>`),zU=e=>e.truncated&&e.totalFiles?Math.max(0,e.totalFiles-e.files.length):0,[BU,VU]=u(zS(localStorage));function HU(e){let t=()=>!BU().has(e.id);return(()=>{var r=uU(),i=r.firstChild,a=i.firstChild,o=a.firstChild;return a.$$click=()=>VU(BS(localStorage,e.id)),y(a,n(L,{name:`chevron`,class:`card-chevron`}),o),y(o,()=>e.title),y(i,()=>e.extra,null),y(r,n(l,{get when(){return t()},get children(){return e.children}}),null),s(n=>{var i=`rail-card${t()?``:` collapsed`}`,o=e.label??e.title,s=e.domID,c=e.id,l=t();return i!==n.e&&k(r,n.e=i),o!==n.t&&b(r,`aria-label`,n.t=o),s!==n.a&&b(r,`id`,n.a=s),c!==n.o&&b(r,`data-card`,n.o=c),l!==n.i&&b(a,`aria-expanded`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),r})()}var UU=e=>e>=1e3?`${(e/1e3).toFixed(e>=1e5?0:1)}k`:String(e);function WU(t){let i=()=>t.found?.session,o=()=>i()?.open?i()?.terminal?.source===`herdr`?`herdr`:`tui`:`background`,c=()=>Ki(i()?.status,N()),d=()=>c().filter(e=>e.status===`running`).length,f=()=>i()?.state===`working`||i()?.status?.some(e=>e.state===`working`)?Xi(i()?.status,i()?.id,se()):void 0,p=()=>Vi(i()?.status,i()?.id),h=C(()=>{let e=i()?.id;return e?(X.machines??[]).flatMap(t=>t.processes.flatMap(t=>t.sessions.filter(t=>t.parentID===e))):[]}),g=C(()=>{let e=i()?.id;return e?oU(e,i()?.status,h()):{running:[],finished:[]}}),_=C(()=>new Map([...g().running,...g().finished].map(e=>[e.id,e]))),[v,S]=u(!1);x(e(()=>i()?.id,()=>S(!1),{defer:!0}));let w=C(()=>{let{running:e,finished:t}=g();return[...e,...v()?t:t.slice(0,3)].map(e=>e.id)},[],{equals:(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n])}),T=e=>n(l,{get when(){return _().get(e)},children:r=>(()=>{var i=dU(),a=i.firstChild,o=a.firstChild,c=o.firstChild,l=c.nextSibling;return a.$$click=()=>Q()&&t.onClose(),b(a,`data-session`,e),y(a,n(A,{get state(){return r().state}}),o),y(c,()=>r().title),y(l,()=>lU(r(),N())),y(a,n(L,{name:`chevron`,class:`chev`}),null),s(t=>{var n=`subagent-row ${r().state}`,i=Dt(e),o=r().title,s=`Open subagent ${r().title} (${lU(r(),N())})`;return n!==t.e&&k(a,t.e=n),i!==t.t&&b(a,`href`,t.t=i),o!==t.a&&b(a,`title`,t.a=o),s!==t.o&&b(a,`aria-label`,t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),i})()}),E=()=>{let e=t.summary?.mcp;return e?.length?`Connectors · ${e.filter(e=>e.status===`connected`).length} connected`:`Connectors`};return(()=>{var e=gU(),u=e.firstChild;return u.firstChild,y(u,n(F,{icon:`close`,label:`Close details`,get onClick(){return t.onClose}}),null),y(e,n(l,{get when(){return p()},children:e=>(()=>{var t=_U(),n=t.firstChild;return y(n,()=>e().label),y(t,(()=>{var t=r(()=>!!e().status);return()=>t()?` · ${e().status}`:``})(),null),y(t,(()=>{var t=r(()=>!!(e().title&&e().sessionID!==i()?.id));return()=>t()?` · ${e().title}`:``})(),null),s(()=>b(t,`title`,e().text)),t})()}),null),y(e,n(HU,{id:`environment`,title:`Environment`,get children(){return n(l,{get when(){return t.found},get fallback(){return(()=>{var e=vU();return y(e,()=>X.machines?`Not reported by any connected machine.`:`Loading…`),e})()},children:e=>(()=>{var a=yU(),c=a.firstChild.nextSibling,l=c.firstChild,u=l.nextSibling,d=u.nextSibling;d.firstChild;var f=c.nextSibling.nextSibling,p=f.nextSibling.nextSibling,m=p.firstChild,h=m.firstChild,g=p.nextSibling.nextSibling,_=g.nextSibling.nextSibling;return y(c,()=>e().machine.name,u),y(d,(()=>{var t=r(()=>X.connection!==`live`);return()=>t()?`Connecting`:e().machine.online?`online`:`offline`})(),null),y(f,()=>j(t.summary?.directory??e().session.directory)),y(h,()=>t.summary?.directory??e().session.directory),y(p,n(F,{icon:`copy`,label:`Copy the directory`,onClick:()=>{let n=t.summary?.directory??e().session.directory;navigator.clipboard.writeText(n).then(()=>J(`Directory copied`),()=>J(`Could not copy the directory`,`err`))}}),null),y(g,()=>t.summary?.branch??(()=>{var e=bU();return y(e,()=>t.loading?`…`:`—`),e})()),y(_,()=>oe[o()],null),y(_,(()=>{var e=r(()=>!!i()?.terminal?.workspace);return()=>e()?` · ${i().terminal.workspace}`:``})(),null),s(n=>{var r=`online-dot${e().machine.online&&X.connection===`live`?` on`:``}`,i=t.summary?.directory??e().session.directory,a=t.summary?.directory??e().session.directory;return r!==n.e&&k(l,n.e=r),i!==n.t&&b(f,`title`,n.t=i),a!==n.a&&b(m,`title`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),a})()})}}),null),y(e,n(l,{get when(){return i()?.id},children:e=>n(HU,{id:`intent`,title:`Intent`,label:`Session intent`,get children(){return n(bH,{get sessionID(){return e()}})}})}),null),y(e,n(l,{get when(){return c().length||f()},get children(){return n(HU,{id:`jobs`,get title(){return`Jobs${d()?` · ${d()} running`:``}`},label:`Background jobs`,get children(){return[n(l,{get when(){return f()},children:e=>(()=>{var t=xU();return y(t,e),t})()}),(()=>{var e=fU();return y(e,n(m,{get each(){return c()},children:e=>(()=>{var t=SU(),n=t.firstChild,a=n.nextSibling,o=a.nextSibling;return y(a,()=>e.command??e.id),y(o,()=>Ji(e,N()),null),y(o,(()=>{var t=r(()=>!!(e.sessionID!==i()?.id&&e.sessionTitle));return()=>t()?` · ${e.sessionTitle}`:``})(),null),s(r=>{var i=`job ${e.status}`,a=e.command??e.id,o=`job-dot ${e.status===`running`?`on`:e.exit?`bad`:``}`;return i!==r.e&&k(t,r.e=i),a!==r.t&&b(t,`title`,r.t=a),o!==r.a&&k(n,r.a=o),r},{e:void 0,t:void 0,a:void 0}),t})()})),e})()]}})}}),null),y(e,n(l,{get when(){return g().running.length||g().finished.length},get children(){return n(HU,{id:`subagents`,get title(){return sU(g())},label:`Subagents`,get children(){return[(()=>{var e=pU();return y(e,n(m,{get each(){return w()},children:T})),e})(),n(l,{get when(){return g().finished.length>3},get children(){var e=mU();return e.$$click=()=>S(!v()),y(e,(()=>{var e=r(()=>!!v());return()=>e()?`Show fewer`:`${g().finished.length-3} more finished`})()),s(()=>b(e,`aria-expanded`,v())),e}})]}})}}),null),y(e,n(l,{get when(){return i()?.id},children:e=>n(HU,{id:`context-cards`,title:`Context cards`,get children(){return n(QH,{get sessionID(){return e()}})}})}),null),y(e,n(l,{get when(){return i()?.id},children:e=>n(HU,{id:`subscriptions`,title:`Subscriptions`,label:`Session subscriptions`,get children(){return n(RH,{get sessionID(){return e()}})}})}),null),y(e,n(HU,{id:`context`,title:`Context`,get children(){return n(l,{get when(){return t.summary?.context},get fallback(){return(()=>{var e=vU();return y(e,()=>t.loading?`Loading…`:`No usage reported yet.`),e})()},children:e=>[(()=>{var t=CU(),n=t.firstChild;return s(r=>{var i=e().percent??0,o=`${e().percent??0}%`,s=(e().percent??0)>80?`hot`:``;return i!==r.e&&b(t,`aria-valuenow`,r.e=i),o!==r.t&&a(n,`width`,r.t=o),s!==r.a&&k(n,r.a=s),r},{e:void 0,t:void 0,a:void 0}),t})(),(()=>{var t=wU(),n=t.firstChild,i=n.nextSibling;return i.firstChild,y(n,(()=>{var t=r(()=>e().percent!==void 0);return()=>t()?`${e().percent}%`:UU(e().used)})()),y(i,(()=>{var t=r(()=>!!e().limit);return()=>t()?`${UU(e().used)} / ${UU(e().limit)} tokens`:`tokens`})(),null),y(i,(()=>{var t=r(()=>!!e().model);return()=>t()?` · ${e().model}`:``})(),null),t})()]})}}),null),y(e,n(HU,{id:`mcp`,get title(){return E()},label:`MCP servers`,get children(){return n(l,{get when(){return t.summary?.mcp?.length},get fallback(){return(()=>{var e=vU();return y(e,()=>t.loading?`Loading…`:`No MCP servers.`),e})()},get children(){var e=hU();return y(e,n(m,{get each(){return t.summary.mcp},children:e=>(()=>{var t=TU(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling;return y(r,()=>e.name),y(i,()=>e.status.replace(`_`,` `)),s(r=>{var i=e.error??e.status,a=`mcp-dot ${e.status}`;return i!==r.e&&b(t,`title`,r.e=i),a!==r.t&&k(n,r.t=a),r},{e:void 0,t:void 0}),t})()})),e}})}}),null),y(e,n(HU,{id:`changes`,title:`Changes`,domID:`rail-changes`,get extra(){return n(l,{get when(){return t.summary?.changes},children:e=>(()=>{var t=EU(),n=t.firstChild;n.firstChild;var r=n.nextSibling.nextSibling;return r.firstChild,y(n,()=>e().additions,null),y(r,()=>e().deletions,null),t})()})},get children(){return n(l,{get when(){return t.summary?.changes},get fallback(){return(()=>{var e=vU();return y(e,(()=>{var e=r(()=>!!t.loading);return()=>e()?`Loading…`:t.summaryError||`No working-tree changes reported (not a git repository, or OpenCode is still warming up).`})()),e})()},children:e=>n(l,{get when(){return e().files.length},get fallback(){return OU()},get children(){return[(()=>{var r=DU();return y(r,n(m,{get each(){return e().files},children:e=>(()=>{var n=kU(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild,c=a.nextSibling.firstChild;c.firstChild;var l=c.nextSibling.nextSibling;return l.firstChild,r.$$click=()=>t.onFile(e.file),y(i,()=>e.status[0].toUpperCase()),y(o,()=>e.file),y(c,()=>e.additions,null),y(l,()=>e.deletions,null),s(t=>{var n=e.file,a=`file-status ${e.status}`;return n!==t.e&&b(r,`title`,t.e=n),a!==t.t&&k(i,t.t=a),t},{e:void 0,t:void 0}),n})()})),r})(),n(l,{get when(){return zU(e())},children:e=>(()=>{var t=AU(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(t,e,n),y(t,()=>e()===1?`file`:`files`,r),t})()})]}})})}}),null),e})()}function GU(e){let[t]=d(()=>e.file,async t=>K(`${U(e.sessionID)}/diff?file=${q(t)}`)),[i,a]=u(!1);return(()=>{var o=NU(),c=o.firstChild,u=c.firstChild,d=u.nextSibling,f=d.firstChild,p=c.nextSibling;return y(c,n(L,{name:`diff`}),u),u.addEventListener(`change`,t=>e.onFile(t.currentTarget.value)),y(u,n(m,{get each(){return e.files},children:e=>(()=>{var t=PU();return t.value=e,y(t,e),t})()})),y(c,n(l,{get when(){return t()},children:e=>(()=>{var t=EU(),n=t.firstChild;n.firstChild;var r=n.nextSibling.nextSibling;return r.firstChild,y(n,()=>e().additions,null),y(r,()=>e().deletions,null),t})()}),d),f.addEventListener(`change`,e=>a(e.currentTarget.checked)),y(c,n(F,{icon:`close`,label:`Close diff`,get onClick(){return e.onClose}}),null),y(p,n(l,{get when(){return!t.loading},get fallback(){return FU()},get children(){return n(l,{get when(){return!t.error},get fallback(){return(()=>{var e=IU();return y(e,(()=>{var e=r(()=>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 n(l,{get when(){return t()?.patch},get fallback(){return LU()},get children(){return[(()=>{var e=jU(),i=e.firstChild;return y(i,n(m,{get each(){return QV(t().patch).filter(e=>e.type!==`meta`)},children:e=>(()=>{var t=RU(),n=t.firstChild,i=n.nextSibling,a=i.nextSibling,o=a.firstChild;return y(n,()=>e.oldNo??``),y(i,()=>e.newNo??``),y(o,(()=>{var t=r(()=>e.type===`add`);return()=>t()?`+`:e.type===`del`?`−`:` `})()),y(a,()=>e.text,null),s(()=>k(t,e.type)),t})()})),e})(),n(l,{get when(){return t().truncated},get children(){return MU()}})]}})}})}})),s(t=>{var n=`Changes in ${e.file}`,r=`diff-body${i()?` wrap`:``}`;return n!==t.e&&b(o,`aria-label`,t.e=n),r!==t.t&&k(p,t.t=r),t},{e:void 0,t:void 0}),s(()=>u.value=e.file),s(()=>f.checked=i()),o})()}B([`click`]);function KU(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 qU(e,t){return e&&(e.type===`number`||e.type===`integer`)&&typeof t==`string`&&t.trim()?Number(t):typeof t==`string`?t.trim():t}function JU(e,t){let n=new Map(e.map(e=>[e.key,e]));return e.filter(e=>(e.when??[]).every(e=>{let r=qU(n.get(e.key),t[e.key])===e.value;return e.op===`eq`?r:!r}))}var YU=e=>typeof e==`string`?e.trim():``;function XU(e,t){let n={};for(let r of JU(e,t)){let e=ZU(r,t[r.key]);e&&(n[r.key]=e)}return n}function ZU(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=YU(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=YU(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 QU(e,t){let n={};for(let r of JU(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=YU(e);if(!t)continue;n[r.key]=r.type===`number`||r.type===`integer`?Number(t):t}}}return n}var $U=I(`<p class="muted small"data-answer-unavailable> can't take this answer from the hub; answer it in the terminal.`),eW=I(`<p class="blocker-recommendation small"data-recommendation>`),tW=I(`<p class=blocker-text>`),nW=I(`<div role=group><p class=blocker-head><strong>`),rW=I(`<p class="muted small">This question has nothing to fill in here; answer it in the terminal.`),iW=I(`<p class="answered-by small muted"data-answered-by>`),aW=I(`<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`),oW=I(`<form class=form-card novalidate><fieldset><div class=row><button type=submit class="btn small primary"></button><button type=button class="btn small">Dismiss`),sW=I(`<p class="field-error small"role=alert>`),cW=I(`<div>`),lW=I(`<span class=field-title>`),uW=I(`<span class="field-desc muted small">`),dW=I(`<a class="btn small"target=_blank rel="noopener noreferrer">Open link`),fW=I(`<label class=check><input type=checkbox>`),pW=I(`<input type=text placeholder="Other (comma separated)">`),mW=I(`<div role=group class=choice-group>`),hW=I(`<input type=text placeholder="Type your own answer">`),gW=I(`<div role=radiogroup class=choice-group>`),_W=I(`<label class=text-field>`),vW=I(`<input type=text>`),yW=I(`<span class="muted small"> — `),bW=I(`<label class=choice><input type=checkbox><span>`),xW=I(`<label class=choice><input type=radio><span>`);function SW(e,t){return!(e instanceof G)||e.status!==409||e.code!==`gone`?!1:(J(`Already answered or expired`),t(),!0)}function CW(e){let[t,i]=u(!1),a=()=>e.blocker,c=()=>a().sessionID&&a().sessionID!==e.rootID?` (${a().sessionTitle||`subagent`})`:``,d=()=>a().kind===`permission`?`Permission request`:`Question`;return n(l,{get when(){return!t()},get children(){var t=nW(),u=t.firstChild,f=u.firstChild;return y(f,(()=>{var e=r(()=>a().kind===`permission`);return()=>e()?`Permission`:a().question?`Question`:`Form`})()),y(u,c,null),y(t,n(v,{get fallback(){return rW()},get children(){return[n(o,{get when(){return e.canAnswer===!1},get children(){return[n(xg,{get class(){return`blocker-text${a().kind===`permission`?` mono`:``}`},get text(){return a().summary},what:`the request`,get reveal(){return a().kind===`permission`}}),(()=>{var t=$U(),n=t.firstChild;return y(t,()=>e.harnessName??`This harness`,n),t})()]}}),n(o,{get when(){return a().kind===`permission`},get children(){return[n(xg,{class:`blocker-text mono`,get text(){return a().summary},what:`the request`,reveal:!0}),n(l,{get when(){return Et(a().recommendation,Hu)},get children(){var e=eW();return y(e,()=>Et(a().recommendation,Hu)),e}}),n(wW,{get sessionID(){return e.sessionID},get blocker(){return a()},onGone:()=>i(!0)})]}}),n(o,{get when(){return r(()=>a().kind===`form`)()&&a().fields?.length},get children(){return[n(l,{get when(){return!a().question||a().summary!==`Questions`},get children(){var e=tW();return y(e,()=>a().summary),e}}),n(TW,{get sessionID(){return e.sessionID},get blocker(){return a()},get fields(){return a().fields},onGone:()=>i(!0)})]}})]}}),null),y(t,n(l,{get when(){return $t(Du(),a().id,Hu,Nu)},children:e=>(()=>{var t=iW();return y(t,()=>e().text),s(()=>b(t,`title`,e().title)),t})()}),null),s(e=>{var n=`card blocker ${a().kind}`,r=`${d()}: ${a().summary}`;return n!==e.e&&k(t,e.e=n),r!==e.t&&b(t,`aria-label`,e.t=r),e},{e:void 0,t:void 0}),t}})}function wW(e){let[t,n]=u(!1),r=async t=>{n(!0);try{await H(`${U(e.sessionID)}/permission`,{method:`POST`,json:{requestID:e.blocker.id,decision:t}}),J(t===`reject`?`Denied`:`Allowed`)}catch(t){SW(t,e.onGone)||J(fB(t)??W(t),`err`),n(!1)}};return(()=>{var e=aW(),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 TW(e){let[t,r]=u(KU(e.fields)),[i,a]=u({}),[o,c]=u(!1),[d,f]=u(!1),p=C((n=[])=>{let r=JU(e.fields,t()).map(e=>e.key);return r.length===n.length&&r.every((e,t)=>e===n[t])?n:r}),h=t=>e.fields.find(e=>e.key===t),g=(e,t)=>{r(n=>({...n,[e]:t})),i()[e]&&a(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e)))},_=async(t,n)=>{c(!0);try{await H(`${U(e.sessionID)}/form`,{method:`POST`,json:{formID:e.blocker.id,...t}}),f(!0),J(n)}catch(t){SW(t,e.onGone)||J(fB(t)??W(t),`err`),c(!1)}},v=n=>{n.preventDefault();let r=XU(e.fields,t());if(a(r),Object.keys(r).length)return;let i=QU(e.fields,t());e.blocker.question&&!Object.values(i).some(e=>Array.isArray(e)?e.length>0:e!==``&&e!==!1)?J(`Pick or type an answer first (Dismiss skips the questions)`,`err`):_({answer:i},`Answer sent`)},x=()=>o()||d();return(()=>{var r=oW(),a=r.firstChild,o=a.firstChild,c=o.firstChild,u=c.nextSibling;return r.addEventListener(`submit`,v),y(a,n(m,{get each(){return p()},children:r=>n(l,{get when(){return h(r)},children:a=>(()=>{var o=cW();return b(o,`data-key`,r),y(o,n(EW,{get field(){return a()},get value(){return t()[r]},onChange:e=>g(r,e),get formID(){return e.blocker.id}}),null),y(o,n(l,{get when(){return i()[r]},get children(){var e=sW();return y(e,()=>i()[r]),e}}),null),s(()=>k(o,`form-field ${a().type}`)),o})()})}),o),y(c,()=>d()?`Sent`:`Submit`),u.$$click=()=>void _({cancel:!0},`Dismissed`),s(()=>a.disabled=x()),r})()}function EW(e){let t=()=>e.field,i=()=>`f-${e.formID}-${t().key}`,a=()=>t().title||t().key,c=()=>typeof e.value==`string`?e.value:``,u=()=>Array.isArray(e.value)?e.value:[],d=()=>new Set((t().options??[]).map(e=>e.value)),f=()=>[(()=>{var e=lW();return y(e,a,null),y(e,()=>t().required?` *`:``,null),e})(),n(l,{get when(){return t().description},get children(){var e=uW();return y(e,()=>t().description),e}})];return n(v,{get children(){return[n(o,{get when(){return t().type===`external`},get children(){return[n(f,{}),(()=>{var e=dW();return s(()=>b(e,`href`,t().url)),e})()]}}),n(o,{get when(){return t().type===`boolean`},get children(){var t=fW(),r=t.firstChild;return r.addEventListener(`change`,t=>e.onChange(t.currentTarget.checked)),y(t,n(f,{}),null),s(()=>r.checked=e.value===!0),t}}),n(o,{get when(){return t().type===`multiselect`},get children(){var r=mW();return y(r,n(f,{}),null),y(r,n(m,{get each(){return t().options??[]},children:t=>(()=>{var r=bW(),i=r.firstChild,a=i.nextSibling;return i.addEventListener(`change`,n=>e.onChange(n.currentTarget.checked?[...u(),t.value]:u().filter(e=>e!==t.value))),y(a,()=>t.label),y(r,n(l,{get when(){return t.description},get children(){var e=yW();return e.firstChild,y(e,()=>t.description,null),e}}),null),s(()=>i.checked=u().includes(t.value)),r})()}),null),y(r,n(l,{get when(){return t().custom},get children(){var t=pW();return t.addEventListener(`change`,t=>e.onChange([...u().filter(e=>d().has(e)),...t.currentTarget.value.split(`,`).map(e=>e.trim()).filter(Boolean)])),s(()=>b(t,`aria-label`,`${a()}: other`)),s(()=>t.value=u().filter(e=>!d().has(e)).join(`, `)),t}}),null),s(()=>b(r,`aria-label`,a())),r}}),n(o,{get when(){return r(()=>t().type===`string`)()&&t().options?.length},get children(){var r=gW();return y(r,n(f,{}),null),y(r,n(m,{get each(){return t().options??[]},children:t=>(()=>{var r=xW(),a=r.firstChild,o=a.nextSibling;return a.addEventListener(`change`,()=>e.onChange(t.value)),y(o,()=>t.label),y(r,n(l,{get when(){return t.description},get children(){var e=yW();return e.firstChild,y(e,()=>t.description,null),e}}),null),s(()=>b(a,`name`,i())),s(()=>a.checked=c()===t.value),r})()}),null),y(r,n(l,{get when(){return t().custom},get children(){var t=hW();return t.$$input=t=>e.onChange(t.currentTarget.value),s(()=>b(t,`aria-label`,`${a()}: your own answer`)),s(()=>t.value=d().has(c())?``:c()),t}}),null),s(()=>b(r,`aria-label`,a())),r}}),n(o,{when:!0,get children(){return[(()=>{var e=_W();return y(e,n(f,{})),s(()=>b(e,`for`,i())),e})(),(()=>{var n=vW();return n.$$input=t=>e.onChange(t.currentTarget.value),s(e=>{var r=i(),a=t().type===`number`||t().type===`integer`?`decimal`:void 0,o=t().placeholder??``;return r!==e.e&&b(n,`id`,e.e=r),a!==e.t&&b(n,`inputmode`,e.t=a),o!==e.a&&b(n,`placeholder`,e.a=o),e},{e:void 0,t:void 0,a:void 0}),s(()=>n.value=c()),n})()]}})]}})}B([`click`,`input`]);var DW=I(`<span class=file-chip> `),OW=I(`<button type=button class="icon-btn msg-more"aria-label="Copy, fork or revert"title="Copy, fork (here or beside) or revert"aria-haspopup=true>`),kW=I(`<div class=pill>`),AW=I(`<p class="msg-note muted small"data-answered-note>`),jW=I(`<div><div class=user-body>`),MW=I(`<div class=msg-images>`),NW=I(`<div class=msg-tools role=toolbar aria-label="Copy, fork, revert">`),PW=I(`<span>`),FW=I(`<div class=transcript aria-label=Conversation>`),IW=I(`<div>`),LW=I(`<p class="note sys turn-denied">`),RW=I(`<span class=turn-error-status>`),zW=I(`<div class=turn-error-message>`),BW=I(`<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>`),VW=I(`<p><span class=turn-retry-mark aria-hidden=true>↻</span><span>`),HW=I(`<a><span class=sub-mark aria-hidden=true></span><span class=sub-label>Subagent · <strong></strong></span><span class="sub-state muted">`),UW=I(`<span class=spinner>`),WW=I(`<span class=hub-msg-kind>`),GW=I(`<span class="hub-msg-state muted">`),KW=I(`<span class="hub-msg-delivery muted"title="Not delivered into a turn yet: the recipient's harness takes it at its next step">`),qW=I(`<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>`),JW=I(`<div class="fold-body hub-msg-text">`),YW=I(`<div><button type=button class=fold-head><span class=hub-msg-mark aria-hidden=true>⇄</span><span>`),XW=I(`<a>`),ZW=I(`<span class="spinner small">`),QW=I(`<div class="fold thought"><button type=button class=fold-head><span>`),$W=I(`<ul class="fold-body tool-list">`),eG=I(`<div><button type=button class=fold-head><span>`),tG=I(`<pre class=code>`),nG=I(`<div class=tool-detail>`),rG=I(`<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">`),iG=I(`<span class="muted small">Loading full details…`),aG=I(`<span class="error small">`),oG=I(`<span class="muted small">No details for this call yet.`),sG={pending:[`…`,`Sending`],sent:[`✓`,`Sent`],queued:[`◷`,`Queued: the harness takes it at its next step`],heard:[`✓✓`,`Heard by the agent`],failed:[`!`,`Not sent`]};function cG(e){return n(l,{get when(){return e.image.src},get fallback(){return(()=>{var t=DW(),r=t.firstChild;return y(t,n(L,{name:`file`}),r),y(t,()=>e.image.name,null),s(()=>b(t,`title`,e.image.mime)),t})()},get children(){return n(Pn,{get image(){return e.image},class:`msg-image`,get onOpen(){return e.onOpen}})}})}var lG=500;function uG(e){let[t,a]=u(!1),o,c=()=>clearTimeout(o),d=t=>{t.pointerType===`touch`&&e.actions&&(c(),o=setTimeout(()=>a(!0),lG))},f=(e,t)=>()=>{a(!1),e.enabled&&t()};return(()=>{var o=jW(),u=o.firstChild;return i(o,_({get class(){return`msg user${t()?` tools-open`:``}`},get"data-key"(){return e.block.key}},()=>e.block.messageID?{"data-message":e.block.messageID}:{},{onPointerDown:d,onPointerUp:c,onPointerCancel:c,onPointerLeave:c,onFocusOut:e=>!e.currentTarget.contains(e.relatedTarget)&&a(!1),onKeyDown:e=>{if(e.key!==`Escape`)return;let n=e.target?.closest?.(`.msg-tools`);(t()||n)&&(a(!1),n&&e.currentTarget.querySelector(`.msg-more`)?.focus(),e.stopPropagation())}}),!1,!0),y(o,n(l,{get when(){return e.actions},get children(){var r=OW();return r.$$click=e=>{let n=!t(),r=e.currentTarget;a(n),n&&e.detail===0&&queueMicrotask(()=>r.closest(`.msg`)?.querySelector(`.msg-tools button`)?.focus())},y(r,n(L,{name:`more`})),s(n=>{var i=t(),a=`msg-tools-${e.block.key}`;return i!==n.e&&b(r,`aria-expanded`,n.e=i),a!==n.t&&b(r,`aria-controls`,n.t=a),n},{e:void 0,t:void 0}),r}}),u),y(u,n(l,{get when(){return e.block.images?.length},get children(){return n(Rn,{get images(){return e.block.images??[]},children:t=>(()=>{var r=MW();return y(r,n(m,{get each(){return e.block.images},children:e=>n(cG,{image:e,onOpen:()=>t(e.key)})})),r})()})}}),null),y(u,n(l,{get when(){return e.block.text},get children(){var t=kW();return y(t,()=>e.block.text),t}}),null),y(u,n(l,{get when(){return e.block.note},get children(){var t=AW();return y(t,()=>e.block.note),t}}),null),y(u,n(l,{get when(){return e.actions},children:t=>(()=>{var i=NW();return y(i,n(F,{icon:`copy`,label:`Copy`,"data-action":`copy`,onClick:()=>(a(!1),t().onCopy(e.block.text))}),null),y(i,n(l,{get when(){return e.block.messageID},children:i=>[n(F,{icon:`fork`,get label(){return r(()=>!!t().fork.enabled)()?`Fork: a new session with the conversation up to here`:t().fork.reason??`Fork is not available`},"data-action":`fork`,get"aria-disabled"(){return!t().fork.enabled},get onClick(){return f(t().fork,()=>t().onFork(i(),e.block.text))}}),n(l,{get when(){return t().onForkBeside},children:a=>n(F,{icon:`split`,get label(){return r(()=>!!t().fork.enabled)()?`Fork and open beside: the new session in a pane next to this one`:t().fork.reason??`Fork is not available`},"data-action":`fork-beside`,get"aria-disabled"(){return!t().fork.enabled},get onClick(){return f(t().fork,()=>a()(i(),e.block.text))}})}),n(F,{icon:`undo`,get label(){return r(()=>!!t().revert.enabled)()?`Revert: undo from here on (restores the files)`:t().revert.reason??`Revert is not available`},"data-action":`revert`,get"aria-disabled"(){return!t().revert.enabled},get onClick(){return f(t().revert,()=>t().onRevert(i(),e.block.text))}})]}),null),s(()=>b(i,`id`,`msg-tools-${e.block.key}`)),i})()}),null),y(o,n(l,{get when(){return e.tick},children:e=>(()=>{var t=PW();return y(t,()=>sG[e()][0]),s(n=>{var r=`tick ${e()}`,i=sG[e()][1],a=sG[e()][1];return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`aria-label`,n.t=i),a!==n.a&&b(t,`title`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),o})()}function dG(e){return n(Fn,{get children(){return n(fG,e)}})}function fG(e){let t=C(()=>e.previews?TM(e.blocks,e.partialMessage):void 0),i=(n,r)=>{let i=t()?.get(n);return i?{sessionID:e.sessionID,messageID:i.messageID,base:i.base}:e.previews&&r&&r===e.partialMessage?{sessionID:e.sessionID,messageID:r,base:0,waiting:!0}:void 0},a=C(()=>new Map(e.blocks.map(e=>[e.key,e]))),c=C(()=>e.blocks.map(e=>e.key),void 0,{equals:(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n])});return(()=>{var t=FW();return y(t,n(m,{get each(){return c()},children:t=>{let c,u=C(()=>c=a().get(t)??c),d=e=>{let t=u();return t.type===e?t:void 0};return n(v,{get children(){return[n(o,{get when(){return d(`user`)},children:t=>n(uG,{get block(){return t()},get tick(){return e.ticks[t().key]},get actions(){return e.actions}})}),n(o,{get when(){return d(`assistant`)},children:t=>(()=>{var a=IW();return y(a,n(qN.Provider,{get value(){return e.sessionID},get children(){return n(sF,{get text(){return t().text},get streaming(){return t().live},get preview(){return i(t().key,t().messageID)},get images(){return r(()=>!!e.previews)()?t().media:void 0},links:!0})}})),s(e=>{var n=`msg assistant${t().live?` live`:``}`,r=t().key;return n!==e.e&&k(a,e.e=n),r!==e.t&&b(a,`data-key`,e.t=r),e},{e:void 0,t:void 0}),a})()}),n(o,{get when(){return d(`thought`)},children:t=>n(mG,{get block(){return t()},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})}),n(o,{get when(){return d(`tools`)},children:t=>n(hG,{get block(){return t()},get sessionID(){return e.sessionID},get onDetail(){return e.onDetail},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})}),n(o,{get when(){return d(`message`)},children:t=>n(pG,{get block(){return t()},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})}),n(o,{get when(){return r(()=>!!d(`error`)?.denied)()&&d(`error`)},children:e=>(()=>{var t=LW();return y(t,()=>e().label),s(()=>b(t,`data-key`,e().key)),t})()}),n(o,{get when(){return d(`error`)},children:e=>(()=>{var t=BW(),r=t.firstChild.nextSibling,i=r.firstChild,a=i.firstChild;return y(a,()=>e().label),y(i,n(l,{get when(){return e().status},get children(){var t=RW();return y(t,()=>e().status),t}}),null),y(r,n(l,{get when(){return e().message},get children(){var t=zW();return y(t,()=>e().message),t}}),null),s(n=>{var r=e().key,i=`Error: ${e().label}`;return r!==n.e&&b(t,`data-key`,n.e=r),i!==n.t&&b(t,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(o,{get when(){return d(`retry`)},children:e=>{let t=()=>FB(e(),se());return(()=>{var n=VW(),r=n.firstChild.nextSibling;return y(r,()=>t().text),s(r=>{var i=`msg turn-retry${t().waiting?` waiting`:``}`,a=e().key;return i!==r.e&&k(n,r.e=i),a!==r.t&&b(n,`data-key`,r.t=a),r},{e:void 0,t:void 0}),n})()}}),n(o,{get when(){return d(`subagent`)},children:e=>(()=>{var t=HW(),i=t.firstChild,a=i.nextSibling,o=a.firstChild.nextSibling,c=a.nextSibling;return y(i,(()=>{var t=r(()=>e().state===`working`);return()=>t()?UW():`◆`})()),y(o,()=>e().label),y(c,()=>e().state),y(t,n(L,{name:`chevron`,class:`chev`}),null),s(n=>{var r=`subagent ${e().state}`,i=Dt(e().sessionID),a=e().key;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`href`,n.t=i),a!==n.a&&b(t,`data-key`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})]}})}})),t})()}function pG(e){let t=()=>!!e.expanded[e.block.key];return n(l,{get when(){return r(()=>!e.block.primer)()&&!e.block.summary},get fallback(){return(()=>{var r=YW(),a=r.firstChild,o=a.firstChild.nextSibling;return i(r,_({get class(){return`fold hub-note${e.block.summary?` hub-update`:``}`},get"data-key"(){return e.block.key}},()=>e.block.summary?{"data-concierge-update":``}:{}),!1,!0),a.$$click=()=>e.onToggle(e.block.key,!t()),y(o,()=>e.block.summary??e.block.label),y(a,n(L,{name:`chevron`,class:`chev`}),null),y(r,n(l,{get when(){return t()},get children(){var t=JW();return y(t,()=>e.block.text),t}}),null),s(n=>{var r=t(),i=e.block.summary?`Sent by the hub, not by you: show the full update`:void 0;return r!==n.e&&b(a,`aria-expanded`,n.e=r),i!==n.t&&b(a,`title`,n.t=i),n},{e:void 0,t:void 0}),r})()},get children(){var t=qW(),r=t.firstChild,i=r.firstChild,a=i.nextSibling,o=r.nextSibling;return y(i,()=>e.block.direction===`out`?`↗`:`↘`),y(r,n(l,{get when(){return e.block.kind!==`msg`},get children(){var t=WW();return y(t,()=>e.block.kind),t}}),a),y(a,()=>ze(e.block.label,Hu)),y(r,n(l,{get when(){return e.block.state===`open`||e.block.state===`answered`||e.block.state===`declined`||e.block.state===`expired`},get children(){var t=GW();return y(t,()=>e.block.state),t}}),null),y(r,n(l,{get when(){return e.block.delivery},get children(){var t=KW();return y(t,()=>e.block.delivery),s(()=>b(t,`data-delivery`,e.block.delivery)),t}}),null),y(o,n(l,{get when(){return e.block.parts},get fallback(){return e.block.text},children:e=>n(m,{get each(){return e()},children:e=>e.href?(()=>{var t=XW();return y(t,()=>e.text),s(()=>b(t,`href`,e.href)),t})():e.text})})),s(n=>{var r=`msg hub-msg ${e.block.direction}`,i=e.block.key,o=`Hub ${e.block.kind} ${ze(e.block.label,Hu)}`,s=e.block.label;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`data-key`,n.t=i),o!==n.a&&b(t,`aria-label`,n.a=o),s!==n.o&&b(a,`title`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t}})}function mG(e){let t=()=>!!e.expanded[e.block.key],r=t=>e.onToggle(e.block.key,t),i=()=>RB(e.block);return(()=>{var a=QW(),o=a.firstChild,c=o.firstChild;return o.$$click=()=>r(!t()),y(o,n(l,{get when(){return e.block.running},get children(){return ZW()}}),c),y(c,()=>i().label),y(o,n(L,{name:`chevron`,class:`chev`}),null),y(a,n(l,{get when(){return t()},get children(){var e=IW();return y(e,()=>i().body),s(()=>k(e,`fold-body reasoning${i().muted?` hidden-reasoning`:``}`)),e}}),null),s(n=>{var r=e.block.key,i=t();return r!==n.e&&b(a,`data-key`,n.e=r),i!==n.t&&b(o,`aria-expanded`,n.t=i),n},{e:void 0,t:void 0}),a})()}function hG(e){let t=()=>!!e.expanded[e.block.key],r=t=>e.onToggle(e.block.key,t),i=()=>e.block.items.length,a=()=>{let t=e.block;return t.running?`Using ${i()===1?t.items[0].name??`a tool`:`${i()} tools`}…`:`Used ${i()} tool${i()===1?``:`s`}${t.failed?` (${t.failed} failed)`:``}`};return(()=>{var i=eG(),o=i.firstChild,c=o.firstChild;return o.$$click=()=>r(!t()),y(o,n(l,{get when(){return e.block.running},get children(){return ZW()}}),c),y(c,a),y(o,n(L,{name:`chevron`,class:`chev`}),null),y(i,n(l,{get when(){return e.block.media?.length},get children(){return n(Ln,{get images(){return e.block.media},label:`Tool images`})}}),null),y(i,n(l,{get when(){return t()},get children(){var t=$W();return y(t,n(m,{get each(){return e.block.items},children:t=>n(gG,{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 r=`fold tools${e.block.failed?` has-failed`:``}`,a=e.block.key,s=t();return r!==n.e&&k(i,n.e=r),a!==n.t&&b(i,`data-key`,n.t=a),s!==n.a&&b(o,`aria-expanded`,n.a=s),n},{e:void 0,t:void 0,a:void 0}),i})()}function gG(e){let t=()=>!!e.expanded[`tool:${e.row.key}`],i=t=>e.onToggle(`tool:${e.row.key}`,t),[a,o]=u(!1),[c,d]=u(``),f=()=>e.row,p=()=>f().completed&&f().at?Ya(f().completed-f().at):``,m=async()=>{let n=!t();if(i(n),n&&f().detail===void 0&&f().messageID&&f().partID!==void 0){o(!0),d(``);try{let t=await K(`${U(e.sessionID)}/timeline/messages/${q(f().messageID)}/parts/${q(String(f().partID))}`);e.onDetail(f().key,t.detail)}catch(e){d(W(e))}finally{o(!1)}}},h=()=>typeof f().summary==`string`?f().summary:``;return(()=>{var e=rG(),i=e.firstChild,o=i.firstChild,u=o.nextSibling,d=u.nextSibling,g=d.nextSibling;return i.$$click=m,y(o,(()=>{var e=r(()=>f().state===`running`);return()=>e()?ZW():f().state===`failed`?`✕`:`✓`})()),y(u,()=>f().name??`tool`),y(d,h),y(g,p),y(e,n(l,{get when(){return t()},get children(){var e=nG();return y(e,n(l,{get when(){return!a()},get fallback(){return iG()},get children(){return n(l,{get when(){return!c()},get fallback(){return(()=>{var e=aG();return y(e,c),e})()},get children(){return n(l,{get when(){return f().detail!==void 0||h()||f().error},get fallback(){return oG()},get children(){var e=tG();return y(e,()=>BB(f().detail,{summary:h(),error:f().error})),e}})}})}})),e}}),null),s(n=>{var r=`tool ${f().state??``}`,a=t(),s=f().state??``;return r!==n.e&&k(e,n.e=r),a!==n.t&&b(i,`aria-expanded`,n.t=a),s!==n.a&&b(o,`aria-label`,n.a=s),n},{e:void 0,t:void 0,a:void 0}),e})()}B([`click`]);var _G={profilesPerUser:200,versionsPerProfile:100,skillsPerProfile:32,commandsPerProfile:64,instructionsChars:32e3,skillChars:32e3,commandChars:8e3,versionBytes:524288,projectsPerProfile:16},vG=[`pending`,`applied`,`partial`,`rejected`,`unsupported`,`restart_required`];function yG(e){if(!Pe(e))return`content must be an object`;if(e.instructions!==void 0&&!Re(e.instructions,_G.instructionsChars))return`instructions must be at most ${_G.instructionsChars} characters`;if(e.model!==void 0&&(typeof e.model!=`string`||!/^[A-Za-z0-9._-]{1,80}\/[A-Za-z0-9._:/-]{1,200}$/.test(e.model)))return`model must be provider/model`;let t=[[e.skills,_G.skillsPerProfile,_G.skillChars,`body`,`skills`],[e.commands,_G.commandsPerProfile,_G.commandChars,`template`,`commands`]];for(let[e,n,r,i,a]of t){if(!Array.isArray(e)||e.length>n)return`${a} must be a list of at most ${n}`;let t=new Set;for(let n of e){if(!Pe(n)||!Ie(n.name))return`each of ${a} needs a slug name`;if(t.has(n.name))return`${a} names must be unique (${n.name})`;if(t.add(n.name),!Ct(n.description,300))return`${a}.${n.name}.description must be 1–300 characters`;if(!Re(n[i],r)||n[i].trim()===``)return`${a}.${n.name}.${i} must be 1–${r} characters`}}if(new TextEncoder().encode(JSON.stringify(e)).length>_G.versionBytes)return`profile version is too large`}function bG(e){if(e===void 0)return;let t=_G.projectsPerProfile;if(!Array.isArray(e)||e.length>t||!e.every(e=>Ct(e))||new Set(e).size!==e.length)return`projects must be at most ${t} unique project names`}function xG(e){return Pe(e)?Ie(e.name)?Ct(e.title)?e.description!==void 0&&!Re(e.description,4e3)?`description must be at most ${Tt} characters`:Te(e.tags)??He(e.metadata)??bG(e.projects)??yG(e.content):`title must be 1–120 characters of text`:`name must be 2–40 lowercase letters, digits or dashes`:`body must be an object`}function SG(e){return Array.isArray(e)?`[${e.map(SG).join(`,`)}]`:Pe(e)?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${SG(e[t])}`).join(`,`)}}`:JSON.stringify(e)}var CG=/^[a-z][a-z0-9_]{0,39}$/,wG=/^[A-Z][A-Z0-9_]{0,63}$/,TG=`secret:`;function EG(e){let t=[],n=``,r=0;for(;r<e.length;){if(e.startsWith(`\\{{`,r)){n+=`{{`,r+=3;continue}if(!e.startsWith(`{{`,r)){n+=e[r],r++;continue}let i=e.indexOf(`}}`,r+2);if(i<0)return`unclosed placeholder at character ${r+1}`;let a=e.slice(r+2,i).trim();if(a.startsWith(TG)){if(!wG.test(a.slice(7)))return`secret reference at character ${r+1} must be {{secret:NAME}} (uppercase letters, digits, _)`;n&&t.push({text:n}),n=``,t.push({secret:a.slice(7),raw:e.slice(r,i+2)})}else{if(!CG.test(a))return`placeholder at character ${r+1} is not a {{name}} parameter (no expression, condition or filter is allowed; write \\{{ for a literal {{)`;n&&t.push({text:n}),n=``,t.push({param:a})}r=i+2}return n&&t.push({text:n}),t}var DG=e=>typeof e==`object`&&!!e&&!Array.isArray(e),$=e=>typeof e==`string`,OG=e=>typeof e==`number`&&Number.isFinite(e),kG=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=1,AG=e=>Array.isArray(e)?e.filter($):[];function jG(e,t){return{items:DG(e)&&Array.isArray(e.items)?e.items.map(t).filter(e=>e!==void 0):[],...DG(e)&&$(e.cursor)?{cursor:e.cursor}:{}}}function MG(e){if(DG(e)&&$(e.id)&&$(e.name)&&$(e.title)&&kG(e.latestVersion)&&OG(e.revision))return{id:e.id,name:e.name,title:e.title,...$(e.description)&&e.description?{description:e.description}:{},state:e.state===`archived`?`archived`:`active`,tags:AG(e.tags),metadata:DG(e.metadata)?Object.fromEntries(Object.entries(e.metadata).filter(e=>$(e[1]))):{},projects:AG(e.projects),latestVersion:e.latestVersion,revision:e.revision,updatedAt:OG(e.updatedAt)?e.updatedAt:0}}var NG=e=>jG(e,MG),PG=[`sessions`,`online`,`olderVersion`,`teamRoles`,`staffedSeats`,`launches`,`liveLaunches`];function FG(e){if(!DG(e))return;let t={};for(let n of PG)OG(e[n])&&(t[n]=e[n]);return Array.isArray(e.teams)&&(t.teams=AG(e.teams)),Array.isArray(e.harnesses)&&(t.harnesses=AG(e.harnesses)),t}function IG(e){if(DG(e)&&kG(e.version)&&OG(e.skills)&&OG(e.commands))return{version:e.version,skills:e.skills,commands:e.commands,instructions:e.instructions===!0}}function LG(e){let t=NG(e),n=DG(e)&&DG(e.usage)?e.usage:void 0,r=DG(e)&&DG(e.summaries)?e.summaries:void 0;return{items:t.items.map(e=>{let t=n?FG(n[e.id]):void 0,i=r?IG(r[e.id]):void 0;return{profile:e,...t?{usage:t}:{},...i?{summary:i}:{}}}),...t.cursor?{cursor:t.cursor}:{}}}var RG=e=>!!e&&((e.sessions??0)>0||(e.teamRoles??0)>0||(e.launches??0)>0);function zG(e){if(!e)return[];let t=[];e.sessions&&t.push(gn(e.sessions,`session`)),e.teamRoles&&t.push(gn(e.teamRoles,`team role`)),e.launches&&t.push(gn(e.launches,`launch`)),e.olderVersion&&t.push(`${e.olderVersion} on older version${e.olderVersion===1?``:`s`}`);let n=e.sessions!==void 0||e.teamRoles!==void 0||e.launches!==void 0;return t.length?t:n?[`Unused`]:[]}var BG=e=>[...new Set(e)].sort();function VG(e){return{tags:BG(e.flatMap(e=>e.profile.tags)),projects:BG(e.flatMap(e=>e.profile.projects)),teams:BG(e.flatMap(e=>e.usage?.teams??[])),harnesses:BG(e.flatMap(e=>e.usage?.harnesses??[]))}}function HG(e,t){return e.filter(e=>(!t.tag||e.profile.tags.includes(t.tag))&&(!t.project||e.profile.projects.includes(t.project))&&(!t.team||(e.usage?.teams??[]).includes(t.team))&&(!t.harness||(e.usage?.harnesses??[]).includes(t.harness))&&(!t.used||t.used===`used`===RG(e.usage)))}var UG=e=>(e?.sessions??0)+(e?.teamRoles??0)+(e?.launches??0),WG=(e,t)=>e.profile.name<t.profile.name?-1:+(e.profile.name>t.profile.name);function GG(e,t){let n=[...e];return t===`updated`?n.sort((e,t)=>t.profile.updatedAt-e.profile.updatedAt||WG(e,t)):t===`usage`?n.sort((e,t)=>UG(t.usage)-UG(e.usage)||WG(e,t)):n.sort(WG)}var KG=[`sessions`,`teams`,`launches`,`workspaces`];function qG(e){if(!DG(e)||!$(e.sessionID)||!kG(e.version)||!OG(e.revision))return;let t=DG(e.effective)&&kG(e.effective.version)?e.effective.version:void 0,n=DG(e.ack)&&vG.includes(e.ack.status)?e.ack.status:void 0,r=t=>$(e[t])?{[t]:e[t]}:{};return{sessionID:e.sessionID,...r(`name`),...r(`title`),...r(`machineID`),...r(`harness`),...r(`project`),online:e.online===!0,...OG(e.lastSeen)?{lastSeen:e.lastSeen}:{},known:e.known!==!1,version:e.version,revision:e.revision,...t===void 0?{}:{running:t},olderVersion:e.olderVersion===!0,...n?{ack:n}:{},offline:DG(e.ack)&&e.ack.offline===!0}}function JG(e){if(!DG(e)||!$(e.profileID)||!kG(e.latestVersion))return;let t=e=>Array.isArray(e)?e.filter(DG):[],n=DG(e.sessions)?e.sessions:void 0;return{profileID:e.profileID,latestVersion:e.latestVersion,counts:{...FG(e.counts),...DG(e.counts)&&OG(e.counts.workspaces)?{workspaces:e.counts.workspaces}:{}},sessions:(n&&Array.isArray(n.items)?n.items:[]).flatMap(e=>qG(e)??[]),...n&&$(n.cursor)?{cursor:n.cursor}:{},teamRoles:t(e.teamRoles).filter(e=>$(e.teamID)&&$(e.role)).map(e=>({teamID:e.teamID,teamName:$(e.teamName)?e.teamName:e.teamID,teamTitle:$(e.teamTitle)?e.teamTitle:$(e.teamName)?e.teamName:e.teamID,role:e.role,...$(e.label)?{label:e.label}:{},...kG(e.version)?{version:e.version}:{},...OG(e.staffed)?{staffed:e.staffed}:{}})),launches:t(e.launches).filter(e=>$(e.id)&&$(e.state)&&kG(e.version)).map(e=>({id:e.id,state:e.state,...$(e.outcome)?{outcome:e.outcome}:{},version:e.version,...$(e.sessionID)?{sessionID:e.sessionID}:{},created:OG(e.created)?e.created:0,updated:OG(e.updated)?e.updated:0})),workspaces:t(e.workspaces).filter(e=>$(e.workspaceID)).map(e=>({workspaceID:e.workspaceID,...$(e.title)?{title:e.title}:{},sessions:OG(e.sessions)?e.sessions:0})),projects:AG(e.projects),hidden:AG(e.hidden).filter(e=>KG.includes(e)),truncated:AG(e.truncated)}}var YG=(e,t)=>t?`/teams/${encodeURIComponent(e)}`:`/watchtower?group=team&team=${encodeURIComponent(e)}`;function XG(e,t){let n={};for(let t of e){let e=t.key.trim(),r=t.value.trim();if(e||r){if(!e)return{ok:!1,error:`Each detail needs a key`};if(e in n)return{ok:!1,error:`The key ${e} is listed twice`};n[e]=r}}let r=[...new Set(t.split(`,`).map(e=>e.trim()).filter(Boolean))],i=He(n)??bG(r);return i?{ok:!1,error:i}:{ok:!0,patch:{metadata:Object.keys(n).length?n:null,projects:r.length?r:null}}}function ZG(e){if(!DG(e)||!$(e.profileID)||!kG(e.version)||!$(e.digest))return;let t=e=>DG(e)&&$(e.name)?{name:e.name,description:$(e.description)?e.description:``}:void 0;return{profileID:e.profileID,version:e.version,digest:e.digest,createdAt:OG(e.createdAt)?e.createdAt:0,bytes:OG(e.bytes)?e.bytes:0,instructions:e.instructions===!0,...$(e.model)?{model:e.model}:{},skills:(Array.isArray(e.skills)?e.skills:[]).flatMap(e=>t(e)??[]),commands:(Array.isArray(e.commands)?e.commands:[]).flatMap(e=>{let n=t(e);return n?[{...n,params:AG(e.params)}]:[]}),secretRefs:AG(e.secretRefs)}}function QG(e){if(DG(e)&&kG(e.version)&&$(e.digest))return{version:e.version,digest:e.digest,bytes:OG(e.bytes)?e.bytes:0,createdAt:OG(e.createdAt)?e.createdAt:0}}var $G=e=>jG(e,QG);function eK(e){let t=DG(e)?e.version:void 0;if(!DG(t)||!$(t.profileID)||!kG(t.version)||!$(t.digest)||!DG(t.content))return;let n=t.content,r={...$(n.instructions)?{instructions:n.instructions}:{},...$(n.model)?{model:n.model}:{},skills:(Array.isArray(n.skills)?n.skills:[]).filter(e=>DG(e)&&$(e.name)).map(e=>({name:e.name,description:$(e.description)?e.description:``,body:$(e.body)?e.body:``})),commands:(Array.isArray(n.commands)?n.commands:[]).filter(e=>DG(e)&&$(e.name)).map(e=>({name:e.name,description:$(e.description)?e.description:``,template:$(e.template)?e.template:``}))};return{profileID:t.profileID,version:t.version,digest:t.digest,createdAt:OG(t.createdAt)?t.createdAt:0,content:r}}function tK(e){if(DG(e)&&vG.includes(e.status)&&$(e.digest))return{status:e.status,digest:e.digest,notes:AG(e.notes),at:OG(e.at)?e.at:0,offline:e.offline===!0}}function nK(e){if(DG(e)&&$(e.profileID)&&kG(e.version)&&$(e.digest)&&(e.status===`applied`||e.status===`partial`))return{profileID:e.profileID,version:e.version,digest:e.digest,status:e.status,at:OG(e.at)?e.at:0}}function rK(e){if(!DG(e)||!$(e.sessionID)||!$(e.profileID)||!kG(e.version)||!OG(e.revision))return;let t=tK(e.ack),n=nK(e.effective);return{sessionID:e.sessionID,profileID:e.profileID,version:e.version,revision:e.revision,...t?{ack:t}:{},...n?{effective:n}:{}}}function iK(e){if(!DG(e)||!(`assignment`in e))return;if(e.assignment===null)return{assignment:null};let t=rK(e.assignment);if(!t)return;let n=MG(e.profile),r=ZG(e.version);return{assignment:t,...n?{profile:n}:{},...r?{version:r}:{}}}var aK={pending:`Pending`,applied:`Applied`,partial:`Partly applied`,rejected:`Rejected`,unsupported:`Unsupported`,restart_required:`Restart required`},oK={applied:`ok`,partial:`warn`,restart_required:`warn`,pending:`pending`,unsupported:`err`,rejected:`err`};function sK(e){let t=e.assignment;if(!t)return{label:`No profile`,tone:`none`,detail:`No agent profile is pinned to this session`};let n=e.profile?.name??`profile`,r=t.ack?.status??`pending`,i=t.effective?.profileID===t.profileID,a=i?t.effective?.version:void 0,o=t.effective?i?t.effective.version===t.version?``:` · running v${t.effective.version}`:` · running another profile`:``,s=e.profile&&e.profile.state===`active`&&e.profile.latestVersion>t.version?e.profile.latestVersion:void 0;return{label:`${n} v${t.version}${o}`,tone:oK[r],detail:`${e.profile?.title??n} v${t.version}: ${aK[r]}${t.ack?.offline?` (machine offline)`:``}${s?` · v${s} available`:``}`,requested:t.version,...a===void 0?{}:{effective:a},...s?{upgrade:s}:{}}}function cK(e){let t=e.assignment;if(!t)return[];let n=`v${t.version}`,r=t.ack,i=[];switch(r?.status??`pending`){case`pending`:i.push(r?.offline?`No connected machine reports this session (offline); the hub applies ${n} when it reconnects.`:`Waiting for the session's harness to confirm ${n} (a busy session answers after its current turn).`);break;case`applied`:i.push(`${n} is in effect from the next prompt.`);break;case`partial`:i.push(`${n} applied in part; the harness says what didn't:`);break;case`restart_required`:i.push(`Accepted: ${n} takes effect only after the session restarts.`);break;case`unsupported`:i.push(`This session's harness can't apply ${n}; nothing changed in the session.`);break;case`rejected`:i.push(`The session refused ${n}; nothing new took effect.`)}i.push(...r?.notes??[]);let a=t.effective;return a&&(a.profileID!==t.profileID||a.version!==t.version)&&i.push(a.profileID===t.profileID?`The session still runs v${a.version} until it confirms ${n}.`:`The session still runs another profile (v${a.version}) until it confirms this pin.`),i}var lK=`Context a session already received can't be withdrawn: unpinning stops re-applying this profile, and what was applied stays until the session restarts. A newer version supersedes earlier context; it doesn't erase it.`,uK={opencode:`OpenCode: instructions, skills and commands apply from the next turn (a busy session finishes its turn first). Commands that use secrets and the model preference are skipped; the hub re-sends the pin after an OpenCode restart.`,"claude-code":`Claude Code: instructions reach the model as hook context. Skills and commands are not applied (Claude Code loads them only at start from its own directories); the model changes only in hub-launched sessions.`,codex:`Codex: instructions apply as one context message; skills are written as session files (partial); commands are not applied, and the model preference is ignored.`},dK=e=>uK[e]??`This harness reports what took effect after you pin; presets can't apply profiles.`,fK=()=>({instructions:``,model:``,skills:[],commands:[]}),pK=e=>({instructions:e.instructions??``,model:e.model??``,skills:e.skills.map(e=>({...e})),commands:e.commands.map(e=>({...e}))});function mK(e){let t=e.instructions.trim(),n=e.model.trim(),r={...t?{instructions:t}:{},...n?{model:n}:{},skills:e.skills.map(e=>({name:e.name.trim(),description:e.description.trim(),body:e.body})),commands:e.commands.map(e=>({name:e.name.trim(),description:e.description.trim(),template:e.template}))},i=yG(r);if(i)return{ok:!1,error:i};for(let e of r.commands){let t=EG(e.template);if(typeof t==`string`)return{ok:!1,error:`commands.${e.name}: ${t}`}}return{ok:!0,content:r}}function hK(e,t){let n=mK(e);return!n.ok||SG(n.content)!==SG(t)}function gK(e,t){let n=mK(t);if(!n.ok)return n;let r=[...new Set(e.tags.split(`,`).map(e=>e.trim()).filter(Boolean))],i=e.description.trim(),a={name:e.name.trim(),title:e.title.trim(),...i?{description:i}:{},...r.length?{tags:r}:{},content:n.content},o=xG(a);return o?{ok:!1,error:o}:{ok:!0,body:a}}function _K(e){let t=EG(e);if(typeof t==`string`)return{error:t};let n=[],r=[];for(let e of t)`param`in e&&!n.includes(e.param)&&n.push(e.param),`secret`in e&&!r.includes(e.secret)&&r.push(e.secret);return{params:n,secrets:r}}var vK=4e3;function yK(e,t){let n={};for(let r of e){let e=t[r]??``;if(e.length>4e3)return{ok:!1,error:`${r} must be at most ${vK} characters`};n[r]=e}return{ok:!0,body:{params:n}}}function bK(e,t){let n=t.trim().replace(/^\//,``).toLowerCase();if(!n)return[...e];let r=e=>e.name.toLowerCase().startsWith(n)?0:e.name.toLowerCase().includes(n)?1:e.description.toLowerCase().includes(n)?2:3;return e.map((e,t)=>({c:e,i:t,r:r(e)})).filter(e=>e.r<3).sort((e,t)=>e.r-t.r||e.i-t.i).map(e=>e.c)}var xK=`Control+Alt+P`,SK=e=>e.ctrlKey&&e.altKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyP`,CK=(e,t)=>e?e.endsWith(`
|
|
31
|
+
`)?e+t:`${e}\n${t}`:t,wK=(e,t,n)=>({profileID:e,version:t,expectedRevision:n.assignment?.revision??0});function TK(e,t,n){let r=e.assignment;return r?r.profileID===t?n>r.version?{kind:`upgrade`,label:`Upgrade to v${n}`}:n<r.version?{kind:`rollback`,label:`Roll back to v${n}`}:{kind:`same`,label:`Re-apply v${n}`}:{kind:`switch`,label:`Switch to v${n}`}:{kind:`pin`,label:`Pin v${n}`}}var EK=e=>!!e.assignment&&(e.assignment.ack?.status??`pending`)===`pending`,DK=15e3,OK=16,kK=e=>e>=OK?void 0:Math.min(DK,1e3*2**e);function AK(e){let t=e,n=t?.message??String(e);switch(t?.code){case`conflict`:return`Changed elsewhere meanwhile${OG(t.details?.currentRevision)?` (now revision ${t.details.currentRevision})`:``}. Reloaded: check and try again. (${n})`;case`unsupported`:return`Not supported: ${n}`;case`offline`:return`The session's machine is offline: ${n}`;case`forbidden`:return`Not allowed: ${n}`;case`not_found`:return`Not found: ${n}`}return t?.status===503?`The session's machine is offline: ${n}`:n}var jK=encodeURIComponent,MK=`/api/agent`,NK={list:(e=`active`,t=!0)=>`${MK}/profiles?state=${e}&limit=200${t?`&include=usage,summary`:``}`,usage:(e,t)=>`${MK}/profiles/${jK(e)}/usage?limit=200${t?`&cursor=${jK(t)}`:``}`,create:()=>`${MK}/profiles`,one:e=>`${MK}/profiles/${jK(e)}`,versions:e=>`${MK}/profiles/${jK(e)}/versions`,version:(e,t)=>`${MK}/profiles/${jK(e)}/versions/${t}`,session:e=>`${MK}/sessions/${jK(e)}/profile`,unpin:(e,t)=>`${MK}/sessions/${jK(e)}/profile?expectedRevision=${t}`,render:(e,t)=>`${MK}/sessions/${jK(e)}/profile/commands/${jK(t)}/render`},PK=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,FK=async e=>e.json().catch(()=>({})),IK=async(e=`active`)=>NG(await K(NK.list(e,!1))),LK=async(e=`active`)=>LG(await K(NK.list(e)));async function RK(e,t){let n=JG(await K(NK.usage(e,t)));if(!n)throw Error(`The hub sent an unreadable usage answer`);return n}async function zK(e,t){let n=MG((await FK(await H(NK.one(e.id),{method:`PATCH`,json:{expectedRevision:e.revision,...t}}))).profile);if(!n)throw Error(`The hub sent an unreadable profile`);return n}async function BK(e){let t=await K(NK.one(e)),n=MG(t.profile);if(!n)throw Error(`The hub sent an unreadable profile`);return{profile:n,latest:ZG(t.latest)}}var VK=async e=>$G(await K(`${NK.versions(e)}?limit=200`));async function HK(e,t){let n=eK(await K(NK.version(e,t)));if(!n)throw Error(`The hub sent an unreadable version`);return n}async function UK(e,t){let n=MG((await FK(await H(NK.create(),{method:`POST`,json:e,headers:{"idempotency-key":t}}))).profile);if(!n)throw Error(`The hub sent an unreadable profile`);return n}async function WK(e,t,n){let r=MG((await FK(await H(NK.versions(e),{method:`POST`,json:t,headers:{"idempotency-key":n}}))).profile);if(!r)throw Error(`The hub sent an unreadable profile`);return r}async function GK(e,t){let n=MG((await FK(await H(NK.one(e.id),{method:`PATCH`,json:{expectedRevision:e.revision,state:t?`archived`:`active`}}))).profile);if(!n)throw Error(`The hub sent an unreadable profile`);return n}async function KK(e){let t=iK(await K(NK.session(e)));if(!t)throw Error(`The hub sent an unreadable profile pin`);return t}async function qK(e,t){await H(NK.session(e),{method:`PUT`,json:t})}async function JK(e,t){await H(NK.unpin(e,t),{method:`DELETE`})}async function YK(e,t,n){let r=await FK(await H(NK.render(e,t),{method:`POST`,json:n}));if(typeof r.prompt!=`string`)throw Error(`The hub sent no rendered text`);return{prompt:r.prompt,secretRefs:Array.isArray(r.secretRefs)?r.secretRefs.filter(e=>typeof e==`string`):[]}}var XK=I(`<p class="error small"role=alert>`),ZK=I(`<input type=search role=combobox aria-label="Search commands"aria-controls=prof-commands aria-expanded=true placeholder="Type a command…"autofocus>`),QK=I(`<ul class=prof-commands id=prof-commands role=listbox aria-label=Commands>`),$K=I(`<p class=prof-note>Inserted text goes into this session's composer; review it, then send.`),eq=I(`<p class="muted small">No profile is pinned to this session, so it has no commands. Pin one from the session's profile chip.`),tq=I(`<p class="muted small">Loading commands…`),nq=I(`<p class="muted small">`),rq=I(`<li role=option class=prof-command><strong>/</strong><span class=prof-sub>`),iq=I(`<p class=prof-secret>Uses secret <!> (name only). The console never asks for or sees its value; the session's machine resolves it only when the harness runs the command itself. Inserted text keeps <code></code> as written.`),aq=I(`<form class=stack><p><strong>/</strong> <span class="muted small"></span></p><div class=row><button type=submit class="btn small primary">Insert into composer</button><button type=button class="btn small">Back`),oq=I(`<label><textarea>`);function sq(e){let t=e.view.assignment,[i]=d(async()=>{if(!t)return[];let n=e.view.version?.commands??[];try{return(await HK(t.profileID,t.version)).content.commands.map(e=>{let t=_K(e.template);return{name:e.name,description:e.description,params:`error`in t?[]:t.params,secrets:`error`in t?[]:t.secrets}})}catch{return n.map(e=>({...e,secrets:[]}))}}),[a,o]=u(``),[c,f]=u(0),[p,h]=u(),[g,_]=u({}),[v,x]=u(``),[S,w]=u(!1),T=C(()=>bK(i()??[],a())),E=e=>{e&&(h(e),_({}),x(``),e.params.length?requestAnimationFrame(()=>document.querySelector(`.prof-palette [data-param]`)?.focus()):D(e))},D=async t=>{let n=yK(t.params,g());if(!n.ok)return x(n.error);w(!0),x(``);try{let{prompt:r}=await YK(e.sessionID,t.name,n.body);Rx.set(e.sessionID,CK(Rx.get(e.sessionID),r)),e.onInserted()}catch(e){x(AK(e))}finally{w(!1)}},O=e=>{let t=T().length;e.key===`ArrowDown`&&t?(e.preventDefault(),f((c()+1)%t)):e.key===`ArrowUp`&&t?(e.preventDefault(),f((c()-1+t)%t)):e.key===`Enter`&&(e.preventDefault(),E(T()[c()]))},k=t=>`prof-cmd-${e.sessionID}-${t}`;return n(de,{open:!0,get title(){return`Commands · ${e.title}`},get onClose(){return e.onClose},class:`prof-dialog prof-palette`,get children(){return[n(l,{get when(){return p()},get fallback(){return n(l,{when:t,get fallback(){return eq()},get children(){return[(()=>{var e=ZK();return e.$$keydown=O,e.$$input=e=>(o(e.currentTarget.value),f(0)),s(()=>b(e,`aria-activedescendant`,T().length?k(c()):void 0)),s(()=>e.value=a()),e})(),n(l,{get when(){return i()},get fallback(){return tq()},get children(){return n(l,{get when(){return T().length},get fallback(){return(()=>{var n=nq();return y(n,(()=>{var n=r(()=>!!i().length);return()=>n()?`No command matches.`:`${e.view.profile?.name??`This profile`} v${t.version} has no commands.`})()),n})()},get children(){var e=QK();return y(e,n(m,{get each(){return T()},children:(e,t)=>(()=>{var n=rq(),i=n.firstChild;i.firstChild;var a=i.nextSibling;return n.addEventListener(`pointerenter`,()=>f(t())),n.$$click=()=>E(e),y(i,()=>e.name,null),y(a,()=>e.description,null),y(a,(()=>{var t=r(()=>!!e.params.length);return()=>t()?` · asks for ${e.params.join(`, `)}`:``})(),null),y(a,(()=>{var t=r(()=>!!e.secrets.length);return()=>t()?` · uses secret ${e.secrets.join(`, `)}`:``})(),null),s(e=>{var r=k(t()),i=t()===c();return r!==e.e&&b(n,`id`,e.e=r),i!==e.t&&b(n,`aria-selected`,e.t=i),e},{e:void 0,t:void 0}),n})()})),e}})}}),$K()]}})},children:e=>(()=>{var t=aq(),r=t.firstChild,i=r.firstChild;i.firstChild;var a=i.nextSibling.nextSibling,o=r.nextSibling,c=o.firstChild,u=c.nextSibling;return t.addEventListener(`submit`,t=>(t.preventDefault(),void D(e()))),y(i,()=>e().name,null),y(a,()=>e().description),y(t,n(m,{get each(){return e().params},children:e=>(()=>{var t=oq(),n=t.firstChild;return y(t,e,n),n.$$input=t=>_({...g(),[e]:t.currentTarget.value}),b(n,`data-param`,e),b(n,`rows`,e===`arguments`?3:1),s(()=>n.value=g()[e]??``),t})()}),o),y(t,n(l,{get when(){return e().secrets.length},get children(){var t=iq(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return y(t,()=>e().secrets.join(`, `),n),y(r,()=>`{{secret:${e().secrets[0]}}}`),t}}),o),y(t,n(l,{get when(){return v()},get children(){var e=XK();return y(e,v),e}}),o),u.$$click=()=>h(void 0),s(()=>c.disabled=S()),t})()}),n(l,{get when(){return r(()=>!p())()&&v()},get children(){var e=XK();return y(e,v),e}})]}})}B([`input`,`keydown`,`click`]);var cq=I(`<span class=prof-up aria-hidden=true>↑v`),lq=I(`<button type=button>`),uq=I(`<section aria-label="Pinned profile"><h3>Pinned`),dq=I(`<label>Profile<select aria-label=Profile>`),fq=I(`<label>Version<select aria-label=Version>`),pq=I(`<div class=row><button type=button class="btn small primary">`),mq=I(`<section aria-label="Pin a profile"><h3></h3><p class=prof-note>`),hq=I(`<p class="error small"role=alert>`),gq=I(`<p class="muted small">No profile is pinned to this session.`),_q=I(`<div class=prof-status><span></span><strong class=small>`),vq=I(`<ul class=prof-guidance aria-label="What took effect">`),yq=I(`<p class=prof-note>`),bq=I(`<div class=row><button type=button class="btn small">Unpin</button><button type=button class="btn small">Commands… (Ctrl+Alt+P)`),xq=I(`<li>`),Sq=I(`<div class=prof-upgrade><span>v<!> of <!> is available. This session stays on v<!> until you upgrade it.</span><button type=button class="btn small primary">Upgrade to v`),Cq=I(`<p class="muted small">`),wq=I(`<p class="muted small">No active profiles. Create one under Agent profiles (/profiles).`),Tq=I(`<option> (<!>)`),Eq=I(`<option>v`),Dq=e=>{let t=Lu(e)?.session.title;return typeof t==`string`&&t?t:`this session`};function Oq(e){let[i,a]=u(),[o,c]=u(!0),[d,f]=u(!1),[p,m]=u(!1),h,g,_=0,v=!0,x=async()=>{try{let t=await KK(e.sessionID);if(!v)return;a(t),c(!0),S()}catch(e){if(!v)return;e instanceof G&&(e.status===404||e.status===403)&&c(!1)}},S=()=>{clearTimeout(g);let e=i();if(!e||!EK(e))return void(_=0);let t=kK(_++);t!==void 0&&(g=setTimeout(()=>void x(),t))},C=async()=>{_=0,await x()};R(()=>void x()),M(()=>{v=!1,clearTimeout(g)}),R(()=>{let t=t=>{SK(t)&&e.takesInput()&&o()&&i()&&(t.preventDefault(),m(!0))};document.addEventListener(`keydown`,t),M(()=>document.removeEventListener(`keydown`,t))});let w=()=>sK(i()??{assignment:null}),T=()=>h?.closest(`.session-layout`)?.querySelector(`textarea[aria-label="Message"]`)?.focus();return n(l,{get when(){return r(()=>!!o())()&&i()},get children(){return[(()=>{var e=lq();e.$$click=()=>{f(!0),x()};var a=h;return typeof a==`function`?t(a,e):h=e,b(e,`aria-keyshortcuts`,xK),y(e,(()=>{var e=r(()=>!!i().assignment);return()=>e()?w().label:`Profile`})(),null),y(e,n(l,{get when(){return w().upgrade},get children(){var e=cq();return e.firstChild,y(e,()=>w().upgrade,null),e}}),null),s(t=>{var n=`prof-chip ${w().tone}`,r=i().assignment?.ack?.status??`none`,a=`${w().detail}. Commands: ${xK}`,o=i().assignment?`Agent profile: ${w().label}, ${aK[i().assignment.ack?.status??`pending`]}${w().upgrade?`, v${w().upgrade} available`:``}`:`Agent profile: none`;return n!==t.e&&k(e,t.e=n),r!==t.t&&b(e,`data-profile-status`,t.t=r),a!==t.a&&b(e,`title`,t.a=a),o!==t.o&&b(e,`aria-label`,t.o=o),t},{e:void 0,t:void 0,a:void 0,o:void 0}),e})(),n(l,{get when(){return d()},get children(){return n(kq,{get sessionID(){return e.sessionID},get harness(){return e.harness},get view(){return i()},onClose:()=>f(!1),onChanged:()=>void C(),onCommands:()=>{f(!1),m(!0)}})}}),n(l,{get when(){return p()},get children(){return n(sq,{get sessionID(){return e.sessionID},get title(){return Dq(e.sessionID)},get view(){return i()},onClose:()=>m(!1),onInserted:()=>{m(!1),requestAnimationFrame(T)}})}})]}})}function kq(t){let[i]=d(()=>IK(`active`).then(e=>e.items)),[a,o]=u(t.view.assignment?.profileID??``),[c,f]=u(0),[p,h]=u(``),[g,_]=u(!1);x(()=>{let e=i.error?void 0:i();e?.length&&!e.some(e=>e.id===a())&&o(e[0].id)});let[v]=d(()=>a()||void 0,e=>VK(e).then(e=>e.items));x(e([()=>v.error?void 0:v(),()=>t.view.assignment?.profileID,()=>t.view.assignment?.version],([e])=>{if(!e?.length)return;let n=t.view.assignment;f(n&&n.profileID===a()&&e.some(e=>e.version===n.version)?n.version:e[0].version)}));let S=()=>sK(t.view),C=()=>cK(t.view),w=()=>TK(t.view,a(),c()),T=async(e,n,r)=>{_(!0),h(``);try{await qK(t.sessionID,wK(e,n,t.view)),J(r),t.onChanged()}catch(e){h(AK(e)),t.onChanged()}finally{_(!1)}},E=async()=>{let e=t.view.assignment;if(e){_(!0),h(``);try{await JK(t.sessionID,e.revision),J(`Unpinned. What the session already applied stays until it restarts.`),t.onChanged()}catch(e){h(AK(e)),t.onChanged()}finally{_(!1)}}};return n(de,{open:!0,get title(){return`Agent profile · ${Dq(t.sessionID)}`},get onClose(){return t.onClose},class:`prof-dialog`,get children(){return[(()=>{var e=uq();return e.firstChild,y(e,n(l,{get when(){return t.view.assignment},get fallback(){return gq()},children:e=>[(()=>{var t=_q(),n=t.firstChild,r=n.nextSibling;return y(n,()=>S().label),y(r,()=>aK[e().ack?.status??`pending`],null),y(r,()=>e().ack?.offline?` · machine offline`:``,null),s(t=>{var i=`prof-chip ${S().tone}`,a=e().ack?.status??`pending`;return i!==t.e&&k(n,t.e=i),a!==t.t&&b(r,`data-ack`,t.t=a),t},{e:void 0,t:void 0}),t})(),(()=>{var e=vq();return y(e,n(m,{get each(){return C()},children:e=>(()=>{var t=xq();return y(t,e),t})()})),e})(),n(l,{get when(){return S().upgrade},children:n=>(()=>{var r=Sq(),i=r.firstChild,a=i.firstChild.nextSibling,o=a.nextSibling.nextSibling,c=o.nextSibling.nextSibling;c.nextSibling;var l=i.nextSibling;return l.firstChild,y(i,n,a),y(i,()=>t.view.profile?.name??`this profile`,o),y(i,()=>e().version,c),l.$$click=()=>void T(e().profileID,n(),`Upgrading to v${n()}…`),y(l,n,null),s(()=>l.disabled=g()),r})()}),(()=>{var e=yq();return y(e,lK),e})(),(()=>{var e=bq(),n=e.firstChild,r=n.nextSibling;return n.$$click=()=>void E(),V(r,`click`,t.onCommands,!0),b(r,`aria-keyshortcuts`,xK),s(()=>n.disabled=g()),e})()]}),null),e})(),(()=>{var e=mq(),u=e.firstChild,d=u.nextSibling;return y(u,()=>t.view.assignment?`Change the pin`:`Pin a profile`),y(d,()=>dK(t.harness)),y(e,n(l,{get when(){return r(()=>!i.error)()&&i()},get fallback(){return(()=>{var e=Cq();return y(e,(()=>{var e=r(()=>!!i.error);return()=>e()?AK(i.error):`Loading profiles…`})()),e})()},get children(){return n(l,{get when(){return i().length},get fallback(){return wq()},get children(){return[(()=>{var e=dq(),t=e.firstChild.nextSibling;return t.addEventListener(`change`,e=>o(e.currentTarget.value)),y(t,n(m,{get each(){return i()},children:e=>(()=>{var t=Tq(),n=t.firstChild,r=n.nextSibling;return r.nextSibling,y(t,()=>e.title,n),y(t,()=>e.name,r),s(()=>t.value=e.id),t})()})),s(()=>t.value=a()),e})(),(()=>{var e=fq(),t=e.firstChild.nextSibling;return t.addEventListener(`change`,e=>f(Number(e.currentTarget.value))),y(t,n(m,{get each(){return r(()=>!!v.error)()?[]:v()??[]},children:(e,t)=>(()=>{var n=Eq();return n.firstChild,y(n,()=>e.version,null),y(n,()=>t()===0?` (latest)`:``,null),s(()=>n.value=String(e.version)),n})()})),s(()=>t.disabled=!!v.error||!v()),s(()=>t.value=String(c())),e})(),(()=>{var e=pq(),t=e.firstChild;return t.$$click=()=>void T(a(),c(),`${w().label}: sent to the session`),y(t,()=>w().label),s(()=>t.disabled=g()||!a()||!c()),e})()]}})}}),null),s(()=>b(d,`data-harness`,t.harness)),e})(),n(l,{get when(){return p()},get children(){var e=hq();return y(e,p),e}})]}})}B([`click`]);var Aq=10;function jq(e){let t=e?.harness||`opencode`,n=new Set(e?.features??[]),r=(e,r)=>n.has(e)?{enabled:!0}:t===`opencode`?{enabled:!1,reason:`${r} needs a newer Hub plugin, or an OpenCode process that reaches its own server`}:{enabled:!1,reason:`${r} is not supported for ${iB(t)} sessions yet`};return{fork:r(`fork`,`Fork`),revert:r(`revert`,`Revert`)}}var Mq=e=>Number.isSafeInteger(e)&&e>=0?e:0;function Nq(e){let t=e?.revert;if(!t||typeof t!=`object`||typeof t.messageID!=`string`||!t.messageID)return;let n=Array.isArray(t.files)?t.files.filter(e=>!!e&&typeof e.file==`string`):[];return{messageID:t.messageID,hidden:Mq(t.hidden),...typeof t.at==`number`&&Number.isFinite(t.at)?{at:t.at}:{},files:n,filesTotal:Math.max(Mq(t.filesTotal),n.length),...Pq(t.stagedAt)?{stagedAt:t.stagedAt}:{}}}var Pq=e=>typeof e==`number`&&Number.isFinite(e);function Fq(e){let t=e?.revertCommitted;if(t&&typeof t==`object`&&typeof t.messageID==`string`&&t.messageID&&Pq(t.until)&&Pq(t.at))return{messageID:t.messageID,...Pq(t.from)?{from:t.from}:{},until:t.until,at:t.at}}function Iq(e){let t=Fq(e);return`${Nq(e)?.messageID??``}|${t?`${t.messageID}@${t.at}`:``}`}function Lq(e){let t=Math.max(e.filesTotal,e.files.length);return{text:`${gn(e.hidden,`message`)} reverted`,...t?{files:`${gn(t,`file`)} restored`}:{}}}function Rq(e){let t=Math.max(e.filesTotal,e.files.length);if(!t)return;let n=e.files.slice(0,Aq).map(e=>e.file),r=t-n.length;return[`Revert ${gn(e.hidden,`message`)}?`,``,`The session changed ${gn(t,`file`)} since then; ${t===1?`it goes`:`they go`} back to how ${t===1?`it was`:`they were`}:`,n.join(`
|
|
32
|
+
`)+(r>0?`\nand ${r} more`:``),``,`Restore undoes the revert until you send the next message.`].join(`
|
|
33
|
+
`)}function zq(e,t,n){return e.kind!==`message`||typeof e.at!=`number`?!1:t?.at!==void 0&&e.at>=t.at&&(t.stagedAt===void 0||e.at<t.stagedAt)||n?.from!==void 0&&e.at>=n.from&&e.at<n.until}function Bq(e,t){return t===void 0?e:e.trim()===t.trim()?``:e}var Vq=new Map;function Hq(e,t){t.length&&Vq.set(e,t)}function Uq(e){let t=Vq.get(e)??[];return Vq.delete(e),t}var Wq=I(`<button type=button class="btn small changes"aria-label="Show changes"><span class=add>+</span> <span class=del>−`),Gq=I(`<div class="banner warn">No connected OpenCode process reports this session. It is read-only until its machine reconnects.`),Kq=I(`<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.`),qq=I(`<div class=history-sentinel aria-hidden=true>`),Jq=I(`<p class="history-edge loading muted small"role=status><span class="spinner small"></span> Loading earlier messages…`),Yq=I(`<p class="history-edge muted small">Beginning of conversation`),Xq=I(`<p class="history-edge error small"role=alert>Couldn't load earlier messages: <!> <button type=button class="btn small">Retry`),Zq=I(`<p class="muted small pane-unstreamed"role=status>Live text isn't streamed to this pane right now; the reply appears when the turn ends.`),Qq=I(`<p class="working-line muted"role=status><span class="spinner small"></span> `),$q=I(`<p class="idle-line muted small"> · last activity `),eJ=I(`<button type=button class="btn primary tap-to-start">Tap to start Voice mode`),tJ=I(`<p class="note err voice-error"role=alert>Voice mode: `),nJ=I(`<div class=sheet-backdrop>`),rJ=I(`<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>`),iJ=I(`<a class="crumb muted"> <span class=crumb-sep aria-hidden=true>/`),aJ=I(`<h1 class=title>`),oJ=I(`<h1 class=title><button type=button class=title-btn>`),sJ=I(`<span class=chip-server><span aria-hidden=true></span><span class=place-sep aria-hidden=true>·</span><span class=place-where>`),cJ=I(`<span> · `),lJ=I(`<span class=place-branch>`),uJ=I(`<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>`),dJ=I(`<span class=session-error-status>`),fJ=I(`<span class="session-error-where muted">in subagent `),pJ=I(`<div class=session-error-message>`),mJ=I(`<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>`),hJ=I(`<p class="muted pad">Loading conversation…`),gJ=I(`<p class="muted pad empty-session">No messages yet. Type below, or start Voice mode.`),_J=I(`<p>`),vJ=I(`<p class="answered-by small muted">`),yJ=I(`<div class=revert-banner role=status><span class=revert-text><span class="muted revert-held"title="Messages from agents and apps are delivered after you restore or send"> · agent messages wait</span></span><button type=button class="btn small"title="Bring the messages and files back">Restore`),bJ=I(`<span class=muted> · `),xJ=I(`<button type=button class="btn stop"aria-label="Stop the session and its subagents"> Stop`),SJ=I(`<div class=composer-unavailable data-no-prompt><p class="muted small">`),CJ=I(`<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`),wJ=3e4,TJ=80,EJ=100,DJ=2e3,OJ;function kJ(i){let a=i.id,c=Tc(a,i.visible);M(()=>c.release()),x(()=>i.focused?.()&&c.focus());let d=()=>Up()&&(i.rail?.()??!0),f,p=()=>{let e=f??d();f=void 0,Kp(!e)},h=()=>document.visibilityState===`visible`&&(i.visible?.()??!0),g=()=>Lu(a),S=()=>Iu().find(e=>e.id===a),w=()=>{let e=g();return e?Ti(e.machine.name,e.session,_t()?.branch):void 0},T=()=>g()?.session.status,E=()=>So(re()?T()?.filter(e=>ie().has(e.id)):T()),D=()=>!g(),j=C(()=>aB(g()?.process)),ee=()=>sB(j()),te=()=>!!g()&&!j().timeline,I=()=>g()?.session.exposed!==!1,ne=()=>typeof g()?.session.rootID==`string`?g().session.rootID:a,re=()=>ne()!==a;x(()=>{let e=g()?.session;if(!Q()||!e)return;let t=ne()===a?e.parentID:ne();Yz(window.history,location.pathname+location.search+location.hash,typeof t==`string`?t:void 0)});let ie=C(()=>xo(T(),a)),oe=(e,t)=>e===ne()&&(!re()||typeof t==`string`&&ie().has(t)),se=()=>{let e=g()?.session.parentID;if(typeof e==`string`&&e)return{id:e,title:T()?.find(t=>t.id===e)?.title||Lu(e)?.session.title||`Parent session`}},[ce,le]=u(),de=()=>{let e=ce();return e?e.value:Nq(g()?.session)};x(()=>{let e=ce();e&&Nq(g()?.session)?.messageID===e.value?.messageID&&le(void 0)});let fe=C(()=>jq(g()?.process)),pe,B=new rt,[V,he]=u(0),ge=()=>he(e=>e+1),[_e,ve]=u(!1),[ye,be]=u(!1),[xe,Se]=u([]),[Ce,we]=u({}),Te=0,Ee=(e,t=``,n)=>Se(r=>[...r.slice(-20),{key:`n${++Te}`,text:e,kind:t,...n?{denial:n}:{}}]),[Oe,ke]=u([]),Ae=!1,je=()=>{let e=Du(),t=Oe();return t.length?[...e,...t.filter(t=>!e.some(e=>e.seq===t.seq))]:e},Me=e=>typeof e.sessionID==`string`?gt(je(),e.sessionID,zB(B.rows(),e),Nu):void 0,Ne=C(()=>(V(),new Set(B.rows().flatMap(e=>e.kind===`error`&&e.declined===!0?[Me(e)?.key??``]:[]).filter(Boolean)))),Pe=new Map,Fe=C(()=>{V(),B.status(T(),a);let e=new Map,t=de(),n=Fq(g()?.session),r=MB(t||n?B.rows().filter(e=>!zq(e,t,n)):B.rows(),{denied:e=>Me(e)?.text}).map(t=>{let n=JSON.stringify(t),r=Pe.get(t.key),i=r&&r.json===n?r:{json:n,block:t};return e.set(t.key,i),i.block});return Pe=e,r}),[Ie,Le]=Ar({}),Re,ze=!0,Be=()=>requestAnimationFrame(()=>Re&&(Re.scrollTop=Re.scrollHeight));x(e(Fe,()=>ze&&Be())),x(e(Fe,e=>{!Ae&&e.some(e=>e.type===`error`&&e.denied&&e.label===`Denied: the turn stopped`)&&(Ae=!0,K(`/api/agent/audit?limit=${EJ}`).then(e=>ke(Yt(e).entries)).catch(()=>{}))}));let[He,Ue]=u(0),We=e=>new URLSearchParams(Object.entries(e).flatMap(([e,t])=>t===void 0?[]:[[e,String(t)]])).toString(),Ge=new eB(B,e=>K(`${U(a)}/timeline?${We(e)}`),{limit:TJ,onChange:()=>{Je(()=>me(()=>{Ue(e=>e+1),ge()})),Ge.state===`idle`&&q()}}),Ke=()=>(He(),{state:Ge.state,error:Ge.error}),qe=C(()=>(He(),Ge.cutMessageID));function Je(e){let t=Re;if(!t||ze)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 Ye,Xe;function q(){Xe&&Re&&typeof IntersectionObserver<`u`&&(Ye??=new IntersectionObserver(e=>e.some(e=>e.isIntersecting)&&void Ge.older(),{root:Re,rootMargin:`${Math.round(window.innerHeight*1.5)}px 0px 0px 0px`}),Ye.unobserve(Xe),Ye.observe(Xe))}M(()=>Ye?.disconnect());let Ze=e=>{Xe=e,requestAnimationFrame(()=>requestAnimationFrame(q))},Qe=()=>`${de()?.messageID??``}|${Iq({revertCommitted:Fq(g()?.session)})}`,$e=ae(Qe),et=!1;x(e(Qe,e=>{if(e===$e)return;let t=e.split(`|`)[0]===$e.split(`|`)[0];$e=e,t&&et?et=!1:_e()&&nt()}));async function nt(){B.clear(),ge();try{await Ge.first(),await at(),ze=!0,Be()}catch(e){Ee(`Could not refresh the conversation: ${W(e)}`,`err`)}}async function it(){if(te())return ve(!0);try{await Ge.first(),ve(!0),ge(),Be()}catch(e){e instanceof G&&e.status===404&&!g()?be(!0):te()||fB(e)||Ee(e instanceof G&&e.status===409?`No OpenCode process for this session is connected; history is unavailable until it reconnects.`:`Could not load the conversation: ${W(e)}`,`err`),ve(!0)}}async function at(){try{let{messages:e}=await K(`${U(a)}/messages?limit=200`);for(let t of e??[]){let e=tt(a,t);e&&B.hubMessage(e)}ge()}catch{}}async function ot(){try{let e=await K(U(a)),t=Ql.feed(ne());t.load(e.activity??[]),e.status&&t.status(e.status)}catch{}}let ct=ae(()=>T()),ut=Fu(e=>{if(e.type===`resync`){_e()?Ge.resync().catch(e=>Ee(`Could not refresh the conversation: ${W(e)}`,`err`)).then(at):it().then(at),ot(),Et();return}let t=typeof e.rootID==`string`?e.rootID:e.sessionID;if(e.type===`activity`&&oe(t,e.sessionID)&&e.item&&e.item.kind!==`thinking`)B.activity(e.sessionID,e.item),ge();else if(e.type===`reasoning`&&oe(t,e.sessionID)&&typeof e.messageID==`string`&&typeof e.delta==`string`)B.appendReasoning({sessionID:e.sessionID,messageID:e.messageID,delta:e.delta}),ge();else if(e.type===`delta`&&oe(t,e.sessionID)&&typeof e.messageID==`string`&&typeof e.text==`string`)B.appendText({sessionID:e.sessionID,messageID:e.messageID,...Number.isInteger(e.ordinal)?{ordinal:e.ordinal}:{},delta:e.text}),ge();else if(e.type===`message`){let t=tt(a,e.message);t&&(B.hubMessage(t),ge())}else if(e.type===`turn`&&e.sessionID===a&&nn){let{sub:t,sentAt:n}=nn;nn=void 0,on(e,t,n)}else if(e.type===`status`&&e.sessionID===ne()){for(let t of xy(ct,e.sessions,a))Ee(t,`sys`);let t=So(ct);if(ct=e.sessions,!So(e.sessions)){for(let e of B.rows())e.live&&B.upsert({key:e.key,live:!1});B.endReasoning(void 0),t&&c.streamed()===!1&&_e()&&Ge.resync().catch(()=>{}).then(at)}ge(),Ot()}}),dt;x(e(()=>g()?.session.updated,()=>{clearTimeout(dt),dt=setTimeout(()=>h()&&void vd(a),400)}));let ft=(e,t=!1)=>H(`${U(a)}/presence`,{method:`POST`,json:{visible:e},keepalive:t}).catch(()=>{}),pt=()=>{ft(h(),document.visibilityState!==`visible`),h()&&vd(a,!0)};x(e(()=>i.visible?.()??!0,()=>pt(),{defer:!0}));let mt=ae(c.streamed);x(e(c.streamed,e=>{if(e===void 0)return;let t=mt===!1&&e;mt=e,t&&_e()&&Ge.resync().catch(()=>{}).then(at)}));let ht,[_t,vt]=u(),[yt,bt]=u(``),[xt,St]=u(!0),Ct=0,wt,Tt=0;async function Et(){if(Ct=Date.now(),g()&&!j().summary)return bt(`Details aren't available for ${j().harnessName} sessions.`),St(!1);try{let e=await K(`${U(a)}/summary`);vt(e),bt(``),(!e.branch||!e.changes)&&Tt<2&&(Tt++,clearTimeout(wt),wt=setTimeout(Et,4e3))}catch(e){bt(e instanceof G&&e.status===409?`The machine is disconnected.`:`Could not load details: ${W(e)}`)}finally{St(!1)}}function Ot(){clearTimeout(wt),wt=setTimeout(Et,Math.max(0,DJ-(Date.now()-Ct)))}let[kt,At]=u(),jt=JV(()=>a),[Mt,Nt]=u(),Pt=()=>j().sessionModel&&j().models,[Ft,It]=u({...J_(),draft:Rx.get(a)}),Lt=e=>{It(t=>Y_(t,e)),Rx.set(a,Ft().draft)};M(Rx.subscribe(e=>{e===a&&Rx.get(a)!==Ft().draft&&It(e=>Y_(e,{type:`input`,text:Rx.get(a)}))}));let Rt=()=>cB(j(),E()),zt=()=>{let e=X_(Ft(),{running:E(),offline:D()}),t=Rt();return{...e,canSubmit:e.canSubmit&&t.allowed,showStop:e.showStop&&j().stop,...!e.hint&&t.hint?{hint:t.hint}:{}}},Vt=0,[Ht,Ut]=u(!1),Wt=Promise.resolve();function Gt(e){Wt=Wt.then(async()=>{Ut(!0);try{for(let t of e)try{Lt({type:`attach`,image:await US(t,Ft().images)})}catch(e){Lt({type:`attachError`,message:W(e)})}}finally{Ut(!1)}})}async function Kt(e,t,n){let r=[];for(let i of n)if(H_(i.mime))try{let n=await(await H(SB(e,t,i.index))).blob();r.push(await US(new File([n],i.name||`image`,{type:i.mime}),r))}catch{}return r}async function qt(e){try{await navigator.clipboard.writeText(e),J(`Copied`)}catch{J(`Could not copy: the browser refused`,`err`)}}async function Jt(e,t=!1){try{let n=await(await H(`${U(a)}/fork`,{method:`POST`,json:{messageID:e}})).json();n.text&&Rx.set(n.sessionID,n.text),Hq(n.sessionID,await Kt(a,e,n.attachments??[])),J(t?`Forked into a new session beside this one`:`Forked into a new session`),t?Cn(n.sessionID):Bt(Dt(n.sessionID))}catch(e){J(fB(e)??`Could not fork: ${W(e)}`,`err`)}}async function Xt(e){if(E())return J(`Wait for the session to finish (or stop it) before reverting`,`warn`);try{let t=Rq(await K(`${U(a)}/revert/preview?messageID=${encodeURIComponent(e)}`));if(t&&!await P(t,`Revert`,{danger:!0}))return;let n=await(await H(`${U(a)}/revert`,{method:`POST`,json:{messageID:e,files:!0}})).json();le({value:Nq({revert:n.revert})}),me(()=>{for(let e of Ft().images)Lt({type:`detach`,id:e.id});Lt({type:`input`,text:n.text??``})}),pe=n.text??``;for(let t of await Kt(a,e,n.attachments??[]))Lt({type:`attach`,image:t})}catch(e){J(fB(e)??`Could not revert: ${W(e)}`,`err`)}}async function Zt(){try{await H(`${U(a)}/revert/restore`,{method:`POST`,json:{}}),le({value:void 0}),Lt({type:`input`,text:Bq(Ft().draft,pe)}),pe=void 0}catch(e){J(`Could not restore: ${W(e)}`,`err`)}}async function Qt(){if(!de())return!0;try{return await H(`${U(a)}/revert/commit`,{method:`POST`,json:{}}),et=!0,le({value:void 0}),pe=void 0,!0}catch(e){return J(`Could not send: the revert could not be completed (${W(e)})`,`err`),!1}}let $t=()=>{let e=fe();return{fork:e.fork,revert:e.revert.enabled&&E()?{enabled:!1,reason:`Wait for the session to finish (or stop it) before reverting`}:e.revert,onCopy:e=>void qt(e),onFork:e=>void Jt(e),onForkBeside:e=>void Jt(e,!0),onRevert:e=>void Xt(e)}};async function tn(){let e=Ft().draft.trim(),t=Ft().images;if(!e&&!t.length||de()&&!await Qt())return;if(dn()&&!t.length){Lt({type:`input`,text:``}),Ex.sendTyped(a,e);return}let n=++Vt,r=`local:${n}`,i=E(),o=Date.now();me(()=>{Lt({type:`submit`,id:n}),B.upsert({key:r,kind:`user`,text:e,at:o,...t.length?{images:t.map(({name:e,mime:t,preview:n})=>({name:e,mime:t,preview:n}))}:{}}),we(e=>({...e,[r]:`pending`})),ge()}),ze=!0,Be();try{let i={text:e,...t.length?{images:t.map(({mime:e,data:t,name:n})=>({mime:e,data:t,name:n}))}:{}},s=await H(`${U(a)}/turn`,{method:`POST`,json:i,headers:{prefer:`respond-async`}}),c=await s.json().catch(()=>({})),l=Z_(s.status,c);Lt({type:`accepted`,id:n});let u=lB(j(),l);we(e=>({...e,[r]:u.tick})),u.toast&&J(u.toast),l===`accepted`?nn={sub:n,sentAt:o}:on(c,n,o)}catch(e){if(e instanceof en&&!i&&await $_(E)){Lt({type:`accepted`,id:n}),we(e=>({...e,[r]:`sent`})),Ee(`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=fB(e);t&&J(t,`err`);let a=t??(e instanceof G&&e.status===504?`OpenCode did not answer in time. The session may still be working.`:W(e));me(()=>{Lt({type:`rejected`,id:n,message:a}),B.upsert({key:r,kind:`user`,text:``,images:[]}),ge()})}}let nn,[rn,an]=u(new Set);function on(e,t,n){let r=B.rows().some(e=>e.kind===`assistant`&&(e.at??0)>=n&&e.text);e.reply&&!r&&B.upsert({key:`reply:${t}`,kind:`assistant`,text:e.reply,at:Date.now()});let i=Ve(Du(),new Set([a,...ie()]),Date.now(),void 0,Nu),o=Q_(e,{denied:i?.text});o&&Ee(o.text,o.kind,i&&o.text.startsWith(i.text)?i.key:void 0),i&&o?.text.startsWith(i.text)&&an(e=>new Set([...e,i.key])),ge()}async function sn(){Lt({type:`stop`});try{let{stopped:e}=await(await H(`${U(a)}/stop`,{method:`POST`,json:{}})).json(),t=Array.isArray(e)?e.length:0;J(t?`Stopped ${t} session${t===1?``:`s`}`:`Nothing was running`)}catch(e){J(fB(e)??`Could not stop: ${W(e)}`,`err`)}finally{Lt({type:`stopped`})}}let cn=()=>Hx(a),ln=()=>c.takesInput()?zx.toggle(a):c.focus(),un=Ix,dn=()=>un().phase!==`off`&&un().sessionID===a,fn=()=>un().phase!==`off`&&un().sessionID!==void 0&&un().sessionID!==a,pn=()=>un().error?.sessionID===a&&!un().error.gesture?un().error.message:void 0,mn=()=>un().error?.sessionID===a&&un().error.gesture===!0,hn=()=>mo(au()??void 0,Z()?.publicURL)?.micBlocked?`Set up speech in Settings to use the microphone`:void 0;M(Ex.attach(a,{user:e=>{let t=`voice:${++Te}`;return B.upsert({key:t,kind:`user`,text:e,at:Date.now()}),we(e=>({...e,[t]:`pending`})),ge(),t},tick:(e,t)=>we(n=>({...n,[e]:t})),agent:e=>{let t=e.messageID?B.liveTextKey(e.messageID):`say:${++Te}`,{mode:n,text:r}=by(B.get(t)?.text??``,e.text);n!==`keep`&&(B.upsert({key:t,messageID:e.messageID,kind:`assistant`,text:r,at:B.get(t)?.at??Date.now()}),ge())},note:(e,t)=>Ee(e,t??`sys`)}));async function gn(){if(!dn()&&!c.takesInput())return c.focus();dn()||($y(),zx.cancel()),await Ex.toggle(a),Ex.isOn(a)&&Ex.state.phase===`on`&&Ee(`Voice mode on${Ex.state.agent?` (${Ex.state.agent} agent)`:``}. Speak naturally; say “stop” to interrupt, “pause listening” to end.`,`sys`)}let _n=pb(location.href);_n.voice&&(OJ=a,Bt(_n.path,{replace:!0})),x(()=>{OJ===a&&g()&&!hn()&&(OJ=void 0,dn()||gn())}),R(()=>{for(let e of Uq(a))Lt({type:`attach`,image:e});let e=QS(a);e&&(me(()=>{Lt({type:`input`,text:e.text});for(let t of e.images)Lt({type:`attach`,image:t})}),tn()),ot(),vd(a,h()),ft(h()),ht=setInterval(()=>h()&&void ft(!0),wJ),document.addEventListener(`visibilitychange`,pt)});let vn=!1;x(()=>{!vn&&X.machines&&(vn=!0,ae(()=>{it().then(at),Et(),(!g()||j().models)&&jt.load()}))});let yn=()=>void ft(!1,!0);window.addEventListener(`pagehide`,yn),M(()=>{ut(),clearInterval(ht),clearTimeout(wt),clearTimeout(dt),document.removeEventListener(`visibilitychange`,pt),window.removeEventListener(`pagehide`,yn),yn()});let bn=!1;x(()=>{if(g())bn=!0;else if(bn&&X.machines){if(i.onGone)return i.onGone();J(`That session is gone (deleted, or its machine was revoked).`,`warn`),Bt(`/`,{replace:!0})}});let xn=()=>Hr(g()?.session).filter(e=>!re()||e.sessionID!==void 0&&ie().has(e.sessionID)),Sn=C(()=>new Map(xn().map(e=>[`${e.kind}:${e.id}`,e]))),wn=C((e=[])=>{let t=[...Sn().keys()];return t.length===e.length&&t.every((t,n)=>t===e[n])?e:t}),Tn=C(()=>{V();let e;for(let t of B.rows())t.kind===`user`&&(t.depth??0)===0&&typeof t.at==`number`&&(e===void 0||t.at>e)&&(e=t.at);return e}),En=()=>{let e=new Set(xn().map(e=>e.id));return st(Du(),new Set([a,...ie()]),On(),Tn(),new Set([...rn(),...Ne()]),Hu,Nu).filter(t=>!e.has(t.key))},Dn=()=>(tu(),N(),Ql.has(ne())?Ql.feed(ne()).pulse():void 0),[On,kn]=u(Date.now()),An=setInterval(()=>kn(Date.now()),1e3);M(()=>clearInterval(An));let jn=()=>{if(re()){let e=T()?.find(e=>e.id===a);return e?.state===`working`?(On(),`Working${e.since?` · ${Ya(Date.now()-e.since)}`:``}`):void 0}let e=Dn();if(!E()||!e?.busy)return;On();let t=Xi(T(),a),n=Gi(T());return`${t??e.label}${e.since?` · ${Ya(Date.now()-e.since)}`:``}${n?` · ${Yi(n)}`:``}`},Mn=()=>Vi(T(),a),Nn=()=>{let e=g()?.session;if(!e)return`Not connected`;let t=xn().length;return j().voice?`${dn()&&un().agent?`${un().agent} agent`:e.conversation?`Voice agent`:`Session agent`} · ${t?`${t} request${t===1?``:`s`} waiting`:I()?`Voice on`:`Voice off`}`:t?`${t} request${t===1?``:`s`} waiting`:`${j().harnessName} session`},Pn=()=>_t()?.changes?.files.map(e=>e.file)??[];return(()=>{var e=rJ(),u=e.firstChild,h=u.firstChild,x=h.firstChild,C=h.nextSibling,T=C.firstChild,M=C.nextSibling.firstChild;e.$$pointerdown=()=>c.focus(),e.$$focusin=()=>c.focus(),y(h,n(l,{get when(){return Q()},get children(){return n(F,{icon:`menu`,label:`Open sidebar`,onClick:qp})}}),x),y(x,n(l,{get when(){return se()},children:e=>(()=>{var t=iJ(),r=t.firstChild,i=r.nextSibling;return y(t,n(L,{name:`chevron`,class:`crumb-chev`}),r),y(t,()=>e().title,i),s(n=>{var r=Dt(e().id),i=`Back to ${e().title}`,a=`Back to ${e().title}`;return r!==n.e&&b(t,`href`,n.e=r),i!==n.t&&b(t,`title`,n.t=i),a!==n.a&&b(t,`aria-label`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),y(x,n(l,{get when(){return S()},get fallback(){return(()=>{var e=aJ();return y(e,()=>g()?.session.title||(X.machines?`Session`:`Loading…`)),e})()},children:e=>[n(A,{get state(){return e().state}}),n($g,{get id(){return e().id},get title(){return e().title},place:`topbar`,class:`title`,get children(){var t=oJ(),n=t.firstChild;return n.$$click=()=>Hh({id:e().id,place:`topbar`}),y(n,()=>e().title),s(()=>b(n,`title`,`${e().title} · click to rename`)),t}}),n(e_,{get id(){return e().id}}),n(O,{label:`Session actions`,class:`icon-btn small`,items:()=>Gh(e(),{open:!1,place:`topbar`})})]}),null),y(h,n(l,{get when(){return w()},children:e=>(()=>{var t=sJ(),i=t.firstChild,a=i.nextSibling,o=a.nextSibling;return y(t,()=>e().machine,a),y(o,()=>e().where),y(t,n(l,{get when(){return e().branch},get children(){return[n(L,{name:`branch`}),r(()=>e().branch)]}}),null),s(n=>{var r=`${e().text} · ${g().session.directory}`,a=`Runs on ${e().text}`,o=`online-dot${g().machine.online?` on`:``}`;return r!==n.e&&b(t,`title`,n.e=r),a!==n.t&&b(t,`aria-label`,n.t=a),o!==n.a&&k(i,n.a=o),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),y(h,n(l,{get when(){return ee()},children:e=>(()=>{var t=cJ(),n=t.firstChild;return y(t,()=>j().harnessName,n),y(t,()=>e().label,null),s(n=>{var r=`chip-evidence ${e().level}`,i=e().level,a=e().detail,o=`${j().harnessName} · evidence: ${e().label}. ${e().detail}`;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`data-evidence`,n.t=i),a!==n.a&&b(t,`title`,n.a=a),o!==n.o&&b(t,`aria-label`,n.o=o),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),null),y(h,n(Oq,{sessionID:a,get harness(){return j().harness},get takesInput(){return c.takesInput}}),null),y(h,n(l,{get when(){return _t()?.changes?.files.length},get children(){var e=Wq(),t=e.firstChild;t.firstChild;var n=t.nextSibling.nextSibling;return n.firstChild,e.$$click=()=>At(Pn()[0]),y(t,()=>_t().changes.additions,null),y(n,()=>_t().changes.deletions,null),e}}),null),y(h,n(l,{get when(){return fn()},get children(){return n(UL,{})}}),null),y(h,n(l,{get when(){return Q()},get children(){return n(lz,{})}}),null),y(h,n(F,{icon:`rail`,get label(){return d()?`Hide details`:`Show details`},get"aria-pressed"(){return d()},onPointerDown:()=>f=d(),onClick:p}),null),y(h,()=>i.paneTools,null),y(u,n(l,{get when(){return r(()=>!!Q())()&&w()},children:e=>(()=>{var t=uJ(),r=t.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return y(i,()=>e().machine),y(a,()=>e().where),y(t,n(l,{get when(){return e().branch},get children(){return[n(L,{name:`branch`}),(()=>{var t=lJ();return y(t,()=>e().branch),t})()]}}),null),s(n=>{var i=g().session.directory,a=`Runs on ${e().text}`,o=`online-dot${g().machine.online?` on`:``}`;return i!==n.e&&b(t,`title`,n.e=i),a!==n.t&&b(t,`aria-label`,n.t=a),o!==n.a&&k(r,n.a=o),n},{e:void 0,t:void 0,a:void 0}),t})()}),C),y(u,n(l,{get when(){return Mn()},children:e=>(()=>{var t=mJ(),i=t.firstChild.nextSibling,o=i.firstChild,c=o.firstChild;return y(c,()=>e().label),y(o,n(l,{get when(){return e().status},get children(){var t=dJ();return y(t,()=>e().status),t}}),null),y(o,n(l,{get when(){return r(()=>e().sessionID!==a)()&&e().title},get children(){var t=fJ();return t.firstChild,y(t,()=>e().title,null),t}}),null),y(i,n(l,{get when(){return r(()=>!!e().message)()&&e().message!==e().label},get children(){var t=pJ();return y(t,()=>e().message),t}}),null),y(t,n(F,{icon:`close`,label:`Dismiss error`,class:`session-error-dismiss`,onClick:()=>void Zd(e().sessionID)}),null),s(()=>b(t,`data-error-session`,e().sessionID)),t})()}),C),y(u,n(l,{get when(){return r(()=>!!D())()&&X.machines},get children(){return Gq()}}),C),C.addEventListener(`scroll`,e=>ze=e.currentTarget.scrollHeight-e.currentTarget.scrollTop-e.currentTarget.clientHeight<80);var P=Re;return typeof P==`function`?t(P,C):Re=C,y(T,n(l,{get when(){return!ye()},get fallback(){return n(AJ,{})},get children(){return[n(l,{get when(){return _e()},get fallback(){return hJ()},get children(){return[n(l,{get when(){return te()},get children(){var e=Kq(),t=e.firstChild.nextSibling;return t.nextSibling,y(e,()=>j().harnessName,t),e}}),n(l,{get when(){return Fe().length||xe().length},get fallback(){return n(l,{get when(){return!te()},get children(){return gJ()}})},get children(){return[(()=>{var e=qq();return t(Ze,e),e})(),n(v,{get children(){return[n(o,{get when(){return Ke().state===`loading`},get children(){return Jq()}}),n(o,{get when(){return r(()=>Ke().state===`done`)()&&Fe().length},get children(){return Yq()}}),n(o,{get when(){return Ke().state===`error`},get children(){var e=Xq(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return y(e,()=>Ke().error,t),n.$$click=()=>void Ge.retry(),e}})]}}),n(dG,{sessionID:a,get blocks(){return Fe()},get ticks(){return Ce()},get actions(){return $t()},previews:!0,get partialMessage(){return qe()},expanded:Ie,onToggle:(e,t)=>Le(e,t),onDetail:(e,t)=>{B.detail(e,t),ge()}})]}})]}}),n(m,{get each(){return lt(xe(),Ne())},children:e=>(()=>{var t=_J();return y(t,()=>e.text),s(n=>{var r=`note ${e.kind}`,i=e.kind===`err`?`alert`:void 0;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`role`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(Jg,{get decisions(){return De(lu(),a)}}),n(m,{get each(){return wn()},children:e=>n(l,{get when(){return Sn().get(e)},children:e=>n(CW,{sessionID:a,get blocker(){return e()},rootID:a,get canAnswer(){return r(()=>e().kind===`permission`)()?j().permission:j().form},get harnessName(){return j().harnessName}})})}),n(m,{get each(){return En()},children:e=>(()=>{var t=vJ();return y(t,()=>e.text),s(n=>{var r=e.key,i=e.title;return r!==n.e&&b(t,`data-answered-by`,n.e=r),i!==n.t&&b(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(l,{get when(){return r(()=>!!E())()&&c.streamed()===!1},get children(){return Zq()}}),n(l,{get when(){return jn()},get children(){var e=Qq();return e.firstChild.nextSibling,y(e,jn,null),e}}),n(l,{get when(){return r(()=>!(E()||!g()))()&&S()},get children(){var e=$q(),t=e.firstChild;return y(e,()=>ue[S().state],t),y(e,()=>z(S().updated,N()),null),e}})]}})),y(M,n(l,{get when(){return dn()},get children(){return n(gV,{get state(){return un().voice},get level(){return un().level},get held(){return un().held},get ignored(){return un().ignored},get working(){return E()},get model(){return qV(jt.prefs(),`voice`)},onMute:()=>Ex.mute(),onEnd:()=>void Ex.end(),onModel:()=>Nt(`voice`),get notifyHint(){return Px()},onAllowNotifications:()=>void Fx(),get timing(){return un().timing},get detector(){return un().detector},get turn(){return un().turn},get front(){return un().front}})}}),null),y(M,n(l,{get when(){return mn()},get children(){var e=eJ();return e.$$click=()=>void gn(),e}}),null),y(M,n(l,{get when(){return pn()},get children(){var e=tJ();return e.firstChild,y(e,pn,null),e}}),null),y(M,n(l,{get when(){return de()},children:e=>(()=>{var t=yJ(),r=t.firstChild,i=r.firstChild,a=r.nextSibling;return y(t,n(L,{name:`undo`}),r),y(r,()=>Lq(e()).text,i),y(r,n(l,{get when(){return Lq(e()).files},children:e=>(()=>{var t=bJ();return t.firstChild,y(t,e,null),t})()}),i),a.$$click=()=>void Zt(),s(()=>b(t,`data-revert`,e().messageID)),t})()}),null),y(M,n(l,{get when(){return Rt().show},get fallback(){return(()=>{var e=SJ(),t=e.firstChild;return y(t,()=>Rt().hint),y(e,n(l,{get when(){return zt().showStop},get children(){var e=xJ(),t=e.firstChild;return e.$$click=()=>void sn(),y(e,n(L,{name:`stop`}),t),s(()=>e.disabled=!zt().canStop),e}}),null),e})()},get children(){return n(fV,_({get draft(){return Ft().draft},get images(){return Ft().images},get attaching(){return Ht()},get view(){return zt()},get error(){return Ft().error},get voiceOn(){return dn()},get voiceBlocked(){return hn()},get dictating(){return cn().recording},get transcribing(){return cn().transcribing},get metaLeft(){return Nn()},get voiceModel(){return r(()=>!!jt.error())()?`unavailable`:qV(jt.prefs(),`voice`)}},()=>j().summary?{sessionModel:AV(_t()?.model,{pickable:Pt()}),sessionModelPickable:Pt()}:{},{onInput:e=>Lt({type:`input`,text:e}),onAttach:Gt,onDetach:e=>{let t=Ft().images.find(t=>t.id===e);t?.preview.startsWith(`blob:`)&&URL.revokeObjectURL(t.preview),Lt({type:`detach`,id:e})},onSubmit:()=>void tn(),onStop:()=>void sn(),onDictate:()=>void ln(),onVoice:()=>void gn(),onModel:e=>Nt(e),get showModels(){return j().models},get showVoice(){return j().voice}}))}}),null),y(u,n(l,{get when(){return kt()},get children(){return n(GU,{sessionID:a,get file(){return kt()},get files(){return r(()=>!!Pn().length)()?Pn():[kt()]},onFile:At,onClose:()=>At(void 0)})}}),null),y(e,n(l,{get when(){return d()},get children(){return[n(l,{get when(){return Q()},get children(){var e=nJ();return e.$$click=()=>Kp(!1),e}}),n(l,{get when(){return!Q()},get children(){return n(OS,{panel:`rail`,label:`Resize details`})}}),n(WU,{get found(){return g()},get summary(){return _t()},get summaryError(){return yt()},get loading(){return xt()},onFile:e=>At(e),onClose:()=>Kp(!1)})]}}),null),y(e,n(YV,{get kind(){return Mt()},models:jt,onClose:()=>Nt(void 0),get sessionCurrent(){return jV(_t()?.model)},onSessionModel:e=>vt(t=>t&&{...t,model:e})}),null),s(t=>{var n=`session-layout${d()?` with-rail`:``}`,r=c.paneID,i=c.takesInput()?``:void 0;return n!==t.e&&k(e,t.e=n),r!==t.t&&b(e,`data-pane`,t.t=r),i!==t.a&&b(e,`data-pane-focused`,t.a=i),t},{e:void 0,t:void 0,a:void 0}),e})()}function AJ(){return CJ()}B([`focusin`,`pointerdown`,`click`]);var jJ=I(`<span class=pane-drop-label>`),MJ=I(`<div class=pane-drop-area><span class=pane-drop-hint>`),NJ=I(`<div aria-hidden=true>`),PJ=I(`<div class=pane-dock-map>`),FJ=I(`<div class=pane-dock role=region aria-label="Drop into a pane"><div class=pane-dock-card><p class=pane-dock-title></p><p class="pane-dock-note muted">Edges split, the centre replaces. Up to 4 panes.`),IJ={left:`Split left`,right:`Split right`,top:`Stack above`,bottom:`Stack below`,center:`Replace`};function LJ(e,t){let n=_m(e);return n===`limit`?{text:`4 panes open: drop in the centre to replace`,refused:!0}:n===`focused`?{text:`Already here`,refused:!1}:n===`moved`&&t===`center`?{text:`Swap`,refused:!1}:n===`moved`?{text:`Move: ${IJ[t].replace(`Split `,``).replace(`Stack `,``)}`,refused:!1}:n===`added`&&`empty`in e?{text:`Open in a pane`,refused:!1}:{text:IJ[t],refused:!1}}function RJ(e){let[t,r]=u(),i=t=>e.index===void 0?{empty:!0}:{index:e.index,zone:t},a=t=>{if(!gm(t))return;t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getBoundingClientRect(),i=e.index===void 0?`center`:gp(t.clientX-n.left,t.clientY-n.top,n.width,n.height);r(i),t.dataTransfer&&(t.dataTransfer.dropEffect=fm()?.move||t.dataTransfer.effectAllowed===`move`?`move`:`copy`)},o=()=>t()?LJ(i(t()),t()):void 0;return(()=>{var c=NJ();return c.addEventListener(`drop`,e=>{if(!gm(e))return;e.preventDefault(),e.stopPropagation();let n=t()??`center`;r(void 0),ym(e,i(n))}),c.addEventListener(`dragleave`,e=>!e.currentTarget.contains(e.relatedTarget)&&r(void 0)),c.addEventListener(`dragover`,a),c.addEventListener(`dragenter`,a),y(c,n(l,{get when(){return e.label},get children(){var t=jJ();return y(t,()=>e.label),t}}),null),y(c,n(l,{get when(){return t()},get children(){var e=MJ(),n=e.firstChild;return y(n,()=>o()?.text),s(()=>b(e,`data-zone`,t())),e}}),null),s(n=>{var r=`pane-drop${e.class?` ${e.class}`:``}`,i=e.style,a=t(),s=o()?.refused?``:void 0;return r!==n.e&&k(c,n.e=r),n.t=h(c,i,n.t),a!==n.a&&b(c,`data-zone`,n.a=a),s!==n.o&&b(c,`data-refused`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),c})()}var zJ=e=>{if(nn(e)!==void 0)return`Artifact`;let t=Lu(e.sessionID)?.session.title,n=typeof t==`string`&&t?t:`Session`;return e.sideChatID?`Side chat: ${n}`:n};function BJ(){let e=bn,t=()=>e().panes.length,i=()=>Rz(e().split,t()),o=n=>{let r=zz(e().split,t(),n);return{"grid-column":`${r.col+1} / span ${r.colSpan}`,"grid-row":`${r.row+1}`}};return(()=>{var c=FJ(),u=c.firstChild,d=u.firstChild,f=d.nextSibling;return y(d,(()=>{var e=r(()=>!!fm()?.label);return()=>e()?`Open “${fm().label}” in a pane`:`Open in a pane`})()),y(u,n(l,{get when(){return t()},get fallback(){return n(RJ,{class:`pane-dock-empty`,label:`No panes open: drop here`})},get children(){var t=PJ();return y(t,n(m,{get each(){return e().panes},children:(e,t)=>n(RJ,{get index(){return t()},get label(){return zJ(e)},class:`pane-dock-pane`,get style(){return o(t())}})})),s(e=>{var n=`repeat(${i().cols}, 1fr)`,r=`repeat(${i().rows}, 1fr)`;return n!==e.e&&a(t,`grid-template-columns`,e.e=n),r!==e.t&&a(t,`grid-template-rows`,e.t=r),e},{e:void 0,t:void 0}),t}}),f),c})()}var VJ=I(`<div role=separator tabindex=0>`);function HJ(e){let[t,n]=u(!1),r=[],i=0,a=0,o,c=()=>Iz[e.axis],l=t=>e.axis===`cols`?t.clientX:t.clientY,d=e=>Math.round(e*100),f=()=>{let t=e.sizes(),n=(t[e.index]??0)+(t[e.index+1]??0),r=Math.min(c()/Math.max(1,e.total()),n/2);return{min:d(r),max:d(n-r)}},p=()=>{a&&cancelAnimationFrame(a),a=0,n(!1),document.documentElement.classList.remove(`resizing`,`resizing-rows`)},m=(t,n)=>{t.hasPointerCapture(n)&&t.releasePointerCapture(n);let r=o;o=void 0,p(),r&&e.onChange(r,!0)};return M(p),(()=>{var u=VJ();return u.$$keydown=t=>{let n=Hz(e.sizes(),e.index,t.key,t.shiftKey,e.total(),c(),e.axis);n&&(t.preventDefault(),e.onChange(n,!0))},u.$$dblclick=()=>e.onChange(Bz(e.sizes().length),!0),u.addEventListener(`pointercancel`,e=>t()&&m(e.currentTarget,e.pointerId)),u.$$pointerup=e=>t()&&m(e.currentTarget,e.pointerId),u.$$pointermove=n=>{t()&&(o=Vz(r,e.index,l(n)-i,e.total(),c()),a||=requestAnimationFrame(()=>{a=0,o&&e.onChange(o,!1)}))},u.$$pointerdown=t=>{t.button===0&&(t.preventDefault(),t.stopPropagation(),t.currentTarget.setPointerCapture(t.pointerId),r=e.sizes(),i=l(t),n(!0),document.documentElement.classList.add(e.axis===`cols`?`resizing`:`resizing-rows`))},s(n=>{var r=`panel-handle pane-handle${t()?` dragging`:``}`,i=e.axis,a=e.axis===`cols`?`vertical`:`horizontal`,o=`Resize ${e.axis===`cols`?`columns`:`rows`} ${e.index+1} and ${e.index+2}`,s=d(e.sizes()[e.index]??0),c=f().min,l=f().max,p=e.style;return r!==n.e&&k(u,n.e=r),i!==n.t&&b(u,`data-axis`,n.t=i),a!==n.a&&b(u,`aria-orientation`,n.a=a),o!==n.o&&b(u,`aria-label`,n.o=o),s!==n.i&&b(u,`aria-valuenow`,n.i=s),c!==n.n&&b(u,`aria-valuemin`,n.n=c),l!==n.s&&b(u,`aria-valuemax`,n.s=l),n.h=h(u,p,n.h),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0}),u})()}B([`pointerdown`,`pointermove`,`pointerup`,`dblclick`,`keydown`]);var UJ=I(`<span role=status>Send this to the main session? It is queued and arrives after its current turn; nothing is interrupted.`),WJ=I(`<button type=submit class="btn small primary">Send`),GJ=I(`<button type=button class="btn small">Back`),KJ=I(`<form class=sidechat-send><label class=muted>Message for </label><textarea rows=3></textarea><div class=sidechat-row>`),qJ=I(`<div class=sidechat-bar role=group aria-label="Side chat"><div class=sidechat-row><strong>Side chat</strong><span class=muted>from </span><span class=sidechat-tools><button type=button class="btn small">Context</button><button type=button class="btn small">Refresh</button><button type=button class="btn small">Send to main…`),JJ=I(`<p class="muted sidechat-note">`),YJ=I(`<span role=status>`),XJ=I(`<ol class=sidechat-context aria-label="Copied context">`),ZJ=I(`<li><span class=muted></span><div class=sidechat-context-text>`),QJ=I(`<p class="muted sidechat-problem"role=alert>`),$J=I(`<button type=submit class="btn small">Review`),eY=I(`<button type=button class=btn>Close pane`),tY=I(`<div class=empty><p class=display>Side chat</p><p class=muted role=status>`),nY=e=>{let t=Lu(e)?.session.title;return typeof t==`string`&&t?t:`the main session`};function rY(e){let[t,i]=u(),[a,o]=u(),[c,d]=u(!1),[f,p]=u(!1),[h,g]=u(!1),[_,v]=u(!1),[x,S]=u(``),[C,w]=u(Date.now()),T,E=0,D=!0,O=e=>{i(e),w(Date.now()),clearTimeout(T),uh(e).kind===`launching`?T=setTimeout(k,yh(E++)):E=0};async function k(){try{let t=await K(vh.one(e.sideChatID));if(!D)return;let n=lh(t.sideChat);if(!n)return o(`The hub answered a side chat this console can't read.`);o(void 0),O(n)}catch(e){if(!D)return;o(e instanceof G&&e.status===404?`This side chat is gone, or it isn't yours.`:W(e))}}R(k),M(()=>{D=!1,clearTimeout(T)});async function A(){let e=t();if(e&&!c()){d(!0);try{let t=await(await H(vh.refresh(e),{method:`POST`,json:{expectedRevision:e.revision}})).json(),n=lh(t.sideChat);n&&O(n),J(ph(t.delivery))}catch(e){e instanceof G&&e.code===`conflict`?(J(`The side chat changed meanwhile. It was reloaded; refresh again.`,`warn`),await k()):J(`Couldn't refresh: ${W(e)}`,`err`)}finally{d(!1)}}}async function j(){let e=t();if(!(!e||c()||hh(x()))){d(!0);try{await H(vh.send(e),{method:`POST`,json:{text:x(),confirmed:!0}}),J(`Sent to the main session. It arrives after its current turn.`),S(``),v(!1),g(!1)}catch(e){J(`Couldn't send: ${W(e)}`,`err`)}finally{d(!1)}}}let N=()=>{let e=t();return e?uh(e):void 0},ee=()=>{let e=N();return e?.kind===`ready`?e.sessionID:void 0},P=()=>{let e=t();return e?fh(e,C()):void 0};return[(()=>{var i=qJ(),a=i.firstChild.firstChild.nextSibling;a.firstChild;var o=a.nextSibling,u=o.firstChild,d=u.nextSibling,C=d.nextSibling;return y(a,()=>nY(t()?.sourceSessionID??``),null),u.$$click=()=>p(!f()),d.$$click=A,C.$$click=()=>(g(!h()),v(!1)),y(o,()=>e.paneTools,null),y(o,n(l,{get when(){return!e.paneTools},get children(){return n(F,{icon:`close`,class:`small`,label:`Close pane`,title:`Close pane (the side chat keeps running)`,onClick:()=>e.onClose()})}}),null),y(i,n(l,{get when(){return P()},children:e=>(()=>{var t=JJ();return y(t,()=>e().summary,null),y(t,n(l,{get when(){return e().stale},children:e=>[` · `,(()=>{var t=YJ();return y(t,e),t})()]}),null),t})()}),null),y(i,n(l,{get when(){return r(()=>!!f())()&&t()},children:e=>(()=>{var t=XJ();return y(t,n(m,{get each(){return e().snapshot.items},children:e=>(()=>{var t=ZJ(),n=t.firstChild,r=n.nextSibling;return y(n,()=>e.role,null),y(n,()=>e.changed?` · changed`:``,null),y(n,()=>e.stale?` · no longer in the main session (earlier copy)`:``,null),y(n,()=>e.clipped?` · shortened`:``,null),y(r,()=>e.text),t})()})),t})()}),null),y(i,n(l,{get when(){return h()},get children(){var i=KJ(),a=i.firstChild;a.firstChild;var o=a.nextSibling,u=o.nextSibling;return i.addEventListener(`submit`,e=>{e.preventDefault(),_()?j():hh(x())||v(!0)}),y(a,()=>nY(t()?.sourceSessionID??``),null),o.$$input=e=>S(e.currentTarget.value),y(i,n(l,{get when(){return r(()=>!!x())()&&hh(x())},children:e=>(()=>{var t=QJ();return y(t,e),t})()}),u),y(u,n(l,{get when(){return _()},get fallback(){return(()=>{var e=$J();return s(()=>e.disabled=!!hh(x())),e})()},get children(){return[UJ(),(()=>{var e=WJ();return s(()=>e.disabled=c()),e})(),(()=>{var e=GJ();return e.$$click=()=>v(!1),s(()=>e.disabled=c()),e})()]}})),s(t=>{var n=`sidechat-send-${e.sideChatID}`,r=`sidechat-send-${e.sideChatID}`,i=_()||c();return n!==t.e&&b(a,`for`,t.e=n),r!==t.t&&b(o,`id`,t.t=r),i!==t.a&&(o.disabled=t.a=i),t},{e:void 0,t:void 0,a:void 0}),s(()=>o.value=x()),i}}),null),s(e=>{var n=f(),r=!t(),i=!t()||c(),a=h(),o=!t();return n!==e.e&&b(u,`aria-expanded`,e.e=n),r!==e.t&&(u.disabled=e.t=r),i!==e.a&&(d.disabled=e.a=i),a!==e.o&&b(C,`aria-expanded`,e.o=a),o!==e.i&&(C.disabled=e.i=o),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),i})(),n(l,{get when(){return ee()},keyed:!0,get fallback(){return(()=>{var t=tY(),r=t.firstChild.nextSibling;return y(r,()=>a()??(N()&&N().kind!==`ready`?N().text:`Loading…`)),y(t,n(l,{get when(){return a()},get children(){var t=eY();return t.$$click=()=>e.onClose(),t}}),null),t})()},children:t=>n(kJ,{id:t,get visible(){return e.visible},get focused(){return e.focused},get onGone(){return e.onGone},get rail(){return e.rail}})})]}B([`click`,`input`]);var iY=()=>{try{return globalThis.localStorage}catch{return}},[aY,oY]=u(Kz(iY())),[sY,cY]=u();function lY(e,t){let n=Jz(aY(),e,t),r=sY();if(!r)return n;let[i,a,o]=r.key.split(`:`);return i===e&&Number(a)===t?{...n,[o]:r.sizes}:n}function uY(e,t,n,r,i=!0){if(!i)return void cY({key:`${e}:${t}:${n}`,sizes:r});cY(void 0),oY(i=>qz(iY(),i,e,t,n,r))}var dY=I(`<span class=pane-tools role=group aria-label=Pane><span class=pane-grip draggable=true title="Drag onto another pane to move this one"aria-hidden=true>`),fY=I(`<div class="cmp-empty pane-empty-drop"><p>No panes are open on this device.</p><p><a href=/>All sessions</a> · <a href=/artifacts>Artifacts</a></p><p class=muted>Drag a session or an artifact here to open it.`),pY=I(`<div class=pane-bar role=toolbar aria-label="Split layout"><span class=seg role=group aria-label=Layout></span><span class="pane-count muted"> of <!> panes · <kbd>F6</kbd> switches`),mY=I(`<div class=pane-tabs role=tablist aria-label="Open sessions">`),hY=I(`<div><div class=pane-grid>`),gY=I(`<button type=button>`),_Y=I(`<div role=presentation><button type=button role=tab>`),vY=I(`<section class=pane tabindex=-1>`),yY=I(`<p class="muted cmp-empty">Loading the artifact…`),bY=E(()=>Vn(()=>import(`./ArtifactPane-7D-M-Ich.js`).then(e=>({default:e.ArtifactPane})),__vite__mapDeps([7,1,8,9,10,11,12,13]))),xY=6,SY=[{split:`vertical`,label:`Side by side`,icon:`split`},{split:`horizontal`,label:`Stacked`,icon:`stack`},{split:`grid`,label:`Grid`,icon:`grid`}],CY=e=>{let t=nn(e);return t===void 0?e.sideChatID?`${e.sessionID}#${e.sideChatID}`:e.sessionID:`!${t}`},wY=e=>e.startsWith(`!`)?e.slice(1):void 0,TY=e=>e.split(`#`)[0],EY=e=>encodeURIComponent(e).replace(/%/g,`_`),DY=e=>{let t=Lu(e)?.session.title;return typeof t==`string`&&t?t:`Session`},OY=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function kY(r){let[i,a]=u(!1),o=C(()=>({at:Nt(),id:r.routed}),void 0,{equals:(e,t)=>e.at===t.at&&e.id===t.id});S(e(o,({id:e})=>{if(e===void 0)return void a(!1);let t=!0;Tn(n=>{let r=mn(n,{sessionID:e});return t=r.outcome!==`invalid`,r.layout}),a(!t)})),S(()=>{let e=Eu();e.size&&Tn(t=>oc(t,e))});let c=bn,d=()=>c().panes.length,p=C(()=>c().panes.map(CY),[],{equals:OY}),g=e=>p().indexOf(e),_=()=>p()[c().focused],v=()=>c().split,w=()=>Q()&&d()>1,[T,E]=u({}),D=e=>{let t=wY(e);return t===void 0?e.includes(`#`)?`Side chat: ${DY(TY(e))}`:DY(TY(e)):`Artifact: ${T()[t]??`…`}`},O=()=>!Q()&&d()>1,A=()=>!!fm()&&!Q();x(e(()=>c().panes[c().focused]?.sideChatID?void 0:c().panes[c().focused]?.sessionID,e=>{e&&!i()&&e!==ae(()=>r.routed)&&Bt(Dt(e),{replace:!0})}));let j=()=>requestAnimationFrame(()=>{let e=document.querySelector(`section.pane[data-focused]`);e&&!e.contains(document.activeElement)&&(e.querySelector(`textarea:not([disabled])`)??e).focus()}),N=e=>Tn(t=>cn(t,e)),ee=e=>{let t=new Map;for(let e of document.querySelectorAll(`section.pane .scroller`))t.set(e,e.scrollTop);e(),requestAnimationFrame(()=>t.forEach((e,t)=>t.scrollTop=e))},P=e=>{let t=c().focused;ee(()=>Tn(n=>fn(n,t,t+e))),j()},te=e=>{e<0||e>=d()||(Tn(t=>dn(t,e)),d()||Bt(`/`,{replace:!0}))},I=e=>{J(d()>1?`That session is gone (deleted, or its machine was revoked). Its pane was closed.`:`That session is gone (deleted, or its machine was revoked).`,`warn`),te(g(e))};R(()=>{let e=e=>{if(i()||e.defaultPrevented||d()<2||e.getModifierState?.(`AltGraph`))return;let t=Pz(e);if(t){if(e.preventDefault(),t.type===`cycle`)Tn(e=>pn(e,t.step));else if(t.type===`focus`)N(Math.min(t.index,d()-1));else if(t.type===`move`)return P(t.step);else return te(c().focused);w()||j()}};document.addEventListener(`keydown`,e),M(()=>document.removeEventListener(`keydown`,e))});let ne,[re,ie]=u({w:0,h:0});R(()=>{if(!ne||typeof ResizeObserver>`u`)return;let e=new ResizeObserver(()=>ne&&ie({w:ne.clientWidth,h:ne.clientHeight}));e.observe(ne),M(()=>e.disconnect())});let oe=()=>O()?Rz(v(),d()):{cols:1,rows:1},se=()=>lY(v(),d()),ce=e=>(e===`cols`?re().w:re().h)-(oe()[e]-1)*xY,le=(e,t)=>t>1?e.map(e=>`minmax(0, ${e}fr)`).join(` ${xY}px `):`minmax(0, 1fr)`,ue=()=>({"grid-template-columns":le(se().cols,oe().cols),"grid-template-rows":le(se().rows,oe().rows)}),de=e=>{if(!O())return{"grid-column":`1`,"grid-row":`1`};let t=zz(v(),d(),e);return{"grid-column":`${2*t.col+1} / span ${2*t.colSpan-1}`,"grid-row":`${2*t.row+1}`}},z=e=>Array.from({length:Math.max(0,e)},(e,t)=>t),fe=e=>(t,n)=>uY(v(),d(),e,t,n),pe=e=>{let t=d(),n=c().focused,r=e.key===`ArrowRight`?(n+1)%t:e.key===`ArrowLeft`?(n-1+t)%t:e.key===`Home`?0:e.key===`End`?t-1:-1;r<0||!e.target.matches(`[role="tab"]`)||(e.preventDefault(),N(r),requestAnimationFrame(()=>document.querySelector(`.pane-tabs [role="tab"][aria-selected="true"]`)?.focus()))},B=e=>{if(e.key!==`ArrowRight`&&e.key!==`ArrowLeft`)return;let t=Array.from(e.currentTarget.querySelectorAll(`button`)),n=t.indexOf(document.activeElement);n<0||(e.preventDefault(),t[(n+(e.key===`ArrowRight`?1:t.length-1))%t.length].focus())};function me(e){let t=()=>g(e.key),r=()=>v()===`horizontal`;return n(l,{get when(){return O()},get children(){var i=dY(),a=i.firstChild;return V(a,`dragend`,hm),a.addEventListener(`dragstart`,n=>{let r=c().panes[t()];(!r||!mm(n,{target:r,label:D(e.key),move:!0}))&&n.preventDefault()}),y(a,n(L,{name:`grip`})),y(i,n(F,{icon:`chevron`,class:`small flip`,get label(){return r()?`Move pane up`:`Move pane left`},get"aria-keyshortcuts"(){return jz.moveEarlier},get disabled(){return t()<=0},onClick:()=>(N(t()),P(-1))}),null),y(i,n(F,{icon:`chevron`,class:`small`,get label(){return r()?`Move pane down`:`Move pane right`},get"aria-keyshortcuts"(){return jz.moveLater},get disabled(){return t()>=d()-1},onClick:()=>(N(t()),P(1))}),null),y(i,n(F,{icon:`close`,class:`small`,label:`Close pane`,title:`Close pane (the session keeps running)`,get"aria-keyshortcuts"(){return jz.close},onClick:()=>te(t())}),null),i}})}return n(l,{get when(){return!i()},get fallback(){return n(l,{get when(){return r.routed},keyed:!0,children:e=>n(kJ,{id:e})})},get children(){return[n(l,{get when(){return!d()},get children(){var e=fY();return e.firstChild.nextSibling.nextSibling,y(e,n(l,{get when(){return A()},get children(){return n(RJ,{label:`Open in a pane`})}}),null),e}}),(()=>{var e=hY(),r=e.firstChild;y(e,n(l,{get when(){return O()},get children(){var e=pY(),t=e.firstChild,r=t.nextSibling,i=r.firstChild,a=i.nextSibling;return a.nextSibling,e.$$keydown=B,y(t,n(m,{each:SY,children:e=>(()=>{var t=gY();return t.$$click=()=>Tn(t=>rn(t,e.split)),y(t,n(L,{get name(){return e.icon}})),s(n=>{var r=e.label,i=e.label,a=v()===e.split;return r!==n.e&&b(t,`aria-label`,n.e=r),i!==n.t&&b(t,`title`,n.t=i),a!==n.a&&b(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})),y(r,d,i),y(r,hn,a),e}}),r),y(e,n(l,{get when(){return w()},get children(){var e=mY();return e.$$keydown=pe,y(e,n(m,{get each(){return p()},children:e=>{let t=()=>_()===e,r=()=>D(e);return(()=>{var i=_Y(),a=i.firstChild;return a.$$click=()=>N(g(e)),y(a,r),y(i,n(F,{icon:`close`,class:`small`,get label(){return`Close ${r()}`},get tabindex(){return t()?0:-1},onClick:()=>te(g(e))}),null),s(n=>{var r=`pane-tab${t()?` selected`:``}`,o=`pane-tab-${EY(e)}`,s=`pane-${EY(e)}`,c=t(),l=t()?0:-1;return r!==n.e&&k(i,n.e=r),o!==n.t&&b(a,`id`,n.t=o),s!==n.a&&b(a,`aria-controls`,n.a=s),c!==n.o&&b(a,`aria-selected`,n.o=c),l!==n.i&&b(a,`tabindex`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),i})()}})),e}}),r);var i=ne;return typeof i==`function`?t(i,r):ne=r,y(r,n(m,{get each(){return p()},children:e=>{let t=TY(e),r=()=>g(e),i=()=>_()===e,a=()=>!w()||i();return(()=>{var o=vY();return o.$$pointerdown=()=>N(g(e)),o.$$focusin=()=>N(g(e)),y(o,n(l,{get when(){return wY(e)===void 0},get fallback(){return n(f,{get fallback(){return yY()},get children(){return n(bY,{get artifactID(){return wY(e)},get paneTools(){return n(me,{key:e})},onTitle:t=>E(n=>({...n,[wY(e)]:t}))})}})},get children(){return n(l,{get when(){return!e.includes(`#`)},get fallback(){return n(rY,{get sideChatID(){return e.slice(e.indexOf(`#`)+1)},visible:a,focused:i,onGone:()=>I(e),onClose:()=>te(g(e)),rail:()=>!O()||i(),get paneTools(){return n(me,{key:e})}})},get children(){return n(kJ,{id:t,visible:a,focused:i,onGone:()=>I(e),rail:()=>!O()||i(),get paneTools(){return n(me,{key:e})}})}})}})),s(t=>{var n=`pane-${EY(e)}`,s=w()?`tabpanel`:`region`,c=w()?`pane-tab-${EY(e)}`:void 0,l=w()?void 0:`Pane ${r()+1} of ${d()}: ${D(e)}`,u=i()?``:void 0,f=!a(),p=de(r());return n!==t.e&&b(o,`id`,t.e=n),s!==t.t&&b(o,`role`,t.t=s),c!==t.a&&b(o,`aria-labelledby`,t.a=c),l!==t.o&&b(o,`aria-label`,t.o=l),u!==t.i&&b(o,`data-focused`,t.i=u),f!==t.n&&(o.hidden=t.n=f),t.s=h(o,p,t.s),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),o})()}}),null),y(r,n(l,{get when(){return A()},get children(){return n(m,{get each(){return p()},children:e=>n(RJ,{get index(){return g(e)},get style(){return de(g(e))}})})}}),null),y(r,n(m,{get each(){return z(oe().cols-1)},children:e=>n(HJ,{axis:`cols`,index:e,sizes:()=>se().cols,total:()=>ce(`cols`),get onChange(){return fe(`cols`)},get style(){return{"grid-column":`${2*e+2}`,"grid-row":v()===`grid`&&d()%2==1?`1`:`1 / -1`}}})}),null),y(r,n(m,{get each(){return z(oe().rows-1)},children:e=>n(HJ,{axis:`rows`,index:e,sizes:()=>se().rows,total:()=>ce(`rows`),get onChange(){return fe(`rows`)},style:{"grid-row":`${2*e+2}`,"grid-column":`1 / -1`}})}),null),s(t=>{var n=`workspace${O()?` ws-split`:``}${w()?` ws-tabs`:``}`,i=v(),a=ue();return n!==t.e&&k(e,t.e=n),i!==t.t&&b(e,`data-split`,t.t=i),t.a=h(r,a,t.a),t},{e:void 0,t:void 0,a:void 0}),e})()]}})}B([`keydown`,`click`,`focusin`,`pointerdown`]);var AY={artifacts:E(()=>Vn(()=>import(`./Library-Cdi83pOV.js`),__vite__mapDeps([14,1,9,10,11,3,12,15]))),teams:E(()=>Vn(()=>import(`./TeamsPage-B4xrlGhp.js`),__vite__mapDeps([16,1,9,17,18,19]))),watchtower:E(()=>Vn(()=>import(`./Watchtower-60B1JX_J.js`).then(e=>e.t),__vite__mapDeps([20,1,9,10,11,3,18,17,19,21]))),profiles:E(()=>Vn(()=>import(`./ProfilesDestination-cryC7P6j.js`),__vite__mapDeps([22,1,9,17])))},jY=I(`<div class=feature-page><header class=topbar><h1 class=title></h1></header><div class=feature-scroll><div class=feature-body>`);function MY(e){return(()=>{var t=jY(),r=t.firstChild,i=r.firstChild,a=r.nextSibling.firstChild;return y(r,n(l,{get when(){return Q()},get children(){return n(F,{icon:`menu`,label:`Open sidebar`,onClick:qp})}}),i),y(i,()=>e.title),y(r,()=>e.actions,null),y(a,()=>e.children),t})()}var NY=I(`<p class=feature-note> isn't available yet. <a href=/>Back to All sessions`),PY=I(`<p class=muted>Loading…`);function FY(e){let t=C(()=>Je.find(t=>t.id===e.id)),r=C(()=>{let e=t();return e&&Be(e,{signedIn:!!Z()})===`ok`?AY[e.id]:void 0});return n(l,{get when(){return r()},get fallback(){return n(MY,{get title(){return t()?.label??`Not found`},get children(){var e=NY(),n=e.firstChild;return y(e,()=>t()?.label??`This page`,n),e}})},children:r=>n(f,{get fallback(){return n(MY,{get title(){return t().label},get children(){return PY()}})},get children(){return n(D,{get component(){return r()},get rest(){return e.rest}})}})})}var IY=I(`<span class="badge-pill armed-left"role=timer title="How long this stays armed for a spoken answer">`),LY=I(`<p class="muted small armed-why">Why: `),RY=I(`<div class="card decision armed-decision"role=group aria-label="The Concierge asks you to confirm"><p class="blocker-head decision-head"><strong>Confirm</strong> <span class=muted>from </span></p><p class=armed-question></p><div class="row armed-options"></div><p class="muted small armed-hint">`),zY=I(`<button type=button>`);function BY(e){let t=()=>e.decision,[i,a]=u(!1),[o,c]=u(Date.now()),d=setInterval(()=>c(Date.now()),1e3);M(()=>clearInterval(d));let f=()=>{let e=Cu()?.expiresAt;return e===void 0?``:Xe(e,o())},p=async e=>{a(!0);try{await Cx(t().id,e)}catch(e){J(W(e),`err`),a(!1)}};return(()=>{var e=RY(),a=e.firstChild,o=a.firstChild.nextSibling.nextSibling;o.firstChild;var c=a.nextSibling,u=c.nextSibling,d=u.nextSibling;return y(o,()=>_e(t(),Hu,Eu()),null),y(a,n(l,{get when(){return f()},get children(){var e=IY();return y(e,f),e}}),null),y(c,()=>Le(t(),Hu,Eu())),y(e,n(jg,{get decision(){return t()}}),u),y(e,n(l,{get when(){return r(()=>!!t().recommendation?.why)()&&t().recommendation.why!==Mg(t())},get children(){var e=LY();return e.firstChild,y(e,()=>t().recommendation.why,null),e}}),u),y(u,n(m,{get each(){return t().options},children:e=>(()=>{var t=zY();return t.$$click=()=>void p(e.id),y(t,()=>e.label),s(n=>{var r=`btn${e.safe||e.id===`always`?``:` primary`}`,a=i();return r!==n.e&&k(t,n.e=r),a!==n.t&&(t.disabled=n.t=a),n},{e:void 0,t:void 0}),t})()})),y(d,()=>$s(!!au()&&!au().reason)),s(n=>{var r=t().id,i=t().id,a=wt(t()),s=t().question;return r!==n.e&&b(e,`data-armed-decision`,n.e=r),i!==n.t&&b(e,`data-decision`,n.t=i),a!==n.a&&b(o,`title`,n.a=a),s!==n.o&&b(c,`title`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),e})()}B([`click`]);var VY=I(`<button type=button class="btn small"aria-label="Restart the Concierge"title="Restart the Concierge (a new session)">Restart`),HY=I(`<header class=concierge-head><div class="concierge-title grow"><h2 class=title>Concierge</h2><p class="small muted concierge-status"role=status aria-live=polite></p></div><a class=icon-btn href=/settings/concierge aria-label="Concierge settings"title="Concierge settings">`),UY=I(`<p role=status data-concierge-notice>`),WY=I(`<div class=concierge-asked aria-label="Decisions from the Concierge"role=group>`),GY=I(`<div class="card decision closed-decision"role=group tabindex=-1><p class="blocker-head decision-head"><strong>Decision</strong> <span class=badge-pill></span><span class=grow></span></p><p class="blocker-text decision-question"></p><p class="muted small"data-closed-note>`),KY=I(`<div class=concierge-idle><form class=concierge-composer><textarea rows=1 aria-label="Ask the Concierge"placeholder="The Concierge is not running"disabled>`),qY=I(`<aside class="concierge-panel side"aria-label=Concierge tabindex=-1>`),JY=I(`<section class="concierge-panel page"aria-label=Concierge tabindex=-1>`),YY=I(`<p class="working-line muted small"role=status><span class="spinner small"></span> Working…`),XY=I(`<div class=concierge-scroll>`),ZY=I(`<p class="note err"role=alert>Voice: `),QY=I(`<button type=button>`),$Y=I(`<div class=concierge-dock><form class=concierge-composer><textarea rows=1 aria-label="Ask the Concierge"></textarea><button type=submit class="btn primary send"aria-label="Send to the Concierge"title="Send (Enter)">`),eX=I(`<p class="muted small pad">Loading…`),tX=I(`<p class="muted small pad">`),nX=I(`<p>`),rX=3e4,iX=80,aX=/^#decision-(dec_[A-Za-z0-9]{1,64})$/,oX=new Set([`starting`,`running`,`waiting_machine`,`backoff`,`failed`]),sX=()=>!!au()&&!au().reason;function cX(i){let a=gu,o=()=>(X.machines??[]).map(e=>({id:e.id,name:e.name,online:e.online===!0})),c=()=>o().find(e=>e.id===a()?.machineID),d=()=>tc(a(),c()),f=()=>a()?.state===`running`&&!!a()?.sessionID&&c()?.online!==!1,p=C(()=>xx()),m=C(()=>uc(lu(),a(),p())),[h,g]=u(!1),[_,v]=u(),S,w=cz(),T=()=>xt(`/`);async function E(){g(!0);try{await H(`/api/agent/concierge/restart`,{method:`POST`,json:{}}),J(`Restarting the Concierge`)}catch(e){J(`Could not restart: ${W(e)}`,`err`)}finally{g(!1)}}R(()=>{if(i.mode!==`side`)return;let e=e=>{e.key!==`Escape`||e.defaultPrevented||ee(S)||document.querySelector(`.menu-pop, [role='menu']`)||(e.preventDefault(),T())};document.addEventListener(`keydown`,e),M(()=>document.removeEventListener(`keydown`,e)),requestAnimationFrame(()=>S&&!S.contains(document.activeElement)&&S.focus())});function D(e){let t=()=>requestAnimationFrame(()=>{let t=S?.querySelector(`[data-decision="${e}"]`);t?(t.scrollIntoView({block:`nearest`,behavior:`smooth`}),t.classList.add(`flash`),setTimeout(()=>t.classList.remove(`flash`),2500),t.focus({preventScroll:!0})):J(`That Decision is no longer available`)});if(S?.querySelector(`[data-decision="${e}"]`))return t();kd(e).then(e=>{e&&e.state!==`open`&&v(e),t()})}x(e(Nt,e=>{let t=aX.exec(e.hash)?.[1];t&&(Bt(`/concierge`,{replace:!0}),D(t))})),R(()=>{let e=e=>{if(e.defaultPrevented||e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey)return;let t=e.target?.closest?.(`a[href]`),n=t&&aX.exec(new URL(t.getAttribute(`href`)??``,location.origin).hash)?.[1];n&&t.getAttribute(`href`).startsWith(`/concierge#`)&&(e.preventDefault(),D(n))};S?.addEventListener(`click`,e),M(()=>S?.removeEventListener(`click`,e))}),M(()=>{w?.isConnected&&w.focus()});let O=()=>[(()=>{var e=HY(),t=e.firstChild,c=t.firstChild.nextSibling,u=t.nextSibling;return y(e,n(l,{get when(){return i.mode===`page`},get children(){return n(F,{icon:`back`,label:`Back`,onClick:T})}}),t),y(e,n(L,{name:`spark`,class:`concierge-mark`}),t),y(c,()=>us(a(),o(),N()),null),y(c,n(l,{get when(){return a()?.sessionID},get children(){return n(VL,{get sessionID(){return a().sessionID}})}}),null),y(e,n(l,{get when(){return r(()=>!!a())()&&oX.has(a().state)},get children(){var e=VY();return e.$$click=()=>void E(),s(()=>e.disabled=h()),e}}),u),y(u,n(L,{name:`settings`})),y(e,n(l,{get when(){return i.mode===`side`},get children(){return n(F,{icon:`close`,label:`Close the Concierge (Esc)`,onClick:T})}}),null),s(()=>b(c,`data-concierge-panel-status`,a()?.state??`none`)),e})(),n(l,{get when(){return d()},get children(){var e=UY();return y(e,d),s(()=>k(e,`concierge-notice${a()?.state===`failed`?` err`:``}`)),e}}),n(l,{get when(){return p()},children:e=>n(BY,{get decision(){return e()}})}),n(l,{get when(){return m().length},get children(){var e=WY();return y(e,n(Jg,{get decisions(){return m()}})),e}}),n(l,{get when(){return _()},keyed:!0,children:e=>(()=>{var t=GY(),r=t.firstChild,i=r.firstChild.nextSibling.nextSibling;i.nextSibling;var a=r.nextSibling,o=a.nextSibling;return y(i,()=>e.state),y(r,n(F,{icon:`close`,label:`Close this Decision`,onClick:()=>v(void 0)}),null),y(a,()=>Le(e,Hu,Eu())),y(t,n(jg,{decision:e}),o),y(o,()=>Wo(e)),s(n=>{var r=`Decision (${e.state}): ${e.question}`,i=e.id,o=e.id,s=e.question;return r!==n.e&&b(t,`aria-label`,n.e=r),i!==n.t&&b(t,`data-decision`,n.t=i),o!==n.a&&b(t,`data-closed-decision`,n.a=o),s!==n.o&&b(a,`title`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),n(l,{get when(){return r(()=>!!f())()&&a()?.sessionID},keyed:!0,get fallback(){return(()=>{var e=KY();return e.firstChild.addEventListener(`submit`,e=>e.preventDefault()),e})()},children:e=>n(lX,{id:e,get autofocus(){return i.mode===`side`}})})];return n(l,{get when(){return i.mode===`side`},get fallback(){return(()=>{var e=JY(),n=S;return typeof n==`function`?t(n,e):S=e,y(e,O),e})()},get children(){var e=qY(),n=S;return typeof n==`function`?t(n,e):S=e,y(e,O),e}})}function lX(r){let i=r.id,a=()=>Lu(i),o=()=>a()?.session.status,c=()=>So(o()),d=new rt,[f,p]=u(0),h=()=>p(e=>e+1),[g,_]=u(!1),[v,S]=u({}),[w,T]=u([]),E=0,D=(e,t=`sys`)=>T(n=>[...n.slice(-10),{key:`n${++E}`,text:e,kind:t}]),O=C(()=>(f(),d.status(o(),i),MB(d.rows()))),A=C(()=>dX(O())),[j,N]=Ar({}),ee,P=!0,F=()=>requestAnimationFrame(()=>ee&&(ee.scrollTop=ee.scrollHeight));x(e(A,()=>P&&F())),x(()=>{for(let e of Jo(O(),pu()))kd(e)});let te=e=>new URLSearchParams(Object.entries(e).flatMap(([e,t])=>t===void 0?[]:[[e,String(t)]])).toString(),I=new eB(d,e=>K(`${U(i)}/timeline?${te(e)}`),{limit:iX,onChange:h});async function ne(){try{let{messages:e}=await K(`${U(i)}/messages?limit=200`);for(let t of e??[]){let e=tt(i,t);e&&d.hubMessage(e)}h()}catch{}}async function re(){try{await I.first()}catch(e){D(`Could not load the conversation: ${W(e)}`,`err`)}_(!0),await ne(),F()}let ie,ae=c(),oe=Fu(e=>{let t=typeof e.rootID==`string`?e.rootID:e.sessionID;if(e.type===`resync`)I.resync().catch(()=>{}).then(ne);else if(t!==i)return;else if(e.type===`activity`&&e.item&&e.item.kind!==`thinking`)d.activity(e.sessionID,e.item);else if(e.type===`reasoning`&&typeof e.messageID==`string`&&typeof e.delta==`string`)d.appendReasoning({sessionID:e.sessionID,messageID:e.messageID,delta:e.delta});else if(e.type===`delta`&&typeof e.messageID==`string`&&typeof e.text==`string`)d.appendText({sessionID:e.sessionID,messageID:e.messageID,...Number.isInteger(e.ordinal)?{ordinal:e.ordinal}:{},delta:e.text});else if(e.type===`message`){let t=tt(i,e.message);t&&d.hubMessage(t)}else if(e.type===`turn`&&ie){let{sentAt:t}=ie;ie=void 0,be(e,t)}else if(e.type===`status`){let t=So(e.sessions),n=ae&&!t;if(ae=t,t)return;for(let e of d.rows())e.live&&d.upsert({key:e.key,live:!1});d.endReasoning(void 0),n&&I.resync().catch(()=>{}).then(ne)}else return;h()}),se=()=>document.visibilityState===`visible`,ce=(e,t=!1)=>(bx(e),H(`${U(i)}/presence`,{method:`POST`,json:{visible:e},keepalive:t}).catch(()=>{})),le=()=>void ce(se(),!se()),ue=()=>void ce(!1,!0),de,z=Ix,fe=()=>z().phase!==`off`&&z().sessionID===i,pe=()=>z().error?.sessionID===i?z().error.message:void 0;M(Ex.attach(i,{user:e=>{let t=`voice:${++E}`;return d.upsert({key:t,kind:`user`,text:e,at:Date.now()}),S(e=>({...e,[t]:`pending`})),h(),t},tick:(e,t)=>S(n=>({...n,[e]:t})),agent:e=>{let t=e.messageID?d.liveTextKey(e.messageID):`say:${++E}`,{mode:n,text:r}=by(d.get(t)?.text??``,e.text);n!==`keep`&&(d.upsert({key:t,messageID:e.messageID,kind:`assistant`,text:r,at:d.get(t)?.at??Date.now()}),h())},note:(e,t)=>D(e,t??`sys`)}));async function B(){fe()||($y(),zx.cancel()),await Ex.toggle(i),Ex.isOn(i)&&Ex.state.phase===`on`&&D(`Voice on. Talk to the Concierge; say “yes” or “no” to answer the Decision it is asking about.`)}let[V,he]=u(``),[ge,_e]=u(!1),ve,ye=()=>{ve&&(ve.style.height=`auto`,ve.style.height=`${Math.min(ve.scrollHeight,200)}px`)};function be(e,t){let n=e.reply?.trim(),r=d.rows().some(e=>e.kind===`assistant`&&(e.at??0)>=t&&e.text?.trim()===n);e.reply&&!r&&d.upsert({key:`reply:${++E}`,kind:`assistant`,text:e.reply,at:Date.now()});let i=Q_(e);i&&D(i.text,i.kind),h()}async function xe(){let e=V().trim();if(!e||ge())return;let t=xx(),n=Ks(e,t);if(n.kind===`answer`){_e(!0);try{await Cx(n.decisionID,n.option,`text`),he(``),d.upsert({key:`answered:${++E}`,kind:`user`,text:e,at:Date.now(),note:Js(t,n.option)}),h(),P=!0,F()}catch(e){J(`Not answered: ${W(e)}${e instanceof G&&e.status===403?`. Tap an option on the card.`:``}`,`err`)}finally{_e(!1)}return}if(he(``),queueMicrotask(ye),fe()){Ex.sendTyped(i,e);return}let r=`local:${++E}`,a=Date.now();me(()=>{d.upsert({key:r,kind:`user`,text:e,at:a}),S(e=>({...e,[r]:`pending`})),h()}),P=!0,F();try{let t=await H(`${U(i)}/turn`,{method:`POST`,json:{text:e},headers:{prefer:`respond-async`}}),n=await t.json().catch(()=>({})),o=Z_(t.status,n);S(e=>({...e,[r]:o===`steered`?`queued`:`sent`})),o===`accepted`?ie={sentAt:a}:be(n,a)}catch(t){S(e=>({...e,[r]:`failed`})),D(`Could not send: ${W(t)}`,`err`),V()||he(e)}}return R(()=>{re(),ce(se()),de=setInterval(()=>se()&&void ce(!0),rX),document.addEventListener(`visibilitychange`,le),window.addEventListener(`pagehide`,ue),r.autofocus&&requestAnimationFrame(()=>ve?.focus())}),M(()=>{oe(),clearInterval(de),document.removeEventListener(`visibilitychange`,le),window.removeEventListener(`pagehide`,ue),ue()}),[(()=>{var e=XY();e.addEventListener(`scroll`,e=>P=e.currentTarget.scrollHeight-e.currentTarget.scrollTop-e.currentTarget.clientHeight<80);var r=ee;return typeof r==`function`?t(r,e):ee=e,y(e,n(l,{get when(){return g()},get fallback(){return eX()},get children(){return n(l,{get when(){return A().length},get fallback(){return(()=>{var e=tX();return y(e,()=>Qs(sX())),e})()},get children(){return n(dG,{sessionID:i,get blocks(){return A()},get ticks(){return v()},expanded:j,onToggle:(e,t)=>N(e,t),onDetail:(e,t)=>{d.detail(e,t),h()}})}})}}),null),y(e,n(m,{get each(){return w()},children:e=>(()=>{var t=nX();return y(t,()=>e.text),s(n=>{var r=`note ${e.kind}`,i=e.kind===`err`?`alert`:void 0;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`role`,n.t=i),n},{e:void 0,t:void 0}),t})()}),null),y(e,n(l,{get when(){return c()},get children(){return YY()}}),null),e})(),(()=>{var e=$Y(),r=e.firstChild,i=r.firstChild,a=i.nextSibling;y(e,n(l,{get when(){return fe()},get children(){return n(gV,{get state(){return z().voice},get level(){return z().level},get held(){return z().held},get ignored(){return z().ignored},get working(){return c()},model:`Concierge`,onMute:()=>Ex.mute(),onEnd:()=>void Ex.end(),onModel:()=>J(`The Concierge keeps its own model: change it in Settings → Concierge`),get notifyHint(){return Px()},onAllowNotifications:()=>void Fx(),get timing(){return z().timing},get detector(){return z().detector},get turn(){return z().turn},get front(){return z().front}})}}),r),y(e,n(l,{get when(){return pe()},get children(){var e=ZY();return e.firstChild,y(e,pe,null),e}}),r),r.addEventListener(`submit`,e=>{e.preventDefault(),xe()}),i.$$keydown=e=>{e.key===`Enter`&&!e.shiftKey&&!e.isComposing&&!(Q()&&`ontouchstart`in window)&&(e.preventDefault(),xe())},i.$$input=e=>{he(e.currentTarget.value),ye()};var o=ve;return typeof o==`function`?t(o,i):ve=i,y(r,n(l,{get when(){return sX()||fe()},get children(){var e=QY();return e.$$click=()=>void B(),y(e,n(L,{name:`wave`})),s(t=>{var n=`icon-btn concierge-voice${fe()?` on`:``}`,r=fe(),i=fe()?`Stop talking to the Concierge`:`Talk to the Concierge`,a=fe()?`End Voice with the Concierge`:`Talk to the Concierge (Voice)`;return n!==t.e&&k(e,t.e=n),r!==t.t&&b(e,`aria-pressed`,t.t=r),i!==t.a&&b(e,`aria-label`,t.a=i),a!==t.o&&b(e,`title`,t.o=a),t},{e:void 0,t:void 0,a:void 0,o:void 0}),e}}),a),y(a,n(L,{name:`send`})),s(e=>{var t=fe()?`Voice is on: talk, or type here`:`Ask the Concierge…`,n=!V().trim()||ge();return t!==e.e&&b(i,`placeholder`,e.e=t),n!==e.t&&(a.disabled=e.t=n),e},{e:void 0,t:void 0}),s(()=>i.value=V()),e})()]}var uX={unknown:`link`};function dX(e){let t=Ru,n=[...pu().values()].map(e=>({...e,question:ze(e.question,Hu)})),r=[];for(let i of e)if(!(i.type===`message`&&i.primer)){if(i.type===`message`&&i.direction===`in`&&Do(i.from)){let e=Po(i.text,t);r.push(e?{...i,summary:e}:i)}else i.type===`message`&&i.text.includes(`dec_`)?r.push({...i,parts:Bo(i.text,n,uX)}):i.type===`assistant`&&i.text.includes(`dec_`)?r.push({...i,text:Vo(i.text,n,uX)}):i.type===`tools`?r.push({...i,items:i.items.map(e=>typeof e.summary==`string`&&e.summary.includes(`ses_`)?{...e,summary:Uo(e.summary,t)}:e)}):r.push(i)}return r}B([`click`,`input`,`keydown`]);var fX=I(`<main class=entry><p></p><button type=button class=btn>Retry`),pX=I(`<main class=entry><p class=muted>Loading…`),mX=I(`<div class=drawer-backdrop>`),hX=I(`<div class=voice-strip>`),gX=I(`<div class=conn-banner role=status>Reconnecting to the hub…`),_X=I(`<div role=status aria-live=polite>`),vX=I(`<p class="muted cmp-empty"data-concierge-wait>Loading…`),yX=I(`<div><main class=main>`),bX=I(`<button type=button class="btn small">`),xX=I(`<div role=status aria-live=polite><span>`),SX=I(`<header class=topbar><span class="title display grow">Hub`),CX=I(`<div class=home-shell><div class=home-scroll>`),wX=()=>ut().name===`concierge`&&!Q(),TX=()=>{let e=CC();return e.name===`session`?is(e.id,gu(),Su(),X.machines,vu(),vu()?[]:Tu()):void 0},EX=()=>{let e=CC();return TX()===`session`?e.id:void 0},DX=()=>hc(wc(Ix().phase===`off`,EX()),ut().name===`concierge`?gu()?.sessionID:void 0);function OX(){rd(()=>Ix().phase!==`off`),x(()=>id(DX()));let[t,i]=u(``),[a,c]=u(!1),d=async()=>{i(``);try{if(!await Gu())return;sd(DX()),Nd(),fp(),c(!0)}catch(e){i(`Cannot reach the hub: ${e.message}`)}};return x(e(()=>ut().name,e=>{e!==`pair`&&!a()&&d(),Q()&&Hp(!1)})),x(()=>{!Z()&&a()&&ut().name!==`pair`&&c(!1)}),x(()=>{let e=ut();e.name===`session`&&Eu().has(e.id)&&Bt(`/concierge`,{replace:!0})}),x(()=>zx.viewing(Cc()??EX())),R(()=>M(tj())),R(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`b`&&(e.preventDefault(),qp())};document.addEventListener(`keydown`,e),M(()=>document.removeEventListener(`keydown`,e))}),x(()=>rm(wX())),x(()=>{let e=im(),t=document.documentElement.style;t.setProperty(`--side-w`,`${e.side}px`),t.setProperty(`--rail-w`,`${e.rail}px`),e.concierge&&t.setProperty(`--concierge-w`,`${e.concierge}px`)}),x(()=>{a()&&location.hash===`#speech`&&ut().name!==`settings`&&Bt(`/settings/voice#speech`,{replace:!0})}),[n(v,{get children(){return[n(o,{get when(){return r(()=>ut().name===`pair`)()&&ut()},children:e=>n(Ff,{get next(){return e().next},get error(){return e().error}})}),n(o,{get when(){return t()},get children(){var e=fX(),n=e.firstChild,r=n.nextSibling;return y(n,t),r.$$click=()=>void d(),e}}),n(o,{get when(){return!a()},get children(){return pX()}}),n(o,{get when(){return r(()=>ut().name===`approve`)()&&ut()},children:e=>n(Lf,{get code(){return e().code}})}),n(o,{get when(){return r(()=>ut().name===`consent`)()&&ut()},children:e=>n(zf,{get flow(){return e().flow}})}),n(o,{when:!0,get children(){var e=yX(),t=e.firstChild;return y(e,n(l,{get when(){return!Q()||Vp()},get children(){return[n(l,{get when(){return Q()},get children(){var e=mX();return e.$$click=()=>Hp(!1),e}}),n(l,{get when(){return!zp()||Q()},get children(){return[n(kz,{get phone(){return Q()},onClose:()=>Hp(!1),onCollapse:qp}),n(l,{get when(){return!Q()},get children(){return n(OS,{panel:`side`,label:`Resize sidebar`})}})]}})]}}),t),y(e,n(l,{get when(){return r(()=>!!zp())()&&!Q()},get children(){return n(nz,{onExpand:qp})}}),t),y(t,n(l,{get when(){return r(()=>Ix().phase!==`off`)()&&CC().name!==`session`},get children(){var e=hX();return y(e,n(UL,{})),e}}),null),y(t,n(l,{get when(){return X.connection===`down`},get children(){return gX()}}),null),y(t,n(l,{get when(){return r(()=>X.connection!==`down`)()&&Qu()},get children(){var e=_X();return y(e,()=>Qu()===`reconnecting`?`Reconnecting…`:`Updated`),s(()=>k(e,`sync-note ${Qu()}`)),e}}),null),y(t,n(l,{get when(){return r(()=>!(!fm()||Q()||EX()))()&&CC().name!==`panes`},get children(){return n(BJ,{})}}),null),y(t,n(v,{get children(){return[n(o,{get when(){return r(()=>!Su())()&&(CC().name===`session`||CC().name===`panes`)||TX()===`wait`},get children(){return vX()}}),n(o,{get when(){return EX()||CC().name===`panes`},get children(){return n(kY,{get routed(){return EX()}})}}),n(o,{get when(){return r(()=>CC().name===`new`)()&&CC()},children:e=>n(bC,_(()=>e()))}),n(o,{get when(){return r(()=>CC().name===`feature`)()&&CC()},children:e=>n(FY,_(()=>e()))}),n(o,{get when(){return CC().name===`settings`},get children(){return n(oL,{})}}),n(o,{get when(){return CC().name===`concierge`},get children(){return n(cX,{mode:`page`})}}),n(o,{when:!0,get children(){return n(kX,{})}})]}}),null),y(e,n(l,{get when(){return wX()},get children(){return n(cX,{mode:`side`})}}),null),s(()=>k(e,`shell${zp()&&!Q()?` collapsed`:``}${Q()?` phone`:``}${Vp()?` drawer`:``}`)),e}})]}}),n(Lh,{}),n(CF,{}),n(re,{}),n(l,{get when(){return Ht()},children:e=>(()=>{var t=xX(),r=t.firstChild;return y(r,()=>e().text),y(t,n(l,{get when(){return e().action},get children(){var t=bX();return t.$$click=()=>{e().action.run(),jt()},y(t,()=>e().action.label),t}}),null),s(()=>k(t,`toast ${e().kind}`)),t})()})]}function kX(){return(()=>{var e=CX(),t=e.firstChild;return y(e,n(l,{get when(){return Q()},get children(){var e=SX(),t=e.firstChild;return y(e,n(F,{icon:`menu`,label:`Open sidebar`,onClick:qp}),t),y(e,n(lz,{}),null),e}}),t),y(t,n(SS,{})),e})()}B([`click`]),pe(()=>n(OX,{}),document.getElementById(`root`)),pp();export{sj as $,$P as A,gN as B,AK as C,_G as D,zG as E,UM as F,pN as G,QM as H,rN as I,uN as J,GM as K,KM as L,QP as M,qP as N,iB as O,VM as P,jM as Q,bN as R,XG as S,YG as T,tN as U,mN as V,nN as W,PM as X,RM as Y,kM as Z,mK as _,BK as a,X as at,HG as b,qK as c,zK as d,Ih as et,VK as f,hK as g,gK as h,HK as i,qp as it,sF as j,xF as k,RK as l,_K as m,WK as n,mm as nt,LK as o,Fu as ot,aK as p,WM as q,UK as r,Q as rt,PK as s,Iu as st,MY as t,hm as tt,GK as u,pK as v,GG as w,VG as x,fK as y,vN as z};
|