@huynle/hub 0.8.4 → 0.8.6
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 +55 -0
- package/README.md +40 -3
- package/package.json +1 -1
- package/packages/claude-code/package.json +1 -1
- package/packages/cli/dist/hub-cli.js +5288 -4415
- package/packages/cli/package.json +1 -1
- package/packages/cli/src/bootstrap/PHASE2-CONTRACT.md +87 -0
- package/packages/cli/src/bootstrap/adapters/claude/node.ts +11 -43
- package/packages/cli/src/bootstrap/adapters/codex/verify.ts +19 -12
- package/packages/cli/src/bootstrap/adapters/opencode/README.md +42 -6
- package/packages/cli/src/bootstrap/adapters/opencode/apply.ts +18 -7
- package/packages/cli/src/bootstrap/adapters/opencode/archive.ts +36 -19
- package/packages/cli/src/bootstrap/adapters/opencode/config.ts +19 -3
- package/packages/cli/src/bootstrap/adapters/opencode/index.ts +2 -5
- package/packages/cli/src/bootstrap/adapters/opencode/plan.ts +37 -6
- package/packages/cli/src/bootstrap/adapters/opencode/verify.ts +49 -26
- package/packages/cli/src/bootstrap/adapters/process-tree.ts +263 -0
- package/packages/cli/src/bootstrap/contracts/paths.ts +7 -4
- package/packages/cli/src/bootstrap/contracts/platform.ts +9 -5
- package/packages/cli/src/bootstrap/contracts/validate.ts +20 -4
- package/packages/cli/src/bootstrap/discovery/discover.ts +3 -1
- package/packages/cli/src/bootstrap/discovery/executables.ts +49 -14
- package/packages/cli/src/bootstrap/discovery/host.ts +16 -8
- package/packages/cli/src/bootstrap/discovery/node-probe.ts +41 -5
- package/packages/cli/src/bootstrap/discovery/probe.ts +7 -3
- package/packages/cli/src/bootstrap/discovery/util.ts +42 -5
- package/packages/cli/src/bootstrap/enrollment/store.ts +13 -6
- package/packages/cli/src/bootstrap/preview/plan.ts +3 -0
- package/packages/cli/src/bootstrap/profiles/desired.ts +10 -3
- package/packages/cli/src/bootstrap/release/README.md +63 -9
- package/packages/cli/src/bootstrap/release/cli.ts +94 -16
- package/packages/cli/src/bootstrap/release/harness-pins.pending.json +24 -0
- package/packages/cli/src/bootstrap/release/manifest.ts +3 -0
- package/packages/cli/src/bootstrap/release/pins.ts +60 -9
- package/packages/cli/src/bootstrap/transaction/builtin.ts +18 -6
- package/packages/cli/src/bootstrap/transaction/engine.ts +166 -12
- package/packages/cli/src/bootstrap/transaction/executor.ts +5 -0
- package/packages/cli/src/bootstrap/transaction/fs.ts +142 -3
- package/packages/cli/src/bootstrap/transaction/shim.ts +31 -0
- package/packages/cli/src/bootstrap/transaction/state.ts +11 -6
- package/packages/cli/src/credentials.ts +5 -2
- package/packages/cli/src/main.ts +3 -2
- package/packages/cli/src/setup/commands.ts +96 -18
- package/packages/cli/src/setup/contributors.ts +45 -10
- package/packages/cli/src/setup/runtime.ts +25 -6
- package/packages/cli/src/setup/self-aside.ts +130 -0
- package/packages/codex/package.json +1 -1
- package/packages/node/package.json +1 -1
- package/packages/node/src/opencode-warm.ts +12 -4
- package/packages/preset/package.json +1 -1
- package/packages/protocol/package.json +1 -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/spoke-sdk/package.json +1 -1
- package/src/central/config.ts +12 -0
- package/src/central/http.ts +10 -0
- package/src/central/install/CONTRACT.md +66 -0
- package/src/central/install/install.ps1 +349 -0
- package/src/central/install/install.sh +266 -0
- package/src/central/install/render.ts +146 -0
- package/src/central/install/templates.ts +6 -0
- package/src/central/install/text-assets.d.ts +9 -0
- package/src/config.ts +12 -7
- package/src/spoke/env-inject.ts +17 -2
- package/src/spoke/herdr.ts +3 -2
- package/src/spoke/launchers.ts +145 -9
- package/src/spoke/localhub.ts +1 -0
- package/src/win-acl.ts +154 -0
- package/web/dist/assets/ArtifactPage-Dq7VW-bU.js +1 -0
- package/web/dist/assets/{ArtifactPane-XTnwXl-Y.js → ArtifactPane-DKwbMTX9.js} +1 -1
- package/web/dist/assets/ArtifactWorkbench-vrgIfncX.js +6 -0
- package/web/dist/assets/Library-D6-Go6Cu.js +2 -0
- package/web/dist/assets/{ProfilesDestination-dZa3vioh.js → ProfilesDestination-BOML2Dgf.js} +1 -1
- package/web/dist/assets/{TeamsPage-DJt-Kk84.js → TeamsPage-CNBTE8gB.js} +1 -1
- package/web/dist/assets/Watchtower-Dor1Ubjy.js +2 -0
- package/web/dist/assets/Watchtower-RphjcL0_.css +1 -0
- package/web/dist/assets/hub-CrbItiwP.js +13 -0
- package/web/dist/assets/index-82Ce0IAf.css +1 -0
- package/web/dist/assets/index-D9SP3_0z.js +22 -0
- package/web/dist/assets/{live-D-RZbeUi.js → live-BNJgy0vg.js} +3 -3
- package/web/dist/assets/{pane-layout-Csk-vPNe.js → pane-layout-EdR1kRrG.js} +1 -1
- package/web/dist/assets/preload-helper-DqrJTq0t.js +1 -0
- package/web/dist/assets/{renderer2d-DILxLFEq.js → renderer2d-CYag1CnR.js} +1 -1
- package/web/dist/assets/{renderer3d-PvN9Qbt2.js → renderer3d-BRB6rgDJ.js} +1 -1
- package/web/dist/assets/{safe-area-BS6ii3M7.js → safe-area-fOy0AOuG.js} +1 -1
- package/web/dist/assets/{source-BFLJQ43_.js → source-Wbq35qGp.js} +1 -1
- package/web/dist/assets/{ui-Qo2Pd9-O.js → ui-j5FFk90B.js} +1 -1
- package/web/dist/index.html +6 -4
- package/web/dist/assets/ArtifactPage-Cb1DcrQf.js +0 -1
- package/web/dist/assets/ArtifactWorkbench-C37tZZ3e.js +0 -6
- package/web/dist/assets/Library-CZSSHvOJ.js +0 -2
- package/web/dist/assets/Watchtower-BXaUaXO1.js +0 -2
- package/web/dist/assets/Watchtower-CTgqHk5g.css +0 -1
- package/web/dist/assets/index-DVSkeAvn.css +0 -1
- package/web/dist/assets/index-DifgVuKS.js +0 -34
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ArtifactPane-XTnwXl-Y.js","assets/ui-Qo2Pd9-O.js","assets/ArtifactWorkbench-C37tZZ3e.js","assets/source-BFLJQ43_.js","assets/ArtifactWorkbench-9eTj1CeW.css","assets/Library-CZSSHvOJ.js","assets/Library-DYsFj_5c.css","assets/TeamsPage-DJt-Kk84.js","assets/plural-Bspvoqfq.js","assets/live-D-RZbeUi.js","assets/live-BUofsQpz.css","assets/Watchtower-BXaUaXO1.js","assets/Watchtower-CTgqHk5g.css","assets/ProfilesDestination-dZa3vioh.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{$ as e,A as t,At as n,B as r,Bt as i,C as a,Ct as o,D as s,Dt as c,E as l,Et as u,F as d,Ft as f,Gt as p,H as m,Ht as h,I as g,It as _,J as v,K as y,L as b,Lt as x,M as S,Mt as C,N as w,Nt as T,O as E,Ot as ee,P as te,Pt as D,Q as O,R as ne,Rt as re,S as ie,St as ae,T as k,Tt as A,U as oe,Ut as j,V as se,Vt as ce,W as le,Wt as ue,X as M,Y as de,_ as fe,_t as pe,a as me,at as N,b as he,bt as ge,c as _e,ct as ve,d as ye,dt as P,et as be,f as F,ft as I,g as xe,gt as Se,h as Ce,ht as L,i as R,it as z,j as we,jt as Te,k as Ee,kt as De,l as Oe,lt as ke,m as Ae,mt as je,n as Me,nt as B,o as Ne,ot as Pe,p as Fe,pt as V,q as Ie,r as H,rt as U,s as Le,st as Re,t as ze,tt as W,u as Be,ut as G,v as Ve,vt as He,w as Ue,wt as We,x as Ge,xt as Ke,y as K,yt as q,z as qe,zt as Je}from"./ui-Qo2Pd9-O.js";import{a as Ye,c as Xe,d as Ze,f as Qe,g as $e,h as et,i as tt,l as nt,m as rt,n as it,o as at,p as ot,r as st,s as ct,t as lt,u as ut}from"./pane-layout-Csk-vPNe.js";import{t as dt}from"./plural-Bspvoqfq.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 ft=e=>e==null?``:String(e).trim(),pt=Object.freeze([[`role`,`Admins first`],[`email`,`Email`],[`lastSeen`,`Last seen`]]),mt=Object.freeze([[`all`,`All`],[`admins`,`Admins`],[`active`,`Active`],[`disabled`,`Disabled`]]),ht=Object.freeze({signin:`Signed in`,"signin.denied":`Sign-in refused`,"device.pair":`Paired a device`,"device.revoke":`Revoked a device`,"machine.approve":`Approved a machine`,"machine.deny":`Denied a machine`,"machine.revoke":`Revoked a machine`,"user.role":`Changed a role`,"user.disable":`Disabled a user`,"user.enable":`Enabled a user`,"speech.default":`Changed the server speech default`,"migrate.local":`Moved the hub owner's machines and devices to the first admin`});function gt(e){return e?.user?.role===`admin`}function _t(e){let t=e?.user,n=e?.auth===`oidc`?`oidc`:`pairing`,r=gt(e);if(n!==`oidc`)return{mode:n,admin:r,title:`This hub`,initial:`H`};let i=ft(t?.name),a=ft(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 vt=Object.freeze([[`users`,`Users`],[`machines`,`Machines`],[`approvals`,`Approvals`],[`audit`,`Audit log`]]);function yt(e){return gt(e)?vt.filter(([t])=>t!==`users`||e?.auth===`oidc`):[]}function bt(e,t){return gt(e)&&t?.scope===`user`?[`user`,`default`]:[`user`]}function xt(e){return e&&e.startsWith(`/`)&&!e.startsWith(`//`)&&!e.includes(`\\`)?e:`/`}function St(e,t){if(e?.mode===`oidc`&&typeof e.signIn==`string`&&e.signIn)return`${e.signIn}?next=${encodeURIComponent(xt(t))}`}function Ct(e){let t=e?.auth===`oidc`?ft(e?.user?.email):``;return t?`This machine will belong to you (${t}).`:`This machine will belong to you.`}var wt={stt:[`provider`,`model`,`baseURL`,`language`],tts:[`provider`,`model`,`voice`,`baseURL`,`speed`]};function Tt(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 wt[e]){let n=r?s[t]===void 0||s[t]===null:ft(a[t])===ft(o[t]),l=ft(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 Et(e){return{[e]:Object.fromEntries([...wt[e],`apiKey`].map(e=>[e,null]))}}function Dt(e){let t=ft(e);if(!t)return`Unknown action`;if(ht[t])return ht[t];let n=t.replace(/[._-]+/g,` `).trim().toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)}function Ot(e,t=[]){let n=new Map(t.map(e=>[e.id,ft(e.email)||ft(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:Dt(e.action),target:e.target===void 0?void 0:n.get(e.target)??e.target,detail:e.detail}))}var kt=e=>(ft(e.email)||ft(e.name)||e.id).toLowerCase();function At(e,{query:t=``,filter:n=`all`,sort:r=`role`}={}){let i=ft(t).toLowerCase(),a=e=>(!i||`${ft(e.email)} ${ft(e.name)}`.toLowerCase().includes(i))&&(n===`admins`?e.role===`admin`:n===`disabled`?!!e.disabled:n!==`active`||!e.disabled),o=(e,t)=>kt(e).localeCompare(kt(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 jt(e,t,n){let r=ft(e.email)||ft(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 Mt(e){let t=ft(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 Nt=e=>String(e??``).normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase(),Pt=e=>`${e.providerID}/${e.modelID}`,Ft=class{models;constructor(e=[]){this.models=Array.isArray(e)?e.filter(e=>e&&typeof e.providerID==`string`&&typeof e.modelID==`string`):[]}groups(e=``){let t=Nt(e.trim()),n=new Map,r=this.models.some(e=>e.enabled!==!1);for(let e of this.models){if(r&&e.enabled===!1||t&&!Nt([e.name,e.modelID,e.providerID].join(` `)).includes(t))continue;let i=n.get(e.providerID)??[];i.push({...e,variants:[...e.variants??[]]}),n.set(e.providerID,i)}return[...n].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>({providerID:e,items:t.sort((e,t)=>(e.name||e.modelID).localeCompare(t.name||t.modelID))}))}selection(e){if(!e)return;let t=this.models.find(t=>t.providerID===e.providerID&&t.modelID===e.modelID);return t?{...t,variants:[...t.variants??[]],stale:t.enabled===!1}:{...e,name:Pt(e),variants:e.variant?[e.variant]:[],stale:!0}}},It=e=>`${e}:reasoning`,Lt=(e,t)=>t===void 0?`${e}:text`:`${e}:text:${t}`,Rt=e=>`hubmsg:${e}`,zt=1e3,Bt=(e,t)=>`activity:${e}:${t}`,Vt=(e,t)=>e.pos-t.pos||e.live-t.live,Ht=class{items=new Map;subagents=new Map;details=new Map;places=new Map;top=0;bottom=0;liveSeq=0;seenSeq=0;loaded=!1;snapshots=0;history=new Set;load(e,t={}){let n=(e??[]).filter(e=>e&&typeof e.key==`string`),r=n.filter(e=>typeof e.pos!=`number`&&!this.places.has(e.key));r.forEach((e,n)=>{this.places.set(e.key,{pos:t.older?this.bottom-r.length+n:this.top+1+n,live:0})});for(let e of n){typeof e.pos==`number`&&Number.isFinite(e.pos)&&this.places.set(e.key,{pos:e.pos,live:0});let t=this.places.get(e.key).pos;this.top=Math.max(this.top,t),this.bottom=Math.min(this.bottom,t),this.history.add(e.key)}for(let e of n){let t=this.liveTwin(e);t?(this.items.delete(t.key),this.places.delete(t.key),t.kind===`reasoning`?this.put({...e,text:e.text||t.text||``}):t.kind===`tool`?this.put({...Ut(t,[`summary`,`error`]),...e}):this.put(e)):this.put(e)}if(!t.older){this.loaded=!0;for(let[e,t]of this.places)t.live>0&&t.pos<this.top&&this.places.set(e,{...t,pos:this.top});for(let e of this.subagents.values())e.place&&e.place.pos<this.top&&(e.place={...e.place,pos:this.top})}}liveTwin(e){if(this.history.has(e.key)&&this.items.has(e.key))return;let t=typeof e.messageID==`string`?e.messageID:void 0,n=[];e.kind===`reasoning`&&t&&n.push(It(t)),e.kind===`assistant`&&t&&(typeof e.ordinal==`number`&&n.push(Lt(t,e.ordinal)),(e.ordinal===void 0||e.ordinal===0)&&n.push(Lt(t))),e.kind===`tool`&&typeof e.callID==`string`&&typeof e.sessionID==`string`&&n.push(Bt(e.sessionID,e.callID)),e.kind===`message`&&t&&n.push(Rt(t));for(let t of n){let n=t===e.key?void 0:this.items.get(t);if(n&&!this.history.has(t))return n}if(e.kind===`user`&&typeof e.text==`string`&&e.text){for(let t of this.items.values())if(t.kind===`user`&&!t.messageID&&!this.history.has(t.key)&&t.text===e.text)return t}}appendReasoning({sessionID:e,messageID:t,delta:n,at:r=Date.now()}){let i;for(let e of this.items.values())e.kind===`reasoning`&&e.messageID===t&&e.state===`running`&&(i=e);i??=this.items.get(It(t));let a=i?.key??It(t);this.upsert({key:a,kind:`reasoning`,messageID:t,...e?{sessionID:e}:{},text:`${i?.text??``}${n}`,state:`running`,at:i?.at??r})}appendText({sessionID:e,messageID:t,ordinal:n,delta:r,at:i=Date.now()}){let a=Lt(t,n),o=this.items.get(a);this.upsert({key:a,messageID:t,...e?{sessionID:e}:{},kind:`assistant`,text:`${o?.text??``}${r}`,live:!0,at:o?.at??i}),this.endReasoning(e)}liveTextKey(e){let t=Lt(e),n=-1;for(let r of this.items.values()){if(r.kind!==`assistant`||r.messageID!==e||this.history.has(r.key))continue;let i=r.key.startsWith(`${e}:text:`)?Number(r.key.slice(e.length+6)):NaN;Number.isInteger(i)&&i>n&&([t,n]=[r.key,i])}return t}activity(e,t){if(!t||typeof t.id!=`string`||t.kind===`thinking`)return;let n=Bt(e,t.id),r=this.items.get(n);this.upsert({key:n,sessionID:e,kind:`tool`,callID:t.id,...t.tool?{name:t.tool}:{},...t.summary?{summary:t.summary}:{},...t.error?{error:t.error}:{},...t.childSessionID?{childSessionID:t.childSessionID}:{},state:t.state,at:r?.at??t.at})}endReasoning(e,t=Date.now()){for(let n of this.items.values())n.kind===`reasoning`&&n.state===`running`&&(e===void 0||n.sessionID===e)&&this.upsert({key:n.key,kind:n.kind,state:`done`,completed:t})}upsert(e){e&&typeof e.key==`string`&&(this.places.has(e.key)||this.places.set(e.key,this.livePlace()),this.put(e))}livePlace(){return{pos:this.top,live:++this.liveSeq}}put(e){this.items.set(e.key,{...this.items.get(e.key)??{},...e})}hubMessage(e){if(e&&typeof e.key==`string`&&typeof e.messageID==`string`){for(let[t,n]of this.items)if(t!==e.key&&n.kind===`message`&&n.messageID===e.messageID&&this.history.has(t))return;if(!this.places.has(e.key)){if(typeof e.at==`number`&&Number.isFinite(e.at)){let t=e.at*zt;this.places.set(e.key,{pos:t,live:0}),this.top=Math.max(this.top,t)}else this.places.set(e.key,this.livePlace())}this.put(e)}}fromHistory(e){return this.history.has(e)}forgetHistory(){for(let e of this.history)this.items.delete(e),this.places.delete(e);this.history.clear()}clear(){this.items.clear(),this.places.clear(),this.details.clear(),this.history.clear(),this.top=0,this.bottom=0,this.loaded=!1}get(e){return this.items.get(e)}status(e,t){let n=new Set,r=new Set([t]);for(let t=!0;t;){t=!1;for(let n of e??[])typeof n?.id==`string`&&typeof n.parentID==`string`&&r.has(n.parentID)&&!r.has(n.id)&&(r.add(n.id),t=!0)}let i=(e??[]).every(e=>e?.id===t||typeof e?.parentID!=`string`),a=this.snapshots>0&&this.loaded;e?.length&&this.snapshots++;for(let o of e??[]){let s=o?.id;if(!o||typeof s!=`string`||!s||s===t||!r.has(s)&&!(i&&(e??[])[0]?.id===t))continue;n.add(s);let c=typeof o.since==`number`?o.since:void 0,l=o.state===`idle`?`done`:o.state,u=this.subagents.get(s)??{id:s,seen:++this.seenSeq,...a&&l===`working`?{place:this.livePlace()}:{}};this.subagents.set(s,{...u,title:typeof o.title==`string`?o.title:void 0,state:l,since:c})}for(let e of this.subagents.values())!n.has(e.id)&&e.state===`working`&&(e.state=`done`)}detail(e,t){this.details.set(e,t)}rows(){let e=[],t=new Map;for(let n of this.items.values()){let r={...n,depth:0,...this.details.has(n.key)?{detail:this.details.get(n.key)}:{}};if(n.sessionID&&this.subagents.has(n.sessionID)){let e=t.get(n.sessionID)??[];e.push({...r,depth:1}),t.set(n.sessionID,e)}else e.push(r)}let n=e=>this.places.get(e)??{pos:this.top,live:2**53-1},r=(e,t)=>Vt(n(e.key),n(t.key)),i=e=>[{key:`sub:${e.id}`,kind:`subagent`,label:e.title||e.id,state:e.state,sessionID:e.id,depth:0},...(t.get(e.id)??[]).sort(r)],a=[],o=new Set;for(let t of e.sort(r)){let e=typeof t.childSessionID==`string`&&!o.has(t.childSessionID)?this.subagents.get(t.childSessionID):void 0;e&&o.add(e.id),a.push({place:n(t.key),rows:e?i(e):[t]})}let s=[...this.subagents.values()].filter(e=>!o.has(e.id));s.filter(e=>!e.place).sort((e,t)=>(e.since??1/0)-(t.since??1/0)||e.seen-t.seen).forEach((e,t)=>a.push({place:{pos:-1/0,live:t},rows:i(e)}));for(let e of s)e.place&&a.push({place:e.place,rows:i(e)});return a.sort((e,t)=>Vt(e.place,t.place)).flatMap(e=>e.rows)}};function Ut(e,t){return Object.fromEntries(t.filter(t=>e[t]!==void 0).map(t=>[t,e[t]]))}function Wt(e){let t=e&&typeof e==`object`?e:{},n=e=>typeof e==`string`&&e?e:void 0;return t.kind===`session`?n(t.name)?`@${t.name}`:String(t.sessionID??`?`):t.kind===`user`?`@me`:t.kind===`app`?`app ${n(t.label)??String(t.tokenID??`?`)}`:`?`}function Gt(e,t){let n=t&&typeof t==`object`?t:void 0;if(!n||typeof n.id!=`string`||!n.id||typeof n.kind!=`string`||typeof n.to!=`string`)return;let r=t=>t?.kind===`session`&&t.sessionID===e,i=r(n.from)?`out`:r(n.recipient)?`in`:void 0;if(i)return{key:Rt(n.id),kind:`message`,messageID:n.id,sessionID:e,text:typeof n.text==`string`?n.text:``,...typeof n.at==`number`?{at:n.at}:{},direction:i,message:{kind:n.kind,from:Wt(n.from),to:n.to,...typeof n.replyTo==`string`?{replyTo:n.replyTo}:{}},recipient:Wt(n.recipient),...typeof n.state==`string`?{state:n.state}:{},...typeof n.delivery==`string`?{delivery:n.delivery}:{}}}var Kt=new Set([`open`,`answered`,`expired`,`closed`]),qt=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function Jt(e){if(!qt(e))return;let{id:t,question:n,options:r,state:i,about:a,at:o,from:s}=e;if(typeof t!=`string`||!t.startsWith(`dec_`)||typeof n!=`string`||!Array.isArray(r)||!Array.isArray(a)||typeof i!=`string`||!Kt.has(i)||typeof o!=`number`||!qt(s))return;let c=r.filter(e=>qt(e)&&typeof e.id==`string`&&typeof e.label==`string`),{as:l,...u}=e;return{...u,...l===`concierge`?{as:`concierge`}:{},options:c,about:a.filter(e=>typeof e==`string`)}}var Yt=(e,t)=>t.at-e.at||(e.id<t.id?1:-1);function Xt(e){return e.filter(e=>e.state===`open`).sort(Yt)}function Zt(e,t){return Xt([...e.filter(e=>e.id!==t.id),t])}function Qt(e,t){return e.filter(e=>e.from.kind===`session`&&e.from.sessionID===t||e.about.includes(t))}var $t=new Set,en=(e,t=$t)=>e.as===`concierge`||e.from.kind===`session`&&t.has(e.from.sessionID)?`@@concierge`:Wt(e.from),tn=e=>e.tier===`tap`?`Answer here (tap): only a signed-in console can answer this one.`:``;function nn(e,t){let n=e-t;if(n<0)return``;let r=Math.floor(n/1e3),i=Math.floor(r/86400),a=Math.floor(r%86400/3600),o=Math.floor(r%3600/60);return i?`${i}d ${a}h`:a?`${a}h ${o}m`:o?`${o}m ${r%60}s`:`${r}s`}function rn(e,t){if(e.deadline===void 0)return``;let n=nn(e.deadline,t);if(!n)return`Past its deadline`;let r=e.onTimeout?e.options.find(t=>t.id===e.onTimeout)?.label:void 0;return`Deadline in ${n}${r?` · then ${r}`:``}`}function an(e,t,n){let r=n.trim();return e.options.length?t===void 0||!e.options.some(e=>e.id===t)?{ok:!1,problem:`Pick one of the options`}:{ok:!0,body:{option:t,...r?{text:r}:{}}}:r?{ok:!0,body:{text:r}}:{ok:!1,problem:`Type an answer`}}var on=class{seq=0;settled=0;pending=new Map;begin(e=Date.now()){let t=++this.seq;return this.pending.set(t,{at:e,events:[]}),t}event(e,t=Date.now()){for(let[n,r]of this.pending)t-r.at>3e4?this.pending.delete(n):r.events.push(e)}settle(e,t){let n=this.pending.get(e)?.events;if(this.pending.delete(e),!(!n||e<this.settled))return this.settled=e,n.reduce((e,t)=>Zt(e,t),Xt(t))}fail(e){this.pending.delete(e)}},sn=`@@concierge`,cn=/\nThe Concierge's note: ([\s\S]*)$/,ln=/proposes to deny ([\s\S]*) in (?:@[\w-]+|ses_\w+)\.(?:\nThe Concierge's note: [\s\S]*)?$/,un=/^[\s\S]*? asks to approve( always(?: \(saves [\s\S]*?\))?)? ([\s\S]*)\. Outside its grant: ([\s\S]*)$/,dn=`a permission request (details unknown)`,fn=e=>typeof e==`string`&&e?e:void 0;function pn(e){let t=Array.isArray(e.resources)?e.resources.filter(e=>typeof e==`string`):void 0,n=fn(e.action);if(n&&t)return e.summary===`${n}: ${t.join(`, `)}`||!e.summary.startsWith(`${n}: `)?{action:n,resources:t}:{action:n,resources:[e.summary.slice(n.length+2)]};let r=e.summary.indexOf(`: `);return r<0?{action:n??fn(e.summary),resources:t??[]}:{action:n??e.summary.slice(0,r),resources:t??[e.summary.slice(r+2)]}}function mn(e){let t=e.indexOf(`: `);return t<0?{action:e,resources:[]}:{action:e.slice(0,t),resources:[e.slice(t+2)]}}function hn(e,t,n){if(e)return{...pn(e),...t?.save?.length?{saves:[...t.save]}:{},source:`live`};if(t&&typeof t.action==`string`){let e=[...t.resources??[]],n=t.save?.length?[...t.save]:void 0,r=(e,t)=>typeof e==`number`&&e>t?e-t:void 0,i=r(t.resourcesTotal,e.length),a=r(t.savesTotal,n?.length??0),o=Array.isArray(t.cut)?t.cut.filter(e=>(e.field===`resources`||e.field===`save`)&&Number.isInteger(e.index)&&typeof e.length==`number`):[];return{action:t.action,resources:e,...n?{saves:n}:{},source:`request`,...i?{resourcesMore:i}:{},...a?{savesMore:a}:{},...o.length?{cut:o}:{},...t.truncated===!0?{incomplete:!0}:{}}}let r=n();return r?{...r,source:`text`}:void 0}var gn=e=>e?{...e.action?{action:e.action}:{},resources:e.resources,...e.saves?{saves:e.saves}:{},source:e.source,...e.resourcesMore?{resourcesMore:e.resourcesMore}:{},...e.savesMore?{savesMore:e.savesMore}:{},...e.cut?{cut:e.cut}:{},...e.incomplete?{incomplete:e.incomplete}:{}}:{resources:[]};function _n(e,t,n,r){if(r)for(let i of new Set(t.filter(e=>!!e))){let t=e.blockers(i).find(e=>e.kind===n&&e.id===r);if(t)return t}}var vn=(e,t)=>({id:t,label:e.label(t)??t}),yn=e=>Array.isArray(e)?e.map(String).join(`, `):typeof e==`object`&&e?JSON.stringify(e):String(e);function bn(e,t){let n=e.action;if(n?.kind===`permission`){let r=en(e),i=e.from.kind===`session`&&r===e.from.sessionID?t.label(e.from.sessionID)??r:r,a=un.exec(e.question),o=n.sessionID??n.rootID??e.about[0],s=hn(_n(t,[n.sessionID,n.rootID,...e.about],`permission`,n.requestID),n.request,()=>a&&a[2]!==dn?mn(a[2]):void 0),c=fn(n.reason)??a?.[3]?.trim(),l=e.recommendation?.why;return{kind:`permission`,requester:i,...o?{target:vn(t,o)}:{},...gn(s),always:n.always===!0||!!a?.[1],...n.requestID?{requestID:n.requestID}:{},...c?{outsideGrant:c}:{},...l?{purpose:{by:i,text:l}}:{}}}if(n?.kind===`act`&&n.target){let r=n.input??{},i=e.recommendation?.why??cn.exec(e.question)?.[1]?.trim(),a={kind:`proposal`,verb:n.verb??`act`,target:vn(t,n.target),always:!1,...i?{purpose:{by:sn,text:i}}:{}};switch(n.verb){case`deny`:{let i=fn(r.requestID),o=_n(t,[n.target],`permission`,i),s=ln.exec(e.question)?.[1],c=hn(o,n.request,()=>s&&s!==`permission request ${i}`?mn(s):void 0);return{...a,...gn(c),...i?{requestID:i}:{}}}case`prompt`:return{...a,resources:[],...fn(r.text)?{text:fn(r.text)}:{}};case`answer`:{let e=fn(r.formID),i=_n(t,[n.target],`form`,e),o=r.answer&&typeof r.answer==`object`&&!Array.isArray(r.answer)?Object.entries(r.answer).map(([e,t])=>({key:e,value:yn(t)})):void 0;return{...a,resources:[],...e?{formID:e}:{},...i?{form:i.summary}:{},...r.cancel===!0?{cancel:!0}:o?{answer:o}:{},...i?{source:`live`}:{}}}default:return{...a,resources:[]}}}if(n)return;let r=[...new Set(e.about)].flatMap(e=>t.blockers(e).filter(e=>e.kind===`permission`).map(t=>({s:e,b:t})));if(r.length!==1)return;let{s:i,b:a}=r[0],o=pn(a);return{kind:`ask`,target:vn(t,i),...o.action?{action:o.action}:{},resources:o.resources,always:!1,requestID:a.id,source:`live`}}function xn(e){if(e.action?.kind!==`act`)return e.question;let t=e.question.replace(cn,``);return e.action.verb===`prompt`||e.action.verb===`answer`?t.split(`
|
|
3
|
-
`)[0]:t}var Sn=typeof Intl<`u`&&`Segmenter`in Intl?new Intl.Segmenter(void 0,{granularity:`grapheme`}):void 0;function Cn(e){return Sn?Array.from(Sn.segment(e),e=>e.segment):Array.from(e)}function wn(e,{chars:t=400,lines:n=8}={}){let r=e,i=!1,a=r.split(`
|
|
4
|
-
`);a.length>n&&(r=a.slice(0,n).join(`
|
|
5
|
-
`),i=!0);let o=Cn(r);return o.length>t&&(r=o.slice(0,t).join(``),i=!0),{text:i?`${r}…`:r,cut:i}}var Tn=RegExp(`(\\u{1F3F4}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,30}\\u{E007F})|[\\u0000-\\u0008\\u000B-\\u001F\\u007F-\\u009F\\u00AD\\u034F\\u061C\\u115F\\u1160\\u180E\\u200B\\u200C\\u200E\\u200F\\u2028-\\u202E\\u2060-\\u2064\\u2066-\\u206F\\u3164\\uFEFF\\uFFA0\\uFFF9-\\uFFFB\\u{E0000}-\\u{E007F}]`,`gu`);function En(e){return e.replace(Tn,(e,t)=>t||`⟨U+${e.codePointAt(0).toString(16).toUpperCase().padStart(4,`0`)}⟩`)}var Dn=/(?<![\w/.-])ses_[A-Za-z0-9]{1,64}(?![\w])/g,On=10,kn=e=>e.length>12?`${e.slice(0,On)}…`:e,An=e=>e.replace(/[/\\]+$/,``).split(/[/\\]/).pop()||``;function jn(e,t,n=!1){if(n)return`the Concierge`;let r=t?.name?.trim().replace(/^@+/,``);if(r)return`@${r}`;let i=t?.title?.trim();if(i)return i;let a=t?.directory?An(t.directory):``;return a?`${a} · ${kn(e)}`:kn(e)}function Mn(e,t){return e.replace(Dn,e=>t(e))}function Nn(e,t){let n=e&&typeof e==`object`?e:{},r=e=>typeof e==`string`&&e?e:void 0;return n.kind===`session`?r(n.name)?`@${String(n.name).replace(/^@+/,``)}`:typeof n.sessionID==`string`?t(n.sessionID):`?`:n.kind===`user`?`@me`:n.kind===`app`?`app ${r(n.label)??String(n.tokenID??`?`)}`:`?`}function Pn(e,t,n=new Set){return en(e,n)===`@@concierge`?`@@concierge`:Nn(e.from,t)}var Fn=e=>e.from.kind===`session`?e.from.sessionID:e.from.kind===`app`?e.from.tokenID:void 0;function In(e,t,n=new Set){let r=e.action;return r?.kind===`permission`&&r.request&&typeof r.request.action==`string`?`${Pn(e,t,n)} asks to approve ${r.request.action}${r.always?` always`:``}`:Mn(xn(e),t)}var Ln=[`approve`,`deny`,`answer`,`prompt`,`stop`,`roles`,`launch`],Rn=new Set([`active`,`expired`,`revoked`]),zn=e=>!!e&&typeof e==`object`&&!Array.isArray(e),Bn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),Vn=[`sessions:read`,`sessions:manage`,`messages:send`,`messages:read`,`sessions:act`,`sessions:launch`,`events:subscribe`,`profiles:read`,`profiles:manage`,`profiles:assign`,`workspaces:read`,`workspaces:manage`,`artifacts:read`,`artifacts:write`,`artifacts:ai`,`teams:read`,`teams:manage`,`teams:submit`];function Hn(e){if(zn(e)&&typeof e.id==`string`&&/^[0-9a-f]{16}$/.test(e.id)&&Bn(e.scopes))return{id:e.id,...typeof e.label==`string`?{label:e.label}:{},scopes:e.scopes.filter(e=>Vn.includes(e)),...typeof e.created==`number`?{created:e.created}:{}}}function Un(e){return(zn(e)&&Array.isArray(e.tokens)?e.tokens:[]).map(Hn).filter(e=>!!e)}function Wn(e,t){let n=e.trim();if(!n)return{ok:!1,error:`Give the token a label`};if(!t.length)return{ok:!1,error:`Pick at least one scope`};let r=t.find(e=>!Vn.includes(e));return r?{ok:!1,error:`Unknown scope: ${r}`}:{ok:!0,body:{label:n,scopes:[...new Set(t)]}}}var Gn={"sessions:read":`Read your sessions and their activity`,"sessions:manage":`Name sessions and claim roles`,"messages:send":`Send messages and asks, reply and decline`,"messages:read":`Read messages to it`,"sessions:act":`Approve, deny, answer, prompt and stop sessions (only under a grant)`,"sessions:launch":`Launch sessions (only under a grant with verb launch for the repo)`,"events:subscribe":`Subscribe webhooks to events`,"profiles:read":`Read your shared agent profiles (instructions, skills, commands)`,"profiles:manage":`Create, revise and archive your agent profiles`,"profiles:assign":`Pin agent profiles to sessions (also needs a prompt grant on the session)`,"workspaces:read":`Read your workspaces, their members, supervision and boards`,"workspaces:manage":`Create, edit and archive workspaces; add members, supervise, start side chats`,"artifacts:read":`Read your artifacts and their revisions (including workspace-shared ones)`,"artifacts:write":`Create and revise artifacts, and accept AI edits the app requested`,"artifacts:ai":`Ask AI about artifacts and request edits or actions (run by sessions it may already use)`,"teams:read":`Read your teams, their roles, roster and intake`,"teams:manage":`Create, edit, publish, staff, pause and archive teams`,"teams:submit":`Submit work to a team's intake`},Kn=e=>Vn.includes(e);function qn(e){let t=zn(e)?e.login:void 0;if(zn(t)&&typeof t.userCode==`string`&&typeof t.clientName==`string`&&Bn(t.scopes)&&typeof t.created==`number`&&typeof t.expiresAt==`number`)return{userCode:t.userCode,clientName:t.clientName,scopes:t.scopes.filter(Kn),created:t.created,expiresAt:t.expiresAt}}function Jn(e){return Vn.map(t=>{let n=e.scopes.includes(t);return{scope:t,label:Gn[t],requested:n,checked:n}})}function Yn(e){if(!e.length)return{ok:!1,error:`Pick at least one scope`};let t=e.find(e=>!Kn(e));return t?{ok:!1,error:`Unknown scope: ${t}`}:{ok:!0,body:{scopes:[...new Set(e)]}}}function Xn(e){if(!zn(e))return;let{id:t,holder:n,scope:r,allow:i,permissions:a,allowAlways:o,maxActionsPerHour:s,created:c,expiresAt:l,state:u}=e;if(typeof t==`string`&&typeof n==`string`&&typeof u==`string`&&Rn.has(u)&&zn(r)&&Bn(r.projects)&&Bn(i)&&zn(a)&&Bn(a.allow)&&Bn(a.never)&&typeof o==`boolean`&&typeof s==`number`&&typeof c==`number`&&typeof l==`number`)return e}function Zn(e){return(zn(e)&&Array.isArray(e.grants)?e.grants:[]).map(Xn).filter(e=>!!e)}function Qn(e,t){return e.state===`revoked`||e.revokedAt!==void 0?`revoked`:e.state===`expired`||t>=e.expiresAt?`expired`:`active`}var $n={active:`Active`,expired:`Expired`,revoked:`Revoked`};function er(e,t){if(e<=t)return``;let n=Math.ceil((e-t)/6e4),r=Math.floor(n/1440),i=Math.floor(n%1440/60),a=n%60;return r>=2?`${Math.round(n/1440)} d`:r===1?i?`1 d ${i} h`:`1 d`:i?a?`${i} h ${a} min`:`${i} h`:`${a} min`}function tr(e,t){let n=Qn(e,t);return{id:e.id,holder:e.holderSessionID?`${e.holder} (${e.holderSessionID})`:e.holder,state:n,stateLabel:$n[n],projects:e.scope.projects.join(`, `),verbs:e.allow.join(`, `),permit:e.permissions.allow.join(`, `),never:e.permissions.never.join(`, `),limits:[e.allowAlways?`may allow always`:``,`${e.maxActionsPerHour} actions an hour`].filter(Boolean).join(` · `),expiry:n===`active`?`Expires in ${er(e.expiresAt,t)}`:$n[n],editable:n===`active`}}function nr(e){return{holder:e?.holder??``,projects:e?e.scope.projects.join(`
|
|
6
|
-
`):``,allow:e?[...e.allow]:[],permit:e?e.permissions.allow.join(`
|
|
7
|
-
`):``,never:e?e.permissions.never.join(`
|
|
8
|
-
`):``,expires:`8h`,maxActionsPerHour:String(e?.maxActionsPerHour??60),allowAlways:e?.allowAlways??!1}}var rr=e=>e.split(`
|
|
9
|
-
`).map(e=>e.trim()).filter(Boolean),ir=/^\d+(s|m|h|d)?$/,ar=e=>/^([A-Za-z]:)?[\\/]/.test(e);function or(e){let t={},n=e.holder.trim();n||(t.holder=`Who holds it: @@orchestrator, @name, ses_… or app:<token id>`);let r=rr(e.projects),i=r.find(e=>!ar(e));r.length?i!==void 0&&(t.projects=`${i} is not an absolute directory`):t.projects=`At least one project directory`;let a=Ln.filter(t=>e.allow.includes(t));a.length||(t.allow=`Pick at least one action`);let o=e.expires.trim();ir.test(o)||(t.expires=`A duration: seconds, or 30m, 8h, 2d`);let s=e.maxActionsPerHour.trim(),c=/^\d+$/.test(s)?Number(s):NaN;return c>=1&&c<=1e3||(t.maxActionsPerHour=`A whole number from 1 to 1000`),Object.keys(t).length?{ok:!1,errors:t}:{ok:!0,body:{holder:n,scope:{projects:r},allow:a,permissions:{allow:rr(e.permit),never:rr(e.never)},expires:o,maxActionsPerHour:c,allowAlways:e.allowAlways}}}function sr(e){if(/^permissions\.never/.test(e))return`never`;if(/^permissions/.test(e))return`permit`;if(/^scope/.test(e))return`projects`;if(/^allow\b/.test(e))return`allow`;if(/^expires/.test(e))return`expires`;if(/^maxActionsPerHour/.test(e))return`maxActionsPerHour`;if(/^allowAlways/.test(e))return`allowAlways`;if(/holder|^No app token|^No session|^No such session/i.test(e))return`holder`}function cr(e){if(!zn(e))return;let{seq:t,at:n,actor:r,verb:i,target:a,decision:o,outcome:s}=e;if(typeof t==`number`&&typeof n==`number`&&zn(r)&&typeof r.kind==`string`&&typeof i==`string`&&zn(a)&&typeof o==`string`&&typeof s==`string`)return e}function lr(e){if(!zn(e))return{entries:[]};let t=(Array.isArray(e.entries)?e.entries:[]).map(cr).filter(e=>!!e);return typeof e.next==`number`?{entries:t,next:e.next}:{entries:t}}var ur={allow:`allowed`,needs_user:`needs you`,forbidden:`refused`,paused:`paused`,rate_limited:`rate limited`,busy:`hub busy`},dr={ok:`done`,failed:`failed`,gone:`already answered`,offline:`offline`,unsupported:`unsupported`,escalated:`sent to you`,refused:`refused`},fr=new Set([`forbidden`,`paused`,`rate_limited`,`busy`]),pr=new Set([`failed`,`refused`,`offline`,`unsupported`]),mr={"acting.pause":`turned agent actions off`,"acting.resume":`turned agent actions on`},hr={approve:[`approved`,`approved $`],deny:[`denied`,`denied $`],answer:[`answered`,`answered $`],prompt:[`prompted a session`,`prompted $`],stop:[`stopped a session`,`stopped $`],propose:[`proposed an action`,`proposed an action for $`],msg:[`sent a message`,`messaged $`],roles:[`claimed a role`,`claimed a role for $`],"roles.release":[`released a role`,`released a role of $`],launch:[`launched a session`,`launched $`],"launch.stop":[`stopped a launch`,`stopped the launch of $`],"team.staff":[`staffed a team role`,`staffed a team role with $`],"team.unstaff":[`unstaffed a team role`,`unstaffed $ from a team role`],"team.denied":[`sent a message the team's rules refused`,`sent $ a message the team's rules refused`],"grant.request":[`asked for a grant`,`asked for a grant for $`],"grant.approve":[`approved a grant request`,`approved a grant request from $`],"grant.deny":[`denied a grant request`,`denied a grant request from $`]},gr={deny:[`proposed denying`,`proposed denying a request in`],answer:[`proposed answering`,`proposed answering a form in`],prompt:[`proposed prompting`,`proposed a prompt to`],stop:[`proposed stopping`,`proposed stopping`]},_r=/^Decision dec_[A-Za-z0-9]{1,64}: (\w+)$/;function vr(e,t,n){let r=gr[_r.exec(e??``)?.[1]??``],i=n?` in ${n}`:``;return t?`${r?r[0]:`proposed an action on`} ${t}${i}`:n?`${r?r[1]:`proposed an action for`} ${n}`:`proposed an action`}function yr(e,t,n,r){if(e===`propose`)return vr(r,t,n);let i=hr[e];return i?t?`${i[0]} ${t}${n?` in ${n}`:``}`:n?i[1].replace(`$`,n):i[0]:[e.replace(/[._]+/g,` `).trim()||e,t,t&&n?`in ${n}`:n].filter(Boolean).join(` `)}var br=(e,t)=>e.as===`concierge`?`@@concierge`:e.actor.kind===`user`?`you`:t?Nn(e.actor,e=>t(e)??kn(e)):Wt(e.actor);function xr(e,t){if(e.outcome!==`escalated`)return;let n=/\bDecision (dec_[A-Za-z0-9]{1,64})\b/.exec(e.reason??``)?.[1];for(let r of t)if(n?r.id===n:e.target.requestID&&r.action?.requestID===e.target.requestID)return r}function Sr(e){if(e.state!==`answered`)return e.state;let t=e.answer?.option,n=e.options.find(e=>e.id===t)?.label??t;return n?`answered “${n}”`:`answered`}var Cr=`Shell, outside folders and tools always need the user's tap`,wr=`The Concierge never answers “always”: the user decides`,Tr={approve:`Approved`,deny:`Denied`,answer:`Answered`,prompt:`Prompted`,stop:`Stopped`},Er=e=>e.replace(/\binGrant\s*=\s*yes\b/gi,`inside your grant`).replace(/\binGrant\s*=\s*no\b/gi,`outside your grant`).replace(/\bauto\s*=\s*yes\b/gi,`approvable without you`).replace(/\bauto\s*=\s*no\b/gi,`needs your tap`).replace(/\bdec_[A-Za-z0-9]{1,64}\b/g,`a Decision`),Dr=/[\u061c\u200b-\u200f\u2028-\u202e\u2060-\u206f\ufeff\u{E0000}-\u{E007F}]/gu,Or=300;function kr(e){let t=Er(e).replace(Dr,``).replace(/«/g,`‹`).replace(/»/g,`›`).replace(/[\u0000-\u001f\u007f-\u009f]/g,` `).replace(/\s+/g,` `).trim(),n=Array.from(t);return`«${n.length>Or?`${n.slice(0,299).join(``)}…`:t}»`}function Ar(e){let t=e.reason??``;if(e.decision===`busy`)return`Refused: the hub was busy (its state did not answer in time); try again`;if(e.reason===`concierge inbound rule`)return`Refused: only you can message the Concierge`;if(e.actor.kind===`user`&&/^Decision dec_[A-Za-z0-9]{1,64} proposed by @@concierge$/.test(t))return`You said yes to the Concierge's proposal`;if(e.as!==`concierge`)return t;if(t===`concierge outbound rule`)return`Refused: the Concierge may message only you`;if(e.verb===`propose`)return`The Concierge proposed this for your answer`;if(t===Cr)return`Needed your tap: shell commands, outside folders and tools always do`;if(t===wr)return`Needed your tap: the Concierge never answers “always”`;if(e.decision===`needs_user`)return t?`Needed you: ${Er(t).replace(/ outside the grant\b/,` outside the Concierge's grant`)}`:`Needed you`;let n=Tr[e.verb];return n&&e.decision===`allow`&&e.outcome===`ok`?`${n} by the Concierge inside your grant${t?`. Its note: ${kr(t)}`:``}`:Er(t)}function jr(e,t,n){let r=e.target.requestID??e.target.formID,i=e.target.requestID?`a permission request`:e.target.formID?`a form`:void 0,a=e.target.sessionID,o=a?n?.(a)??kn(a):``,s=mr[e.verb]??yr(e.verb,i,o,e.reason),c=mr[e.verb]?void 0:[r,r&&a?`in ${a}`:a].filter(Boolean).join(` `)||void 0,l=ur[e.decision]??e.decision,u=dr[e.outcome]??e.outcome,d=e.decision===`allow`&&e.outcome===`ok`,f=t&&t.state!==`open`?`${u} · ${Sr(t)}`:void 0;return{seq:e.seq,at:e.at,who:br(e,n??(()=>void 0)),what:s,...c?{whatTitle:c}:{},result:d?`done`:f??(l===u?l:`${l} · ${u}`),tone:d||t?.state===`answered`?`ok`:fr.has(e.decision)||pr.has(e.outcome)?`err`:`warn`,grant:e.grant?`grant`:``,...e.grant?{grantTitle:e.grant}:{},reason:Ar(e)}}var Mr={approve:`Approved`,deny:`Denied`,answer:`Answered`},Nr=3,Pr=3,Fr=e=>e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()||e;function Ir(e,t,n){let r=n?.(e);if(t.as===`concierge`||r?.holder===`@@concierge`)return`the Concierge's grant`;let i=r?.scope.projects.map(Fr)??[];if(!i.length)return`your grant`;let a=i.slice(0,Pr).join(`, `);return`your grant for ${i.length>Pr?`${a} and ${i.length-Pr} more`:a}`}function Lr(e,t,n){let r=Mr[e.verb];if(!r||e.decision!==`allow`||e.outcome!==`ok`)return;let i=`${r} by ${br(e,t)}`;return e.grant?{text:`${i} · ${Ir(e.grant,e,n)}`,title:e.grant}:{text:i}}function Rr(e,t,n){return Lr(e,t,n)?.text}function zr(e,t){return[t,...e.filter(e=>e.seq!==t.seq)].sort((e,t)=>t.seq-e.seq).slice(0,100)}function Br(e,t,n,r){for(let i of e){if(i.target.requestID!==t&&i.target.formID!==t)continue;let e=Lr(i,n,r);if(e)return e}}function Vr(e,t,n,r,i,a,o){let s=[];for(let c of[...e].sort((e,t)=>t.at-e.at||t.seq-e.seq)){if(s.length>=Nr)break;if(!c.target.sessionID||!t.has(c.target.sessionID)||n-c.at>6e5||r!==void 0&&c.at<r)continue;let e=Lr(c,a,o),l=c.target.requestID??c.target.formID??`seq-${c.seq}`;e&&!i?.has(l)&&!s.some(e=>e.key===l)&&s.push({key:l,...e,at:c.at})}return s}function Hr(e,t,n,r=6e4,i){for(let a of[...e].sort((e,t)=>t.at-e.at||t.seq-e.seq)){if(n-a.at>r)break;if(a.verb!==`deny`||!a.target.sessionID||!t.has(a.target.sessionID))continue;let e=Rr(a,void 0,i);if(e)return{key:a.target.requestID??a.target.formID??`seq-${a.seq}`,text:e}}}function Ur(e,t,n,r){let{since:i,until:a}=n,o;for(let n of e){if(n.verb!==`deny`||n.target.sessionID!==t||i!==void 0&&n.at<i||a!==void 0&&n.at>=a)continue;let e=Rr(n,void 0,r);e&&(!o||(i===void 0?n.at>o.e.at||n.at===o.e.at&&n.seq>o.e.seq:n.at<o.e.at||n.at===o.e.at&&n.seq<o.e.seq))&&(o={e:n,text:e})}return o&&{key:o.e.target.requestID??o.e.target.formID??`seq-${o.e.seq}`,text:o.text}}function Wr(e,t){return e.filter(e=>e.denial===void 0||!t.has(e.denial))}function Gr(e){let t=e.enabled!==!1,n=e.hubEnabled!==!1;return{on:t,hubOn:n,note:n?t?``:`Agents cannot act for you (approve, deny, answer, prompt, stop, launch). Reading and messaging still work.`:`An admin turned agent actions off for the whole hub: no agent can approve, deny, answer, prompt, stop or launch until it is on again.`}}var Kr=/^(.*?) asks to approve( always(?: \(saves .*?\))?)? (.*?)\. Outside its grant: (.*)$/s,qr=`a permission request (details unknown)`;function Jr(e){if(e.action?.kind!==`permission`)return;let t={requester:en(e),always:e.action.always===!0,...e.action.requestID?{requestID:e.action.requestID}:{}},n=Kr.exec(e.question);if(!n)return{...t,action:void 0,resources:[],reason:void 0};let r=n[3],i=r.indexOf(`: `),a=r!==qr;return{...t,always:t.always||!!n[2],action:a?i<0?r:r.slice(0,i):void 0,resources:a&&i>=0?r.slice(i+2).split(`, `).filter(Boolean):[],reason:n[4].trim()||void 0}}function Yr(e,t){return!zn(e)||typeof e.by!=`string`||e.recommends!==`approve`?``:`${t?Mn(e.by,t):e.by} recommends Approve${typeof e.why==`string`&&e.why?`: ${e.why}`:``}`}var Xr=Symbol(`store-raw`),Zr=Symbol(`store-node`),Qr=Symbol(`store-has`),$r=Symbol(`store-self`);function ei(e){let t=e[Ke];if(!t&&(Object.defineProperty(e,Ke,{value:t=new Proxy(e,ci)}),!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 ti(e){let t;return typeof e==`object`&&!!e&&(e[Ke]||!(t=Object.getPrototypeOf(e))||t===Object.prototype||Array.isArray(e))}function ni(e,t=new Set){let n,r,i,a;if(n=e!=null&&e[Xr])return n;if(!ti(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=ni(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=ni(i,t))!==i&&(e[a]=r))}return e}function ri(e,t){let n=e[t];return n||Object.defineProperty(e,t,{value:n=Object.create(null)}),n}function ii(e,t,n){if(e[t])return e[t];let[r,i]=x(n,{equals:!1,internal:!0});return r.$=i,e[t]=r}function ai(e,t){let n=Reflect.getOwnPropertyDescriptor(e,t);return!n||n.get||!n.configurable||t===Ke||t===Zr||(delete n.value,delete n.writable,n.get=()=>e[Ke][t]),n}function oi(e){Je()&&ii(ri(e,Zr),$r)()}function si(e){return oi(e),Reflect.ownKeys(e)}var ci={get(e,t,n){if(t===Xr)return e;if(t===Ke)return n;if(t===ae)return oi(e),n;let r=ri(e,Zr),i=r[t],a=i?i():e[t];if(t===Zr||t===Qr||t===`__proto__`)return a;if(!i){let n=Object.getOwnPropertyDescriptor(e,t);Je()&&(typeof a!=`function`||Object.prototype.hasOwnProperty.call(e,t))&&!(n&&n.get)&&(a=ii(r,t,a)())}return ti(a)?ei(a):a},has(e,t){return t===Xr||t===Ke||t===ae||t===Zr||t===Qr||t===`__proto__`||(Je()&&ii(ri(e,Qr),t)(),t in e)},set(){return!0},deleteProperty(){return!0},ownKeys:si,getOwnPropertyDescriptor:ai};function li(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[Qr]&&e[Qr][t]&&i!==void 0&&e[Qr][t].$()):(e[t]=n,e[Qr]&&e[Qr][t]&&i===void 0&&e[Qr][t].$());let o=ri(e,Zr),s;if((s=ii(o,t,i))&&s.$(()=>n),Array.isArray(e)&&e.length!==a){for(let t=e.length;t<a;t++)(s=o[t])&&s.$();(s=ii(o,`length`,a))&&s.$(e.length)}(s=o[$r])&&s.$()}function ui(e,t){let n=Object.keys(t);for(let r=0;r<n.length;r+=1){let i=n[r];di(i)||li(e,i,t[i])}}function di(e){return e===`__proto__`||e===`constructor`||e===`prototype`}function fi(e,t){if(typeof t==`function`&&(t=t(e)),t=ni(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&&li(e,n,r)}li(e,`length`,r)}else ui(e,t)}function pi(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&&di(r)))return;if(Array.isArray(r)){for(let i=0;i<r.length;i++)pi(e,[r[i]].concat(t),n);return}if(o&&a===`function`){for(let i=0;i<e.length;i++)r(e[i],i)&&pi(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)pi(e,[r].concat(t),n);return}if(t.length>1){pi(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=ni(a),r===void 0||ti(i)&&ti(a)&&!Array.isArray(a)?ui(i,a):li(e,r,a))}function mi(...[e,t]){let n=ni(e||{}),r=Array.isArray(n),i=ei(n);function a(...e){De(()=>{r&&e.length===1?fi(n,e[0]):pi(n,e)})}return[i,a]}var hi=Symbol(`store-root`);function gi(e){return e===`__proto__`||e===`constructor`||e===`prototype`}function _i(e,t,n,r,i){if(gi(n))return;let a=t[n];if(e===a)return;let o=Array.isArray(e);if(n!==hi&&(!ti(e)||!ti(a)||o!==Array.isArray(a)||i&&e[i]!==a[i])){li(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++)_i(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++)li(a,n,e[n]);for(;n<e.length;n++)li(a,n,f[n]),_i(e[n],a,n,r,i);a.length>e.length&&li(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?(li(a,n,f[n]),_i(e[n],a,n,r,i)):li(a,n,e[n])}else for(let t=0,n=e.length;t<n;t++)_i(e[t],a,t,r,i);a.length>e.length&&li(a,`length`,e.length);return}let s=Object.keys(e);for(let t=0,n=s.length;t<n;t++)gi(s[t])||_i(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&&li(a,c[t],void 0)}function vi(e,t={}){let{merge:n,key:r=`id`}=t,i=ni(e);return e=>{if(!ti(e)||!ti(i))return i;let t=_i(i,{[hi]:e},hi,n,r);return t===void 0?e:t}}var yi=new WeakMap,bi={get(e,t){if(t===Xr)return e;let n=e[t];if(t===Ke||t===ae||t===Zr||t===Qr||t===`__proto__`)return n;let r;return ti(n)?yi.get(n)||(yi.set(n,r=new Proxy(n,bi)),r):n},set(e,t,n){return li(e,t,ni(n)),!0},deleteProperty(e,t){return li(e,t,void 0,!0),!0}};function xi(e){return t=>{if(ti(t)){let n;(n=yi.get(t))||yi.set(t,n=new Proxy(t,bi)),e(n)}return t}}var Si={blocked:0,working:1,error:2,idle:3},Ci=e=>Si[e]??3,wi=e=>String(e??``).replace(/(.)[\\/]+$/,`$1`);function Ti(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 Si?e.state:`idle`}function Ei(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 Di(e){let t=`idle`;for(let n of e)Ci(n)<Si[t]&&(t=n);return t}function Oi(e){if(!e)return;if(e.kind===`thinking`)return`Thinking…`;let t=e.tool||`tool`;return e.summary?`${t} · ${e.summary}`:t}function ki(e){return String(e??``).normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase()}var Ai=e=>ki(e).split(/\s+/).filter(Boolean);function ji(e,t){let n=Ai(t);if(!n.length)return!0;let r=[e.title||`Untitled`,e.projectName,e.project,e.directory].filter(Boolean).map(ki);return n.every(e=>r.some(t=>t.includes(e)))}function Mi(e,t){let n=wi(e),r=wi(t);return n===r?``:n.startsWith(`${r}/`)?n.slice(r.length+1):n}var Ni=e=>String(e??``).replace(/(.)[\\/]+$/,`$1`),Pi=e=>Ni(e).split(/[\\/]/).pop()||String(e??``),Fi=[`hiddenSessions`,`hiddenWorkspaces`,`pinnedSessions`,`pinnedWorkspaces`],Ii=500,Li=5e3,Ri=4096,zi=e=>e===`hiddenSessions`?Li:Ii,Bi=(e,t=Ii)=>{if(!Array.isArray(e))return[];let n=[...new Set(e.filter(e=>typeof e==`string`&&e.length>0&&e.length<=Ri))];return n.length>t?n.slice(n.length-t):n};function Vi(e){let t=e,n=t&&typeof t==`object`&&t.prefs&&typeof t.prefs==`object`?t.prefs:e??{};return Object.fromEntries(Fi.map(e=>[e,Bi(n[e],zi(e))]))}function Hi(e){let t=e.trim();return t?t.length>200?{error:`Title is longer than 200 characters`}:{title:t}:{error:`Enter a title`}}function Ui(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 Wi=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=Gi(e,n);a===r||t-i>this.graceMs?this.pending.delete(n):a!==void 0&&Ui(e,n,r)}}},Gi=(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 Ki(e,t,n,r){if(!Fi.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?Bi([...i,...o],zi(t)):i.filter(e=>!o.has(e));return{prefs:{...e,[t]:s},patch:{[t]:s}}}var qi=e=>{try{let t=JSON.parse(e??`null`);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}};function Ji(e,t,n){let r=e!=null||t!=null,i={};for(let[r,a]of[[`pinnedSessions`,e],[`pinnedWorkspaces`,t]]){let e=n[r]??[],t=qi(a).filter(t=>!e.includes(t));t.length&&(i[r]=Bi([...e,...t]))}return{clear:r,patch:Object.keys(i).length?i:void 0}}var Yi={working:`working`,blocked:`blocked`};function Xi(e){let t=Ti(e);return Di([t,e?.terminal?.status===`blocked`&&t!==`blocked`?`working`:Yi[e?.terminal?.status??``]??`idle`])}function Zi(e){return e?.terminal?.status===`blocked`&&Ti(e)!==`blocked`}var Qi=e=>!!e?.open&&e.terminal?.source===`herdr`&&!!e.terminal.workspaceID,$i=e=>Ni(e?.project||e?.directory);function ea(e){return Qi(e)?`herdr:${e.terminal.workspaceID}`:$i(e)}var ta=(e,t)=>$i(e)===t||Ni(e.directory)===t||Qi(e)&&ea(e)===t;function na(e,t){if(t.sessions.has(e.id))return!0;for(let n of t.workspaces)if(ta(e,n))return!0;return!1}function ra(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 ia(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?ra(e,t):t)}return[...r.values()]}function aa(e){let t=oa(e);return e=>na(e,t)}var oa=e=>({sessions:new Set(e?.hiddenSessions??[]),workspaces:new Set(e?.hiddenWorkspaces??[])}),sa=e=>e?.terminals?.herdr?.workspaces??[];function ca(e){let t=Ni(e.project||e.directory),n=e.project?Mi(e.directory,t):``;return`${e.projectName||Pi(t)}${n?` › ${n}`:``}`}function la(e,t,n){let r=ca(t),i=n?.trim()||void 0;return{machine:e,where:r,...i?{branch:i}:{},text:[e,r,i].filter(Boolean).join(` · `)}}function ua(e,t,n){let r=Qi(e)?e.terminal.workspace||sa(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:Xi(e),waitingInTerminal:Zi(e),blockers:Ei(e),exposed:e.exposed!==!1,pinned:n.has(e.id),nowText:Oi(e.now),where:ca(e),workspace:r??(e.projectName||Pi($i(e))),machineID:t?.id}}var da=50,fa=200;function pa(e){let t=sa(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(Ni))),r=ia(e),i=new Map,a=new Map;for(let e of r){let t=Ni(e.directory);t&&(i.set(t,Math.max(i.get(t)??0,e.updated??0)),a.set(t,ca(e)))}for(let e of r){let t=Ni(e.project);if(!t||a.has(t))continue;let n=Math.max(...r.filter(e=>Ni(e.project)===t).map(e=>e.updated??0));i.set(t,n),a.set(t,e.projectName||Pi(t))}let o=[...i.entries()].filter(([e])=>!n.has(e)).sort((e,t)=>t[1]-e[1]).slice(0,da).map(([e])=>({kind:`folder`,key:e,label:a.get(e)??Pi(e),directories:[e]}));return{herdr:!!e?.terminals?.herdr,targets:[...t,...o]}}function ma({target:e,directory:t,title:n,openInHerdr:r}){let i={directory:t},a=String(n??``).trim().slice(0,fa);return a&&(i.title=a),r&&e?.kind===`herdr`&&e.workspaceID&&(i.herdrWorkspace=e.workspaceID),i}function ha(e){if(typeof e==`string`&&e)return e.includes(`budget`)?`Quota exceeded`:ga[e]}var ga={"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 _a(e){return typeof e==`number`&&Number.isInteger(e)&&e>=100&&e<=999?`HTTP ${e}`:void 0}function va(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 ya=e=>typeof e==`string`&&e.trim()?e.trim():void 0,ba=(e,t)=>e.toLowerCase()===t.toLowerCase(),xa=(e,t)=>e&&t&&!ba(e,t)?t:void 0;function Sa(e){let t=ha(e.errorType),n=ya(e.message),r=_a(e.errorStatus),i=xa(t,n);return`${t??n??`Error`}${r?` (${r})`:``}${i?`: ${i}`:``}`}function Ca(e,t){let n=typeof e.attempt==`number`?` (attempt ${e.attempt})`:``,r=va(e.next,t),i=ha(e.errorType),a=ya(e.message),o=xa(i,a),s=i?o?`${i} — ${o}`:i:a;return`Retrying${n}${r?` · next in ${r}`:``}${s?`: ${s}`:``}`}var wa=e=>!!e&&typeof e==`object`&&typeof e.id==`string`;function Ta(e,t){let n=Array.isArray(e)?e.filter(wa):[],r=t?n.find(e=>e.id===t):n[0];if(!r)return;if(r.state===`error`)return Ea(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?Ea(a):void 0}function Ea(e){let t=ya(e.detail),n=_a(e.errorStatus),r=ya(e.title);return{sessionID:e.id,...r?{title:r}:{},label:ha(e.errorType)??t??`Error`,...t?{message:t}:{},...n?{status:n}:{},text:Sa({errorType:e.errorType,errorStatus:e.errorStatus,message:t})}}var Da=e=>Array.isArray(e)?e:[];function Oa(e){return Da(e).flatMap(e=>(Array.isArray(e.jobs)?e.jobs:[]).map(t=>({...t,sessionID:e.id,sessionTitle:e.title??``})))}function ka(e){return Oa(e).filter(e=>e.status===`running`).length}function Aa(e,t){let n=Oa(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 ja(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 Ma(e,t){if(e.status===`running`)return e.started===void 0?`running`:`running · ${ja(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?ja(e.ended-e.started):void 0;return n?[n,r].filter(Boolean).join(` · `):[r??`ended`,i].filter(Boolean).join(` · `)}function Na(e){return e<=0?``:`${e} job${e===1?``:`s`}`}function Pa(e,t,n=Date.now()){let r=Da(e),i=(t?r.find(e=>e.id===t&&e.retry):void 0)??r.find(e=>e.retry);return i?.retry?Ca(i.retry,n):void 0}function Fa(e,t,n,r=new Set){let i=new Set(t.pinnedSessions),a=new Set(t.hiddenSessions),o=aa(t),s=[];for(let t of e??[])for(let e of ia(t)){if(r.has(e.id))continue;let c=ua(e,t,i),l=c.open?c.terminal?.source===`herdr`?`herdr`:`tui`:`background`,u=n[c.id],d=c.state===`working`?Pa(e.status,void 0,1/0):void 0,f=c.state===`error`?Ta(e.status,c.id)?.text??`Error`:void 0;s.push({...c,machineName:t.name,machineOnline:!!t.online,source:l,running:c.state===`working`||c.state===`blocked`,hidden:o(e),archived:a.has(c.id),unread:u!==void 0&&c.updated>u,group:ea(e),jobs:ka(e.status),...d?{retry:d}:{},...f?{error:f}:{}})}return s.sort((e,t)=>t.updated-e.updated)}function Ia(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 La=Object.freeze({query:``,filters:Object.freeze({status:`all`,source:`all`,machine:``,archived:!1}),sort:Object.freeze({key:`activity`,dir:`desc`})}),Ra=[`status`,`title`,`project`,`server`,`source`,`activity`],za=[`all`,`needs`,`running`,`idle`],Ba=[`all`,`open`,`background`],Va=(e,t)=>e.localeCompare(t,void 0,{sensitivity:`base`}),Ha=(e,t)=>t.updated-e.updated,Ua={status:(e,t)=>Si[e.state]-Si[t.state]||Ha(e,t),title:(e,t)=>Va(e.title,t.title)||Ha(e,t),project:(e,t)=>Va(e.workspace,t.workspace)||Ha(e,t),server:(e,t)=>Va(e.machineName,t.machineName)||Ha(e,t),source:(e,t)=>Va(e.source,t.source)||Ha(e,t),activity:(e,t)=>e.updated-t.updated};function Wa(e,t){let n=t.status===`needs`&&e.state===`blocked`;return!((t.archived?!e.hidden:e.hidden&&!n)||t.status===`needs`&&!Xa(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 Ga(e,t){if(!t.trim()||ji(e,t))return!0;let n=ki(t).split(/\s+/).filter(Boolean),r=[e.title,e.workspace,e.where,e.directory,e.machineName].map(ki);return n.every(e=>r.some(t=>t.includes(e)))}function Ka(e,t){let n=Ua[t.sort.key],r=t.sort.key===`activity`?t.sort.dir===`desc`?-1:1:t.sort.dir===`asc`?1:-1;return e.filter(e=>Wa(e,t.filters)&&Ga(e,t.query)).sort((e,t)=>r*n(e,t))}var qa=(e,t,n)=>t.includes(e)?e:n;function Ja(e){let t;try{if(t=JSON.parse(e??`null`)??{},typeof t!=`object`||Array.isArray(t))return La}catch{return La}let n=t.filters??{},r=t.sort??{},i=La,a=qa(r.key,Ra,i.sort.key),o=a===r.key?qa(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:qa(n.status,za,i.filters.status),source:qa(n.source,Ba,i.filters.source),machine:typeof n.machine==`string`&&n.machine.length<=200?n.machine:``,archived:n.archived===!0||n.hidden===!0},l=Object.keys(c).every(e=>c[e]===i.filters[e]);return l&&s===i.sort?La:{query:``,filters:l?i.filters:c,sort:s}}function Ya(e){return JSON.stringify({filters:e.filters,sort:e.sort})}var Xa=e=>e.state===`blocked`||e.state===`error`&&!e.hidden;function Za(e,{query:t,groupBy:n,sortBy:r,recentLimit:i=20}){let a=e.filter(e=>!e.hidden),o=e.filter(Xa),s=r===`title`?(e,t)=>Va(e.title,t.title)||Ha(e,t):Ha;if(t.trim())return[{id:`results`,title:`Results`,kind:`results`,rows:a.filter(e=>Ga(e,t)).sort(Ha)}];let c=new Set,l=e=>{for(let t of e)c.add(t.id);return e},u=[],d=e=>e.rows.length&&u.push(e);d({id:`needs`,title:`Needs you`,kind:`needs`,rows:l(o.sort(Ha))}),d({id:`running`,title:`Running`,kind:`running`,rows:l(a.filter(e=>!c.has(e.id)&&e.running).sort(Ha))}),d({id:`pinned`,title:`Pinned`,kind:`pinned`,rows:l(a.filter(e=>!c.has(e.id)&&e.pinned).sort(s))});let f=new Map;for(let e of a){if(c.has(e.id)||!e.open)continue;let t=n===`machine`?e.machineID:`${e.machineID}\u0000${e.group}`,r=f.get(t);r||(r={title:n===`machine`?e.machineName:e.workspace,key:n===`machine`?e.machineID:e.group,machineID:e.machineID,directory:e.directory,rows:[]},f.set(t,r)),r.rows.push(e)}let p=e=>Math.max(...e.map(e=>e.updated)),m=[...f.values()].sort((e,t)=>r===`title`&&Va(e.title,t.title)||p(t.rows)-p(e.rows));for(let e of m){e.rows.sort(s),l(e.rows);let t=[...e.rows].sort(Ha);d({id:`group:${e.machineID}:${e.key}`,title:e.title,kind:`group`,key:e.key,machineID:e.machineID,directory:t[0].directory,rows:e.rows})}return d({id:`recents`,title:`Recents`,kind:`recents`,rows:a.filter(e=>!c.has(e.id)).sort(Ha).slice(0,i)}),u}var Qa=864e5;function $a(e,t,n){if(!Number.isInteger(t)||t<1)return[];let r=n-t*Qa;return e.filter(e=>!e.hidden&&!e.running&&!e.pinned&&!e.open&&e.updated<r)}function eo(e,t){return t.phase!==`off`&&t.sessionID===e.id||e.conversation===!0}function to(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 no=.75,ro=.05;function io(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/ro)/Math.round(1/ro);return Math.min(2,Math.max(no,Number(n.toFixed(2))))}function ao(e){let t=io(e);return`${Number.isInteger(t)?t.toFixed(1):String(t)}×`}var oo={working:`working`,blocked:`blocked`,error:`failed`,idle:`done`},so=160,co=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(`
|
|
10
|
-
`).map(e=>e.trim()).filter(Boolean).at(-1);a&&(i.line=a.length>so?`…${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=oo[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`:uo(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 uo(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 ${uo(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 lo(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 uo(e){if(e.kind===`thinking`)return`Thinking…`;let t=e.tool||`tool`;return e.summary?`${t} · ${e.summary}`:t}var fo=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 po(){let e=Object.values(fo),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 mo=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=fo[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}},ho=class{ackMs;quietMs;stillMs;enabled=!0;busy=!1;awaiting;pendingSubagent=!1;lastSay=-1/0;lastSpoke=-1/0;user=!1;agent=!1;cue=!1;pick;constructor({ackMs:e=2500,quietMs:t=3e3,stillMs:n=4e4,pick:r}={}){if(!r){let e=new mo;r=t=>e.pick(t)}this.pick=r,this.ackMs=e,this.quietMs=t,this.stillMs=n}get gated(){return this.user||this.agent||this.cue}heard(e,{tone:t=!0}={}){return this.awaiting=Math.min(this.awaiting??e,e),t&&this.enabled&&!this.user?[{type:`earcon`,name:`heard`}]:[]}awaitReply(e){this.awaiting=e}speechEnded(e){return this.userTalking(!1,e),this.enabled?[{type:`earcon`,name:`heard`}]:[]}working(e,t){e&&!this.busy&&(this.lastSpoke=Math.max(this.lastSpoke,t)),e||(this.awaiting=void 0,this.pendingSubagent=!1),this.busy=e}agentSaid(e){this.lastSay=e,this.spoke(e)}agentSpeaking(e,t){this.agent=e,this.spoke(t)}userTalking(e,t){this.user=e,e||(this.lastSpoke=Math.max(this.lastSpoke,t))}cueSpeaking(e,t){this.cue=e,e||(this.lastSpoke=Math.max(this.lastSpoke,t))}subagentStarted(e){e-this.lastSay>=this.quietMs&&(this.pendingSubagent=!0)}subagentFinished(e){return this.enabled&&!this.user?[{type:`earcon`,name:`done`}]:[]}nextDue(e){if(this.enabled&&!this.gated){if(this.pendingSubagent)return e;if(this.busy)return Math.min(this.awaiting===void 0?1/0:this.awaiting+this.ackMs,this.lastSpoke+this.stillMs)}}tick(e){return!this.enabled||this.gated?[]:this.pendingSubagent?this.say(`subagent`,e):this.awaiting!==void 0&&this.busy&&e-this.awaiting>=this.ackMs?this.say(`working`,e):this.busy&&e-this.lastSpoke>=this.stillMs?this.say(`still`,e):[]}spoke(e){this.awaiting=void 0,this.pendingSubagent=!1,this.lastSpoke=Math.max(this.lastSpoke,e)}say(e,t){return this.spoke(t),[{type:`speak`,cue:e,text:this.pick(e)}]}},go=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}},_o=new Set([`working`,`blocked`]);function vo(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`&&!_o.has(t??``)?i.push(e.id):_o.has(t??``)&&!_o.has(e.state)&&a.push(e.id)}for(let[e,t]of r)_o.has(t)&&a.push(e);return{started:i,finished:a}}function yo(e){return(e??[]).some(e=>e.state===`working`)}var bo=Object.freeze([`openrouter`,`openai-compatible`]),xo={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(xo[n].map(e=>[e,So(r[e])])),t[n].apiKey={action:`keep`,value:``}}return t}function wo(e,t){let n={};for(let r of[`stt`,`tts`]){let i=e?.[r]??{},a=t[r],o={};for(let e of xo[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 To(e){let t={};for(let n of[`stt`,`tts`]){let r=e[n],i=(e,r)=>t[`${n}.${e}`]=r;if(bo.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 Eo(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 Do=/^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i;function Oo(e,t){if(!e||e.stt&&e.tts)return;let n=!1;try{n=Do.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 ko=()=>({machines:void 0,reads:{},prefs:Vi({}),prefsSource:`unknown`,prefsPending:0,prefsStale:!1,connection:`connecting`,enrollmentRev:0}),Ao=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function jo(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 Mo(e,t){if(!Ao(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 jo(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 jo(e.machines,t.sessionID,e=>{e.conversation=t.on,n=!0}),n}case`reads`:return Ao(t.reads)?(e.reads=Object.fromEntries(Object.entries(t.reads).filter(e=>typeof e[1]==`number`)),!0):!1;case`prefs`:return e.prefsSource===`hub`?e.prefsPending?(e.prefsStale=!0,!0):(e.prefs=Vi(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 No(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??Po(e,t)}function Po(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=Fo(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 Fo(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 Io(e){return(e??[]).some(e=>e.state===`working`||e.state===`blocked`)}var Lo=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 co(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(!Ao(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 Ao(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 Ro(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 zo=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=Ro(e)===Ro(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(Ro(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 Bo(e,t){return t===`scope`&&e===`live`?{connection:`live`,reconnecting:!1}:{connection:`connecting`,reconnecting:e!==`connecting`}}var Vo=e=>e===`app:concierge`||e===`app concierge`,Ho=/^(ses_[A-Za-z0-9]+)(?: \(sub ses_[A-Za-z0-9]+\))? (.*)$/,Uo=/^[!+-] (.*)$/,Wo=/^… (\d+) more updates not listed$/,Go=2,Ko={permission:`needs a permission`,question:`has a question`};function qo(e,t){let n=/^machine \S+ (online|offline)$/.exec(e);if(n)return`a machine went ${n[1]}`;let r=Ho.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} ${Ko[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 Jo(e,t){if(typeof e!=`string`)return;let[n=``,...r]=e.split(`
|
|
11
|
-
`),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=Wo.exec(e);n&&(o+=Number(n[1]));let r=Uo.exec(e);r&&(a.length<Go?a.push(qo(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 Yo=60,Xo=/(`[^`]*`|\]\([^)]*\)|<[a-z][a-z0-9+.-]*:[^>\s]*>|\b[a-z][a-z0-9+.-]*:\/\/[^\s<>()]+)|(?<![\w#/[(])((?:Decision )?)(dec_[A-Za-z0-9]{1,64})(?!\w)/g,Zo=e=>{let t=Intl.Segmenter;return t?Array.from(new t(void 0,{granularity:`grapheme`}).segment(e),e=>e.segment):Array.from(e)},Qo=e=>{let t=e.replace(/\s+/g,` `).trim(),n=Zo(t);return n.length>Yo?`${n.slice(0,59).join(``)}…`:t};function $o(e){if(!e.includes(`dec_`))return[];let t=new Set;for(let n of e.matchAll(Xo))!n[1]&&n[3]&&t.add(n[3]);return[...t]}function es(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(Xo)){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 “${Qo(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 ts(e,t,n={}){return es(e,t,n).map(e=>e.href?`[${ns(e.text)}](${e.href})`:e.text).join(``)}var ns=e=>e.replace(/[\\`*_[\]<>~=]/g,`\\$&`);function rs(e,t){return e.replace(/(?<![\w/])ses_[A-Za-z0-9]{1,64}(?!\w)/g,e=>t(e)??e)}function is(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===`timeout`?`Answered “${n}” when it timed out`:`You answered “${n}”`}var as=2e3,os=6e4,ss=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(as*2**(t-1),os)})}return}finally{this.running--,this.asking.delete(e),this.queue.shift()?.()}}};function cs(e,t){let n=new Set;for(let r of e)if((r.type===`assistant`?r.live!==!0:r.type===`message`&&!r.primer&&!Vo(r.from))&&typeof r.text==`string`)for(let e of $o(r.text))t.has(e)||n.add(e);return[...n]}var ls=new Set([`disabled`,`starting`,`running`,`waiting_machine`,`backoff`,`failed`,`stopping`]),us=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ds=e=>typeof e==`string`,fs=e=>typeof e==`number`&&Number.isFinite(e);function ps(e){if(us(e)&&ds(e.state)&&ls.has(e.state))return{state:e.state,...ds(e.reason)?{reason:e.reason.slice(0,200)}:{},...ds(e.sessionID)?{sessionID:e.sessionID}:{},hiddenSessionIDs:Array.isArray(e.hiddenSessionIDs)?e.hiddenSessionIDs.filter(ds):[],...ds(e.launchID)?{launchID:e.launchID}:{},...ds(e.machineID)?{machineID:e.machineID}:{},generation:fs(e.generation)?e.generation:0,since:fs(e.since)?e.since:0,...fs(e.nextAttemptAt)?{nextAttemptAt:e.nextAttemptAt}:{}}}function ms(e){if(!us(e)||!us(e.settings))return;let t=ps(e.status);if(!t)return;let n=Array.isArray(e.machines)?e.machines.filter(us).filter(e=>ds(e.id)&&ds(e.name)).map(e=>({id:e.id,name:e.name,eligible:e.eligible===!0,online:e.online===!0,...ds(e.reason)?{reason:e.reason}:{},roots:Array.isArray(e.roots)?e.roots.filter(ds):[]})):[];return{settings:e.settings,status:t,machines:n}}function hs(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 gs=4e3,_s=(e,t,n)=>e||t&&n;function vs(e,t,n,r,i,a){return hs(t,r,a).has(e)?`concierge`:!n||i===!1&&!ys(e,r)?`wait`:`session`}var ys=(e,t)=>(t??[]).some(t=>(t.processes??[]).some(t=>(t.sessions??[]).some(t=>t.id===e))),bs=e=>`concierge.hidden.${e??`local`}`;function xs(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 Ss(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 Cs=e=>e<6e4?`${Math.max(1,Math.ceil(e/1e3))} s`:`${Math.ceil(e/6e4)} min`;function ws(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 ${Cs(e.nextAttemptAt-n)}`;case`failed`:return`Failed${e.reason?`: ${e.reason}`:``}`;case`stopping`:return`Stopping`}}function Ts(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 Es=(e,t)=>{let n=t.replace(/\/+$/,``);return e===n||e.startsWith(`${n}/`)};function Ds(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=>Es(e.directory,t)))return`The directory must be under one of ${n.name}'s workspace roots: ${n.roots.join(`, `)}`}var Os=e=>({allow:[`answer`,`deny`,`approve`],projects:[...e],permissions:{allow:[`read`,`edit`],never:[`shell:git push*`,`shell:rm *`]},allowAlways:!1,expires:`7d`,maxActionsPerHour:60}),ks=[`answer`,`deny`,`approve`,`stop`,`prompt`];function As(e,t){let n=e??Os(t?[t]:[]);return{projects:[...n.projects],allow:[...n.allow],permit:n.permissions.allow.join(`
|
|
12
|
-
`),never:n.permissions.never.join(`
|
|
13
|
-
`),expires:n.expires,maxActionsPerHour:String(n.maxActionsPerHour)}}var js=e=>e.split(`
|
|
14
|
-
`).map(e=>e.trim()).filter(Boolean),Ms=/^(\d+)(h|d)$/;function Ns(e){let t={},n=[...new Set(e.projects.map(e=>e.trim()).filter(Boolean))];n.length||(t.projects=`Pick at least one project`),ks.filter(t=>e.allow.includes(t)).length||(t.allow=`Pick at least one action`);let r=e.expires.trim(),i=Ms.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=>ks.includes(e)),projects:n,permissions:{allow:js(e.permit),never:js(e.never)},allowAlways:!1,expires:r,maxActionsPerHour:s}}}function Ps(e){let t=js(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 Fs(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 Is(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 Ls(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 Rs(e,t){let n=er(e,t);return n?`expires in ${n}`:`expired`}var zs=[`machineID`,`directory`,`model`,`grant`,`connectors`,`timeZone`,`quietHours`,`quietAllowsUrgent`,`digests`];function Bs(e,t){let n={};for(let r of zs)JSON.stringify(e[r])!==JSON.stringify(t[r])&&(n[r]=t[r]===void 0?null:t[r]);return{...n,expectedRevision:e.revision}}var Vs=`__other__`,Hs=e=>(e??``).replace(/\/+$/,``);function Us(e,t){if(!e)return{projects:[],roots:[]};let n=[...new Set(e.roots.map(Hs).filter(Boolean))],r=(t??[]).find(t=>t.id===e.id)?.processes.flatMap(e=>e.sessions.map(e=>Hs(e.project)||Hs(e.directory)))??[],i=[...new Set(r)].filter(e=>e.startsWith(`/`)&&(!n.length||n.some(t=>Es(e,t)))).sort();return{projects:i,roots:n.filter(e=>!i.includes(e))}}function Ws(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(Hs).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 Gs=(e,t)=>e?t.includes(e)?e:Vs:``;function Ks(e,t,n,r){if(e.machineID===t.id)return e;let{projects:i,roots:a}=Us(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 qs=(e,t)=>e.model!==void 0&&!t.includes(e.model)?{...e,model:void 0}:e,Js=/^[A-Za-z0-9._-]{1,80}\/[!-~]{1,200}$/;function Ys(e){let t=us(e)&&Array.isArray(e.models)?e.models:[],n=new Map;for(let e of t){if(!us(e)||!ds(e.providerID)||!ds(e.modelID)||e.enabled===!1)continue;let t=`${e.providerID}/${e.modelID}`;Js.test(t)&&!n.has(t)&&n.set(t,{value:t,label:ds(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 Xs(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 Zs=new Set([`yes`,`approve`,`go ahead`,`do it`]),Qs=new Set([`no`,`deny`,`don't`,`dont`,`hold`]),$s=new Set([`um`,`umm`,`uh`,`uhm`,`uhh`,`er`,`erm`,`hm`,`hmm`,`ah`,`please`]),ec=80;function tc(e){if(typeof e!=`string`||e.length>ec||/[??]/.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&&$s.has(t[n]);)n++;for(;r>n&&$s.has(t[r-1]);)r--;let i=t.slice(n,r).join(` `);if(Zs.has(i))return`yes`;if(Qs.has(i))return`no`}function nc(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 rc(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 ic(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 ac(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 oc(e,t){if(!t||t.tier!==`confirm`||t.state!==`open`)return{kind:`speech`};let n=tc(e),r=n&&ac(t,n);return n&&r?{kind:`answer`,decisionID:t.id,option:r,intent:n}:{kind:`speech`}}var sc=60;function cc(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>sc?`${n.slice(0,59).join(``)}…`:n.join(``)}” by text: ${e.options.find(e=>e.id===t)?.label??t}`}var lc=e=>e&&e.state!==`disabled`?!0:`hidden`,uc={starting:`starting`,backoff:`restarting soon`,waiting_machine:`waiting for its machine`,stopping:`stopping`};function dc(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 (${uc[e.state]}${c})`,s?`attention`:`busy`];return{label:l,title:`${l} — ${n?`close`:`open`} it`,indicator:u,...i>0?{count:s}:{}}}var fc=e=>e?`Ask what needs you, or start Voice and talk.`:`Ask what needs you.`,pc=e=>`${e?`Say or type`:`Type`} “yes” or “no” (or tap). Anything else goes to the Concierge.`,mc=`The Concierge is off. Turn it on in Settings → Concierge.`;function hc(e,t){if(!e||e.state===`disabled`)return mc;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 gc(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=oc(a,t.armed());return o.kind===`speech`?e(r,i):(await t.answer(o.decisionID,o.option),Response.json({inboxID:`decision:${o.decisionID}`}))}}var _c=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function vc(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 yc(e,t,n){return n===void 0||!e||e.sessionID===t.sessionID?n:null}function bc(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=it(n,e))}return n}function xc(e,t){if(e&&e.expiresAt!==void 0)return Math.max(0,e.expiresAt-t)}function Sc(e,t){return e&&e.expiresAt!==void 0&&e.expiresAt<=t?null:e}var Cc=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 wc(e,t,n){return ic(e,t,{tiers:`all`}).filter(e=>e.id!==n?.id)}var Tc=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 Ec(e){let t=e.find(e=>e.focused);return t?.visible?t:void 0}function Dc(e,t=lt){let n=[],r=Ec(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 Oc(e,t,n){let r=t.length?Dc(t):n?[n]:[],[i]=r;return i?r.length>1?{lite:e,session:i,sessions:r}:{lite:e,session:i}:{lite:e}}function kc(e,t,n=lt){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 Ac(e){return Ec(e)?.sessionID}function jc(e,t){return Ec(e)?.paneID===t}var Mc=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}},[Nc,Pc]=x(0),Fc=new Tc(()=>Pc(e=>e+1));function Ic(){return Nc(),Fc.views()}var Lc=()=>Ac(Ic()),Rc=(e,t)=>Oc(e,Ic(),t);function zc(e,t=()=>!0){let n=Fc.register(e,t);return{paneID:n,focus:()=>void Fc.focus(n),takesInput:()=>jc(Ic(),n),streamed:()=>Gc(e),release:()=>Fc.release(n)}}var Bc=new Mc,[Vc,Hc]=x(0);function Uc(e){Bc.opened(e),Hc(e=>e+1)}function Wc(e){Bc.message(e)&&Hc(e=>e+1)}function Gc(e){return Vc(),Bc.covers(e)}var Kc=`x-hub-recording`,qc=`x-hub-segment`,Jc=`x-hub-tts-ref`,Yc=`x-hub-recording-audio`,Xc={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},J=(e,t=[])=>({required:e,optional:t}),Zc={state:J([`state`]),detector:J([`mode`],[`avgMs`]),"speech.start":J([`bargeIn`]),"speech.end":J([`segment`,`durationMs`,`speechMs`,`forced`]),"segment.closed":J([`segment`,`bytes`,`durationMs`,`speechMs`,`forced`]),"stt.sent":J([`segment`,`bytes`]),"stt.received":J([`segment`,`text`],[`junk`,`empty`,`failed`,`audio`]),"utterance.held":J([`text`]),"utterance.merged":J([`segments`,`pauseMs`]),"utterance.sent":J([`text`,`segments`,`reason`,`holdMs`]),"utterance.accepted":J([`inboxID`]),"utterance.failed":J([`message`],[`status`]),"utterance.command":J([`command`,`text`]),heard:J([`inboxID`]),"say.received":J([`messageID`,`ordinal`,`chars`,`sentences`,`muted`],[`seq`]),"tts.sentence.queued":J([`ref`,`text`]),"tts.request":J([`ref`]),"tts.first.byte":J([`ref`]),"tts.sentence.played":J([`ref`]),"tts.sentence.ended":J([`ref`,`playedMs`,`completed`],[`durationMs`]),"barge.in":J([`cause`,`spoken`,`unplayed`,`mutedMessages`],[`playing`]),"cue.played":J([`cue`],[`name`,`text`]),mic:J([`live`],[`reason`]),control:J([`action`],[`on`]),"turn.timing":J([`firstAudio`],[`speechEnd`,`transcript`,`accepted`,`firstSay`,`firstByte`]),"decision.voice":J([`decisionID`,`option`,`outcome`]),"clock.sync":J([`t0`,`t1`,`hubAt`]),error:J([`where`,`message`])},Qc=Xc,$c={"stt.received":{text:Qc.textChars,failed:Qc.messageChars},"utterance.held":{text:Qc.utteranceChars},"utterance.sent":{text:Qc.utteranceChars},"utterance.failed":{message:Qc.messageChars},"utterance.command":{text:Qc.utteranceChars},"tts.sentence.queued":{text:Qc.textChars},"cue.played":{text:Qc.textChars},error:{message:Qc.messageChars}};function el(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 tl(e,t){let n=Zc[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=$c[e]?.[i];r[i]=t!==void 0&&typeof a==`string`?el(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:el(e.text,Qc.textChars)}),t=r.spoken;r.spoken={text:el(t.text,Qc.replyChars),estimated:t.estimated},r.playing&&=e(r.playing),r.unplayed=r.unplayed.slice(0,il).map(e),r.mutedMessages=r.mutedMessages.slice(0,il)}return r}var nl=e=>`${e.messageID}:${e.ordinal}:${e.seq??``}:${e.i}`;function rl(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 il=20,al=14;function ol(e,t,n){let r=n&&n>0?n:e.length/al*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 sl(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(ol(r.text,r.playedMs,r.durationMs)),tl(`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 cl(e,t){return(e===200||e===201)&&typeof t?.recording?.id==`string`?{kind:`started`,recording:t.recording,audio:t.audio!==!1,...typeof t.hubAt==`number`?{hubAt:t.hubAt}:{}}: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??Qc.activePerUser} recordings are already running`}:e===429&&t?.code===`limit`?{kind:`failed`,reason:`${t.limit??Qc.recordingsStored} recordings stored; delete some in Settings → Voice`}:{kind:`failed`,reason:typeof t?.error==`string`&&t.error?t.error:`HTTP ${e}`}}var ll=new TextEncoder,ul=e=>ll.encode(e).length,dl=ul(`{"events":[]}`),fl=e=>e.kind===`clock.sync`,pl=e=>Math.max(0,Math.round(e*10)/10);function ml(e,t){let n=[],r=dl;for(let i of e){if(n.length&&i.seq!==n[n.length-1].seq+1)break;let e=ul(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+ul(JSON.stringify(o))<=t&&n.push(o),n}var hl=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={...Xc,...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=pl(this.now()),i={...e,seq:n,t:r},a=ul(JSON.stringify(i));for(dl+a>this.limits.batchBytes&&(i={seq:n,t:r,kind:`error`,where:`upload`,message:`event too large: ${e.kind}`},a=ul(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&&!fl(i)&&this.scheduled(),n}open(e){this.stopped||this.ready||(this.ready=!0,e&&this.record(tl(`clock.sync`,e)),this.pending.some(e=>!fl(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=ml(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(!fl(this.pending[e].e))return this.pending[e].e.seq;let e=this.batch??[];for(let t=e.length-1;t>=0;t--)if(!fl(e[t]))return e[t].seq;return 0}activePending(){let e=0;for(let t of this.pending)fl(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=dl;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=>!fl(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(tl(`clock.sync`,{t0:pl(t),t1:pl(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(tl(`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)}},gl=1048576,_l={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 ${Qc.userBytes/gl} MB in all (${Qc.recordingBytes/gl} MB per recording, ${Qc.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.`]};function vl(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 yl=e=>`${vl(e.bytes)} of ${vl(e.capBytes)}`;function bl(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 xl={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 Sl(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 Cl(e,t,n=xl,r=()=>Sl(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)}`,length:i?`${bl(t-e.startedAt)} · recording now`:bl((e.endedAt??t)-e.startedAt),segments:`${e.segments} segment${e.segments===1?``:`s`}`,size:vl(e.bytes),expires:`deleted on ${n.date(e.expiresAt)}`,active:i,...e.audio?{}:{note:`no audio (storage full)`}}}function wl(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 Tl={on:!1,audio:!0},El=wl(Tl),Dl=e=>e.audio?`Recording`:`Recording · no audio (storage full)`,Ol=e=>e.on?` · recording`:``,kl=wl({}),Al=5e3,jl=new Set([`stored`,`skipped-cap`,`failed`,`off`]),Ml=e=>e&&jl.has(e)?e:void 0,Nl=()=>{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)}`},Pl=(e,t=!1)=>({method:`POST`,credentials:`same-origin`,headers:{"content-type":`application/json`},body:JSON.stringify(e),...t?{keepalive:!0}:{}}),Fl;function Il(e){e?.type===`recording`&&(e.settings&&typeof e.settings.enabled==`boolean`&&Ll(e.settings),Fl?.onMessage(e))}function Ll(e){kl.set({supported:!0,settings:e}),e.enabled||Fl?.turnedOff()}function Rl(e,t){Fl?.event(e,t)}var zl=class{fetch;now;epoch;limits;take;running=!1;rolled=!1;sessionID=``;client={};retried=new Set;audio=!0;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 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:rl(n?.userAgent??``),...t},Fl=this,this.indicate(Tl),this.begin()}event(e,t){try{this.take?.uploader.record(tl(e,t))}catch{}}record(e){try{this.take?.uploader.record(e)}catch{}}transcribeHeaders(e){let t=this.recordingID;return t?{[Kc]:t,[qc]:String(e)}:{}}speakHeaders(e){let t=this.recordingID;return t&&e?{[Kc]:t,[Jc]:nl(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,Fl===this&&(Fl=void 0);let n=this.take;this.take=void 0,this.indicate(Tl),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,Al))]),n.uploader.close(),await this.end(n.id,t,!1))))}turnedOff(){let e=this.take;e&&(e.uploader.discard(),this.take=void 0,this.indicate(Tl))}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.state===`deleted`)t.uploader.discard(),this.take=void 0,this.indicate(Tl);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 hl({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()},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 kl.set({supported:!1}),e.uploader.discard();if(n.ok){let{settings:e}=await n.json();e&&kl.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`,Pl({sessionID:this.sessionID,clientID:Nl(),anchor:n,client:this.client}));i=e.status,a=await e.json().catch(()=>({}))}catch{}let o=this.now(),s=cl(i,a);s.kind===`started`?(e.id=s.recording.id,this.audio=s.audio,e.uploader.open(s.hubAt===void 0?void 0:{t0:r,t1:o,hubAt:s.hubAt}),this.take===e&&this.running&&this.indicate({on:!0,audio:this.audio,sessionID:this.sessionID,recordingID:e.id})):(e.uploader.discard(),s.kind===`failed`&&t===!0&&this.take===e&&this.running&&this.onNote?.(`Not recording: ${s.reason}`))}async sendEvents(e,t,n){let r=await this.fetch(`/api/recordings/${encodeURIComponent(e.id??``)}/events`,Pl({events:t},n));return{status:r.status,body:await r.json().catch(()=>({}))}}end(e,t,n){return this.fetch(`/api/recordings/${encodeURIComponent(e)}/end`,Pl({reason:t},n)).then(()=>{},()=>{})}ended(e,t){if(this.take!==e)return;this.take=void 0;let n=t.reason;if(n===`max_duration`&&this.running&&!this.rolled){this.rolled=!0,this.indicate(Tl),this.begin();return}let r=t.code===`limit`||n===`limit`?`Recording stopped: limit reached`:void 0;this.indicate(r?{...Tl,note:r}:Tl),r&&this.onNote?.(r)}audioChanged(e,t){if(this.take!==e||t===this.audio)return;this.audio=t;let n=El.get();n.on&&n.recordingID===e.id&&this.indicate({...n,audio:t})}indicate(e){El.set(e)}};async function Bl(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[Y,Vl]=mi(ko()),Hl=new Lo,[Ul,Wl]=x(0),Gl=Ul,[X,Kl]=x(),[ql,Jl]=x(),[Yl,Xl]=x(),[Zl,Ql]=x([]),[$l,eu]=x([]),[tu,nu]=x(new Map),ru=tu,iu=200;function au(e){e.length&&nu(t=>{let n=new Map(t);for(let t of e)n.delete(t.id),n.set(t.id,t);for(;n.size>iu;)n.delete(n.keys().next().value);return n})}var[ou,su]=x(),[cu,lu]=x(!1),[uu,du]=x(!1),fu=()=>_s(cu(),uu(),Y.machines!==void 0),[pu,mu]=x();_(()=>C(()=>{let e=pu(),t=xc(e,Date.now());if(t===void 0)return;let n=setTimeout(()=>mu(t=>t===e?Sc(t,Date.now()):t),t+50);j(()=>clearTimeout(n))}));var hu=_(()=>T(()=>{let e=X();if(!e)return[];try{return Ss(localStorage.getItem(bs(e.user?.id)))}catch{return[]}}));_(()=>C(()=>{let e=ou(),t=X();if(cu()&&t)try{localStorage.setItem(bs(t.user?.id),JSON.stringify((e?.hiddenSessionIDs??[]).slice(-20)))}catch{}}));var gu=_(()=>T(()=>hs(ou(),Y.machines,cu()?[]:hu()),void 0,{equals:(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e))}));l(()=>gu());var[_u,vu]=x([]),[yu,bu]=x(new Map),xu=new Set;async function Su(){try{bu(new Map(Zn(await z(`/api/agent/grants`)).map(e=>[e.id,e])))}catch{}}var Cu=e=>yu().get(e),wu=new Set;function Tu(e){return wu.add(e),()=>wu.delete(e)}var Eu=_(()=>T(e=>Ia(e,Fa(Y.machines,Y.prefs,Y.reads,gu())))),Du=e=>No(Y.machines,e),Ou=e=>gu().has(e)?`the Concierge`:Du(e)?.session.title||void 0,[ku,Au]=x(new Map);async function ju(){try{let e=await z(`/api/agent/who`),t=Array.isArray(e?.sessions)?e.sessions:[];Au(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 Mu(e){if(gu().has(e))return jn(e,void 0,!0);let t=Du(e)?.session,n=ku().get(e);if(!n)for(let t of ru().values())t.from.kind===`session`&&t.from.sessionID===e&&t.from.name&&(n=t.from.name);return jn(e,{name:n,title:t?.title,directory:typeof t?.project==`string`&&t.project||t?.directory})}var Nu=new Wi;Pe(()=>{Ue().name!==`pair`&&(td(),Kl(void 0),Pu())});function Pu(){let e=location.pathname+location.search;a(`/pair${e===`/`||e.startsWith(`/pair`)?``:`?next=${B(e)}`}`,{replace:!0})}async function Fu(){if(X())return!0;let e=await fetch(`/api/me`,{credentials:`same-origin`});if(e.status===401)return Pu(),!1;if(!e.ok)throw Error(`HTTP ${e.status}`);return Kl(await e.json()),!0}async function Iu(){if(ql()!==void 0)return ql()??null;try{let e=await fetch(`/api/auth`,{credentials:`same-origin`}),t=e.ok?await e.json():null;return Jl(t),t}catch{return null}}var Lu,Ru,zu=1e3,Bu=()=>!1,Vu={lite:!1},[Hu,Uu]=x(``),Wu,Gu=!1,Ku=new zo({setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e),open:(e,t)=>$u(e,t),close:()=>Qu(),keepOpen:()=>Bu()});function qu(e){Bu=e}function Ju(e){Vu=e,Ku.setScope(e)}var Yu=!1;function Xu(){Yu||(Yu=!0,document.addEventListener(`visibilitychange`,()=>document.visibilityState===`hidden`?Ku.hidden():Ku.visible()),window.addEventListener(`pageshow`,e=>{e.persisted&&Ku.state!==`stopped`&&Ku.reopen()}),window.addEventListener(`online`,()=>Ku.state===`open`&&Y.connection===`down`&&Ku.reopen()))}function Zu(e={lite:!1}){Ku.state===`stopped`&&(Xu(),Vu=e,Ku.start(e),cu()||(cd(),setTimeout(()=>!cu()&&du(!0),gs)),document.visibilityState===`hidden`&&Ku.hidden())}function Qu(){clearTimeout(Ru),Lu?.close(),Lu=void 0,Ku.state===`paused`&&Vl(`connection`,`paused`)}function $u(e,t){clearTimeout(Ru),Lu?.close();let n=Bo(Y.connection,t);Gu=n.reconnecting,n.reconnecting&&ed(`reconnecting`),Vl(`connection`,n.connection),Uc(Vu);let r=new EventSource(e,{withCredentials:!0});Lu=r,r.onopen=()=>{zu=1e3,Vl(`connection`,`live`),Gu&&ed(`updated`,2e3),Gu=!1,Cd(),rd(),vd(),pd(),ju(),Su(),cd()},r.onerror=async()=>{Lu===r&&(Vl(`connection`,`down`),(await fetch(`/api/me`,{credentials:`same-origin`}).catch(()=>void 0))?.status===401?(td(),Kl(void 0),Pu()):r.readyState===EventSource.CLOSED&&Lu===r&&(Lu=void 0,Ru=setTimeout(()=>Ku.state===`open`&&Ku.reopen(),zu),zu=Math.min(3e4,zu*2)))},r.addEventListener(`ping`,()=>Ku.received()),r.onmessage=e=>{Ku.received(e.lastEventId||void 0);let t;try{t=JSON.parse(e.data)}catch{return}nd(t)}}function ed(e,t){clearTimeout(Wu),Uu(e),t&&(Wu=setTimeout(()=>Uu(``),t))}function td(){Ku.stop(),Lu?.close(),Lu=void 0,clearTimeout(Ru)}function nd(e){De(()=>{if(Wc(e),e.type===`prefs`?(Vl(xi(t=>Mo(t,e))),Y.prefsStale&&!Y.prefsPending&&wd()):e.type===`catalog`?Vl(xi(t=>{Mo(t,e),Nu.apply(t.machines,Date.now())})):Vl(xi(t=>Mo(t,e))),e.type===`status`){let t=Du(e.sessionID);!Hl.has(e.sessionID)&&t&&Hl.feed(e.sessionID)}if(Hl.apply(e)!==void 0&&Wl(e=>e+1),e.type===`enrollment`&&vd(),e.type===`recording`&&Il(e),e.type===`decision`){let t=Jt(e.decision);t&&(fd.event(t),eu(e=>Zt(e,t)),au([t]))}if(e.type===`concierge`){let t=ps(e.status);t&&(mu(e=>yc(ou(),t,e)),su(t),lu(!0),ad++);let n=nc(e.armed);n!==void 0&&(ud.event(),mu(n))}if(e.type===`agent`){let t=cr(e.entry);t&&vu(e=>zr(e,t)),t?.grant&&!yu().has(t.grant)&&!xu.has(t.grant)&&(xu.add(t.grant),Su())}if(e.type===`resync`&&(rd(),wd(),vd(),pd(),ju(),Su(),cd()),e.type===`handoff`&&(Ue().name!==`session`||Ue().id!==e.sessionID)){let t=Du(e.sessionID);K(`Handed off: ${t?.session.title||e.sessionID}`,``,{label:`Open`,run:()=>a(`/s/${B(e.sessionID)}`)})}});for(let t of wu)t(e)}async function rd(){try{let{reads:e}=await z(`/api/reads`);Vl(`reads`,e??{})}catch{}}async function id(e){try{let{reads:t}=await(await W(`${N(e)}/read`,{method:`POST`,json:{}})).json();t&&typeof t==`object`&&Vl(`reads`,t)}catch{}}var ad=0,od,sd;function cd(){return od?(sd??=od.then(()=>(sd=void 0,cd())),sd):(od=ld().finally(()=>od=void 0),od)}async function ld(){let t=ad;try{let e=ms(await z(`/api/agent/concierge`));e&&t===ad&&su(e.status)}catch(n){n instanceof e&&n.status===404&&t===ad&&su(void 0);return}finally{lu(!0)}await dd()}var ud=new Cc;async function dd(){let t=ud.begin();try{let e=nc((await z(`/api/agent/concierge/arm`)).armed);ud.fresh(t)&&e!==void 0&&mu(Sc(e,Date.now()))}catch(n){ud.fresh(t)&&n instanceof e&&(n.status===404||n.status===403)&&mu(void 0)}}var fd=new on;async function pd(){let t=fd.begin();try{let{decisions:e}=await z(`/api/decisions?state=open`),n=fd.settle(t,(e??[]).map(Jt).filter(e=>!!e));if(!n)return;eu(n),au(n)}catch(n){fd.fail(t),n instanceof e&&n.status===404&&eu([])}}var md=new ss({fetch:e=>z(`/api/decisions/${B(e)}`),parse:e=>Jt(e?.decision)??void 0,status:t=>t instanceof e?t.status:void 0});function hd(e){let t=tu().get(e);return t?Promise.resolve(t):md.recall(e).then(t=>(t&&!tu().has(e)&&au([t]),t))}function gd(e){fd.event(e),eu(t=>Zt(t,e)),au([e])}function _d(e){let t=$l().find(t=>t.id===e);t&&fd.event({...t,state:`closed`}),eu(t=>t.filter(t=>t.id!==e)),pd()}async function vd(){if(!gt(X()))Ql([]);else try{Ql((await z(`/api/enrollments`)).enrollments??[])}catch{Ql([])}}async function yd(){try{Xl((await z(`/api/settings/speech`)).ready??null)}catch{Xl(null)}}var bd=`voice.viewPrefs`,xd=!1,Sd=()=>Y.prefsSource===`hub`||Y.prefsSource===`local`;async function Cd(){if(!(Sd()||xd)){xd=!0;try{Vl({prefs:Vi(await z(`/api/prefs/view`)),prefsSource:`hub`})}catch(t){if(t instanceof e&&t.status===404){let e;try{e=JSON.parse(localStorage.getItem(bd)??`null`)}catch{}Vl({prefs:Vi(e),prefsSource:`local`})}else Vl(`prefsSource`,`error`)}finally{xd=!1}Sd()&&await Td()}}async function wd(){Vl({prefsStale:!1,prefsSource:`unknown`}),await Cd()}async function Td(){let{clear:e,patch:t}=Ji(localStorage.getItem(`voice.pins`),localStorage.getItem(`voice.pinnedWorkspaces`),Y.prefs);e&&(t&&(Vl(`prefs`,e=>({...e,...t})),!(await Ed(t)).ok)||(localStorage.removeItem(`voice.pins`),localStorage.removeItem(`voice.pinnedWorkspaces`)))}async function Ed(e){if(Y.prefsSource===`local`)return localStorage.setItem(bd,JSON.stringify(Y.prefs)),{ok:!0};Vl(`prefsPending`,e=>e+1);try{let t=await(await W(`/api/prefs/view`,{method:`PUT`,json:e})).json().catch(()=>void 0);return Y.prefsPending===1&&t&&!Y.prefsStale&&Vl(`prefs`,Vi(t)),{ok:!0}}catch(e){return{ok:!1,error:e}}finally{Vl(`prefsPending`,e=>e-1),!Y.prefsPending&&Y.prefsStale&&wd()}}function Dd(e,t,n,r={}){Od(e,[t],n,r)}function Od(e,t,n,{message:r,undo:i=!1}={}){if(!Sd()){K(`Your view settings are still loading. Try again in a moment.`,`err`),Cd();return}let a=new Set(Y.prefs[e]),o=t.filter(e=>a.has(e)!==n),{prefs:s,patch:c}=Ki(Y.prefs,e,o,n);c&&(Vl(`prefs`,s),r&&K(r,``,i?{label:`Undo`,run:()=>Od(e,o,!n)}:void 0),Ed(c).then(({ok:t,error:r})=>{t||(Vl(`prefs`,Ki(Y.prefs,e,o,!n).prefs),K(`Could not save that change: ${U(r)}`,`err`))}))}async function kd(e,t){try{return await W(`${N(e)}/expose`,{method:`POST`,json:{on:t}}),K(t?`Voice enabled`:`Voice disabled`),!0}catch(e){return K(`Could not ${t?`enable`:`disable`} Voice: ${U(e)}`,`err`),!1}}async function Ad(e,t){let n=Hi(t);if(`error`in n)return K(n.error,`err`),!1;let{title:r}=n,i=Du(e)?.session.title;if(i===r)return!1;Nu.set(e,r,Date.now()),Vl(xi(t=>void Ui(t.machines,e,r)));try{let t=await(await W(`${N(e)}/rename`,{method:`POST`,json:{title:r}})).json().catch(()=>void 0),n=typeof t?.title==`string`&&t.title?t.title:r;return n!==r&&Du(e)?.session.title===r&&(Nu.drop(e,r),Nu.set(e,n,Date.now()),Vl(xi(t=>void Ui(t.machines,e,n)))),!0}catch(t){return Nu.drop(e,r),i!==void 0&&Du(e)?.session.title===r&&Vl(xi(t=>void Ui(t.machines,e,i))),K(`Could not rename: ${U(t)}`,`err`),!1}}var[jd,Md]=x(new Set),Nd=e=>jd().has(e),Pd=(e,t)=>Md(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r}),Fd=6e4;async function Id(e){if(Nd(e))return;let t=Du(e)?.session.title;Pd(e,!0);let n=!1;try{let r=await(await W(`${N(e)}/rename`,{method:`POST`,json:{auto:!0}})).json().catch(()=>void 0);if(r?.pending){n=!0,K(`OpenCode is still naming it; the title changes when it's ready`);let r=Date.now()+Fd,i=()=>{let n=Du(e)?.session.title;n!==void 0&&n!==t?(Pd(e,!1),K(`Renamed to “${n}”`)):Date.now()>=r?Pd(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){K(`OpenCode kept the title`);return}Nu.set(e,i,Date.now()),Vl(xi(t=>void Ui(t.machines,e,i))),K(`Renamed to “${i}”`)}catch(e){K(`Could not auto-name: ${U(e)}`,`err`)}finally{n||Pd(e,!1)}}async function Ld(e){try{await W(`${N(e)}/error/dismiss`,{method:`POST`,json:{}})}catch(e){K(`Could not dismiss the error: ${U(e)}`,`err`)}}async function Rd(e){try{let{stopped:t}=await(await W(`${N(e)}/stop`,{method:`POST`,json:{}})).json(),n=Array.isArray(t)?t.length:0;K(n?`Stopped ${n} session${n===1?``:`s`}`:`Nothing was running`)}catch(e){K(`Could not stop: ${U(e)}`,`err`)}}var zd=q(`<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 Bd(e){let t=()=>e.size??18;return(()=>{var n=zd();return D(r=>{var i=`hub-mark${e.class?` ${e.class}`:``}`,a=t(),o=t();return i!==r.e&&L(n,`class`,r.e=i),a!==r.t&&L(n,`width`,r.t=a),o!==r.a&&L(n,`height`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})()}var Vd=q(`<p class=error role=alert>`),Hd=q(`<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`),Ud=q(`<p class=muted>Sign in to see and control your own OpenCode sessions.`),Wd=q(`<a class="btn primary signin">Sign in with Google`),Gd=q(`<details class=card><summary>Have a pairing code?`),Kd=q(`<main class=entry><h1 class="display brand-big"> Hub`),qd=q(`<p class=muted>Loading…`),Jd=q(`<p class=muted>Pair this browser with your hub to see and control your OpenCode sessions.`),Yd=q(`<p>A terminal on <strong></strong> asks to act as you through the hub CLI.`),Xd=q(`<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.`),Zd=q(`<fieldset class=stack><legend class=small>What it may do`),Qd=q(`<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.`),$d=q(`<div class=row><button type=button class="btn primary">Approve</button><button type=button class="btn danger">Deny`),ef=q(`<p role=status>`),tf=q(`<main class=entry><h1 class=display>CLI login for </h1><div class="card stack"><a class=btn href=/>Back to sessions`),nf=q(`<label class=check><input type=checkbox><span><span class=mono></span> `),rf=q(`<main class=entry><p class=muted>Loading…`),af=q(`<strong>`),of=q(`<p>`),sf=q(`<p class="small muted">Approve only if this code matches the one shown in OpenCode.`),cf=q(`<p class=small>`),lf=q(`<main class=entry><h1 class=display>Approve machine</h1><div class="card stack"><a class=btn href=/>Back to sessions`),uf=q(`<p>No code given.`),df=q(`<strong class=mono>`);function ff(){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 pf(t){let[r,i]=x(),[o,s]=x(!1),[c,l]=x(``),[d,f]=x(ff()),[p,m]=x(t.error?`Sign-in did not work: ${t.error}`:``),[h,g]=x(!1);ue(async()=>{let[e,n]=await Promise.all([fetch(`/api/me`,{credentials:`same-origin`}).catch(()=>void 0),Iu()]);if(e?.ok)return Kl(await e.json()),a(t.next,{replace:!0});i(St(n??void 0,t.next)),s(!0)});let _=async n=>{n.preventDefault();let r=c().replace(/\D/g,``);if(r.length!==6)return m(`Enter the 6-digit code.`);g(!0),m(``);try{await W(`/api/pair`,{method:`POST`,json:{code:r,deviceName:d().trim()||ff()}}),Kl(void 0),a(t.next,{replace:!0})}catch(t){m(t instanceof e&&t.status===401?`That code is wrong or expired. Get a fresh one and try again.`:U(t)),g(!1)}},v=()=>(()=>{var e=Hd(),t=e.firstChild,r=t.firstChild.nextSibling,i=t.nextSibling.nextSibling,a=i.firstChild.nextSibling,o=i.nextSibling;return e.addEventListener(`submit`,_),r.$$input=e=>l(e.currentTarget.value),a.$$input=e=>f(e.currentTarget.value),I(e,n(u,{get when(){return p()},get children(){var e=Vd();return I(e,p),e}}),o),D(()=>o.disabled=h()),D(()=>r.value=c()),D(()=>a.value=d()),e})();return(()=>{var e=Kd(),i=e.firstChild,a=i.firstChild;return I(i,n(Bd,{class:`brand-mark`,size:30}),a),I(e,n(u,{get when(){return o()},get fallback(){return qd()},get children(){return n(u,{get when(){return r()},get fallback(){return[Jd(),V(v)]},get children(){return[Ud(),(()=>{var e=Wd();return D(()=>L(e,`href`,r())),e})(),(()=>{var e=Gd();return e.firstChild,I(e,v,null),D(()=>e.open=!!t.error),e})()]}})}}),null),e})()}function mf(t){let r=Jn(t.login),[i,a]=x(r.filter(e=>e.checked).map(e=>e.scope)),[s,c]=x(``),[l,d]=x(``),[f,p]=x(!1),m=()=>t.login.userCode,h=async n=>{let r=n===`approve`?Yn(i()):{ok:!0,body:{}};if(!r.ok)return c(r.error);p(!0);try{await W(`/api/cli-logins/${B(m())}/${n}`,{method:`POST`,json:r.body}),d(n===`approve`?`The terminal on ${t.login.clientName} is logged in as you, with ${i().join(`, `)}.${i().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 ${t.login.clientName}.`)}catch(t){c(t instanceof e&&t.status===404?`No pending request with code ${m()}. It may have expired or been answered already.`:U(t)),p(!1)}};return(()=>{var e=tf(),c=e.firstChild;c.firstChild;var d=c.nextSibling,p=d.firstChild;return I(c,()=>t.login.clientName,null),I(d,n(u,{get when(){return!l()},get fallback(){return(()=>{var e=ef();return I(e,l),e})()},get children(){return[(()=>{var e=Yd(),n=e.firstChild.nextSibling;return I(n,()=>t.login.clientName),e})(),(()=>{var e=Xd(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,I(e,m,n),I(e,()=>Be(t.login.created),r),e})(),(()=>{var e=Zd();return e.firstChild,I(e,n(o,{each:r,children:e=>(()=>{var t=nf(),n=t.firstChild,r=n.nextSibling,o=r.firstChild;return o.nextSibling,n.addEventListener(`change`,t=>a(t.currentTarget.checked?[...i(),e.scope]:i().filter(t=>t!==e.scope))),I(o,()=>e.scope),I(r,()=>e.label,null),I(r,()=>e.requested?` (requested)`:``,null),D(()=>n.disabled=f()),D(()=>n.checked=e.checked),t})()}),null),e})(),n(u,{get when(){return i().includes(`sessions:launch`)},get children(){return Qd()}}),(()=>{var e=$d(),t=e.firstChild,n=t.nextSibling;return t.$$click=()=>void h(`approve`),n.$$click=()=>void h(`deny`),D(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(u,{get when(){return s()},get children(){var e=ef();return I(e,s),e}})]}}),p),e})()}function hf(e){let[t,r]=x(),[i,a]=x(!e.code);return ue(async()=>{if(e.code){try{r(qn(await(await W(`/api/cli-logins/${B(e.code.toUpperCase())}`)).json()))}catch{}a(!0)}}),n(u,{get when(){return i()},get fallback(){return rf()},get children(){return n(u,{get when(){return t()},get fallback(){return n(gf,{get code(){return e.code}})},children:e=>n(mf,{get login(){return e()}})})}})}function gf(t){let r=()=>t.code.toUpperCase(),[i,a]=x(``),[o,s]=x(``),[c,l]=x(!1),[d,f]=x(!gt(X()));ue(async()=>{await vd(),f(!0)});let p=()=>Zl().find(e=>e.userCode===r()),m=()=>`No pending request with code ${r()}. It may have expired or been answered already.`,h=async t=>{l(!0);let n=p()?.machineName;try{await W(`/api/enrollments/${B(r())}/${t}`,{method:`POST`,json:{}}),s(t===`approve`?`${n??`The machine`} is approved and belongs to you. It will connect in a few seconds.`:`Denied ${n??`the request with code ${r()}`}.`)}catch(t){a(t instanceof e&&t.status===404?m():U(t)),l(!1)}};return(()=>{var e=lf(),t=e.firstChild.nextSibling,a=t.firstChild;return I(t,n(u,{get when(){return!o()},get fallback(){return(()=>{var e=ef();return I(e,o),e})()},get children(){return n(u,{get when(){return r()},get fallback(){return uf()},get children(){return n(u,{get when(){return d()},get fallback(){return qd()},get children(){return n(u,{get when(){return!gt(X())||p()},get fallback(){return(()=>{var e=of();return I(e,m),e})()},get children(){return[(()=>{var e=of();return I(e,n(u,{get when(){return p()},get fallback(){return[`A machine showing code `,(()=>{var e=df();return I(e,r),e})(),` wants to connect to this hub.`]},get children(){return[(()=>{var e=af();return I(e,()=>p().machineName),e})(),` wants to connect to this hub.`]}})),e})(),(()=>{var e=sf(),t=e.firstChild;return I(e,(()=>{var e=V(()=>!!p());return()=>e()?`Code ${p().userCode} · requested ${Be(p().created)}. `:``})(),t),e})(),(()=>{var e=cf();return I(e,()=>Ct(X())),e})(),(()=>{var e=$d(),t=e.firstChild,n=t.nextSibling;return t.$$click=()=>void h(`approve`),n.$$click=()=>void h(`deny`),D(e=>{var r=c(),i=c();return r!==e.e&&(t.disabled=e.e=r),i!==e.t&&(n.disabled=e.t=i),e},{e:void 0,t:void 0}),e})(),n(u,{get when(){return i()},get children(){var e=ef();return I(e,i),e}})]}})}})}})}}),a),e})()}P([`input`,`click`]);var _f=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window&&window.isSecureContext;function vf(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 yf=(e,t)=>!e||e.byteLength!==t.byteLength?!1:new Uint8Array(e).every((e,n)=>e===t[n]),[bf,xf]=x(0),[Sf,Cf]=x(new Set),wf=()=>`Notification`in window?Notification.permission:`default`;async function Tf(){if(`serviceWorker`in navigator)return await navigator.serviceWorker.getRegistration(`/`).catch(()=>void 0)??void 0}async function Ef(){if(_f())return await(await Tf())?.pushManager.getSubscription()??void 0}async function Df(e){let t=await z(`/api/push/prefs${e?`?endpoint=${encodeURIComponent(e)}`:``}`);return Cf(new Set(t.muted??[])),t}async function Of(){let e=_f(),t=e?await Tf():void 0,n=await t?.pushManager.getSubscription().catch(()=>null)??void 0,r=await Df(n?.endpoint).catch(()=>void 0);return{env:{supported:e,permission:wf(),worker:!!t,...n?{endpoint:n.endpoint}:{},hubSubscribed:!!r?.subscribed,hubSubscriptions:r?.subscriptions??0},view:r}}async function kf(){let{publicKey:e}=await z(`/api/push/key`),t=vf(e);await Tf()||await navigator.serviceWorker.register(`/sw.js`,{scope:`/`});let n=await navigator.serviceWorker.ready,r=await n.pushManager.getSubscription();return r&&!yf(r.options?.applicationServerKey,t)&&(await r.unsubscribe(),r=null),r??=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),await W(`/api/push/subscribe`,{method:`POST`,json:{subscription:r.toJSON()}}),r}async function Af(){if(!_f())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 kf()}async function jf(){let e=await Ef();e&&(await W(`/api/push/unsubscribe`,{method:`POST`,json:{endpoint:e.endpoint}}).catch(()=>{}),await e.unsubscribe().catch(()=>{}))}async function Mf(e){return(await W(`/api/push/test`,{method:`POST`,json:e?{kind:e}:{}})).json()}async function Nf(e,t){let n=Sf(),r=new Set(n);t?r.add(e):r.delete(e),Cf(r);try{let n=await(await W(`/api/push/mute`,{method:`PUT`,json:{sessionID:e,muted:t}})).json();Cf(new Set(n.muted)),K(t?`Notifications muted for this session`:`Notifications on for this session`)}catch(e){Cf(n),K(e instanceof Error?e.message:String(e),`err`)}}async function Pf(){let{env:e}=await Of().catch(()=>({env:void 0}));e&&qe(e)&&await kf().then(()=>xf(e=>e+1),e=>console.warn(`push re-subscribe:`,e?.message??e))}function Ff(){`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&&a(e.pathname+e.search)}for(let e of If)e(t)}))}var If=new Set;function Lf(e){return If.add(e),()=>If.delete(e)}var Rf=()=>{try{return globalThis.localStorage}catch{return}},[zf,Bf]=x(Ye(Rf())??ot()),Vf=zf;function Hf(e){let t=zf(),n=e(t);return n===t||(Bf(n),ut(Rf(),n))}var Uf=`Up to ${lt} panes side by side. Close one to open another.`;function Wf(e){if(Ge(e))return a(`/concierge`);let{layout:t,outcome:n}=ct(Vf(),{sessionID:e},{beside:!0});if(n===`limit`)return K(Uf,`warn`);n!==`invalid`&&Hf(()=>t),a(k(e))}function Gf(e){if(e.sessionID!==void 0&&Ge(e.sessionID))return!1;let{layout:t,outcome:n}=ct(Vf(),e,{beside:!0});if(n===`limit`)return K(Uf,`warn`),!1;if(n===`invalid`)return!1;Hf(()=>t);let r=Ue();return r.name!==`session`&&r.name!==`panes`&&a(`/panes`),!0}var Kf=e=>Gf({artifactID:e}),qf=(e,t)=>Gf({sessionID:e,sideChatID:t});function Jf(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 Yf=e=>e===`left`||e===`right`?`vertical`:`horizontal`;function Xf(e,t,n,r){let i=r?t+1:t;if(i<=1)return`single`;let a=Yf(n);return i===2?a:e===`grid`?`grid`:e===a?r&&i>=lt?`grid`:a:`grid`}function Zf(e,t,n,r){return r===`grid`&&n===`bottom`?Math.min(e,t+2):n===`left`||n===`top`?t:t+1}var Qf=(e,t)=>Number.isInteger(t)&&t>=0&&t<e.panes.length;function $f(e,t,n){if(!Qf(e,t))return{layout:e,outcome:`invalid`};let r=()=>({layout:Qe(e.split,e.panes,t),outcome:`focused`});if(`empty`in n)return r();let{index:i,zone:a}=n;if(!Qf(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:Qe(e.split,n,i),outcome:`moved`}}let s=e.panes.filter((e,n)=>n!==t),c=Xf(e.split,e.panes.length,a,!1),l=Zf(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:Qe(c,u,l),outcome:d?`focused`:`moved`}}function ep(e,t,n){let r=rt(t);if(!r)return{layout:e,outcome:`invalid`};let i=e.panes.findIndex(e=>nt(e,r));if(i>=0)return $f(e,i,n);let a=e.panes.length;if(!a)return{layout:Qe(e.split,[r],0),outcome:`added`};let{index:o,zone:s}=`empty`in n?{index:a-1,zone:`right`}:n;if(!Qf(e,o))return{layout:e,outcome:`invalid`};if(s===`center`)return{layout:Qe(e.split,e.panes.map((e,t)=>t===o?r:e),o),outcome:`replaced`};if(a>=lt)return{layout:e,outcome:`limit`};let c=Xf(e.split,a,s,!0),l=Zf(a,o,s,c);return{layout:Qe(c,[...e.panes.slice(0,l),r,...e.panes.slice(l)],l),outcome:`added`}}var tp={side:{min:180,max:480,default:235},rail:{min:220,max:640,default:260}},np=`hub.panels`,rp=(e,{min:t,max:n})=>Math.min(n,Math.max(t,e));function ip(e,t,n){let{min:r,max:i}=tp[e];return{min:r,max:Math.max(r,Math.min(i,Math.floor(t-420-n)))}}var ap={min:320,max:440,share:.4};function op(e,t,n){let r=e=>t-(n.concierge&&e?ap.min:0),i=rp(e.side,ip(`side`,r(n.side),n.rail?tp.rail.min:0)),a=rp(e.rail,ip(`rail`,r(n.rail),n.side?i:0));if(!n.concierge)return{side:i,rail:a};let o=Math.min(ap.max,Math.floor(t*ap.share)),s=t-420-(n.side?i:0)-(n.rail?a:0);return{side:i,rail:a,concierge:Math.max(ap.min,Math.min(o,s))}}function sp(e,t,n,r,i){let a=r?64:16,o=e===`side`?`ArrowRight`:`ArrowLeft`,s=e===`side`?`ArrowLeft`:`ArrowRight`;if(n===o)return rp(t+a,i);if(n===s)return rp(t-a,i);if(n===`Home`)return i.min;if(n===`End`)return i.max}function cp(e,t,n,r){let i=e===`side`?t+n:t-n;return e===`side`&&i<r.min-48?{collapse:!0}:{width:rp(Math.round(i),r)}}var lp=(e,t)=>{let{min:n,max:r,default:i}=tp[e];return typeof t==`number`&&Number.isFinite(t)?rp(Math.round(t),{min:n,max:r}):i};function up(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:lp(`side`,n.side),rail:lp(`rail`,n.rail)}}function dp(e,t,n){try{e.setItem(np,JSON.stringify({...up(e),[t]:lp(t,n)}))}catch{}}var fp=window.matchMedia(`(max-width: 760px)`),[pp,mp]=x(fp.matches);fp.addEventListener(`change`,()=>{mp(fp.matches),Sp(!fp.matches&&localStorage.getItem(gp)!==`0`)});var Z=pp,hp=`hub.sidebar.collapsed`,gp=`hub.rail.open`,[_p,vp]=x(localStorage.getItem(hp)===`1`),[yp,bp]=x(!1),[xp,Sp]=x(!fp.matches&&localStorage.getItem(gp)!==`0`);function Cp(e){vp(e),localStorage.setItem(hp,e?`1`:`0`)}function wp(e){Sp(e),pp()||localStorage.setItem(gp,e?`1`:`0`)}function Tp(){pp()?bp(!yp()):Cp(!_p())}var[Ep,Dp]=x(window.innerWidth);window.addEventListener(`resize`,()=>Dp(window.innerWidth));var[Op,kp]=x(up(localStorage)),[Ap,jp]=x(!1),[Mp,Np]=x(),[Pp,Fp]=x(!1),Ip=()=>op(Op(),Ep(),{side:!_p()&&!pp(),rail:Ap(),concierge:Pp()&&!pp()});function Lp(e){let t=Ip(),n=e===`side`?Ap()?t.rail:0:!_p()&&!pp()?t.side:0;return ip(e,Ep()-(t.concierge??0),n)}function Rp(e,t,n=!0){kp(n=>({...n,[e]:t})),n&&dp(localStorage,e,t)}var zp=`application/x-hub-pane`,[Bp,Vp]=x(),Hp=``,Up=0,Wp=Bp,Gp=()=>typeof globalThis.crypto?.randomUUID==`function`?crypto.randomUUID():`${Date.now()}-${Math.random()}`;function Kp(e,t){let n=e.dataTransfer;return Z()||!n?!1:(n.clearData(),Hp=Gp(),n.setData(zp,Hp),n.effectAllowed=t.move?`move`:`copyMove`,cancelAnimationFrame(Up),Up=requestAnimationFrame(()=>Vp(t)),!0)}function qp(){cancelAnimationFrame(Up),Up=0,Hp=``,Vp(void 0)}function Jp(e){return!!Bp()&&[...e.dataTransfer?.types??[]].includes(`application/x-hub-pane`)}function Yp(e){let t=Bp();return t?ep(Vf(),t.target,e).outcome:void 0}function Xp(e,t){let{layout:n,outcome:r}=ep(Vf(),e,t);if(r===`limit`&&K(Uf,`warn`),r===`limit`||r===`invalid`)return r;Hf(()=>n);let i=n.panes[n.focused],o=i&&!i.sideChatID?i.sessionID:void 0,s=Ue();return s.name!==`session`&&s.name!==`panes`?a(o?k(o):`/panes`):s.name===`session`&&!o&&!n.panes.some(e=>e.sessionID===s.id&&!e.sideChatID)&&a(`/panes`,{replace:!0}),r}function Zp(e,t){let n=Bp(),r=n&&e.dataTransfer?.getData(`application/x-hub-pane`)===Hp;return qp(),r?Xp(n.target,t):`invalid`}function Qp(e,t){let n=Vf();return Xp(e,n.panes.length?{index:n.focused,zone:t}:{empty:!0})}if(typeof document<`u`){let e=()=>Bp()&&qp();document.addEventListener(`dragend`,e,!0),document.addEventListener(`drop`,()=>queueMicrotask(e)),document.addEventListener(`mousemove`,t=>t.buttons===0&&e(),{passive:!0})}var $p=e=>!!e&&typeof e==`object`&&!Array.isArray(e),em=e=>typeof e==`string`&&e.length>0,tm=e=>typeof e==`number`&&Number.isFinite(e),nm=new Set([`online`,`offline`,`archived`,`deleted`,`unknown`]),rm=new Set([`current`,`left`,`missing`]),im=new Set([`open`,`in_progress`,`blocked`,`done`,`cancelled`]),am=new Set([`done`,`cancelled`]),om=e=>tm(e)&&e>=0?e:0;function sm(e){if(!$p(e)||!em(e.memberID)||!em(e.sessionID)||!em(e.role))return;let t=$p(e.session)&&typeof e.session.state==`string`?e.session:void 0,n=$p(e.assignments)?e.assignments:{};return{memberID:e.memberID,sessionID:e.sessionID,role:e.role,master:e.master===!0,presence:nm.has(e.presence)?e.presence:`unknown`,generation:tm(e.generation)?e.generation:1,...t?{session:{state:t.state,online:t.online===!0,...em(t.machineID)?{machineID:t.machineID}:{},...em(t.name)?{name:t.name}:{},...tm(t.lastSeen)?{lastSeen:t.lastSeen}:{}}}:{},workload:{open:om(n.open),in_progress:om(n.in_progress),blocked:om(n.blocked)},...$p(e.blockers)&&e.blockers.reported===!0&&tm(e.blockers.count)?{blockers:e.blockers.count}:{}}}function cm(e){if($p(e)&&em(e.memberID)&&em(e.supervisorMemberID)&&tm(e.order))return{memberID:e.memberID,supervisorMemberID:e.supervisorMemberID,order:e.order,member:rm.has(e.member)?e.member:`missing`,supervisor:rm.has(e.supervisor)?e.supervisor:`missing`}}function lm(e){if($p(e)&&em(e.id)&&em(e.memberID)&&em(e.title)&&im.has(e.status))return{id:e.id,memberID:e.memberID,title:e.title,status:e.status,...em(e.ref)?{ref:e.ref}:{},assignee:rm.has(e.assignee)?e.assignee:`missing`,...Array.isArray(e.stale)?{stale:e.stale.filter(em)}:{}}}function um(e){if($p(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 dm=(e,t)=>Array.isArray(e)?e.map(t).filter(e=>e!==void 0):[];function fm(e){if(!$p(e)||!$p(e.workspace)||!$p(e.members)||!$p(e.supervision))return;let t=e.workspace;if(!em(t.id)||typeof t.title!=`string`||!em(t.state)||!tm(t.revision)||!tm(e.supervision.revision))return;let n=$p(e.assignments)?e.assignments:{},r=um(e.decisions),i=um(e.artifacts);return{workspace:{id:t.id,title:t.title,state:t.state,revision:t.revision,...em(t.masterMemberID)?{masterMemberID:t.masterMemberID}:{}},revision:e.supervision.revision,members:dm(e.members.items,sm),membersTruncated:e.members.truncated===!0,links:dm(e.supervision.links,cm),linksTruncated:e.supervision.truncated===!0,assignments:dm(n.items,lm),assignmentsTruncated:n.truncated===!0,sections:{...r?{decisions:r}:{},...i?{artifacts:i}:{}}}}function pm(e){return $p(e)?{items:dm(e.items,e=>$p(e)&&em(e.id)&&typeof e.title==`string`&&em(e.state)&&tm(e.revision)?{id:e.id,title:e.title,...em(e.description)?{goal:e.description}:{},state:e.state,revision:e.revision}:void 0),...em(e.cursor)?{cursor:e.cursor}:{}}:{items:[]}}function mm(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 hm(e){let{links:t,stale:n}=mm(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)am.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 gm(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}=mm(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 $e(o,t.memberID,t.supervisorMemberID)}function _m(e,t){return e===void 0&&t===void 0?0:e===void 0?t-1:t===void 0?e+1:(e+t)/2}var vm=(e,t)=>e.flat.find(e=>e.member.memberID===t),ym=(e,t)=>t.supervisorMemberID===void 0?e.roots:vm(e,t.supervisorMemberID).children,bm=(e,t)=>{let n=e.children.filter(e=>e.member.memberID!==t);return n.length?n[n.length-1].order+1:0};function xm(e,t,n){if(!vm(e,t))return;if(`root`in n)return{memberID:t,supervisorMemberID:null};if(n.memberID===t)return;let r=vm(e,n.memberID);if(!r)return;if(n.position===`inside`)return{memberID:t,supervisorMemberID:r.member.memberID,order:bm(r,t)};if(r.supervisorMemberID===void 0)return{memberID:t,supervisorMemberID:null};let i=ym(e,r).filter(e=>e.member.memberID!==t),a=i.indexOf(r),o=n.position===`before`?_m(i[a-1]?.order,r.order):_m(r.order,i[a+1]?.order);return{memberID:t,supervisorMemberID:r.supervisorMemberID,order:o}}function Sm(e,t,n){let r=vm(e,t);if(!r)return;let i=ym(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:bm(e)}:void 0}case`outdent`:{if(o===void 0)return;let n=vm(e,o);if(n.supervisorMemberID===void 0)return{memberID:t,supervisorMemberID:null};let r=ym(e,n);return{memberID:t,supervisorMemberID:n.supervisorMemberID,order:_m(n.order,r[r.indexOf(n)+1]?.order)}}case`up`:return o===void 0||a===0?void 0:{memberID:t,supervisorMemberID:o,order:_m(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:_m(i[a+1].order,i[a+2]?.order)};case`detach`:return o===void 0?void 0:{memberID:t,supervisorMemberID:null}}}function Cm(e,t){return{memberID:e.memberID,supervisorMemberID:e.supervisorMemberID,...e.order!==void 0&&e.supervisorMemberID!==null?{order:e.order}:{},expectedRevision:t}}var wm={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 ${et.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.`},Tm=e=>wm[e];function Em(e,t){let n=gm(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. ${wm[n]}`}:{kind:`reapply`,body:Cm(e,t.revision)}}function Dm(e){let t=e.details?.violation;if(e.status===400&&(t===`cycle`||t===`depth`))return wm[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 Om(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 km(e,t){let n=Om(e,t);if(!n)return{found:!1};let{machine:r,process:i,session:a}=n,o=a.parentID,s=o?Om(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 Am(e,t,n){let r=km(n,e.member.sessionID),i=e.supervisorMemberID?t.members.find(t=>t.memberID===e.supervisorMemberID):void 0,a=i?km(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 jm={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 Mm(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:jm[e.presence]}),n}var Nm=e=>e.length>1?e.replace(/\/+$/,``):e,Pm=(e,t)=>{let n=Nm(e),r=Nm(t);return n===r||n.startsWith(`${r}/`)};function Fm(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=>Pm(n,e))}}))}var Im=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Lm=e=>typeof e==`string`&&e.length>0,Rm=e=>typeof e==`number`&&Number.isFinite(e),zm=[`launching`,`ready`,`failed`,`unknown`];function Bm(e){if(Im(e)&&Lm(e.id)&&typeof e.text==`string`)return{id:e.id,role:Lm(e.role)?e.role:`message`,text:e.text,...Rm(e.at)?{at:e.at}:{},...e.clipped===!0?{clipped:!0}:{},...e.changed===!0?{changed:!0}:{},...e.stale?{stale:!0}:{}}}function Vm(e){if(!Im(e)||!Lm(e.id)||!Lm(e.workspaceID)||!Lm(e.sourceSessionID)||!Rm(e.revision))return;let t=e.snapshot;if(!Im(t)||!Rm(t.generation)||!Rm(t.takenAt))return;let n=Im(e.launch)&&Lm(e.launch.state)?e.launch:void 0;return{id:e.id,workspaceID:e.workspaceID,sourceSessionID:e.sourceSessionID,...Lm(e.sessionID)?{sessionID:e.sessionID}:{},...Lm(e.machineID)?{machineID:e.machineID}:{},revision:e.revision,status:zm.includes(e.status)?e.status:`unknown`,...n?{launch:{state:n.state,...Lm(n.outcome)?{outcome:n.outcome}:{},...Lm(n.reason)?{reason:n.reason}:{}}}:{},snapshot:{generation:t.generation,takenAt:t.takenAt,omitted:Rm(t.omitted)?t.omitted:0,items:Array.isArray(t.items)?t.items.map(Bm).filter(e=>e!==void 0):[]},...typeof e.stale==`boolean`?{stale:e.stale}:{}}}function Hm(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 Um(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 Wm(e,t){let n=e.snapshot,r=[`${dt(n.items.length,`message`)} from the main session`,`copied ${Um(n.takenAt,t)}`];return n.generation>1&&r.push(`refreshed ${dt(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 Gm(e){let t=Im(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${Lm(t.message)?`: ${t.message}`:`.`}`:`Context refreshed.`}var Km=9900;function qm(e){if(!e.trim())return`Write what to send to the main session.`;if(e.length>9900)return`At most ${Km} characters.`}var Jm=encodeURIComponent,Ym=e=>`/api/agent/workspaces/${Jm(e.workspaceID)}/side-chats/${Jm(e.id)}`,Xm={one:e=>`/api/agent/side-chats/${Jm(e)}`,create:e=>`/api/agent/workspaces/${Jm(e)}/side-chats`,refresh:e=>`${Ym(e)}/refresh`,send:e=>`${Ym(e)}/send`},Zm=e=>Math.min(3e4,2e3*2**Math.max(0,e)),Qm=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function $m(e,t){return t?{sourceSessionID:e,bindingID:t}:{sourceSessionID:e}}function eh(e){return(Qm(e)&&Array.isArray(e.bindings)?e.bindings:[]).flatMap(e=>Qm(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 th(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 nh=`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 rh(e){return e.status===0?`The hub can't be reached. Check your connection and try again.`:e.status===422&&e.details?.feature===`sideChatHost`?nh: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 ih=q(`<label><span>Workspace</span><select aria-label=Workspace><option value>Choose a workspace…`),ah=q(`<p class=cmp-note role=status>`),oh=q(`<label><span>Host repository</span><select aria-label="Host repository"><option value>Choose a repository…`),sh=q(`<p class="cmp-note err"role=alert>`),ch=q(`<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`),lh=q(`<p class=muted role=status>Loading workspaces…`),uh=q(`<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.`),dh=q(`<option>`),[fh,ph]=x(),mh=(e,t={})=>ph({sessionID:e,...t});function hh(){return n(u,{get when(){return fh()},keyed:!0,children:e=>n(vh,{request:e,onClose:()=>ph(void 0)})})}var gh=()=>`console-sidechat-${[...crypto.getRandomValues(new Uint8Array(12))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`,_h=t=>t instanceof e?{status:t.status,...t.code?{code:t.code}:{},message:t.message,...t.details?{details:t.details}:{}}:{status:t instanceof be?0:-1,message:t instanceof Error?t.message:String(t)};function vh(t){let[r,i]=x(),[a,s]=x(),[c,l]=x(t.request.workspaceID??``),[d,f]=x(),[p,m]=x(``),[h,g]=x(!1),[_,v]=x(),y,b=()=>{let e=Du(t.request.sessionID)?.session.title;return typeof e==`string`&&e?e:t.request.sessionID};async function S(e){if(f(void 0),m(``),e)try{f(eh(await z(`/api/agent/workspaces/${B(e)}/bindings`)))}catch(e){f([]),v(rh(_h(e)))}}ue(async()=>{try{i(pm(await z(`/api/agent/workspaces?state=active&limit=50`)).items)}catch(e){i([]),s(rh(_h(e)))}c()&&S(c())});let C=T(()=>d()?th(d(),p()||void 0):void 0);async function w(n){n.preventDefault();let r=c(),i=C();if(!r||!i||i.kind===`pick`||h())return;let a=$m(t.request.sessionID,i.kind===`ready`?i.bindingID:void 0),o=JSON.stringify([r,a]);y?.body!==o&&(y={body:o,value:gh()}),g(!0),v(void 0);try{let n=Vm((await(await W(`/api/agent/workspaces/${B(r)}/side-chats`,{method:`POST`,json:a,headers:{"idempotency-key":y.value}})).json()).sideChat);if(!n)throw new e(502,`The hub answered a side chat this console can't read.`);t.onClose(),qf(t.request.sessionID,n.id)&&K(`Side chat started beside the main session.`)}catch(e){e instanceof be||(y=void 0),v(rh(_h(e)))}finally{g(!1)}}return n(ze,{open:!0,title:`Start a side chat`,get onClose(){return t.onClose},get children(){var e=ch(),i=e.firstChild,s=i.firstChild.nextSibling,f=i.nextSibling,g=f.firstChild,y=g.nextSibling;return e.addEventListener(`submit`,w),I(s,b),I(e,n(u,{get when(){return r()},get fallback(){return lh()},get children(){return n(u,{get when(){return!a()},get fallback(){return(()=>{var e=sh();return I(e,a),e})()},get children(){return n(u,{get when(){return r().length},get fallback(){return uh()},get children(){var e=ih(),t=e.firstChild.nextSibling;return t.firstChild,t.addEventListener(`change`,e=>{l(e.currentTarget.value),v(void 0),S(e.currentTarget.value)}),I(t,n(o,{get each(){return r()},children:e=>(()=>{var t=dh();return I(t,()=>e.title||e.id),D(()=>t.value=e.id),t})()}),null),D(()=>t.value=c()),e}})}})}}),f),I(e,n(u,{get when(){return C()?.kind===`none`},get children(){var e=ah();return I(e,nh),e}}),f),I(e,n(u,{get when(){return V(()=>!!d())()&&d().length>1},get children(){var e=oh(),t=e.firstChild.nextSibling;return t.firstChild,t.addEventListener(`change`,e=>m(e.currentTarget.value)),I(t,n(o,{get each(){return d()},children:e=>(()=>{var t=dh();return I(t,(()=>{var t=V(()=>!!e.label);return()=>t()?`${e.label} (${e.repo})`:e.repo})()),D(()=>t.value=e.id),t})()}),null),D(()=>t.value=p()),e}}),f),I(e,n(u,{get when(){return _()},get children(){var e=sh();return I(e,_),e}}),f),I(g,()=>h()?`Starting…`:`Start side chat`),ke(y,`click`,t.onClose,!0),D(e=>{var t=!c()||!C()||C().kind===`pick`||h(),n=h();return t!==e.e&&(g.disabled=e.e=t),n!==e.t&&L(g,`aria-busy`,e.t=n),e},{e:void 0,t:void 0}),e}})}P([`click`]);var[yh,bh]=x(),xh=(e,t)=>yh()?.id===e&&yh()?.place===t;function Sh(e,t){if(!e.length)return;let n=t?`Archived`:`Unarchived`,r=e.length===1?`${n} “${e[0].title}”`:`${n} ${e.length} sessions`;Od(`hiddenSessions`,e.map(e=>e.id),t,{message:r,undo:!0})}function Ch(e,{open:t=!0,place:n}={}){return[...t?[{label:`Open`,run:()=>a(k(e.id))}]:[],...n===`topbar`?[]:[{label:`Open beside`,run:()=>Wf(e.id)}],{label:`Start side chat…`,run:()=>mh(e.id)},...n?[{label:`Rename…`,run:()=>bh({id:e.id,place:n})}]:[],{label:Nd(e.id)?`Naming…`:`Auto-name`,run:()=>void Id(e.id),disabled:Nd(e.id)},{label:e.pinned?`Unpin`:`Pin`,run:()=>Dd(`pinnedSessions`,e.id,!e.pinned)},{label:e.archived?`Unarchive`:`Archive`,run:()=>Sh([e],!e.archived)},...e.running?[{label:`Stop`,run:()=>void Rd(e.id),danger:!0}]:[],...e.state===`error`?[{label:`Dismiss error`,run:()=>void Ld(e.id)}]:[],`sep`,{label:e.exposed?`Disallow Voice`:`Allow Voice`,run:()=>void kd(e.id,!e.exposed)},Sf().has(e.id)?{label:`Unmute notifications`,run:()=>void Nf(e.id,!1)}:{label:`Mute notifications`,run:()=>void Nf(e.id,!0)},...n!==`topbar`&&!Z()?[`sep`,...[`left`,`right`,`top`,`bottom`].map(t=>({label:`Open in pane → ${t}`,run:()=>void Qp({sessionID:e.id},t)}))]:[]]}var wh=q(`<button type=button class="link-btn small clamp-toggle">`),Th=q(`<span>`),Eh=q(`<p>`),Dh=q(`<span class="muted small cut-note"data-cut>… cut at <!> characters (of <!>)`),Oh=q(`<span class="muted small cut-note"data-more>+<!> more <!> not stored`),kh=q(`<dt>Requested by`),Ah=q(`<dd>`),jh=q(`<dt>Proposes`),Mh=q(`<dt>Action`),Nh=q(`<dd class=mono data-action>`),Ph=q(`<dt>`),Fh=q(`<span class="muted small cut-note"data-incomplete>The hub received this request already shortened`),Ih=q(`<dd data-resources>`),Lh=q(`<dt>Always saves`),Rh=q(`<dd data-saves>`),zh=q(`<dt>Shown from`),Bh=q(`<dd class=muted>`),Vh=q(`<dt>Prompt`),Hh=q(`<dt>Form`),Uh=q(`<dt>Answer`),Wh=q(`<dd data-answer>`),Gh=q(`<dt>Outside its grant`),Kh=q(`<dl class="escalation-details decision-details small">`),qh=q(`<dt>Session`),Jh=q(`<dd><a>`),Yh=q(`<span class=decision-answer-field><span class=muted>:</span> `),Xh=q(`<dt>Purpose`),Zh=q(`<dd data-purpose> <span class=muted>(<!>)`),Qh={label:Mu,blockers:e=>Ei(Du(e)?.session)};function $h(e){let[t,r]=x(!1),i=re(),a=T(()=>e.reveal?En(e.text):e.text),o=T(()=>wn(a(),{chars:e.chars,lines:e.lines})),s=()=>t()||!o().cut?a():o().text,c=()=>n(u,{get when(){return o().cut},get children(){var n=wh();return n.$$click=()=>r(!t()),L(n,`aria-controls`,`clamp-${i}`),I(n,()=>t()?`Show less`:`Show all`),D(r=>{var i=t(),a=`${t()?`Show less`:`Show all`} of ${e.what??`the text`}`;return i!==r.e&&L(n,`aria-expanded`,r.e=i),a!==r.t&&L(n,`aria-label`,r.t=a),r},{e:void 0,t:void 0}),n}});return n(u,{get when(){return e.tag===`span`},get fallback(){return[(()=>{var n=Eh();return L(n,`id`,`clamp-${i}`),I(n,s),D(r=>{var i=e.class,a=o().cut&&!t()?``:void 0;return i!==r.e&&G(n,r.e=i),a!==r.t&&L(n,`data-clamped`,r.t=a),r},{e:void 0,t:void 0}),n})(),V(c)]},get children(){return[(()=>{var n=Th();return L(n,`id`,`clamp-${i}`),I(n,s),D(r=>{var i=e.class,a=o().cut&&!t()?``:void 0;return i!==r.e&&G(n,r.e=i),a!==r.t&&L(n,`data-clamped`,r.t=a),r},{e:void 0,t:void 0}),n})(),V(()=>c())]}})}var eg={live:`Live request`,request:`The hub's record of the request`,text:`From the request text`},tg=new Set([`bash`,`shell`]),ng=e=>e&&tg.has(e)?`the command`:`the request`,rg=e=>e.toLocaleString(`en-US`);function ig(e){let t=()=>e.detail.cut?.find(t=>t.field===e.field&&t.index===e.index);return n(u,{get when(){return t()},children:e=>(()=>{var t=Dh(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,I(t,()=>rg(og),n),I(t,()=>rg(e().length),r),t})()})}function ag(e){return n(u,{get when(){return e.count},get children(){var t=Oh(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,I(t,()=>rg(e.count),n),I(t,()=>e.count===1?`item`:`items`,r),t}})}var og=2e3,sg={stop:`Stop the session`,deny:`Deny its permission request`,prompt:`Send a prompt as you`,answer:`Answer its form as you`},cg=e=>e.verb===`answer`&&e.cancel?`Dismiss its form`:sg[e.verb??``]??e.verb;function lg(e){let t=T(()=>bn(e.decision,e.context??Qh));return n(u,{get when(){return t()},children:t=>(()=>{var r=Kh();return I(r,n(u,{get when(){return t().requester},get children(){return[kh(),(()=>{var n=Ah();return I(n,()=>t().requester),D(()=>L(n,`title`,Fn(e.decision))),n})()]}}),null),I(r,n(u,{get when(){return t().verb},get children(){return[jh(),(()=>{var e=Ah();return I(e,()=>cg(t())),D(()=>L(e,`data-verb`,t().verb)),e})()]}}),null),I(r,n(u,{get when(){return t().target},children:e=>[qh(),(()=>{var t=Jh(),n=t.firstChild;return I(n,()=>e().label),D(t=>{var r=k(e().id),i=e().id;return r!==t.e&&L(n,`href`,t.e=r),i!==t.t&&L(n,`title`,t.t=i),t},{e:void 0,t:void 0}),t})()]}),null),I(r,n(u,{get when(){return t().action},get children(){return[Mh(),(()=>{var e=Nh();return I(e,()=>t().action,null),I(e,()=>t().always?` (always)`:``,null),e})()]}}),null),I(r,n(u,{get when(){return t().resources.length},get children(){return[(()=>{var e=Ph();return I(e,()=>t().resources.length===1?`Resource`:`Resources`),e})(),(()=>{var e=Ih();return I(e,n(o,{get each(){return t().resources},children:(e,r)=>[n($h,{tag:`span`,class:`escalation-resource mono`,text:e,chars:240,lines:4,get what(){return ng(t().action)},reveal:!0}),n(ig,{get detail(){return t()},field:`resources`,get index(){return r()}})]}),null),I(e,n(ag,{get count(){return t().resourcesMore}}),null),I(e,n(u,{get when(){return t().incomplete},get children(){return Fh()}}),null),e})()]}}),null),I(r,n(u,{get when(){return t().saves?.length},get children(){return[Lh(),(()=>{var e=Rh();return I(e,n(o,{get each(){return t().saves},children:(e,r)=>[n($h,{tag:`span`,class:`escalation-resource mono`,text:e,chars:240,lines:4,what:`the saved pattern`,reveal:!0}),n(ig,{get detail(){return t()},field:`save`,get index(){return r()}})]}),null),I(e,n(ag,{get count(){return t().savesMore}}),null),e})()]}}),null),I(r,n(u,{get when(){return V(()=>!!t().source)()&&(t().action||t().resources.length||t().form)},get children(){return[zh(),(()=>{var e=Bh();return I(e,()=>eg[t().source]),D(()=>L(e,`data-source`,t().source)),e})()]}}),null),I(r,n(u,{get when(){return t().text},get children(){return[Vh(),(()=>{var e=Ah();return I(e,n($h,{class:`decision-prompt mono`,get text(){return t().text},chars:400,lines:6,what:`the prompt`,reveal:!0})),e})()]}}),null),I(r,n(u,{get when(){return t().formID},get children(){return[Hh(),(()=>{var e=Ah();return I(e,()=>t().form??t().formID),e})()]}}),null),I(r,n(u,{get when(){return t().answer?.length},get children(){return[Uh(),(()=>{var e=Wh();return I(e,n(o,{get each(){return t().answer},children:e=>(()=>{var t=Yh(),r=t.firstChild,i=r.firstChild;return r.nextSibling,I(r,()=>e.key,i),I(t,n($h,{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),I(r,n(u,{get when(){return t().outsideGrant},get children(){return[Gh(),(()=>{var e=Ah();return I(e,()=>t().outsideGrant),e})()]}}),null),I(r,n(u,{get when(){return t().purpose},children:e=>[Xh(),(()=>{var t=Zh(),n=t.firstChild,r=n.nextSibling,i=r.firstChild.nextSibling;return i.nextSibling,I(t,()=>e().text,n),I(r,()=>e().by,i),t})()]}),null),D(e=>{var n=t().kind,i=t().kind===`permission`?``:void 0,a=t().source===`live`?``:void 0;return n!==e.e&&L(r,`data-decision-detail`,e.e=n),i!==e.t&&L(r,`data-escalation`,e.t=i),a!==e.a&&L(r,`data-live`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),r})()})}var ug=(e,t=Qh)=>bn(e,t)?.purpose?.text;P([`click`]);var dg=q(`<span class="badge-pill agent-request"title="An agent asked to act outside its grant">Agent request`),fg=q(`<span>`),pg=q(`<p role=timer>`),mg=q(`<div role=radiogroup aria-label=Options class=choice-group>`),hg=q(`<p class="muted small decision-why">Why: `),gg=q(`<input type=text class=decision-note aria-label="Note (optional)"placeholder="Note (optional)">`),_g=q(`<p class="muted small decision-tier">`),vg=q(`<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`),yg=q(`<a>`),bg=q(`<label class=text-field><span class=field-title>Your answer</span><textarea rows=2 aria-label="Your answer">`),xg=q(`<span class="badge-pill safe"title="A timeout may pick this option">safe`),Sg=q(`<span class="badge-pill recommended">Recommended`),Cg=q(`<label><input type=radio><span>`),wg={low:`Low urgency`,normal:``,high:`Urgent`};function Tg(t){let r=()=>t.decision,[i,a]=x(),[s,c]=x(``),[l,d]=x(!1),[f,p]=x(Date.now()),m=setInterval(()=>r().deadline!==void 0&&p(Date.now()),1e3);j(()=>clearInterval(m));let h=()=>ie().searchParams.get(`decision`)===r().id,g;ue(()=>{h()&&g?.scrollIntoView({block:`center`})});let _=()=>r().sessionID?Du(r().sessionID):void 0,v=async t=>{t.preventDefault();let n=an(r(),i(),s());if(!n.ok)K(n.problem,`err`);else{d(!0);try{let{decision:e}=await(await W(`/api/decisions/${B(r().id)}/answer`,{method:`POST`,json:n.body})).json();K(`Answer sent`),e?gd(e):_d(r().id)}catch(t){if(t instanceof e&&t.status===409&&t.code===`gone`){K(`Already answered or expired`),_d(r().id);return}K(U(t),`err`),d(!1)}}},y=e=>r().recommendation?.option===e;return(()=>{var e=vg(),d=e.firstChild,p=d.firstChild.nextSibling.nextSibling;p.firstChild;var m=d.nextSibling,b=m.nextSibling,x=b.firstChild,S=x.firstChild,C=g;return typeof C==`function`?ge(C,e):g=e,I(p,()=>Pn(r(),Mu,gu()),null),I(d,n(u,{get when(){return Jr(r())},get children(){return dg()}}),null),I(d,n(u,{get when(){return wg[r().urgency]},get children(){var e=fg();return I(e,()=>wg[r().urgency]),D(()=>G(e,`badge-pill urgency ${r().urgency}`)),e}}),null),I(d,n(u,{get when(){return V(()=>!!t.showSession)()&&_()},children:e=>[` · `,(()=>{var t=yg();return I(t,()=>e().session.title||e().session.id),D(()=>L(t,`href`,k(e().session.id))),t})()]}),null),I(m,()=>In(r(),Mu,gu())),I(e,n(lg,{get decision(){return r()}}),b),I(e,n(u,{get when(){return rn(r(),f())},get children(){var e=pg();return I(e,()=>rn(r(),f())),D(()=>G(e,`decision-deadline small${r().escalatedAt!==void 0||r().deadline<=f()?` overdue`:``}`)),e}}),b),b.addEventListener(`submit`,e=>void v(e)),I(x,n(u,{get when(){return r().options.length},get fallback(){return(()=>{var e=bg(),t=e.firstChild.nextSibling;return t.$$input=e=>c(e.currentTarget.value),D(()=>t.value=s()),e})()},get children(){return[(()=>{var e=mg();return I(e,n(o,{get each(){return r().options},children:e=>(()=>{var t=Cg(),o=t.firstChild,s=o.nextSibling;return o.addEventListener(`change`,()=>a(e.id)),I(s,()=>e.label),I(t,n(u,{get when(){return e.safe},get children(){return xg()}}),null),I(t,n(u,{get when(){return y(e.id)},get children(){return Sg()}}),null),D(n=>{var i=`choice${y(e.id)?` recommended`:``}`,a=`d-${r().id}`;return i!==n.e&&G(t,n.e=i),a!==n.t&&L(o,`name`,n.t=a),n},{e:void 0,t:void 0}),D(()=>o.value=e.id),D(()=>o.checked=i()===e.id),t})()})),e})(),n(u,{get when(){return V(()=>!!r().recommendation?.why)()&&r().recommendation.why!==ug(r())},get children(){var e=hg();return e.firstChild,I(e,()=>r().recommendation.why,null),e}}),(()=>{var e=gg();return e.$$input=e=>c(e.currentTarget.value),D(()=>e.value=s()),e})()]}}),S),I(x,n(u,{get when(){return tn(r())},get children(){var e=_g();return I(e,()=>tn(r())),e}}),S),D(t=>{var n=`card decision urgency-${r().urgency}${h()?` targeted`:``}`,i=`Decision: ${r().question}`,a=r().id,o=Fn(r()),s=r().question,c=l();return n!==t.e&&G(e,t.e=n),i!==t.t&&L(e,`aria-label`,t.t=i),a!==t.a&&L(e,`data-decision`,t.a=a),o!==t.o&&L(p,`title`,t.o=o),s!==t.i&&L(m,`title`,t.i=s),c!==t.n&&(x.disabled=t.n=c),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),e})()}function Eg(e){let t=T(()=>new Map(e.decisions.map(e=>[e.id,e]))),r=T((e=[])=>{let n=[...t().keys()];return n.length===e.length&&n.every((t,n)=>t===e[n])?e:n});return n(o,{get each(){return r()},children:r=>n(u,{get when(){return t().get(r)},children:t=>n(Tg,{get decision(){return t()},get showSession(){return e.showSession}})})})}P([`input`]);var Dg=q(`<span class="naming muted small"role=status><span class="spinner small"aria-hidden=true></span>Naming…`),Og=q(`<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">✨`),kg,Ag=0;function jg(e){return n(u,{get when(){return xh(e.id,e.place)},get fallback(){return e.children},get children(){return n(Ng,{get id(){return e.id},get title(){return e.title},get place(){return e.place},get class(){return e.class}})}})}function Mg(e){return n(u,{get when(){return Nd(e.id)},get children(){return Dg()}})}function Ng(e){let t,n=!1,r=kg&&kg.id===e.id&&kg.place===e.place?kg.value:void 0,i=()=>{n||(n=!0,kg=void 0,bh(void 0),Id(e.id))},a=r=>{if(n)return;n=!0;let i=t.value;kg=void 0,bh(void 0),r&&i.trim()&&i.trim()!==e.title&&Ad(e.id,i)};return ue(()=>{Ag++,t.focus(),r===void 0&&t.select()}),j(()=>{if(Ag--,setTimeout(()=>{Ag>0||(kg=void 0,yh()?.id===e.id&&yh()?.place===e.place&&bh(void 0))},0),n)return;n=!0;let r=yh();r?.id===e.id&&r.place===e.place&&(kg={id:e.id,place:e.place,value:t.value})}),(()=>{var n=Og(),o=n.firstChild,s=o.nextSibling;o.addEventListener(`blur`,()=>a(!0)),o.$$keydown=e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),a(!0)):e.key===`Escape`&&(e.preventDefault(),a(!1))},o.$$mousedown=e=>e.stopPropagation(),o.$$click=e=>e.stopPropagation();var c=t;return typeof c==`function`?ge(c,o):t=o,L(o,`maxlength`,200),s.$$click=e=>{e.preventDefault(),e.stopPropagation(),i()},s.$$mousedown=e=>{e.preventDefault(),e.stopPropagation()},D(()=>G(o,`rename-field${e.class?` ${e.class}`:``}`)),D(()=>o.value=r??e.title),n})()}P([`click`,`mousedown`,`keydown`]);var Pg=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()}},Fg={phase:`off`,voice:`off`,level:0,held:``,paused:!1},Ig=class{deps;state=Fg;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({...Fg,phase:`starting`,sessionID:e,voice:`starting`});let i=await this.deps.expose(e);if(t!==this.run)return;if(!i)return this.set({...Fg,error:{sessionID:e,message:`Could not turn Voice on for this session.`}});let a=this.deps.create(e,{state:e=>t===this.run&&this.set({...this.state,voice:e,paused:e===`paused`}),level:e=>t===this.run&&this.set({...this.state,level:e}),held:e=>t===this.run&&this.set({...this.state,held:e}),ignored:e=>t===this.run&&this.set({...this.state,ignored:e}),timing:e=>t===this.run&&this.set({...this.state,timing:e}),detector:e=>t===this.run&&this.set({...this.state,detector:e}),user:t=>this.sinks.get(e)?.user(t)??`voice:${++this.bubbles}`,tick:(t,n)=>this.sinks.get(e)?.tick(t,n),agent:t=>this.sinks.get(e)?.agent(t),note:(i,a)=>{if((a===`err`||a===`gesture`)&&t===this.run&&this.state.phase===`starting`){n=i,r=a===`gesture`;return}if(a===`gesture`&&t===this.run&&this.state.phase===`on`){let t=this.stop(),n=this.run;t.then(()=>n===this.run&&this.set({...Fg,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(Fg))}});this.conversation=a;let o=await a.start();if(t===this.run){if(!o)return this.run++,this.conversation=void 0,this.set({...Fg,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(Fg),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()}},Lg=3e3,Rg=`Voice mode on`,zg=`Voice mode paused · unlock to talk`,Bg={starting:`starting`,listening:`listening`,hearing:`listening`,transcribing:`thinking`,sent:`thinking`,speaking:`speaking`,paused:`muted`,suspended:`paused`,off:`off`},Vg=(e,t,n,r=``)=>({sessionID:e,title:n===`suspended`?zg:Rg,body:`${t} · ${Bg[n]??n}${r}`}),Hg=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:Rg,artist:`${n}${r}`},()=>void this.controller.end())),!this.surface.allowed())return;let a=Vg(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+Lg-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)}},Ug=[`image/png`,`image/jpeg`,`image/webp`,`image/gif`],Wg={maxImages:4,maxSide:1600,perImageBase64:18e4,totalBase64:7e5},Gg=[.85,.72,.6,.48,.36],Kg=[1,.75,.55,.4,.28,.2],qg=class extends Error{constructor(e=`This image is too large to attach, even after shrinking it`){super(e),this.name=`ImageTooLargeError`}},Jg=e=>4*Math.ceil(e/3),Yg=e=>Ug.includes(e);function Xg(e,t,n=Wg){if(e>=n.maxImages)return`Attach at most ${n.maxImages} images to a message`;if(!Yg(t))return`Only PNG, JPEG, WebP or GIF images can be attached`}function Zg(e,t=Wg){return Math.max(0,Math.min(t.perImageBase64,t.totalBase64-e))}function Qg(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 $g(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 e_(e,t,n,r=Wg){if(t<=0)throw new qg(`No room for another image in this message`);let i=Qg(e.width,e.height,r.maxSide);for(let r of Kg){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}]:[],...Gg.map(e=>({type:`image/jpeg`,quality:e,width:a,height:o}))];for(let e of s){let r=await n(e);if(Jg(r.size)<=t)return{blob:r,request:e}}}throw new qg}var t_=()=>({draft:``,images:[],pending:[],stopping:!1});function n_(e,t){switch(t.type){case`input`:return{...e,draft:t.text,error:void 0};case`attach`:return e.images.length>=Wg.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,Wg.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 r_(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 i_(e,t){return e===202?t.mode===`turn`?`accepted`:`steered`:`result`}function a_(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 o_(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 s_=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)}},c_=-19.5,l_=-50,u_=20,d_=9,f_=2,p_=60,m_=.4,h_=.1,g_=-70,__=-10,v_=e=>e>0?20*Math.log10(e):-1/0,y_=e=>e>0?-.691+10*Math.log10(e):-1/0;function b_(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 x_(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 S_(e,t){if(!e.length)return-1/0;let[n,r]=b_(t),i=x_(x_(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(m_*t),s=Math.round(h_*t);if(i.length<o){let e=y_(a[i.length]/i.length);return e>g_?e:-1/0}let c=[];for(let e=0;e+o<=i.length;e+=s){let t=(a[e+o]-a[e])/o;y_(t)>g_&&c.push(t)}if(!c.length)return-1/0;let l=e=>e.reduce((e,t)=>e+t,0)/e.length,u=y_(l(c))+__,d=c.filter(e=>y_(e)>u);return y_(l(d.length?d:c))}function C_(e){let t=0;for(let n=0;n<e.length;n++)t=Math.max(t,Math.abs(e[n]));return v_(t)}function w_(e,t){let n=10**(l_/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 T_(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,f_/1e3*t)),n=Math.exp(-1/Math.max(1,p_/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 E_(e,t,n){let r=w_(e,t),i=S_(r,t);if(!Number.isFinite(i))return{samples:r,gainDb:0,loudness:i};let a=10**(-1/20),o=Math.min(u_,-1-C_(r)+d_),s=Math.min(n-i,o),c=T_(r,t,10**(s/20),a);for(let e=0;e<3;e++){let e=n-S_(c,t);if(e<.1||s>=o)break;s=Math.min(s+e,o),c=T_(r,t,10**(s/20),a)}return{samples:c,gainDb:s,loudness:i}}function D_(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 O_=`voice.replyLoudness`,k_=8;function A_(e){try{let t=JSON.parse(e.getItem(O_)??`{}`);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}function j_(e,t){let n=A_(e)[t];return Array.isArray(n)?n.filter(e=>typeof e==`number`&&Number.isFinite(e)):[]}function M_(e,t,n){if(!(!Number.isFinite(n)||n<-50||n>0))try{let r=A_(e),i=[...j_(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-k_)))delete r[e];e.setItem(O_,JSON.stringify(r))}catch{}}var N_=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 P_(e,t){let n=[];try{t!==void 0&&(n=j_(e,t))}catch{n=[]}return n.length?Math.min(-14,Math.max(-26,N_(n))):c_}var F_={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}]},I_=`hub-cues-v2`,L_=[`hub-cues-v1`],R_=`x-hub-cue-target`,z_=1,B_=`https://hub-cues.invalid`,V_=e=>`${B_}/${encodeURIComponent(e)}/`,H_=(e,t)=>`${V_(e)}${encodeURIComponent(t)}`;async function U_(){try{let e=globalThis.caches;return e?await e.open(I_):void 0}catch{return}}function W_(e,t){e.defaultPlaybackRate=t,e.playbackRate=t,e.preservesPitch=!0,e.webkitPreservesPitch=!0}var G_=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))}},K_=class{api;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({api:e,speed:t,onSpeaking:n,onPlayed:r,audio:i,normalize:a,target:o,memory:s=G_}){this.api=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=F_[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 U_():void 0,i=n?H_(n,e):``,a=this.target?.(n)??-19.5,o=e=>!this.normalize||Math.abs((e??NaN)-a)<=z_,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(R_);l=t==null?void 0:Number(t)}if(!c||!o(l)){let n=c??await(await this.api(`/api/speak`,{method:`POST`,json:{text:e},signal:t})).blob();c=n;let o={};if(this.normalize)try{c=await this.normalize(n,a),o[R_]=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 U_():void 0;if(!t||!e)return;let n=globalThis.caches;for(let e of L_)await n?.delete(e).catch(()=>!1);try{for(let n of await t.keys())n.url.startsWith(V_(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,W_(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}},q_=new Set([`um`,`umm`,`uh`,`uhh`,`uhm`,`erm`,`er`,`eh`,`ah`,`hmm`,`hm`,`mm`,`mmm`,`mhm`,`mm-hmm`,`uh-huh`]),J_=new Set([...q_,`and`,`but`,`so`,`or`,`because`,`cause`,`then`,`with`,`to`,`the`,`a`,`an`,`of`,`for`,`if`,`that`,`like`,`maybe`]),Y_=new Map([[`stop`,`interrupt`],[`cancel`,`interrupt`],[`never mind`,`interrupt`],[`nevermind`,`interrupt`],[`stop that`,`interrupt`],[`hold on`,`interrupt`],[`pause listening`,`pause`]]);function X_(e){return String(e??``).toLowerCase().replace(/[^\p{L}\p{N}'\s-]+/gu,` `).split(/\s+/).map(e=>e.replace(/^[-']+|[-']+$/g,``)).filter(Boolean)}function Z_(e){return Y_.get(X_(e).join(` `))}function Q_(e){return X_(e).every(e=>q_.has(e))}function $_(e){let t=String(e??``).trim(),n=X_(t);return!n.length||J_.has(n[n.length-1])||/(\.\.\.|…|[,;:\-–—])["'”’)\]]*$/.test(t)?!1:/[.?!]["'”’)\]]*$/.test(t)?!0:n.length>=3}var ev=new Set([`e.g.`,`i.e.`,`mr.`,`mrs.`,`ms.`,`dr.`,`st.`,`vs.`,`cf.`,`prof.`,`jr.`,`sr.`,`approx.`,`no.`,`fig.`]),tv=/[.?!…]+["'”’)\]]*(?=\s|$)/g;function nv(e,{minChars:t=4,maxChars:n=300}={}){let r=String(e??``).replace(/```[\s\S]*?(?:```|$)/g,`
|
|
15
|
-
(code omitted)
|
|
16
|
-
`).split(/\r?\n/).map(e=>e.replace(/\s+/g,` `).trim()).filter(Boolean).flatMap(rv),i=[],a=``;for(let e of r){let n=a?`${a} ${e}`:e;n.length<t?a=n:(i.push(n),a=``)}return a&&(i.length?i[i.length-1]+=` ${a}`:i.push(a)),i.flatMap(e=>iv(e,n))}function rv(e){let t=[],n=0;for(let r of e.matchAll(tv)){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(ev.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 iv(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 av=16e3;function ov(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 sv(e,t){return D_(ov(e,t,av),av)}function cv(e){return{audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,...e?{deviceId:{exact:e}}:{}}}}var lv=Object.freeze({minSpeechMs:300,endSilenceMs:350,trailingKeepMs:200,preRollMs:300,holdMs:1600,finishedHoldMs:1e3}),uv=lv.trailingKeepMs,dv=120,fv=4,pv=e=>e.reduce((e,t)=>e+t.ms,0);function mv(e,t){for(;e.length>1&&pv(e)-e[0].ms>=t;)e.shift()}var hv=class{sampleRate;minSpeechMs;endSilenceMs;preRollMs;maxSegmentMs;onsetGapMs;minVoicedRatio;state=`silence`;preroll=[];frames=[];segmentMs=0;onsetMs=0;voicedMs=0;gapMs=0;silenceMs=0;constructor({sampleRate:e,minSpeechMs:t=lv.minSpeechMs,endSilenceMs:n=lv.endSilenceMs,preRollMs:r=lv.preRollMs,maxSegmentMs:i=6e4,onsetGapMs:a=dv,minVoicedRatio:o=0}){this.sampleRate=e,this.minSpeechMs=t,this.endSilenceMs=n,this.preRollMs=r,this.maxSegmentMs=i,this.onsetGapMs=a,this.minVoicedRatio=o,this.reset()}get active(){return this.state===`speech`}reset(){this.state=`silence`,this.preroll=[],this.frames=[],this.segmentMs=0,this.onsetMs=0,this.voicedMs=0,this.gapMs=0,this.silenceMs=0}process(e,t){let n={samples:Float32Array.from(e),ms:e.length/this.sampleRate*1e3},r=[];if(this.state===`silence`)t?(this.state=`onset`,this.frames=[...this.preroll,n],this.segmentMs=pv(this.frames),this.preroll=[],this.onsetMs=this.voicedMs=n.ms,this.gapMs=0):(this.preroll.push(n),mv(this.preroll,this.preRollMs));else if(this.state===`onset`)this.frames.push(n),this.segmentMs+=n.ms,this.onsetMs+=n.ms,t?(this.voicedMs+=n.ms,this.gapMs=0):((this.gapMs+=n.ms)>this.onsetGapMs||this.voicedMs<this.minVoicedRatio*this.onsetMs)&&(this.preroll=this.frames,mv(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-uv;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}}},gv=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-fv: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}}},_v=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;constructor({send:e,holdMs:t=lv.holdMs,finishedHoldMs:n=lv.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()}){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.reset()}get held(){return this.text}reset(){this.cancelHold(),this.pending=[],this.text=``,this.ms=0,this.segments=[],this.speaking=!1,this.onHeld?.(``)}speechStarted(){this.speaking=!0,this.cancelHold()}segmentEnded(e){this.speaking=!1,this.endedAt=this.now();let t=this.nextID++;return this.pending.push({id:t,ms:e,endedAt:this.endedAt}),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}){Z_(t)?(this.cancelHold(),this.text=``,this.ms=0,this.segments=[],this.sent(t,[e],`command`)):Q_(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;this.cancelHold();let e=$_(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();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}},vv=2,yv=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?vv: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))}},bv=class{parts=new Map;limit;constructor({limit:e=50}={}){this.limit=e}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=nv(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=>nv(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]}},xv=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)}}},Sv=e=>`${(e/1e3).toFixed(1)} s`;function Cv(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} ${Sv(n-i)}`),i=n)}return{summary:`last turn: ${Sv(e.firstAudio-t)} to first audio`,detail:r.join(` · `)}}var wv=12,Tv=e=>String(e??``).replace(/\s+/g,` `).trim();function Ev(e,t){let n=Tv(e),r=Tv(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>=wv;e--)if(n.endsWith(r.slice(0,e)))return{mode:`update`,text:n+r.slice(e)};return{mode:`new`,text:t}}function Dv(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 Ov=16e3,kv=512/Ov*1e3,Av=Object.freeze({startProb:.6,endProb:.35,speakingStartProb:.85,minSpeechMs:250,endSilenceMs:lv.endSilenceMs,maxSegmentMs:6e4,gateDb:3,energyMarginDb:10,energyMinSpeechMs:lv.minSpeechMs}),jv=Object.freeze([`low`,`normal`,`high`]);function Mv(e){return jv.includes(e)?e:`normal`}var Nv=Object.freeze({low:Object.freeze({...Av,startProb:.75,endProb:.45,speakingStartProb:.92,minSpeechMs:350,gateDb:6,energyMarginDb:13,energyMinSpeechMs:400}),normal:Av,high:Object.freeze({...Av,startProb:.45,endProb:.25,speakingStartProb:.75,minSpeechMs:180,gateDb:0,energyMarginDb:7,energyMinSpeechMs:250})});function Pv(e){return Nv[Mv(e)]}var Fv=.75,Iv=class{speaking=!1;segmenter;current;constructor(e,t=Ov){this.current=e,this.segmenter=new hv({sampleRate:t,endSilenceMs:e.endSilenceMs,maxSegmentMs:e.maxSegmentMs})}get params(){return this.current}set params(e){this.current=e,this.segmenter.endSilenceMs=e.endSilenceMs,this.segmenter.maxSegmentMs=e.maxSegmentMs}get state(){return this.segmenter.state}get active(){return this.segmenter.active}reset(){this.segmenter.reset()}process(e,t){let n=this.current;this.segmenter.minSpeechMs=n.minSpeechMs,this.segmenter.minVoicedRatio=Fv;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)}},Lv=class{from;ratio;input=new Float32Array;pos=0;out=new Float32Array(512);filled=0;constructor(e){this.from=e,this.ratio=e/Ov}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}},Rv=64,zv=class{sampleRate=Ov;stats={frames:0,avgMs:0,maxMs:0,skipped:0};resampler;meter;vad;onEvents;onLevel;warn;now;model;queue=[];inFlight=0;generation=0;warned=new Set;speakingOn=!1;tail=0;constructor({sampleRate:e,params:t=Av,onEvents:n,onLevel:r,warn:i=e=>console.warn(e),now:a=()=>performance.now()}){this.resampler=new Lv(e),this.meter=new gv({marginDb:t.energyMarginDb}),this.vad=new Iv(t),this.onEvents=n,this.onLevel=r,this.warn=i,this.now=a}get classifier(){return this.model}set classifier(e){this.model=e}get mode(){return this.model?`silero`:`energy`}get params(){return this.vad.params}set params(e){this.vad.params=e,this.meter.marginDb=e.energyMarginDb}get speaking(){return this.speakingOn}set speaking(e){this.speakingOn&&!e&&(this.tail=Math.ceil(400/kv)),this.speakingOn=e}get active(){return this.vad.active}reset(){this.generation++,this.queue=[],this.inFlight=0,this.vad.reset()}push(e){for(let t of this.resampler.push(e))this.chunk(t)}chunk(e){let t=this.speakingOn||this.tail>0;!this.speakingOn&&this.tail>0&&this.tail--,this.meter.speaking=t;let n=this.vad.state===`speech`,{db:r,floor:i,level:a,voiced:o}=this.meter.measure(e,kv,n);this.onLevel?.(a);let s={chunk:e,energyVoiced:o,guarded:t};this.queue.push(s),this.model&&this.inFlight>=Rv&&this.drop(`stalled`);let c=this.model;if(!c)s.energy=!0;else if(!n&&r<i+this.vad.params.gateDb+(t?this.meter.speakingBoostDb:0))s.prob=0,this.stats.skipped++;else{let t=this.generation,n=this.now();this.inFlight++,c(e).then(e=>{t===this.generation&&(this.inFlight--,this.record(this.now()-n),s.prob=e,this.drain())},e=>{t===this.generation&&(this.inFlight--,s.energy=!0,this.model===c&&this.drop(e?.message??String(e)),this.drain())})}this.drain()}drop(e){this.model=void 0,this.generation++,this.inFlight=0;for(let e of this.queue)e.prob===void 0&&(e.energy=!0);this.warnOnce(`failed`,`Voice: on-device speech detection stopped (${e}); using the energy detector`)}record(e){let t=this.stats;t.frames++,t.avgMs+=(e-t.avgMs)/t.frames,t.maxMs=Math.max(t.maxMs,e)}drain(){let e=[];for(;this.queue.length&&(this.queue[0].energy||this.queue[0].prob!==void 0);){let t=this.queue.shift();this.vad.speaking=t.guarded,e.push(...t.energy?this.vad.processEnergy(t.chunk,t.energyVoiced):this.vad.process(t.chunk,t.prob))}e.length&&this.onEvents(e)}warnOnce(e,t){this.warned.has(e)||(this.warned.add(e),this.warn(t))}};function Bv(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 Vv(e){return e.audioState===`suspended`||e.error===`NotAllowedError`&&!e.activated&&e.micPermission!==`denied`}var Hv=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(`.`)),Uv=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`]),Wv=[/^(?:subtitles?|captions?|subtitled|captioned|transcribed|transcription|translated|translation)\b.*\bby\b/,/\bamara\s*\.?\s*org\b/,/^sous-titr/,/^untertitel\b/],Gv=/^(?:\[[^\]]*\]|\([^)]*\)|\*[^*]*\*|♪[^♪]*♪|\s)+$/u;function Kv(e){return e.toLowerCase().replace(/[^\p{L}\p{N}'\s]+/gu,` `).replace(/\s+/g,` `).trim()}function qv(e,{speechMs:t}={}){let n=String(e??``).trim();if(!n)return`empty`;if(!/[\p{L}\p{N}]/u.test(n))return`no words`;if(Gv.test(n))return`sound`;let r=Kv(n);if(r.replace(/\s/g,``).length<2)return`too short`;if(Uv.has(r)||Uv.has(r.replace(/ /g,``))||Wv.some(e=>e.test(r)||e.test(n.toLowerCase())))return`noise`;let i=r.split(` `),a=i.some(e=>Hv.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 Jv=3e4,Yv;function Xv(){return Yv??=Zv().catch(e=>{throw Yv=void 0,e}),Yv}function Zv(){return new Promise((e,t)=>{let n;try{n=new Worker(new URL(`/assets/silero-worker-DhlIHyD_.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(),Yv=void 0,a||t(e)},s=setTimeout(()=>o(Error(`the speech model took too long to load`)),Jv);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 Qv=()=>Object.assign(Error(`The download was aborted`),{name:`AbortError`}),$v=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 Qv();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 ey(e,t){let n=new $v;if(!e)return n.end(),n;let r=e.getReader(),i=()=>{n.fail(Qv()),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?Qv():e)}finally{t?.removeEventListener(`abort`,i)}})(),n}async function ty(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 ny(e){try{return e.MediaSource?.isTypeSupported?.(`audio/mpeg`)===!0}catch{return!1}}var ry=24e3,iy=1,ay=2;async function oy(e){let t=globalThis,n=t.OfflineAudioContext||t.webkitOfflineAudioContext;if(!n)throw Error(`No OfflineAudioContext here`);let r=new n(1,1,ry),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 sy(e,t){let{samples:n,rate:r}=await oy(await e.arrayBuffer()),i=E_(n,r,t);return new Blob([D_(i.samples,r)],{type:`audio/wav`})}function cy(e){try{return P_(localStorage,e)}catch{return P_({getItem:()=>null,setItem:()=>{}},e)}}var ly=0,uy=e=>{let t=globalThis;t.requestIdleCallback?t.requestIdleCallback(e,{timeout:5e3}):setTimeout(e,500)};function dy(e,t){!t||!e.length||ly>=ay||(ly++,uy(()=>{(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 oy(n.buffer);if(i.length<a*iy)return;M_(localStorage,t,S_(i,a))}catch{}finally{ly--}})()}))}var fy=500,py=8e3,my=e=>Math.min(py,fy*2**Math.max(0,e)),hy=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)}},gy=2500,_y=3e3,vy=!1,yy=2,by=`Tap to start Voice mode`,xy=`GestureRequired`,Sy=500,Cy=500,wy=3e3,Ty=()=>navigator.userActivation?.hasBeenActive??!0;async function Ey(){try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return`unknown`}}var Dy={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`},Oy=50,ky=class{sessionID;api;player;ui;opts;rec;heldText=``;spoken=[];playingRef;reachedEnd=!1;active=!1;paused=!1;agent;inflight=0;sent=new Map;typed=new Set;typing=0;heardAt=0;lastStatus;cuePicker=new mo({ready:e=>this.cuePlayer?.ready(e)??!1});scheduler=new ho({pick:e=>this.cuePicker.pick(e)});cuePlayer;voiceKey;onVisibility;liveness=new hy({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=ny(window);says=new bv;turns;cueClock;speechEndedAt;silence;silenceURL;wakeLock;warnedAutoplay=!1;state;ignoredTimer;sensitivity=`normal`;cueSpeaking=!1;attempt=0;constructor({sessionID:e,api:t,player:n,ui:r,options:i={}}){this.sessionID=e,this.api=t,this.player=n,this.ui=r;let{recorder:a,...o}=i;this.opts={cues:!0,background:!1,speed:()=>1,title:()=>`OpenCode session`,sensitivity:()=>`normal`,...o},this.rec=a,a&&(a.onNote=e=>this.ui.note(e)),this.turns=new xv({now:a?()=>performance.now():()=>Date.now()}),this.lastStatus=i.status,this.scheduler.enabled=this.opts.cues!==!1,this.scheduler.working(yo(i.status),Date.now()),this.cuePlayer=new K_({api:this.api,speed:this.opts.speed,normalize:sy,target:cy,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 go({scheduler:this.scheduler,play:e=>this.cuePlayer.play(e),ready:()=>this.active&&!this.paused}),this.onVisibility=()=>{let e=document.visibilityState===`visible`;this.liveness.visibility(e,Date.now()),this.active&&(e?(this.opts.background||this.lockScreen(),this.recover()):this.opts.background&&!this.paused&&this.silence?.play().catch(()=>{}))}}onWake=()=>{this.active&&document.visibilityState===`visible`&&this.recover()};onTrackMute=()=>this.liveness.muted(!0,Date.now());onTrackUnmute=()=>{this.liveness.muted(!1,Date.now()),this.recover()};onTrackEnded=()=>this.liveness.ended(Date.now());get path(){return`/api/sessions/${encodeURIComponent(this.sessionID)}`}async start(){if(this.active)return!0;let e=++this.attempt,t=()=>e!==this.attempt;this.ui.state(`starting`),this.cuePlayer.unlock(),this.opts.background&&this.startSilence();let n=window;if(!navigator.mediaDevices?.getUserMedia||!(n.AudioContext||n.webkitAudioContext))return this.ui.note(`This browser cannot listen here (the microphone needs HTTPS).`,`err`),this.ui.state(`off`),!1;let r;try{r=await navigator.mediaDevices.getUserMedia(cv(this.opts.deviceId))}catch(e){if(t())return!1;let n=e;return Vv({error:n.name,micPermission:await Ey(),activated:Ty()})?this.ui.note(by,`gesture`):this.ui.note(n.name===`NotAllowedError`?`Microphone permission was denied. Allow it in the browser's site settings.`:`Microphone: ${n.message}`,`err`),this.ui.state(`off`),this.stopSilence(),!1}if(t())return r.getTracks().forEach(e=>e.stop()),!1;this.stream=r;try{let{agent:e}=await(await this.api(`${this.path}/conversation`,{method:`POST`,json:{on:!0}})).json();this.agent=e}catch(e){return this.release(),this.stopSilence(),t()||(this.ui.note(`Could not start Voice mode: ${e.message}`,`err`),this.ui.state(`off`)),!1}if(t())return this.release(),await this.api(`${this.path}/conversation`,{method:`POST`,json:{on:!1}}).catch(()=>{}),!1;this.active=!0,this.rec?.start(this.sessionID,{detector:`energy`,sensitivity:this.opts.sensitivity(),cues:this.opts.cues!==!1,background:!!this.opts.background,streaming:this.streaming,timings:{...lv}}),this.prefetchCues();try{await this.listen()}catch(e){return t()||(e.name===xy?this.ui.note(by,`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(),Cy),this.cueClock.poke(),this.refresh(),!0)}prefetchCues(){this.opts.cues!==!1&&this.scheduler.enabled&&this.cuePlayer.prefetch(po(),this.voiceKey=this.cueKey())}async cueKey(){try{let{tts:e}=await(await this.api(`/api/settings/speech`)).json();return e?.voice?[e.provider,e.model,e.voice,e.speed??``,e.baseURL??``].join(`|`):void 0}catch{return}}async listen(){let e=window,t=e.AudioContext||e.webkitAudioContext,n=this.ctx=new t;if(await Promise.race([n.resume().catch(()=>{}),new Promise(e=>setTimeout(e,Sy))]),Vv({audioState:n.state,activated:Ty()}))throw Object.assign(Error(by),{name:xy});if(this.liveness.start(Date.now()),n.onstatechange=()=>this.liveness.audio(n.state,Date.now()),this.watchTrack(this.stream),this.source=n.createMediaStreamSource(this.stream),this.sink=n.createGain(),this.sink.gain.value=0,this.sink.connect(n.destination),n.audioWorklet&&`AudioWorkletNode`in window){await n.audioWorklet.addModule(`/vad-worklet.js`);let e=new AudioWorkletNode(n,`vad-tap`,{numberOfInputs:1,numberOfOutputs:1,channelCount:1});e.port.onmessage=e=>this.frame(e.data),this.tap=e}else{let e=n.createScriptProcessor(1024,1,1);e.onaudioprocess=e=>this.frame(Float32Array.from(e.inputBuffer.getChannelData(0))),this.tap=e}this.source.connect(this.tap),this.tap.connect(this.sink),this.sensitivity=this.opts.sensitivity();let r=this.vad=new zv({sampleRate:n.sampleRate,params:Pv(this.sensitivity),onEvents:e=>this.vadEvents(e),onLevel:e=>this.ui.level(e)});this.detected({mode:`energy`}),Xv().then(e=>{this.vad===r&&(e.reset(),r.classifier=t=>e.classify(t),this.detected({mode:`silero`}))},e=>{vy||console.warn(`Voice: on-device speech detection unavailable (${e?.message??e}); using the energy detector`),vy=!0}),this.endpointer=new _v({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},...this.rec?{onSend:e=>this.rec?.event(`utterance.sent`,{text:e.text,segments:[...e.segments],reason:e.reason,holdMs:Math.round(e.holdMs)}),onMerge:e=>this.rec?.event(`utterance.merged`,{segments:[...e.segments],pauseMs:Math.round(e.pauseMs)})}:{}}),this.queue=new yv({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)}:{}})}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>Oy&&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;let t=this.opts.sensitivity();t!==this.sensitivity&&(this.sensitivity=t,this.vad.params=Pv(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.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=sv(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});try{let n=await this.api(`/api/transcribe`,{method:`POST`,body:t,headers:{"content-type":`audio/wav`,...this.rec?.transcribeHeaders(e)}});a=Ml(n.headers?.get?.(Yc)),r=(await n.json()).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{this.inflight--}if(!this.active)return;let o=r,s=qv(r,{speechMs:n});s&&(r.trim()&&this.showIgnored(r.trim()),r=``),this.rec&&(this.rec.event(`stt.received`,{segment:e,text:o,...s&&o.trim()?{junk:!0}:{},...!o.trim()&&i===void 0?{empty:!0}:{},...i===void 0?{}:{failed:i},...a?{audio:a}:{}}),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?.(``),_y)}async deliver(e,t=!1){let n=Z_(e);if(n&&this.rec?.event(`utterance.command`,{command:n,text:e}),n===`pause`)return this.ui.note(`Paused listening.`),this.stop();if(n===`interrupt`){this.hushReplies(`command`),this.ui.note(`“${e}” — interrupting.`);try{await this.api(`${this.path}/interrupt`,{method:`POST`,json:{}})}catch(e){this.ui.note(`Could not interrupt: ${e.message}`,`err`),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(await this.api(`${this.path}/utterance`,{method:`POST`,json:{text:e}})).json();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,i=sl({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:yo(this.lastStatus)});i&&this.rec.record(i),this.spoken=[]}onEvent(e){if(e.sessionID===this.sessionID){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?nv(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&&(this.ui.note(`Voice mode was turned off.`),this.stop({post:!1}))}}onStatus(e){let t=Date.now(),{started:n,finished:r}=vo(this.lastStatus,e,this.sessionID);if(this.lastStatus=e,this.scheduler.working(yo(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.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];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<wy)&&(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.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()},my(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,Sy))])}async reacquire(){let e;try{e=await navigator.mediaDevices.getUserMedia(cv(this.opts.deviceId))}catch(e){if(!this.active)return;Vv({error:e.name,micPermission:await Ey(),activated:Ty()})&&this.ui.note(by,`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([sv(new Float32Array(16e3*yy),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=ey((await this.api(`/api/speak`,{method:`POST`,json:{text:e},signal:t,...r&&Object.keys(r).length?{headers:r}:{}})).body,t);return i.firstByte.then(()=>{this.markTurn(`firstByte`),n&&this.rec?.event(`tts.first.byte`,{ref:n})},()=>{}),i.whole().then(async e=>dy(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 ty(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(Dy[e])}catch{}let t=e===`firstAudio`?Cv(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<gy?`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`)}catch{}}release(){this.unwatchTrack(),this.stream?.getTracks().forEach(e=>e.stop()),this.stream=void 0}async stop({post:e=!0,keepalive:t=!1}={}){this.attempt++;let n=this.active;this.active=!1,this.paused=!1,this.state=void 0,document.removeEventListener(`visibilitychange`,this.onVisibility),window.removeEventListener?.(`pageshow`,this.onWake),window.removeEventListener?.(`focus`,this.onWake),clearInterval(this.micTimer),clearTimeout(this.recoverTimer),this.micTimer=this.recoverTimer=void 0,this.recoverAttempt=0,this.ctx&&(this.ctx.onstatechange=null),this.cueClock.stop(),this.cuePlayer.close(),this.stopSilence(),this.opts.background&&this.clearMediaSession(),this.hushReplies(`stop`),this.endpointer?.reset(),this.vad?.reset();try{this.source?.disconnect(),this.tap?.disconnect(),this.tap&&`port`in this.tap&&(this.tap.port.onmessage=null),this.sink?.disconnect()}catch{}this.ctx?.close().catch(()=>{}),this.ctx=this.source=this.tap=this.sink=this.vad=void 0,this.release(),this.wakeLock?.release().catch(()=>{}),this.wakeLock=void 0,this.ui.level(0),this.ui.held?.(``),clearTimeout(this.ignoredTimer),this.ui.ignored?.(``),this.ui.state(`off`),this.ui.ended(),this.rec&&(this.rec.event(`state`,{state:`off`}),this.rec.stop({keepalive:t,reason:e?`stopped`:`conversation_off`})),e&&n&&await this.api(`${this.path}/conversation`,{method:`POST`,json:{on:!1},keepalive:t}).catch(()=>{})}},Ay=`voice.speed`,jy=`voice.cues`,My=`voice.background`,Ny=`voice.micDevice`,Py=`voice.sensitivity`,Fy=Mv(localStorage.getItem(Py)),Iy={get speed(){return io(localStorage.getItem(Ay))},set speed(e){localStorage.setItem(Ay,String(io(e))),W_(Ly,io(e))},get cues(){return localStorage.getItem(jy)!==`0`},set cues(e){localStorage.setItem(jy,e?`1`:`0`)},get background(){return localStorage.getItem(My)===`1`},set background(e){localStorage.setItem(My,e?`1`:`0`)},get sensitivity(){return Fy},set sensitivity(e){Fy=Mv(e),localStorage.setItem(Py,Fy)}},Ly=new Audio;Ly.preload=`none`,Ly.volume=1,W_(Ly,Iy.speed);function Ry(){Ly.paused&&(Ly.muted=!0,Ly.play().catch(()=>{}).finally(()=>{Ly.pause(),Ly.muted=!1}))}var[zy,By]=x(localStorage.getItem(Ny)??``);function Vy(e){By(e),localStorage.setItem(Ny,e)}async function Hy(){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 Uy(e,t){let n=await navigator.mediaDevices.getUserMedia(cv(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 Wy=6e4;function Gy(){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 Ky(e){if(!navigator.mediaDevices?.getUserMedia||!window.MediaRecorder)throw Error(`This browser cannot record here (the microphone needs HTTPS).`);let t;try{t=await navigator.mediaDevices.getUserMedia(cv(zy()||void 0))}catch(e){let t=e;throw Error(t.name===`NotAllowedError`?`Microphone permission was denied. Allow it in the browser's site settings.`:`Microphone: ${t.message}`)}let n=Gy(),r=new MediaRecorder(t,n?{mimeType:n}:void 0),i=[],a=Date.now();r.ondataavailable=e=>e.data.size&&i.push(e.data);let o=!1,s=new Promise((e,a)=>{r.onstop=async()=>{if(clearInterval(c),clearTimeout(l),t.getTracks().forEach(e=>e.stop()),o)return e(``);let s=new Blob(i,{type:(r.mimeType||n||`audio/webm`).split(`;`)[0]});if(!s.size)return e(``);try{let{text:t}=await(await W(`/api/transcribe`,{method:`POST`,body:s,headers:{"content-type":s.type}})).json();e(String(t??``).trim())}catch(e){let t=e;a(Error(t.status===413?`That recording was too long.`:`Transcription failed: ${t.message}`))}}});r.start();let c=setInterval(()=>e?.(Math.max(0,Math.ceil((Wy-(Date.now()-a))/1e3))),1e3),l=setTimeout(()=>r.state===`recording`&&r.stop(),Wy);return{finish(){return r.state===`recording`&&r.stop(),s},cancel(){o=!0,r.state===`recording`&&r.stop()}}}var[qy,Jy]=x(Date.now());setInterval(()=>pu()&&Jy(Date.now()),1e3);var[Yy,Xy]=x(!1),Zy=e=>Xy(e),Qy=()=>rc($l(),pu(),Math.max(qy(),Date.now())),$y=(e,t)=>$l().find(t=>t.id===e)?.options.find(e=>e.id===t)?.label??t;async function eb(t,n,r){let i=$y(t,n);try{let{decision:e}=await(await W(`/api/decisions/${B(t)}/answer`,{method:`POST`,json:{option:n,...r?{via:r}:{}}})).json().catch(()=>({}));e?gd(e):_d(t),K(`Answered “${i}”${r?` by ${r}`:``}`)}catch(n){throw n instanceof e&&n.status===409&&n.code===`gone`?(_d(t),new e(409,`Already answered or expired`)):n}}function tb(t){return gc(W,{sessionID:t,current:()=>ou()?.sessionID,armed:()=>Qy(),present:()=>Yy()&&document.visibilityState===`visible`,answer:async(t,n)=>{try{await eb(t,n,`voice`),Rl(`decision.voice`,{decisionID:t,option:n,outcome:`answered`})}catch(r){let i=r instanceof e&&r.status===403;throw Rl(`decision.voice`,{decisionID:t,option:n,outcome:i?`refused`:`failed`}),Object.assign(Error(i?`Not answered by voice: ${r.message}. Tap an option on the card.`:`Not answered: ${r instanceof Error?r.message:String(r)}`),{status:409})}}})}var nb=new Ig({async expose(e){let t=()=>Du(e)?.session.exposed!==!1;if(t())return!0;if(!await kd(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 ky({sessionID:e,api:tb(e),player:Ly,ui:t,options:{cues:Iy.cues,background:Iy.background,speed:()=>Iy.speed,sensitivity:()=>Iy.sensitivity,title:()=>Du(e)?.session.title||`OpenCode session`,status:Du(e)?.session.status,deviceId:zy()||void 0,recorder:new zl}}),stopPlayback:()=>{Ly.paused||Ly.pause()},notify:(e,t)=>K(e,t===`err`?`err`:``)}),[rb,ib]=x(0);nb.subscribe(()=>ib(e=>e+1));var ab=`voice-mode`,ob=Promise.resolve(),sb=e=>{ob=ob.then(async()=>{let t=`serviceWorker`in navigator?await navigator.serviceWorker.getRegistration(`/`):void 0;t&&await e(t)}).catch(()=>{})},cb={allowed:()=>`Notification`in window&&Notification.permission===`granted`&&`serviceWorker`in navigator,show:e=>sb(t=>t.showNotification(e.title,{body:e.body,tag:ab,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:()=>sb(async e=>(await e.getNotifications({tag:ab})).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{}}},lb=new Hg(nb,cb,{title:e=>Du(e)?.session.title||`OpenCode session`,suffix:()=>Ol(El.get())});El.subscribe(()=>lb.refresh()),Lf(e=>{e?.type===`voice-end`&&typeof e.sessionID==`string`&&lb.endFromNotification(e.sessionID)});function ub(){return rb(),lb.needsPermission()}async function db(){try{await Af()}catch(e){K(e instanceof Error?e.message:String(e),`err`)}lb.refresh(),ib(e=>e+1)}function fb(){return rb(),nb.state}var pb=()=>{let e=fb().sessionID;return e?Du(e)?.session.title||`Session`:``};Tu(e=>{e.type===`say`||e.type===`heard`||e.type===`conversation`?nb.onEvent(e):e.type===`status`&&typeof e.sessionID==`string`&&Array.isArray(e.sessions)&&nb.onStatus(e.sessionID,e.sessions)}),window.addEventListener(`pagehide`,()=>{nb.stop({keepalive:!0}),cb.close()});var mb=new s_,hb=new Pg({record:e=>Ky(e),deliver:(e,t)=>void mb.append(e,t),notify:(e,t)=>K(e,t),hold:()=>nb.hold()}),[gb,_b]=x(0);hb.subscribe(()=>_b(e=>e+1));function vb(e){return gb(),hb.forSession(e)}var yb=q(`<div class=banner><span></span><a class="btn small"href=/settings/machines>Review`),bb=q(`<div class=banner><span><strong>Set up speech</strong> · </span><a class="btn small"href=/settings/voice#speech>Set up`),xb=q(`<section class=decisions aria-label=Decisions><h2 class=section-title>`),Sb=q(`<select aria-label=Server><option value>All servers`),Cb=q(`<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`),wb=q(`<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.`),Tb=q(`<ul class=home-list>`),Eb=q(`<div class=home><header class=home-head><h1 class=display>All sessions</h1><a class="btn primary"href=/new> New session</a></header><div class=home-tools><label class=search><input type=search placeholder="Search title, project, folder or server"aria-label="Search sessions"></label><button type=button class="btn small">Archive inactive…</button></div><div class=chips role=group aria-label=Filters></div><p class="count muted"role=status>`),Db=q(`<option>`),Ob=q(`<button type=button class=chip>`),kb=q(`<p class="muted small offline-line"><strong></strong> · offline · seen `),Ab=q(`<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">`),jb=q(`<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>`),Mb=q(`<th><button type=button class=th-btn><span class=sort-mark aria-hidden=true>`),Nb=q(`<tr><td colspan=9 class="muted empty-cell">No sessions match.`),Pb=q(`<span class=jobs-badge>`),Fb=q(`<a>`),Ib=q(`<span class=unread-dot role=img aria-label=Unread>`),Lb=q(`<tr><td class=col-pick><input type=checkbox></td><td class=col-status><span class=sr-only></span></td><td class=col-title></td><td class=col-project></td><td class=col-server><span></span></td><td class=col-source></td><td class=col-activity></td><td></td><td class=col-actions>`),Rb=q(`<a class=home-item-link><span class=home-item-text><span class=home-item-title></span><span>`),zb=q(`<li>`),Bb=q(`<span class=home-item-link>`),Vb=`hub.table`;function Hb(e){Gl();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=Hl.has(e.id)?Hl.feed(e.id):void 0,r=n?.pulse(),i=e.jobs?` · ${Na(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: ${Na(e.jobs)}`:`Working`}var Ub=[[`status`,`Status`],[`title`,`Title`],[`project`,`Project`],[`server`,`Server`],[`source`,`Open in`],[`activity`,`Last activity`]],Wb=[[`needs`,`Needs you`,{status:`needs`}],[`running`,`Running`,{status:`running`}],[`idle`,`Idle`,{status:`idle`}],[`open`,`Open in terminal`,{source:`open`}],[`background`,`Background`,{source:`background`}],[`archived`,`Archived`,{archived:!0}]];function Gb(){let[e,t]=x(Ja(localStorage.getItem(Vb))),[r,i]=x(``),a=e=>{t(e),localStorage.setItem(Vb,Ya(e))},s=T(()=>Ka(Eu(),{...e(),query:r()})),[c,l]=x(new Set),d=T(()=>s().filter(e=>c().has(e.id))),f=(e,t)=>{let n=new Set(c());t?n.add(e):n.delete(e),l(n)},p=e=>l(e?new Set(s().map(e=>e.id)):new Set),m=()=>{Sh(d(),!e().filters.archived),l(new Set)},[h,g]=x(!1),_=()=>Y.machines??[],v=t=>Object.keys(t).every(n=>e().filters[n]===t[n]),y=t=>{let n=e().filters,r=Object.fromEntries(Object.keys(t).map(e=>[e,La.filters[e]]));a({...e(),filters:v(t)?{...n,...r}:{...n,...t}})},b=t=>{let n=e().sort;a({...e(),sort:{key:t,dir:n.key===t?n.dir===`asc`?`desc`:`asc`:t===`activity`?`desc`:`asc`}})},S=()=>Oo(Yl()??void 0,X()?.publicURL);return(()=>{var t=Eb(),l=t.firstChild,x=l.firstChild.nextSibling,C=x.firstChild,w=l.nextSibling,T=w.firstChild,E=T.firstChild,ee=T.nextSibling,te=w.nextSibling,O=te.nextSibling;return I(x,n(H,{name:`plus`}),C),I(t,n(u,{get when(){return Zl().length},get children(){var e=yb(),t=e.firstChild;return I(t,(()=>{var e=V(()=>Zl().length===1);return()=>e()?`${Zl()[0].machineName} wants to connect.`:`${Zl().length} machines want to connect.`})()),e}}),w),I(t,n(u,{get when(){return S()},get children(){var e=bb(),t=e.firstChild;return t.firstChild.nextSibling,I(t,()=>S().reason,null),e}}),w),I(t,n(u,{get when(){return $l().length},get children(){var e=xb(),t=e.firstChild;return I(t,(()=>{var e=V(()=>$l().length===1);return()=>e()?`A decision waits for you`:`${$l().length} decisions wait for you`})()),I(e,n(Eg,{get decisions(){return $l()},showSession:!0}),null),e}}),w),I(T,n(H,{name:`search`}),E),E.$$input=e=>i(e.currentTarget.value),ee.$$click=()=>g(!0),I(w,n(u,{get when(){return _().length>1},get children(){var t=Sb();return t.firstChild,t.addEventListener(`change`,t=>a({...e(),filters:{...e().filters,machine:t.currentTarget.value}})),I(t,n(o,{get each(){return _()},children:e=>(()=>{var t=Db();return I(t,()=>e.name),D(()=>t.value=e.id),t})()}),null),D(()=>t.value=e().filters.machine),t}}),null),I(te,n(o,{each:Wb,children:([e,t,n])=>(()=>{var r=Ob();return r.$$click=()=>y(n),L(r,`data-chip`,e),I(r,t),D(()=>L(r,`aria-pressed`,v(n))),r})()})),I(t,n(u,{get when(){return d().length},get children(){var t=Cb(),n=t.firstChild,r=n.firstChild,i=n.nextSibling,a=i.nextSibling;return I(n,()=>d().length,r),i.$$click=m,I(i,()=>e().filters.archived?`Unarchive`:`Archive`),a.$$click=()=>p(!1),t}}),O),I(O,(()=>{var t=V(()=>Y.machines===void 0);return()=>t()?`Loading…`:to(s().length,Eu().filter(e=>!e.hidden).length,$l().length,e().filters.status===`needs`)})()),I(t,n(u,{get when(){return V(()=>!!Y.machines)()&&Y.machines.length===0},get children(){return wb()}}),null),I(t,n(u,{get when(){return Z()},get fallback(){return n(Jb,{get rows(){return s()},get table(){return e()},sortBy:b,get picked(){return c()},pick:f,pickAll:p})},get children(){var e=Tb();return I(e,n(o,{get each(){return s()},children:e=>n(Yb,{row:e})})),e}}),null),I(t,n(o,{get each(){return _().filter(e=>!e.online)},children:e=>(()=>{var t=kb(),n=t.firstChild;return n.nextSibling,I(n,()=>e.name),I(t,()=>Be(e.lastSeen,F()),null),t})()}),null),I(t,n(qb,{get open(){return h()},get rows(){return Eu()},onClose:()=>g(!1)}),null),D(()=>E.value=r()),t})()}var Kb=30;function qb(e){let[t,r]=x(String(Kb)),i=T(()=>e.open?$a(e.rows,Number(t()),F()):[]),a=()=>i().length,o=()=>{Sh(i(),!0),e.onClose()};return n(ze,{get open(){return e.open},title:`Archive inactive sessions`,get onClose(){return e.onClose},get children(){var n=Ab(),i=n.firstChild,s=i.firstChild.nextSibling,c=i.nextSibling,l=c.firstChild,u=l.nextSibling;u.nextSibling;var d=c.nextSibling.firstChild,f=d.nextSibling;return n.addEventListener(`submit`,e=>{e.preventDefault(),a()&&o()}),s.$$input=e=>r(e.currentTarget.value),I(c,(()=>{var e=V(()=>a()===1);return()=>e()?`1 session`:`${a()} sessions`})(),l),I(c,(()=>{var e=V(()=>Number(t())===1);return()=>e()?`1 day`:`${t()||`?`} days`})(),u),ke(d,`click`,e.onClose,!0),I(f,(()=>{var e=V(()=>a()===1);return()=>e()?`Archive 1 session`:`Archive ${a()} sessions`})()),D(()=>f.disabled=!a()),D(()=>s.value=t()),n}})}function Jb(e){let t=()=>e.rows.length>0&&e.rows.every(t=>e.picked.has(t.id)),r=t=>e.table.sort.key===t?e.table.sort.dir===`asc`?`ascending`:`descending`:`none`;return(()=>{var i=jb(),s=i.firstChild,c=s.firstChild,l=c.firstChild,d=l.firstChild,f=l.nextSibling,p=s.nextSibling;return d.addEventListener(`change`,t=>e.pickAll(t.currentTarget.checked)),I(c,n(o,{each:Ub,children:([t,n])=>(()=>{var i=Mb(),a=i.firstChild,o=a.firstChild;return G(i,`col-${t}`),a.$$click=()=>e.sortBy(t),I(a,n,o),I(o,(()=>{var n=V(()=>e.table.sort.key===t);return()=>n()?e.table.sort.dir===`asc`?`↑`:`↓`:``})()),D(()=>L(i,`aria-sort`,r(t))),i})()}),f),I(p,n(o,{get each(){return e.rows},get fallback(){return Nb()},children:t=>(()=>{var r=Lb(),i=r.firstChild,o=i.firstChild,s=i.nextSibling,c=s.firstChild,l=s.nextSibling,d=l.nextSibling,f=d.nextSibling,p=f.firstChild,m=f.nextSibling,h=m.nextSibling,g=h.nextSibling,_=g.nextSibling;return r.$$click=e=>!e.target.closest(`button,a,select,input`)&&a(k(t.id)),o.addEventListener(`change`,n=>e.pick(t.id,n.currentTarget.checked)),I(s,n(_e,{get state(){return t.state}}),c),I(c,()=>Le[t.state]),I(s,n(u,{get when(){return t.error},children:e=>n(Me,{get text(){return e()}})}),null),I(s,n(u,{get when(){return t.jobs},get children(){var e=Pb();return I(e,()=>t.jobs),D(n=>{var r=Na(t.jobs),i=Na(t.jobs);return r!==n.e&&L(e,`title`,n.e=r),i!==n.t&&L(e,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),e}}),null),I(l,n(u,{get when(){return eo(t,fb())},get children(){return n(Oe,{})}}),null),I(l,n(jg,{get id(){return t.id},get title(){return t.title},place:`table`,get children(){var e=Fb();return I(e,()=>t.title),D(()=>L(e,`href`,k(t.id))),e}}),null),I(l,n(Mg,{get id(){return t.id}}),null),I(l,n(u,{get when(){return t.unread},get children(){return Ib()}}),null),I(d,()=>t.where),I(p,()=>t.machineName),I(m,()=>Ne[t.source]),I(h,()=>Be(t.updated,F())),I(g,()=>Hb(t)),I(_,n(me,{get label(){return`More actions for ${t.title}`},class:`icon-btn small`,items:()=>Ch(t,{place:`table`})})),D(e=>{var n=`${t.unread?`unread`:``}`,i=`Select ${t.title}`,a=t.directory,s=t.machineOnline?``:`muted`,c=`col-now ${t.error?`error`:`muted`}`,l=t.error;return n!==e.e&&G(r,e.e=n),i!==e.t&&L(o,`aria-label`,e.t=i),a!==e.a&&L(d,`title`,e.a=a),s!==e.o&&G(p,e.o=s),c!==e.i&&G(g,e.i=c),l!==e.n&&L(g,`title`,e.n=l),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),D(()=>o.checked=e.picked.has(t.id)),r})()})),D(()=>d.checked=t()),i})()}function Yb(e){let t=()=>e.row;return(()=>{var e=zb();return I(e,n(u,{get when(){return!xh(t().id,`phone`)},get fallback(){return(()=>{var e=Bb();return I(e,n(_e,{get state(){return t().state}}),null),I(e,n(jg,{get id(){return t().id},get title(){return t().title},place:`phone`,children:null}),null),e})()},get children(){var e=Rb(),r=e.firstChild,i=r.firstChild,a=i.nextSibling;return I(e,n(_e,{get state(){return t().state}}),r),I(e,n(u,{get when(){return t().error},children:e=>n(Me,{get text(){return e()}})}),r),I(i,n(u,{get when(){return eo(t(),fb())},get children(){return n(Oe,{})}}),null),I(i,()=>t().title,null),I(i,n(Mg,{get id(){return t().id}}),null),I(i,n(u,{get when(){return t().unread},get children(){return Ib()}}),null),I(a,()=>Hb(t())||`${t().where} · ${t().machineName} · ${Be(t().updated,F())}`),D(n=>{var r=k(t().id),i=`home-item-meta ${t().error?`error`:`muted`}`;return r!==n.e&&L(e,`href`,n.e=r),i!==n.t&&G(a,n.t=i),n},{e:void 0,t:void 0}),e}}),null),I(e,n(me,{get label(){return`More actions for ${t().title}`},class:`icon-btn small`,items:()=>Ch(t(),{place:`phone`})}),null),D(()=>G(e,`home-item${t().unread?` unread`:``}`)),e})()}P([`input`,`click`]);var Xb=q(`<div role=separator aria-orientation=vertical tabindex=0>`);function Zb(e){let t=0,n=0,r=0,i,a=()=>Ip()[e.panel],o=()=>Lp(e.panel),s=()=>{r=0,i!==void 0&&Rp(e.panel,i,!1)},c=()=>{r&&cancelAnimationFrame(r),r=0,i=void 0,Np(void 0),document.documentElement.classList.remove(`resizing`)},l=(t,n,r)=>{t.hasPointerCapture(n)&&t.releasePointerCapture(n),c(),Rp(e.panel,r)};return ue(()=>e.panel===`rail`&&jp(!0)),j(()=>{e.panel===`rail`&&jp(!1),Mp()===e.panel&&c()}),(()=>{var c=Xb();return c.$$keydown=t=>{let n=sp(e.panel,a(),t.key,t.shiftKey,o());n!==void 0&&(t.preventDefault(),Rp(e.panel,n))},c.$$dblclick=()=>Rp(e.panel,tp[e.panel].default),c.addEventListener(`pointercancel`,t=>Mp()===e.panel&&l(t.currentTarget,t.pointerId,i??a())),c.$$pointerup=t=>Mp()===e.panel&&l(t.currentTarget,t.pointerId,i??a()),c.$$pointermove=a=>{if(Mp()!==e.panel)return;let c=cp(e.panel,t,a.clientX-n,o());`collapse`in c?(l(a.currentTarget,a.pointerId,t),Cp(!0)):(i=c.width,r||=requestAnimationFrame(s))},c.$$pointerdown=r=>{r.button===0&&(r.preventDefault(),r.currentTarget.setPointerCapture(r.pointerId),t=a(),n=r.clientX,Np(e.panel),document.documentElement.classList.add(`resizing`))},D(t=>{var n=`panel-handle${Mp()===e.panel?` dragging`:``}`,r=e.panel,i=e.label,s=a(),l=o().min,u=o().max;return n!==t.e&&G(c,t.e=n),r!==t.t&&L(c,`data-panel`,t.t=r),i!==t.a&&L(c,`aria-label`,t.a=i),s!==t.o&&L(c,`aria-valuenow`,t.o=s),l!==t.i&&L(c,`aria-valuemin`,t.i=l),u!==t.n&&L(c,`aria-valuemax`,t.n=u),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),c})()}P([`pointerdown`,`pointermove`,`pointerup`,`dblclick`,`keydown`]);var Qb={service:`background service`,standalone:`standalone`};function $b(e){return(e??[]).map(e=>{let t=!!e.online,n=e.processes.find(e=>e.kind===`service`)??e.processes[0],r=t?n?[Qb[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 ex(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 tx(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 nx(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:tx(e,i?.machine===t?{key:i.key,dir:i.dir}:{},a?.machine===t?a:void 0)??o}function rx(e,t){let n=ki(t).split(/\s+/).filter(Boolean);return n.length?e.filter(e=>{let t=[e.label,...e.directories].map(ki);return n.every(e=>t.some(t=>t.includes(e)))}):[...e]}var ix=`hub.newSession`;function ax(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 ox(e,t){try{e.setItem(ix,JSON.stringify({machine:t.machine,key:t.key,dir:t.dir}))}catch{}}var sx=`hub.railCollapsed`;function cx(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 lx(e,t){let n=cx(e);n.has(t)?n.delete(t):n.add(t);try{e.setItem(sx,JSON.stringify([...n]))}catch{}return n}var ux=0,dx=e=>e.reduce((e,t)=>e+t.data.length,0);async function fx(e,t){let n=Xg(t.length,e.type);if(n)throw Error(n);let r=await px(e);try{let n=e.type!==`image/jpeg`&&hx(r),{blob:i,request:a}=await e_({width:r.width,height:r.height,keepPng:n},Zg(dx(t)),e=>gx(r,e)),o=await _x(i);return{id:`img${++ux}`,mime:a.type,data:o.slice(o.indexOf(`,`)+1),name:$g(e.name||`image`,a.type),preview:URL.createObjectURL(i)}}finally{`close`in r&&r.close()}}async function px(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 mx(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 hx(e){let t=Math.max(1,Math.min(64,e.width)),n=Math.max(1,Math.min(64,e.height)),[,r]=mx(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 gx(e,t){let[n,r]=mx(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 _x(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 vx(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 yx=new Map;function bx(e,t){yx.set(e,t)}function xx(e){let t=yx.get(e);return yx.delete(e),t}var Sx=q(`<li class="attachment busy"aria-label="Preparing image"><span class="spinner small">`),Cx=q(`<ul class=attachments aria-label="Attached images">`),wx=q(`<span class="spinner small">`),Tx=q(`<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">`),Ex=q(`<span class="meta-chip readonly"title="Branch of this folder"><span class="chip-text mono">`),Dx=q(`<label class="meta-chip toggle-chip"><input type=checkbox><span class=chip-text>Open in Herdr tab`),Ox=q(`<div class=env-meta role=group aria-label="Where the session runs">`),kx=q(`<p data-new-dir>`),Ax=q(`<p class="small new-need-project"role=alert data-need-project>Choose a project first: the session starts in one of <!>'s folders.`),jx=q('<p class="small warn"> has no background service connected; start `opencode serve --service` there to create sessions.'),Mx=q(`<p class=error role=alert>`),Nx=q(`<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?`),Px=q(`<p class=muted>No machine is connected to this hub yet.`),Fx=q(`<li class=attachment><img><button type=button class=attachment-remove>`),Ix=q(`<span aria-hidden=true>`),Lx=q(`<span class=chip-text>`),Rx=q(`<button type=button aria-haspopup=dialog aria-label="Choose project folder"><span class=chip-text>`),zx=q(`<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>`),Bx=q(`<p class="muted small pad">No folder matches.`),Vx=q(`<div class=menu-section> · Herdr`),Hx=q(`<button type=button role=option class=menu-item><span class=menu-check></span><span class=menu-label></span><span class="menu-hint mono">`);function Ux(t){let r=ax(localStorage),i=()=>Y.machines??[],s=T(()=>$b(i())),[c,l]=x(),d=()=>{let e=c();return e&&s().some(t=>t.id===e&&t.online)?e:ex(s(),t.machine,r?.machine)},p=()=>s().find(e=>e.id===d()),m=()=>i().find(e=>e.id===d()),h=T(()=>{let e=m();if(!e)return[];let n=pa(e).targets;return t.key&&t.dir&&e.id===t.machine&&!n.some(e=>e.key===t.key)&&n.push({kind:`folder`,key:t.key,label:ye(t.dir),directories:[t.dir]}),n}),[g,_]=x(),[v,y]=x(!1),b=()=>nx(h(),d(),{...g()?{chosen:g()}:{},switched:v(),linked:{machine:t.machine,key:t.key,dir:t.dir},...r?{remembered:r}:{}}),S=()=>h().find(e=>e.key===b()?.key),C=e=>e.directories.length?e.directories:h().filter(e=>e.kind===`folder`).flatMap(e=>e.directories),w=()=>{let e=b(),t=S();return!e||!t?``:e.dir&&C(t).includes(e.dir)?e.dir:C(t)[0]??``},E=(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],[ee]=f(()=>{let e=E(m(),w());return e?e.id:void 0},async e=>(await z(`${N(e)}/summary`).catch(()=>({}))).branch),[te,O]=x(!0),ne=()=>!!p()?.herdr&&S()?.kind===`herdr`&&te(),[re,ie]=x(``),[ae,A]=x([]),[oe,j]=x(!1),[se,ce]=x(``),[le,M]=x(!1),de=Promise.resolve(),fe=e=>{de=de.then(async()=>{j(!0);try{for(let t of e)try{let e=await fx(t,ae());A(t=>[...t,e])}catch(e){ce(U(e))}}finally{j(!1)}})},pe=()=>!le()&&!oe()&&!!p()?.canCreate&&!!w()&&(!!re().trim()||ae().length>0),[he,_e]=x(!1),ve,P=async()=>{let t=p(),n=S(),r=w();if(!r&&t&&!le()&&(re().trim()||ae().length>0))_e(!0),ve?.focus();else if(pe()&&t&&n){M(!0),ce(``);try{let e=ma({target:n,directory:r,openInHerdr:ne()}),i=await(await W(`/api/machines/${B(t.id)}/sessions`,{method:`POST`,json:e})).json();ox(localStorage,{machine:t.id,key:n.key,dir:r}),bx(i.sessionID,{text:re().trim(),images:ae()}),a(k(i.sessionID),{replace:!0}),i.warning?K(`Session created, but Herdr didn't open it: ${i.warning}`,`warn`):i.openedIn===`herdr`&&K(`Opened in Herdr · ${n.label}`)}catch(n){ce(n instanceof e&&n.status===409?`The background service on ${t.name} isn't connected. Start it, then try again.`:`Could not create the session: ${U(n)}`),M(!1)}}},be=()=>[{section:`Choose environment`},...s().map(e=>({label:e.name,hint:e.online?e.canCreate?e.detail:`${e.detail} · no background service`:`offline`,checked:e.id===d(),disabled:e.disabled,run:()=>{e.id!==d()&&(y(!0),_(void 0),l(e.id))}}))],F,xe;ue(()=>F?.focus());let Se=()=>{F.style.height=`auto`,F.style.height=`${Math.min(F.scrollHeight,320)}px`};return(()=>{var e=Nx(),t=e.firstChild,r=t.firstChild,i=t.nextSibling;return i.firstChild,I(t,n(u,{get when(){return Z()},get children(){return n(R,{icon:`menu`,label:`Open sidebar`,onClick:Tp})}}),r),I(i,n(u,{get when(){return s().length},get fallback(){return Px()},get children(){return[(()=>{var e=Tx(),t=e.firstChild,r=t.firstChild,i=r.nextSibling,a=i.nextSibling.firstChild,s=a.nextSibling.nextSibling;e.addEventListener(`drop`,e=>{let t=vx(e.dataTransfer);t.length&&(e.preventDefault(),fe(t))}),e.addEventListener(`dragover`,e=>[...e.dataTransfer?.types??[]].includes(`Files`)&&e.preventDefault()),e.addEventListener(`submit`,e=>{e.preventDefault(),P()}),I(t,n(u,{get when(){return ae().length||oe()},get children(){var e=Cx();return I(e,n(o,{get each(){return ae()},children:e=>(()=>{var t=Fx(),r=t.firstChild,i=r.nextSibling;return i.$$click=()=>A(t=>t.filter(t=>t.id!==e.id)),I(i,n(H,{name:`close`})),D(t=>{var n=e.preview,a=e.name,o=e.name,s=`Remove ${e.name}`;return n!==t.e&&L(r,`src`,t.e=n),a!==t.t&&L(r,`alt`,t.t=a),o!==t.a&&L(r,`title`,t.a=o),s!==t.o&&L(i,`aria-label`,t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),null),I(e,n(u,{get when(){return oe()},get children(){return Sx()}}),null),e}}),r),r.$$keydown=e=>{e.key===`Enter`&&!e.shiftKey&&!e.isComposing&&!(matchMedia(`(max-width: 760px)`).matches&&`ontouchstart`in window)&&(e.preventDefault(),P())},r.addEventListener(`paste`,e=>{let t=vx(e.clipboardData);t.length&&(e.preventDefault(),fe(t))}),r.$$input=e=>{ie(e.currentTarget.value),Se()};var c=F;typeof c==`function`?ge(c,r):F=r,i.addEventListener(`change`,e=>{let t=[...e.currentTarget.files??[]];e.currentTarget.value=``,t.length&&fe(t)});var l=xe;return typeof l==`function`?ge(l,i):xe=i,a.$$click=()=>xe.click(),I(a,n(H,{name:`plus`})),I(s,n(u,{get when(){return le()},get fallback(){return n(H,{name:`send`})},get children(){return wx()}})),D(e=>{var t=Ug.join(`,`),n=ae().length>=Wg.maxImages||oe(),r=pe()||w()?`Start session`:`Choose a project first`,o=!pe(),c=!pe();return t!==e.e&&L(i,`accept`,e.e=t),n!==e.t&&(a.disabled=e.t=n),r!==e.a&&L(s,`title`,e.a=r),o!==e.o&&(s.disabled=e.o=o),c!==e.i&&L(s,`aria-disabled`,e.i=c),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),D(()=>r.value=re()),e})(),(()=>{var e=Ox();return I(e,n(me,{label:`Choose environment`,class:`meta-chip env-chip`,align:`left`,items:be,get text(){return[n(H,{name:`cloud`}),(()=>{var e=Ix();return D(()=>G(e,`online-dot${p()?.online?` on`:``}`)),e})(),(()=>{var e=Lx();return I(e,()=>p()?.name??`No environment`),e})(),n(H,{name:`down`,class:`chip-caret`})]}}),null),I(e,n(Wx,{get targets(){return h()},get current(){return b()},get dir(){return w()},get disabled(){return!p()},get asked(){return V(()=>!!he())()&&!w()},buttonRef:e=>ve=e,foldersOf:C,onPick:(e,t)=>_({machine:d(),key:e,dir:t})}),null),I(e,n(u,{get when(){return V(()=>!!w())()&&ee()},get children(){var e=Ex(),t=e.firstChild;return I(e,n(H,{name:`branch`}),t),I(t,ee),e}}),null),I(e,n(u,{get when(){return V(()=>!!p()?.herdr)()&&S()?.kind===`herdr`},get children(){var e=Dx(),t=e.firstChild;return t.addEventListener(`change`,e=>O(e.currentTarget.checked)),D(()=>L(e,`title`,`Open the new session in a new tab of the Herdr workspace ${S().label}`)),D(()=>t.checked=te()),e}}),null),e})(),(()=>{var e=kx();return I(e,(()=>{var e=V(()=>!!w());return()=>e()?w():V(()=>!!p())()?`Choose one of ${p().name}'s projects`:``})()),D(t=>{var n=`small muted new-dir${w()?` mono`:``}`,r=w()||void 0;return n!==t.e&&G(e,t.e=n),r!==t.t&&L(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e})(),n(u,{get when(){return V(()=>!(!he()||w()))()&&p()},get children(){var e=Ax(),t=e.firstChild.nextSibling;return t.nextSibling,I(e,()=>p().name,t),e}}),n(u,{get when(){return V(()=>!!p())()&&!p().canCreate},get children(){var e=jx(),t=e.firstChild;return I(e,()=>p().name,t),e}}),n(u,{get when(){return se()},get children(){var e=Mx();return I(e,se),e}})]}}),null),e})()}function Wx(e){let[t,r]=x(!1),[i,a]=x(``),[s,c]=x({top:0,left:0}),l,d,f,p=()=>rx(e.targets,i()),m=()=>e.targets.some(t=>t.key===e.current?.key),h=()=>{let t=e.targets.find(t=>t.key===e.current?.key);return t?t.kind===`herdr`&&e.dir?`${t.label} · ${ye(e.dir)}`:t.label:e.targets.length?`Choose a project`:`No folder`},g=()=>{let e=l.getBoundingClientRect();c({top:e.bottom+4,left:e.left}),a(``),r(!t()),t()&&queueMicrotask(()=>f?.focus())},_=e=>{t()&&!l.contains(e.target)&&!d?.contains(e.target)&&r(!1)},v=e=>{t()&&e.key===`Escape`&&!xe(d)&&(r(!1),l.focus())};ue(()=>{document.addEventListener(`mousedown`,_),document.addEventListener(`keydown`,v)}),j(()=>{document.removeEventListener(`mousedown`,_),document.removeEventListener(`keydown`,v)});let y=(t,n)=>{e.onPick(t,n),r(!1)};return[(()=>{var r=Rx(),i=r.firstChild;return r.$$click=g,ge(t=>{l=t,e.buttonRef?.(t)},r),I(r,n(H,{name:`folder`}),i),I(i,h),I(r,n(H,{name:`down`,class:`chip-caret`}),null),D(n=>{var i=`meta-chip folder-chip${m()?``:` unset`}${e.asked?` asked`:``}`,a=t(),o=e.dir||`Choose a folder`,s=e.disabled;return i!==n.e&&G(r,n.e=i),a!==n.t&&L(r,`aria-expanded`,n.t=a),o!==n.a&&L(r,`title`,n.a=o),s!==n.o&&(r.disabled=n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),r})(),n(u,{get when(){return t()},get children(){return n(ve,{get children(){var t=zx(),r=t.firstChild,c=r.nextSibling,l=d;typeof l==`function`?ge(l,t):d=t,r.$$keydown=t=>{let n=p()[0];t.key===`Enter`&&n&&(t.preventDefault(),y(n.key,e.foldersOf(n)[0]??``))},r.$$input=e=>a(e.currentTarget.value);var m=f;return typeof m==`function`?ge(m,r):f=r,I(c,n(u,{get when(){return p().length},get fallback(){return Bx()},get children(){return n(o,{get each(){return p()},children:t=>n(u,{get when(){return V(()=>t.kind===`herdr`)()&&e.foldersOf(t).length>1},get fallback(){return(()=>{var n=Hx(),r=n.firstChild,i=r.nextSibling,a=i.nextSibling;return n.$$click=()=>y(t.key,e.foldersOf(t)[0]??``),I(r,()=>e.current?.key===t.key?`✓`:``),I(i,()=>t.label),I(a,(()=>{var n=V(()=>t.kind===`herdr`);return()=>n()?`Herdr`:e.foldersOf(t)[0]??``})()),D(r=>{var i=e.current?.key===t.key,a=e.foldersOf(t)[0];return i!==r.e&&L(n,`aria-selected`,r.e=i),a!==r.t&&L(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()},get children(){return[(()=>{var e=Vx(),n=e.firstChild;return I(e,()=>t.label,n),e})(),n(o,{get each(){return e.foldersOf(t)},children:n=>(()=>{var r=Hx(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling;return r.$$click=()=>y(t.key,n),L(r,`title`,n),I(i,()=>e.current?.key===t.key&&e.dir===n?`✓`:``),I(a,()=>ye(n)),I(o,n),D(()=>L(r,`aria-selected`,e.current?.key===t.key&&e.dir===n)),r})()})]}})})}})),D(e=>{var n=`${s().top}px`,r=`${s().left}px`;return n!==e.e&&Se(t,`top`,e.e=n),r!==e.t&&Se(t,`left`,e.t=r),e},{e:void 0,t:void 0}),D(()=>r.value=i()),t}})}})]}P([`input`,`keydown`,`click`]);var Gx={name:`home`},Kx=_(()=>T(()=>{let e=Ue();return e.name===`concierge`?Z()?e:Gx:Gx=e})),qx=e=>String(e??``).normalize(`NFD`).replace(/[\u0300-\u036f]/g,``).toLowerCase();function Jx(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 Yx(e){let t=e?.note;return!Array.isArray(e)&&typeof t==`string`&&t.trim()?t.trim():void 0}var Xx=e=>e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;function Zx(e,t,{current:n=``,limit:r=200,grouped:i=!1}={}){let a=String(t??``).trim(),o=qx(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=qx(e.id),r=`${n} ${qx(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(Xx(t.option.id))||e.set(Xx(t.option.id),e.size);u.sort((t,n)=>e.get(Xx(t.option.id))-e.get(Xx(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 Qx(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 $x=q(`<input type=search class=picker-search autofocus>`),eS=q(`<button type=button class="btn small">Retry`),tS=q(`<p class="muted small"role=status>`),nS=q(`<p class="muted small picker-note">`),rS=q(`<li><button type=button><span class=po-name>Use “<!>”</span><span class="po-id muted">as a custom `),iS=q(`<ul class=picker-list role=listbox>`),aS=q(`<div class="picker-group muted small">`),oS=q(`<span class="po-id muted">`),sS=q(`<span class=po-mark>✓ Current`),cS=q(`<li><button type=button><span class=po-name>`);function lS(e){let[t,r]=x(``),[i,a]=x(),[s,c]=x(``),[l,d]=x(``),[f,p]=x(0),m=()=>{let t=e.request;t&&(a(void 0),c(``),d(``),t.load().then(e=>{if(Array.isArray(e))return a(e);d(e.note??``),a(e.options)},e=>c(U(e))))};C(h(()=>e.request,e=>{e&&(r(``),p(0),m())}));let g=T(()=>Zx(i()??[],t(),{current:e.request?.current,grouped:e.request?.grouped})),_=()=>[...g().items.map(e=>e.id),...g().custom?[g().custom]:[]],v=t=>{let n=e.request;e.onClose(),n?.onPick(t)},y=()=>e.request?.noun??`option`;return n(ze,{get open(){return!!e.request},get title(){return e.request?.title??``},get onClose(){return e.onClose},class:`picker`,get children(){return[(()=>{var e=$x();return e.$$keydown=e=>{let t={ArrowDown:1,ArrowUp:-1};if(e.key in t)e.preventDefault(),p(Qx(f(),t[e.key],_().length));else if(e.key===`Enter`){e.preventDefault();let t=_()[f()];t&&v(t)}},e.$$input=e=>{r(e.currentTarget.value),p(0)},D(t=>{var n=`Search or type a ${y()}`,r=`Search ${y()}s`;return n!==t.e&&L(e,`placeholder`,t.e=n),r!==t.t&&L(e,`aria-label`,t.t=r),t},{e:void 0,t:void 0}),D(()=>e.value=t()),e})(),(()=>{var e=tS();return I(e,(()=>{var e=V(()=>!!s());return()=>e()?`Couldn't load the ${y()} list: ${s()}. Type any ${y()}.`:V(()=>i()===void 0)()?`Loading ${y()}s…`:V(()=>!i().length)()?`No suggestions. Type any ${y()}.`:`${g().total} ${g().total===1?y():`${y()}s`}`})(),null),I(e,n(u,{get when(){return s()},get children(){return[` `,(()=>{var e=eS();return e.$$click=m,e})()]}}),null),e})(),n(u,{get when(){return l()},get children(){var e=nS();return I(e,l),e}}),(()=>{var t=iS();return I(t,n(o,{get each(){return g().items},children:(t,r)=>(()=>{var i=cS(),a=i.firstChild,o=a.firstChild;return I(i,n(u,{get when(){return V(()=>!!e.request?.grouped)()&&(r()===0||Xx(g().items[r()-1].id)!==Xx(t.id))},get children(){var e=aS();return I(e,()=>Xx(t.id)||`Other`),e}}),a),a.$$click=()=>v(t.id),I(o,()=>t.id),I(a,n(u,{get when(){return t.name},get children(){var e=oS();return I(e,()=>t.name),e}}),null),I(a,n(u,{get when(){return t.current},get children(){return sS()}}),null),D(e=>{var n=`picker-opt${f()===r()?` active`:``}`,i=!!t.current;return n!==e.e&&G(a,e.e=n),i!==e.t&&L(a,`aria-selected`,e.t=i),e},{e:void 0,t:void 0}),i})()}),null),I(t,n(u,{get when(){return g().custom},get children(){var e=rS(),t=e.firstChild,n=t.firstChild,r=n.firstChild.nextSibling;r.nextSibling;var i=n.nextSibling;return i.firstChild,t.$$click=()=>v(g().custom),I(n,()=>g().custom,r),I(i,y,null),D(()=>G(t,`picker-opt${f()===g().items.length?` active`:``}`)),e}}),null),t})()]}})}P([`input`,`keydown`,`click`]);var uS=q(`<div class=chips role=group aria-label="Which speech settings"><button type=button class=chip>Yours</button><button type=button class=chip>Server default`),dS=q(`<div class="speech-panel stack">`),fS=q(`<p class=error>`),pS=q(`<p class=muted>Loading…`),mS=q(`<p class="small inherit">`),hS=q(`<p class="small muted">`),gS=q(`<p class=field-error>`),_S=q(`<div class=field><label>`),vS=q(`<input type=text autocomplete=off autocapitalize=off>`),yS=q(`<div class=row><button type=button class="btn small">Browse…`),bS=q(`<input type=password autocomplete=new-password placeholder="Paste the new key"aria-label="New API key">`),xS=q(`<div class=row><button type=button class="btn small">Cancel`),SS=q(`<div class="field key-field"><span class=field-label>API key`),CS=q(`<p>`),wS=q(`<button type=button class="btn small">Undo`),TS=q(`<button type=button class="btn small danger">Clear`),ES=q(`<div class=row><button type=button class="btn small">`),DS=q(`<fieldset class="card speech-card"><legend>`),OS=q(`<div class="row reset-row"><span class="small muted grow"></span><button type=button class="btn small">Reset to server default`),kS=q(`<option>`),AS=q(`<select>`),jS=q(`<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.`),MS=q(`<button type=button class=btn>Preview voice`),NS=q(`<form class=stack novalidate><div class=row><button type=submit class="btn primary">Save</button></div><p role=status>`),PS=q(`<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.`),FS=[[`openrouter`,`OpenRouter`],[`openai-compatible`,`OpenAI-compatible`]],IS={settings:`from settings`,config:`from hub.json`,env:`from env`,user:`yours`},LS={user:`/api/settings/speech`,default:`/api/settings/speech/default`},RS={stt:`Speech-to-text`,tts:`Text-to-speech`};function zS(){let[t,r]=x(`user`),[i,a]=x(!1),[o,s]=x(),[c,l]=x(``),d=async n=>{s(void 0),l(``);try{let e=await z(LS[n]);n===`user`&&a(bt(X(),e).length>1),t()===n&&s(e)}catch(t){l(t instanceof e&&t.status===403?n==="default"?`Only admins can change the server default.`:`This account cannot change speech settings.`:t instanceof e&&t.status===404?`This hub does not support speech settings.`:`Could not load speech settings: ${U(t)}`)}};ue(()=>void d(`user`));let f=e=>{e!==t()&&(r(e),d(e))};return(()=>{var e=dS();return I(e,n(u,{get when(){return i()},get children(){var e=uS(),n=e.firstChild,r=n.nextSibling;return n.$$click=()=>f(`user`),r.$$click=()=>f(`default`),D(e=>{var i=t()===`user`,a=t()==="default";return i!==e.e&&L(n,`aria-pressed`,e.e=i),a!==e.t&&L(r,`aria-pressed`,e.t=a),e},{e:void 0,t:void 0}),e}}),null),I(e,n(u,{get when(){return!c()},get fallback(){return(()=>{var e=fS();return I(e,c),e})()},get children(){return n(u,{get when(){return o()},get fallback(){return pS()},keyed:!0,children:e=>n(BS,{settings:e,get scope(){return t()},onSaved:e=>s(e)})})}}),null),e})()}function BS(e){let[t,r]=mi(Co(e.settings)),[i,a]=x({}),[s,c]=x({text:``,kind:``}),[l,d]=x(!1),[f,p]=x(),m=()=>e.scope===`user`?Tt(e.settings):void 0,h=()=>e.scope===`user`?Oo(e.settings.ready,X()?.publicURL):void 0,g=()=>Object.keys(wo(e.settings,ni(t))).length>0,_={},v=e=>(_[e]??=z(`/api/settings/speech/models?kind=${e}`).then(e=>({options:Jx(e),note:Yx(e)})),_[e].catch(()=>delete _[e]),_[e]),y=(e,t,r,a,o)=>{let s=()=>m()?.[e]?.[t];return(()=>{var c=_S(),l=c.firstChild;return L(l,`for`,`sp-${e}-${t}`),I(l,r),I(c,a,null),I(c,n(u,{get when(){return s()?.inherited},get children(){var e=mS();return I(e,()=>s().note),e}}),null),I(c,n(u,{when:o,get children(){var e=hS();return I(e,o),e}}),null),I(c,n(u,{get when(){return i()[`${e}.${t}`]},get children(){var n=gS();return I(n,()=>i()[`${e}.${t}`]),n}}),null),c})()},b=(e,n,a={})=>(()=>{var o=vS();return L(o,`id`,`sp-${e}-${n}`),L(o,`spellcheck`,!1),pe(o,ce(a,{get value(){return t[e][n]},get"aria-invalid"(){return!!i()[`${e}.${n}`]},onInput:t=>r(e,n,t.currentTarget.value)}),!1,!1),o})(),S=(e,n,i,a,o)=>(()=>{var s=yS(),c=s.firstChild;return I(s,()=>b(e,n,{placeholder:`Choose or type a ${a}`}),c),c.$$click=()=>p({title:i,noun:a,current:t[e][n]??``,load:o,grouped:n===`model`,onPick:t=>r(e,n,t)}),s})(),C=a=>{let o=e.settings[a].apiKey??{set:!1,source:`none`},s=()=>m()?.[a].apiKey,c=()=>t[a].apiKey,l=()=>m()?!s()?.inherited&&o.set:o.set&&o.source===`settings`;return(()=>{var e=SS();return e.firstChild,I(e,n(u,{get when(){return c().action===`set`},get fallback(){return[(()=>{var e=CS();return I(e,(()=>{var e=V(()=>c().action===`clear`);return()=>e()?`Key will be removed when you save.`:V(()=>!!s()?.inherited)()?s().note:V(()=>!!o.set)()?`Key set${o.last4?` ••••${o.last4}`:``} (${IS[o.source]??o.source})`:`No key set`})()),D(()=>G(e,`key-summary${s()?.inherited&&c().action!==`clear`?` inherit`:``}`)),e})(),(()=>{var e=ES(),t=e.firstChild;return t.$$click=()=>r(a,`apiKey`,{action:`set`,value:``}),I(t,(()=>{var e=V(()=>!!s()?.inherited);return()=>e()?`Use your own key`:o.set?`Replace`:`Add key`})()),I(e,n(u,{get when(){return c().action===`clear`},get children(){var e=wS();return e.$$click=()=>r(a,`apiKey`,{action:`keep`,value:``}),e}}),null),I(e,n(u,{get when(){return V(()=>c().action!==`clear`)()&&l()},get children(){var e=TS();return e.$$click=()=>r(a,`apiKey`,{action:`clear`,value:``}),e}}),null),e})()]},get children(){return[(()=>{var e=bS();return e.$$input=e=>r(a,`apiKey`,`value`,e.currentTarget.value),L(e,`id`,`sp-${a}-apiKey`),D(()=>e.value=c().value),e})(),(()=>{var e=xS(),t=e.firstChild;return t.$$click=()=>r(a,`apiKey`,{action:`keep`,value:``}),e})()]}}),null),I(e,n(u,{get when(){return i()[`${a}.apiKey`]},get children(){var e=gS();return I(e,()=>i()[`${a}.apiKey`]),e}}),null),e})()},w=async t=>{if(await Ce(`Reset ${RS[t].toLowerCase()} to the server default? Your own ${RS[t].toLowerCase()} settings are removed.`,`Reset`,{danger:!0}))try{let n=await(await W(LS.user,{method:`PUT`,json:Et(t)})).json().catch(()=>({})),r=n?.stt&&n?.tts?n:await z(LS.user);Xl(r.ready??null),e.onSaved(r),K(`${RS[t]} reset to the server default`)}catch(e){K(`Could not reset: ${U(e)}`,`err`)}},T=i=>(()=>{var a=DS(),s=a.firstChild;return I(s,()=>RS[i]),I(a,n(u,{get when(){return m()},children:e=>(()=>{var t=OS(),n=t.firstChild,r=n.nextSibling;return I(n,(()=>{var t=V(()=>!!e().own[i]);return()=>t()?`${e().own[i]} of your own setting${e().own[i]===1?``:`s`}`:`All from the server default`})()),r.$$click=()=>void w(i),D(()=>r.disabled=!e().own[i]),t})()}),null),I(a,()=>y(i,`provider`,`Provider`,(()=>{var e=AS();return e.addEventListener(`change`,e=>r(i,`provider`,e.currentTarget.value)),L(e,`id`,`sp-${i}-provider`),I(e,n(o,{each:FS,children:([e,t])=>(()=>{var n=kS();return n.value=e,I(n,t),n})()}),null),I(e,n(u,{get when(){return!FS.some(([e])=>e===t[i].provider)},get children(){var e=kS();return I(e,()=>t[i].provider||`—`),D(()=>e.value=t[i].provider),e}}),null),D(()=>e.value=t[i].provider),e})()),null),I(a,n(u,{get when(){return t[i].provider===`openai-compatible`},get children(){return y(i,`baseURL`,`Base URL`,b(i,`baseURL`,{inputmode:`url`,placeholder:`http://host:port/v1`}))}}),null),I(a,()=>y(i,`model`,`Model`,S(i,`model`,i===`stt`?`Speech-to-text model`:`Text-to-speech model`,`model`,()=>v(i))),null),I(a,n(u,{when:i===`tts`,get fallback(){return y(i,`language`,`Language (optional)`,b(i,`language`,{placeholder:`auto, e.g. en`}))},get children(){return[V(()=>y(i,`voice`,`Voice`,S(i,`voice`,`Voice`,`voice`,async()=>Jx(Eo(e.settings.voiceHints,t.tts.model))))),V(()=>y(i,`speed`,`Server-side speed (optional)`,b(i,`speed`,{inputmode:`decimal`,placeholder:`default`}),`0.25–4, applied by the TTS provider. Your device's voice speed is separate.`))]}}),null),I(a,()=>C(i),null),a})(),E=async n=>{n.preventDefault();let i=ni(t),o=To(i);if(a(o),Object.keys(o).length)return c({text:`Fix the highlighted fields.`,kind:`error`});let s=wo(e.settings,i);if(!Object.keys(s).length)return c({text:`Nothing to save.`,kind:`muted`});d(!0),c({text:`Saving…`,kind:`muted`});try{let t=await(await W(LS[e.scope],{method:`PUT`,json:s})).json().catch(()=>({})),n=t?.stt&&t?.tts?t:await z(LS[e.scope]);e.scope===`user`?Xl(n.ready??null):yd(),r(vi(Co(n))),e.onSaved(n),K(e.scope==="default"?`Server default saved`:`Speech settings saved`)}catch(e){let t=e.field;t&&a({[t]:U(e)}),c({text:`Could not save: ${U(e)}`,kind:`error`})}finally{d(!1)}},ee=async()=>{c({text:g()?`Previewing the saved voice (save to hear your changes)…`:`Previewing…`,kind:`muted`});let e;try{let t=await(await W(`/api/settings/speech/test`,{method:`POST`,json:{kind:`tts`,text:`Hi! This is how replies will sound.`}})).blob();if(e=URL.createObjectURL(t),Ly.src=e,W_(Ly,Iy.speed),!await Ly.play().then(()=>!0,()=>!1))throw Error(`the browser blocked playback`);c({text:`Playing preview.`,kind:`muted`}),await new Promise(e=>Ly.onended=Ly.onpause=Ly.onerror=()=>e()),c({text:``,kind:``})}catch(e){c({text:`Preview failed: ${U(e)}`,kind:`error`})}finally{Ly.onended=Ly.onpause=Ly.onerror=null,e&&URL.revokeObjectURL(e)}};return(()=>{var t=NS(),r=t.firstChild,i=r.firstChild,a=r.nextSibling;return t.$$input=()=>c({text:g()?`Unsaved changes.`:``,kind:`muted`}),t.addEventListener(`submit`,E),I(t,n(u,{get when(){return e.scope==="default"},get children(){return jS()}}),r),I(t,n(u,{get when(){return h()},children:e=>(()=>{var t=PS(),r=t.firstChild,i=r.firstChild.nextSibling;return i.nextSibling,I(i,()=>e().reason),I(r,n(u,{get when(){return e().storage},get children(){var t=hS();return I(t,()=>e().storage),t}}),null),t})()}),r),I(t,()=>T(`stt`),r),I(t,()=>T(`tts`),r),I(r,n(u,{get when(){return e.scope===`user`},get children(){var e=MS();return e.$$click=()=>void ee(),e}}),null),I(a,()=>s().text),I(t,n(lS,{get request(){return f()},onClose:()=>p(void 0)}),null),D(e=>{var t=l(),n=`small ${s().kind}`;return t!==e.e&&(i.disabled=e.e=t),n!==e.t&&G(a,e.t=n),e},{e:void 0,t:void 0}),t})()}P([`click`,`input`]);var VS=q(`<p class="small muted">This hub does not record voice conversations.`),HS=q(`<ul class=switches><li><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">`),US=q(`<a class="btn small"href=/api/recordings/export download>Export all`),WS=q(`<button type=button class="btn small danger">Delete all`),GS=q(`<div class=recording-head><span class=small data-recording-usage></span><span class=grow>`),KS=q(`<p class="small muted">No recordings.`),qS=q(`<ul class=recording-list>`),JS=q(`<button type=button class="btn small">Show more`),YS=q(`<section class=settings-section id=recording aria-labelledby=h-recording><h3 class=section-title id=h-recording>Recording`),XS=q(`<li>`),ZS=q(`<span class="recording-live small"> · recording now`),QS=q(`<label class=small>Segment`),$S=q(`<input class=recording-segment type=number min=1 step=1>`),eC=q(`<button type=button class="btn small"aria-label="Play segment">Play`),tC=q(`<li class=recording-row><div class=recording-title><strong></strong> · </div><div class="small muted"> · <!> · <!> · <!> · <!> · </div><div class=recording-actions><a class="btn small"download>Export</a><button type=button class="btn small danger">Delete`),nC=50;function rC(e){let t=Du(e)?.session,n=Mu(e);return Sl({...n.startsWith(`@`)?{name:n}:{},...typeof t?.project==`string`&&t.project||t?.directory?{directory:typeof t?.project==`string`&&t.project||t.directory}:{}})}var iC=e=>Cl(e,F(),void 0,rC);function aC(){let[t,r]=x(void 0),[i,a]=x(),[s,c]=x(),[l,d]=x([]),[f,p]=x(),[m,h]=x(!1),[g,_]=x(!1);async function v(){try{let e=await(await W(`/api/settings/recording`)).json();r(!0),a(e.settings),c(e.usage),kl.set({supported:!0,settings:e.settings})}catch(t){t instanceof e&&(t.status===404||t.status===405)?(r(!1),kl.set({supported:!1})):K(`Could not load the recording setting: ${U(t)}`,`err`)}}async function y(t=!1){try{let e=t?f():void 0,n=await(await W(`/api/recordings?limit=${nC}${e?`&cursor=${B(e)}`:``}`)).json();d(t?[...l(),...n.recordings]:n.recordings),c(n.usage),p(n.next)}catch(t){t instanceof e&&t.status===404||K(`Could not list the recordings: ${U(t)}`,`err`)}finally{_(!0)}}ue(async()=>{await v(),t()&&await y()});let b;j(Tu(e=>{e.type===`recording`&&(e.settings&&typeof e.settings.enabled==`boolean`&&a(e.settings),clearTimeout(b),b=setTimeout(()=>void y(),300))})),j(()=>clearTimeout(b));async function S(t){let n=i();if(!n)return;let r=t.checked;h(!0);try{let e=await(await W(`/api/settings/recording`,{method:`PUT`,json:{enabled:r,expectedRevision:n.revision}})).json();a(e.settings),Ll(e.settings),K(r?`Recording on from the next Voice start`:`Recording off`)}catch(r){t.checked=n.enabled,r instanceof e&&r.status===409?(K(`The setting changed on another device; it is reloaded. Try again.`,`err`),await v()):K(`Could not change the recording setting: ${U(r)}`,`err`)}finally{h(!1)}}async function C(e){let t=iC(e);if(await Ce(`Delete this recording? ${t.kind} · ${t.title}, ${t.started}: its audio and events are deleted now.`,`Delete`,{danger:!0}))try{await W(`/api/recordings/${B(e.id)}`,{method:`DELETE`}),d(l().filter(t=>t.id!==e.id)),K(`Recording deleted`),y()}catch(e){K(`Could not delete the recording: ${U(e)}`,`err`)}}async function w(){let e=l().length;if(await Ce(`Delete all ${e} recording${e===1?``:`s`}${f()?` (and the ones not listed yet)`:``}? Their audio and events are deleted now.`,`Delete all`,{danger:!0}))try{let{deleted:t}=await(await W(`/api/recordings`,{method:`DELETE`})).json();d([]),p(void 0),K(`${t??e} recording${(t??e)===1?``:`s`} deleted`),y()}catch(e){K(`Could not delete the recordings: ${U(e)}`,`err`)}}return(()=>{var e=YS();return e.firstChild,I(e,n(u,{get when(){return t()===!1},get children(){return VS()}}),null),I(e,n(u,{get when(){return V(()=>!!t())()&&i()},get children(){return[(()=>{var e=HS(),t=e.firstChild.firstChild,r=t.firstChild,a=r.firstChild,s=a.nextSibling,c=r.nextSibling,l=t.nextSibling;return I(a,()=>_l.label),I(s,()=>_l.description),c.addEventListener(`change`,e=>void S(e.currentTarget)),I(l,n(o,{get each(){return _l.details},children:e=>(()=>{var t=XS();return I(t,e),t})()})),D(()=>c.disabled=m()),D(()=>c.checked=i().enabled),e})(),(()=>{var e=GS(),t=e.firstChild;return t.nextSibling,I(t,(()=>{var e=V(()=>!!s());return()=>e()?yl(s()):``})()),I(e,n(u,{get when(){return l().length},get children(){return[US(),(()=>{var e=WS();return e.$$click=()=>void w(),e})()]}}),null),e})(),n(u,{get when(){return V(()=>!!g())()&&!l().length},get children(){return KS()}}),(()=>{var e=qS();return I(e,n(o,{get each(){return l()},children:e=>n(oC,{recording:e,onDelete:()=>void C(e)})})),e})(),n(u,{get when(){return f()},get children(){var e=JS();return e.$$click=()=>void y(!0),e}})]}}),null),e})()}function oC(e){let t=()=>iC(e.recording),[r,i]=x(1),[a,o]=x(!1),s=`rec-seg-${e.recording.id}`;async function c(){o(!0);try{await Bl(e.recording.id,r())}catch(e){K(`Could not play segment ${r()}: ${U(e)}`,`err`)}finally{o(!1)}}return(()=>{var o=tC(),l=o.firstChild,d=l.firstChild;d.nextSibling;var f=l.nextSibling,p=f.firstChild,m=p.nextSibling,h=m.nextSibling.nextSibling,g=h.nextSibling.nextSibling,_=g.nextSibling.nextSibling;_.nextSibling;var v=f.nextSibling,y=v.firstChild,b=y.nextSibling;return I(d,()=>t().kind),I(l,()=>t().title,null),I(l,n(u,{get when(){return t().active},get children(){return ZS()}}),null),I(f,()=>t().device,p),I(f,()=>t().started,m),I(f,()=>t().length,h),I(f,()=>t().segments,g),I(f,()=>t().size,_),I(f,()=>t().expires,null),I(f,n(u,{get when(){return t().note},get children(){return[` · `,V(()=>t().note)]}}),null),I(v,n(u,{get when(){return e.recording.segments>0},get children(){return[(()=>{var e=QS();return L(e,`for`,s),e})(),(()=>{var e=$S();return e.$$input=e=>i(Math.max(1,Math.floor(Number(e.currentTarget.value)||1))),L(e,`id`,s),D(()=>e.value=r()),e})(),(()=>{var e=eC();return e.$$click=()=>void c(),D(()=>e.disabled=a()),e})()]}}),y),b.$$click=()=>e.onDelete(),D(t=>{var n=e.recording.id,r=`Session ${e.recording.sessionID} · recording ${e.recording.id}`,i=`/api/recordings/${B(e.recording.id)}/export`;return n!==t.e&&L(o,`data-recording-row`,t.e=n),r!==t.t&&L(l,`title`,t.t=r),i!==t.a&&L(y,`href`,t.a=i),t},{e:void 0,t:void 0,a:void 0}),o})()}P([`click`,`input`]);var sC=[`queued`,`placing`,`provisioning`,`running`],cC=e=>typeof e==`object`&&!!e&&!Array.isArray(e),lC=e=>typeof e==`string`,uC=e=>typeof e==`number`&&Number.isFinite(e);function dC(e){if(!cC(e)||!lC(e.id)||!lC(e.state)||!cC(e.spec)||!cC(e.spec.workspace)||!lC(e.spec.workspace.repo))return;let t=e.spec.workspace,n=e.waiting;return{id:e.id,state:e.state,reason:lC(e.reason)?e.reason:``,repo:t.repo,...lC(t.branch)?{branch:t.branch}:{},...lC(e.by)?{by:e.by}:{},...lC(e.byLabel)?{byLabel:e.byLabel}:{},launcherRevoked:e.launcherRevoked===!0,...cC(n)&&lC(n.wait)&&lC(n.reason)&&uC(n.since)?{waiting:{wait:n.wait,reason:n.reason,since:n.since}}:{},...lC(e.name)?{name:e.name}:{},...lC(e.sessionID)?{sessionID:e.sessionID}:{},...lC(e.machineID)?{machineID:e.machineID}:{},concierge:e.by===`app:concierge`&&cC(e.spec.labels)&&e.spec.labels[`hub/system`]===`concierge`,created:uC(e.created)?e.created:0}}function fC(e){return!cC(e)||!Array.isArray(e.launches)?[]:e.launches.map(dC).filter(e=>e!==void 0)}function pC(e,t){if(!cC(t)||t.type!==`launch`)return e;let n=dC(t.launch);return n?sC.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 mC(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 hC={queued:`Queued`,placing:`Placing`,provisioning:`Starting`,running:`Running`,ended:`Ended`},gC=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 _C(e,t){let n=e.name?`@${e.name.replace(/^@+/,``)}`:`${e.repo}${e.branch?` (${e.branch})`:``}`;return{title:n,status:`${hC[e.state]??e.state} · by ${mC(e)}`,detail:e.state===`queued`&&e.waiting?`${e.waiting.reason} · ${gC(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 vC(e,t){if(e.state!==`ready`&&e.state!==`refreshing`)return;let n=e.latest();return n?pC(n,t):void 0}var yC=q(`<div id=agent-activity>`),bC=q(`<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`),xC=q(`<ul class=list>`),SC=q(`<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`),CC=q(`<p class="small muted">`),wC=q(`<p class="small muted">No app tokens yet.`),TC=q(`<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`),EC=q(`<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`),DC=q(`<p class="small muted">No live launches.`),OC=q(`<div class="small warn"data-launcher-revoked>`),kC=q(`<div class="small muted"data-launch-managed>`),AC=q(`<button type=button class="btn small danger">Stop`),jC=q(`<li class=row><div class=grow><div class=name></div><div class="small muted"></div><div class=small data-launch-reason>`),MC=q(`<div class=stack><p class=warn><strong>Copy this token now.</strong> It will not be shown again.</p><label class=text-field><span class=field-title>Bearer token</span><textarea class=mono readonly rows=3></textarea></label><button type=button class="btn primary">Copy token</button><label class=text-field><span class=field-title>Grant holder</span><span class="field-desc muted small">Use this non-secret value if you later create an acting or launch grant.</span><input class=mono readonly></label><button type=button class="btn small">Copy holder</button><button type=button class="btn small">Done`),NC=q(`<p class=error role=alert>`),PC=q(`<form class=grant-form novalidate><label class=text-field><span class=field-title>Label</span><span class="field-desc muted small">Where this token will be used.</span><input maxlength=100></label><fieldset class=grant-verbs><legend class=field-title>Scopes</legend></fieldset><p class="small muted">Act and launch scopes still require grants. Start with read and message scopes unless the app needs more.</p><div class=row><button type=submit class="btn small primary">Create token</button><button type=button class="btn small">Cancel`),FC=q(`<label class=check><input type=checkbox><span>`),IC=q(`<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>`),LC=q(`<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>`),RC=q(`<p class="small warn"role=status data-acting-note>`),zC=q(`<ul class="list grants">`),BC=q(`<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`),VC=q(`<p class="small muted">No grants. Agents can still ask you (Decisions).`),HC=q(`<dt>Permissions`),UC=q(`<dd class=mono>`),WC=q(`<dt>Never`),GC=q(`<button type=button class="btn small">Edit`),KC=q(`<button type=button class="btn small danger">Revoke`),qC=q(`<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>`),JC=q(`<p class="field-error small"role=alert>`),YC=q(`<span class="field-desc muted small">`),XC=q(`<label class="text-field grow"><span class=field-title></span><input type=text>`),ZC=q(`<label class=text-field><span class=field-title></span><span class="field-desc muted small"></span><textarea rows=2>`),QC=q(`<p class=error role=alert data-error=form>`),$C=q(`<form class=grant-form novalidate><fieldset class=grant-verbs aria-label=Actions><span class=field-title>May</span></fieldset><div class=row></div><label class=check><input type=checkbox aria-label="May allow always"><span>May answer “Always allow” (still only for patterns it may approve)</span></label><div class=row><button type=submit class="btn small primary"></button><button type=button class="btn small">Cancel`),ew=q(`<ol class="list audit agent-audit">`),tw=q(`<p class="small muted">Loading…`),nw=q(`<button type=button class="btn small">Load older`),rw=q(`<div class=stack>`),iw=q(`<p class="small err">Could not load: `),aw=q(`<p class="small muted">No agent actions yet.`),ow=q(`<span>`),sw=q(`<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">`),cw=50,lw=`/api/agent/grants`,uw=`/api/agent/app-tokens`,dw=`/api/agent/launches`,[fw,pw]=x(0);function mw(){let[e,t]=x(`grants`);return C(()=>{let e=ie().hash;e===`#agent-activity`?t(`activity`):e===`#grants`&&t(`grants`)}),(()=>{var r=bC(),i=r.firstChild.nextSibling,a=i.firstChild,o=a.nextSibling;return I(r,n(vw,{}),i),I(r,n(hw,{}),i),I(r,n(gw,{}),i),a.$$click=()=>t(`grants`),o.$$click=()=>t(`activity`),I(r,n(u,{get when(){return e()===`grants`},get children(){return n(yw,{})}}),null),I(r,n(u,{get when(){return e()===`activity`},get children(){var e=yC();return I(e,n(xw,{})),e}}),null),D(t=>{var n=e()===`grants`,r=e()===`activity`;return n!==t.e&&L(a,`aria-pressed`,t.e=n),r!==t.t&&L(o,`aria-pressed`,t.t=r),t},{e:void 0,t:void 0}),r})()}function hw(){let[e,{mutate:t,refetch:r}]=f(()=>z(uw).then(Un)),[i,a]=x(!1),s=async e=>{if(await Ce(`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 W(`${uw}/${B(e.id)}`,{method:`DELETE`}),t(t=>(t??[]).filter(t=>t.id!==e.id)),pw(e=>e+1),K(`App token revoked`)}catch(e){K(U(e),`err`),r()}};return(()=>{var r=SC(),c=r.firstChild.firstChild.nextSibling;return c.$$click=()=>a(!0),I(r,n(u,{get when(){return i()},get children(){return n(_w,{onClose:()=>a(!1),onCreated:e=>t(t=>[e,...(t??[]).filter(t=>t.id!==e.id)])})}}),null),I(r,n(u,{get when(){return e()},get fallback(){return(()=>{var t=CC();return I(t,(()=>{var t=V(()=>!!e.error);return()=>t()?`Could not load: ${U(e.error)}`:`Loading…`})()),t})()},get children(){return n(u,{get when(){return e().length},get fallback(){return wC()},get children(){var t=xC();return I(t,n(o,{get each(){return e()},children:e=>(()=>{var t=TC(),n=t.firstChild,r=n.firstChild,i=r.nextSibling;i.firstChild;var a=i.nextSibling,o=n.nextSibling;return I(r,()=>e.label||`Unnamed app`),I(i,()=>e.id,null),I(a,()=>e.scopes.join(`, `)||`No scopes`,null),I(a,(()=>{var t=V(()=>!!e.created);return()=>t()?` · created ${Be(e.created,F())}`:``})(),null),o.$$click=()=>void s(e),D(()=>L(t,`data-app-token`,e.id)),t})()})),t}})}}),null),r})()}function gw(){let[e,{refetch:t,mutate:r}]=f(fw,()=>z(`${dw}?state=${sC.join(`,`)}`).then(e=>fC(e)));j(Tu(t=>{let n=vC({state:e.state,latest:()=>e.latest},t);n&&r(n)}));let[i,a]=x(),s=async e=>{if(await Ce(`Stop ${_C(e,F()).title}? Its session is stopped and its workspace cleaned up by its policy.`,`Stop`,{danger:!0})){a(e.id);try{await W(`${dw}/${B(e.id)}`,{method:`DELETE`}),K(`Launch stopped`)}catch(e){K(U(e),`err`)}finally{a(void 0),t()}}};return(()=>{var r=EC(),a=r.firstChild.firstChild.nextSibling;return a.$$click=()=>void t(),I(r,n(u,{get when(){return e()},get fallback(){return(()=>{var t=CC();return I(t,(()=>{var t=V(()=>!!e.error);return()=>t()?`Could not load: ${U(e.error)}`:`Loading…`})()),t})()},get children(){return n(u,{get when(){return e().length},get fallback(){return DC()},get children(){var t=xC();return I(t,n(o,{get each(){return e()},children:e=>{let t=()=>_C(e,F());return(()=>{var r=jC(),a=r.firstChild,o=a.firstChild,c=o.nextSibling,l=c.nextSibling;return I(o,()=>t().title),I(c,()=>t().status),I(l,()=>t().detail),I(a,n(u,{get when(){return t().flag},get children(){var e=OC();return I(e,()=>t().flag),e}}),null),I(a,n(u,{get when(){return t().managed},get children(){var e=kC();return I(e,()=>t().managed),e}}),null),I(r,n(u,{get when(){return t().stopLabel},get children(){var n=AC();return n.$$click=()=>void s(e),D(r=>{var a=t().stopLabel,o=i()===e.id;return a!==r.e&&L(n,`aria-label`,r.e=a),o!==r.t&&(n.disabled=r.t=o),r},{e:void 0,t:void 0}),n}}),null),D(()=>L(r,`data-launch`,e.id)),r})()}})),t}})}}),null),r})()}function _w(e){let[t,r]=x(`MCP Gateway`),[i,a]=x([`sessions:read`,`messages:send`,`messages:read`]),[s,c]=x(``),[l,d]=x(``),[f,p]=x(``),[m,h]=x(!1),g=async n=>{n.preventDefault();let r=Wn(t(),i());if(!r.ok)return p(r.error);h(!0),p(``);try{let t=await(await W(uw,{method:`POST`,json:r.body})).json(),n=Hn(t);if(!n||typeof t?.token!=`string`)throw Error(`The hub did not return the new token`);e.onCreated(n),c(t.token),d(`app:${n.id}`)}catch(e){p(U(e))}finally{h(!1)}},_=async(e,t)=>{try{await navigator.clipboard.writeText(e),K(`${t} copied`)}catch{K(`Could not copy ${t.toLowerCase()}`,`err`)}};return n(ze,{open:!0,get title(){return s()?`Save your app token`:`New app token`},get onClose(){return e.onClose},class:`app-token-dialog`,get children(){return n(u,{get when(){return s()},get fallback(){return(()=>{var s=PC(),c=s.firstChild,l=c.firstChild.nextSibling.nextSibling,d=c.nextSibling;d.firstChild;var p=d.nextSibling.nextSibling,h=p.firstChild,_=h.nextSibling;return s.addEventListener(`submit`,e=>void g(e)),l.$$input=e=>r(e.currentTarget.value),I(d,n(o,{each:Vn,children:e=>(()=>{var t=FC(),n=t.firstChild,r=n.nextSibling;return n.addEventListener(`change`,t=>a(t.currentTarget.checked?[...i(),e]:i().filter(t=>t!==e))),I(r,e),D(()=>n.checked=i().includes(e)),t})()}),null),I(s,n(u,{get when(){return f()},get children(){var e=NC();return I(e,f),e}}),p),ke(_,`click`,e.onClose,!0),D(()=>h.disabled=m()),D(()=>l.value=t()),s})()},get children(){var t=MC(),n=t.firstChild.nextSibling,r=n.firstChild.nextSibling,i=n.nextSibling,a=i.nextSibling,o=a.firstChild.nextSibling.nextSibling,c=a.nextSibling,u=c.nextSibling;return i.$$click=()=>void _(s(),`Token`),c.$$click=()=>void _(l(),`Holder`),ke(u,`click`,e.onClose,!0),D(()=>r.value=s()),D(()=>o.value=l()),t}})}})}function vw(){let[e,{mutate:t}]=f(()=>z(`/api/agent/acting`).then(Gr)),[r,i]=f(()=>gt(X())||void 0,()=>z(`/api/admin/agents/acting`).then(e=>e?.enabled!==!1)),[a,o]=x(!1),s=async e=>{let n=e.checked;o(!0);try{t(Gr(await(await W(`/api/agent/acting`,{method:`PUT`,json:{enabled:n}})).json())),K(n?`Agent actions are on for you`:`Agent actions are off for you`)}catch(t){e.checked=!n,K(U(t),`err`)}finally{o(!1)}},c=async e=>{let n=e.checked;if(!n&&!await Ce(`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{o(!0);try{let e=await(await W(`/api/admin/agents/acting`,{method:`PUT`,json:{enabled:n}})).json();i.mutate(e?.enabled!==!1),K(n?`Agent actions are on for this hub`:`Agent actions are off for this hub`);let r=await z(`/api/agent/acting`).catch(()=>void 0);r&&t(Gr(r))}catch(t){e.checked=!n,K(U(t),`err`)}finally{o(!1)}}};return n(u,{get when(){return e()},get fallback(){return(()=>{var t=CC();return I(t,(()=>{var t=V(()=>!!e.error);return()=>t()?`Could not load: ${U(e.error)}`:`Loading…`})()),t})()},children:e=>[(()=>{var t=LC(),i=t.firstChild.firstChild.firstChild.nextSibling;return i.addEventListener(`change`,e=>void s(e.currentTarget)),I(t,n(u,{get when(){return V(()=>!!gt(X()))()&&r()!==void 0},get children(){var e=IC(),t=e.firstChild.firstChild.nextSibling;return t.addEventListener(`change`,e=>void c(e.currentTarget)),D(()=>t.disabled=a()),D(()=>t.checked=r()),e}}),null),D(()=>i.disabled=a()),D(()=>i.checked=e().on),t})(),n(u,{get when(){return e().note},get children(){var t=RC();return I(t,()=>e().note),t}})]})}function yw(){let[e,{refetch:t,mutate:r}]=f(()=>z(lw).then(Zn)),[i,a]=x(),[s,c]=x(Date.now()),l=setInterval(()=>c(Date.now()),1e3);j(()=>clearInterval(l));let d=async e=>{if(await Ce(`Revoke the grant of ${e.holder}? It stops at once.`,`Revoke`,{danger:!0}))try{let n=Xn((await(await W(`${lw}/${B(e.id)}`,{method:`DELETE`})).json())?.grant);n?r(e=>(e??[]).map(e=>e.id===n.id?n:e)):t(),K(`Grant of ${e.holder} revoked`)}catch(e){K(U(e),`err`),t()}},p=e=>{r(t=>[e,...(t??[]).filter(t=>t.id!==e.id)].sort((e,t)=>t.created-e.created)),a(void 0)};return(()=>{var t=BC(),r=t.firstChild.firstChild.nextSibling;return r.$$click=()=>a(`new`),I(t,n(u,{get when(){return i()},keyed:!0,children:e=>n(bw,{grant:e===`new`?void 0:e,onSaved:p,onClose:()=>a(void 0)})}),null),I(t,n(u,{get when(){return e()},get fallback(){return(()=>{var t=CC();return I(t,(()=>{var t=V(()=>!!e.error);return()=>t()?`Could not load: ${U(e.error)}`:`Loading…`})()),t})()},get children(){return n(u,{get when(){return e().length},get fallback(){return VC()},get children(){var t=zC();return I(t,n(o,{get each(){return e()},children:e=>{let t=()=>tr(e,s());return(()=>{var r=qC(),i=r.firstChild.firstChild,o=i.firstChild,s=i.nextSibling,c=s.firstChild.nextSibling,l=c.nextSibling.nextSibling,f=l.nextSibling,p=f.nextSibling,m=s.nextSibling;return I(i,()=>t().holder,o),I(o,()=>t().stateLabel),I(c,()=>t().projects),I(l,()=>t().verbs),I(s,n(u,{get when(){return t().permit},get children(){return[HC(),(()=>{var e=UC();return I(e,()=>t().permit),e})()]}}),f),I(s,n(u,{get when(){return t().never},get children(){return[WC(),(()=>{var e=UC();return I(e,()=>t().never),e})()]}}),f),I(p,()=>t().limits),I(m,()=>t().expiry),I(r,n(u,{get when(){return t().editable},get children(){return[(()=>{var t=GC();return t.$$click=()=>a(e),D(()=>L(t,`aria-label`,`Edit grant of ${e.holder}`)),t})(),(()=>{var t=KC();return t.$$click=()=>void d(e),D(()=>L(t,`aria-label`,`Revoke grant of ${e.holder}`)),t})()]}}),null),D(n=>{var i=`grant-row${t().editable?``:` ended`}`,a=e.id,s=`badge-pill ${t().state}`;return i!==n.e&&G(r,n.e=i),a!==n.t&&L(r,`data-grant`,n.t=a),s!==n.a&&G(o,n.a=s),n},{e:void 0,t:void 0,a:void 0}),r})()}})),t}})}}),null),t})()}function bw(t){let[r,i]=x(nr(t.grant)),[a,s]=x({}),[c,l]=x(``),[d,f]=x(!1),p=(e,t)=>{i(n=>({...n,[e]:t})),a()[e]&&s(t=>({...t,[e]:void 0}))},m=async n=>{n.preventDefault(),l(``);let i=or(r());if(!i.ok)s(i.errors);else{s({}),f(!0);try{let e=t.grant?`${lw}/${B(t.grant.id)}`:lw,n=Xn((await(await W(e,{method:t.grant?`PUT`:`POST`,json:i.body})).json())?.grant);K(t.grant?`Grant updated`:`Grant created`),n?t.onSaved(n):t.onClose()}catch(t){let n=U(t),r=t instanceof e&&(t.status===400||t.status===404)?sr(n):void 0;r?s({[r]:n}):l(t instanceof e&&t.hint?`${n} (${t.hint})`:n)}finally{f(!1)}}},h=e=>n(u,{get when(){return a()[e.field]},get children(){var t=JC();return I(t,()=>a()[e.field]),D(()=>L(t,`data-error`,e.field)),t}}),g=e=>(()=>{var t=XC(),i=t.firstChild,a=i.nextSibling;return I(i,()=>e.label),I(t,n(u,{get when(){return e.hint},get children(){var t=YC();return I(t,()=>e.hint),t}}),a),a.$$input=t=>p(e.field,t.currentTarget.value),I(t,n(h,{get field(){return e.field}}),null),D(t=>{var n=e.label,r=e.placeholder??``,i=e.disabled;return n!==t.e&&L(a,`aria-label`,t.e=n),r!==t.t&&L(a,`placeholder`,t.t=r),i!==t.a&&(a.disabled=t.a=i),t},{e:void 0,t:void 0,a:void 0}),D(()=>a.value=r()[e.field]),t})(),_=e=>(()=>{var t=ZC(),i=t.firstChild,a=i.nextSibling,o=a.nextSibling;return I(i,()=>e.label),I(a,()=>e.hint),o.$$input=t=>p(e.field,t.currentTarget.value),I(t,n(h,{get field(){return e.field}}),null),D(t=>{var n=e.label,r=e.placeholder??``;return n!==t.e&&L(o,`aria-label`,t.e=n),r!==t.t&&L(o,`placeholder`,t.t=r),t},{e:void 0,t:void 0}),D(()=>o.value=r()[e.field]),t})();return n(ze,{open:!0,get title(){return V(()=>!!t.grant)()?`Edit grant of ${t.grant.holder}`:`New grant`},get onClose(){return t.onClose},wide:!0,class:`grant-dialog`,get children(){var e=$C(),i=e.firstChild;i.firstChild;var a=i.nextSibling,s=a.nextSibling,l=s.firstChild,f=s.nextSibling,v=f.firstChild,y=v.nextSibling;return e.addEventListener(`submit`,e=>void m(e)),I(e,n(g,{field:`holder`,label:`Holder`,get hint(){return t.grant?`A grant's holder cannot change: revoke it and create another.`:`@@orchestrator (a reserved role), @name or ses_… (pinned to that session), or app:<token id>`},placeholder:`@@orchestrator`,get disabled(){return!!t.grant}}),i),I(e,n(_,{field:`projects`,label:`Projects`,hint:`Absolute project directories, one per line (subdirectories and worktrees included).`,placeholder:`/home/you/projects/api`}),i),I(i,n(o,{each:Ln,children:e=>(()=>{var t=FC(),n=t.firstChild,i=n.nextSibling;return n.addEventListener(`change`,t=>p(`allow`,t.currentTarget.checked?[...r().allow,e]:r().allow.filter(t=>t!==e))),L(n,`aria-label`,e),I(i,e),D(()=>n.checked=r().allow.includes(e)),t})()}),null),I(e,n(h,{field:`allow`}),a),I(e,n(_,{field:`permit`,label:`Permissions it may approve`,hint:`Patterns action[:glob], one per line (e.g. shell:bun test *).`}),a),I(e,n(_,{field:`never`,label:`Never`,hint:`Patterns it may never approve, one per line; never wins.`,placeholder:`shell:rm *`}),a),I(a,n(g,{field:`expires`,label:`Expires after`,get hint(){return t.grant?`From now: saving restarts the countdown.`:`30m, 8h, 2d (at most 30 days)`}}),null),I(a,n(g,{field:`maxActionsPerHour`,label:`Actions per hour`,hint:`1–1000`}),null),l.addEventListener(`change`,e=>p(`allowAlways`,e.currentTarget.checked)),I(e,n(h,{field:`allowAlways`}),f),I(e,n(u,{get when(){return c()},get children(){var e=QC();return I(e,c),e}}),f),I(v,()=>t.grant?`Save`:`Create grant`),ke(y,`click`,t.onClose,!0),D(()=>v.disabled=d()),D(()=>l.checked=r().allowAlways),e}})}function xw(){let[e,t]=x([]),[r,i]=x(),[a,s]=x(`loading`),[c,l]=x(``),d=async e=>{s(`loading`);try{let n=lr(await z(`/api/agent/audit?limit=${cw}${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))]}),i(n.next),s(`ready`)}catch(e){l(U(e)),s(`failed`)}};d();let[p]=f(async()=>{try{let{decisions:e}=await z(`/api/decisions`);return(e??[]).map(Jt).filter(e=>!!e)}catch{return[]}}),m=()=>{let e=new Map((p()??[]).map(e=>[e.id,e]));for(let t of ru().values())e.set(t.id,t);return[...e.values()]},h=()=>{let t=e()[0]?.seq??0;return[..._u().filter(e=>e.seq>t),...e()]};return(()=>{var e=rw();return I(e,n(u,{get when(){return a()!==`failed`},get fallback(){return(()=>{var e=iw();return e.firstChild,I(e,c,null),e})()},get children(){return[n(u,{get when(){return h().length||a()!==`ready`},get fallback(){return aw()},get children(){var e=ew();return I(e,n(o,{get each(){return h()},children:e=>{let t=()=>jr(e,xr(e,m()),Mu);return(()=>{var r=sw(),i=r.firstChild,a=i.firstChild,o=a.firstChild,s=o.nextSibling.nextSibling,c=a.nextSibling,l=c.firstChild,d=i.nextSibling;return I(o,()=>t().who),I(s,()=>t().what),I(l,()=>t().result),I(c,n(u,{get when(){return t().grant},get children(){return[` · `,(()=>{var e=ow();return I(e,()=>t().grant),D(()=>L(e,`title`,t().grantTitle)),e})()]}}),null),I(c,(()=>{var e=V(()=>!!t().reason);return()=>e()?` · ${t().reason}`:``})(),null),I(d,()=>Be(e.at,F())),D(n=>{var i=e.seq,a=e.actor.kind===`session`?e.actor.sessionID:void 0,c=t().whatTitle,u=`audit-result ${t().tone}`,f=new Date(e.at).toISOString(),p=new Date(e.at).toLocaleString();return i!==n.e&&L(r,`data-seq`,n.e=i),a!==n.t&&L(o,`title`,n.t=a),c!==n.a&&L(s,`title`,n.a=c),u!==n.o&&G(l,n.o=u),f!==n.i&&L(d,`datetime`,n.i=f),p!==n.n&&L(d,`title`,n.n=p),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),r})()}})),e}}),n(u,{get when(){return a()===`loading`},get children(){return tw()}}),n(u,{get when(){return V(()=>a()===`ready`)()&&r()!==void 0},get children(){var e=nw();return e.$$click=()=>void d(r()),e}})]}})),e})()}P([`click`,`input`]);var Sw=q(`<fieldset class=stack id=concierge-watchlist><legend class=field-title>Watchlist`),Cw=q(`<p class="small muted">`),ww=q(`<span class="field-desc muted small"data-watchlist-count>Watching <!> session<!> now.`),Tw=q(`<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)`),Ew=q(`<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)">`),Dw=q(`<label class=check><input type=checkbox><span>Pinned sessions and workspaces<span class=muted> (<!> now)`),Ow=q(`<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`),kw=q(`<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`),Aw=q(`<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">`),jw=q(`<datalist id=concierge-sessions>`),Mw=q(`<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">`),Nw=q(`<li class="small muted">No sessions added.`),Pw=q(`<li class=row><span class="small grow"></span><button type=button class="btn small">Remove`),Fw=q(`<li class="small muted">Nothing muted.`),Iw=q(`<li class=row><span class="small grow"></span><button type=button class="btn small">Unmute`),Lw=q(`<option>`),Rw=`/api/agent/concierge/watchlist`,zw=e=>Mu(e),Bw=(e,t)=>e.filter(e=>e.reasons.includes(t)).length,Vw=e=>[...new Set(e.split(`
|
|
17
|
-
`).map(e=>e.trim()).filter(Boolean))];function Hw(){let[t,{refetch:r,mutate:i}]=f(()=>z(Rw)),[a,s]=x(!1),[c,l]=x(``),[d,p]=x(``),m=async(n,a)=>{s(!0);try{let e=await(await n()).json(),r=t();return r&&e.config&&i({...r,config:e.config}),K(a),!0}catch(t){return K(t instanceof e&&t.status===409?`The watchlist changed elsewhere: reloaded`:`Could not save the watchlist: ${U(t)}`,`err`),!1}finally{s(!1),r()}},h=e=>m(()=>W(Rw,{method:`PUT`,json:{...e,expectedRevision:t().config.revision}}),`Watchlist saved`),g=(e,t)=>m(()=>W(`${Rw}/${e}`,{method:`POST`,json:{session:t}}),e===`watch`?`Watching ${zw(t)}`:e===`mute`?`Muted ${zw(t)} for the Concierge`:`Watchlist saved`);return(()=>{var e=Sw();return e.firstChild,I(e,n(u,{get when(){return t()},get fallback(){return(()=>{var e=Cw();return I(e,(()=>{var e=V(()=>!!t.error);return()=>e()?`Could not load the watchlist: ${U(t.error)}`:`Loading…`})()),e})()},children:e=>{let t=()=>e().config;return[(()=>{var t=ww(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,I(t,()=>e().entries.length,n),I(t,()=>e().truncated?`+`:``,n),I(t,()=>e().entries.length===1?``:`s`,r),t})(),(()=>{var n=Tw(),r=n.firstChild,i=r.nextSibling,o=i.firstChild.nextSibling,s=o.nextSibling.nextSibling,c=s.firstChild.nextSibling;return c.nextSibling,r.addEventListener(`change`,e=>void h({autoActive:e.currentTarget.checked})),I(i,()=>t().activeWithinHours,o),I(s,()=>Bw(e().entries,`active`),c),D(()=>r.disabled=a()),D(()=>r.checked=t().autoActive),n})(),(()=>{var e=Ew(),n=e.firstChild.nextSibling;return n.addEventListener(`change`,e=>{let n=Math.round(Number(e.currentTarget.value));n>=1&&n<=24&&n!==t().activeWithinHours?h({activeWithinHours:n}):e.currentTarget.value=String(t().activeWithinHours)}),D(()=>n.disabled=a()||!t().autoActive),D(()=>n.value=t().activeWithinHours),e})(),(()=>{var n=Dw(),r=n.firstChild,i=r.nextSibling.firstChild.nextSibling,o=i.firstChild.nextSibling;return o.nextSibling,r.addEventListener(`change`,e=>void h({usePins:e.currentTarget.checked})),I(i,()=>Bw(e().entries,`pinned`)+Bw(e().entries,`pinned_project`),o),D(()=>r.disabled=a()),D(()=>r.checked=t().usePins),n})(),(()=>{var e=Ow(),r=e.firstChild.nextSibling,i=r.nextSibling,s=i.firstChild,u=s.nextSibling;return I(r,n(o,{get each(){return t().sessions},get fallback(){return Nw()},children:e=>(()=>{var t=Pw(),n=t.firstChild,r=n.nextSibling;return L(t,`data-watch-session`,e),L(n,`title`,e),L(n,`data-session-id`,e),I(n,()=>zw(e)),r.$$click=()=>void g(`unwatch`,e),D(t=>{var n=a(),i=`Stop watching ${zw(e)}`;return n!==t.e&&(r.disabled=t.e=n),i!==t.t&&L(r,`aria-label`,t.t=i),t},{e:void 0,t:void 0}),t})()})),i.addEventListener(`submit`,e=>(e.preventDefault(),c().trim()&&void g(`watch`,c().trim()).then(e=>e&&l(``)))),s.$$input=e=>l(e.currentTarget.value),D(()=>u.disabled=a()||!c().trim()),D(()=>s.value=c()),e})(),(()=>{var e=kw(),r=e.firstChild.nextSibling,i=r.nextSibling,s=i.firstChild,c=s.nextSibling;return I(r,n(o,{get each(){return t().muted},get fallback(){return Fw()},children:e=>(()=>{var t=Iw(),n=t.firstChild,r=n.nextSibling;return L(t,`data-muted-session`,e),L(n,`title`,e),L(n,`data-session-id`,e),I(n,()=>zw(e)),r.$$click=()=>void g(`unmute`,e),D(t=>{var n=a(),i=`Unmute ${zw(e)}`;return n!==t.e&&(r.disabled=t.e=n),i!==t.t&&L(r,`aria-label`,t.t=i),t},{e:void 0,t:void 0}),t})()})),i.addEventListener(`submit`,e=>(e.preventDefault(),d().trim()&&void g(`mute`,d().trim()).then(e=>e&&p(``)))),s.$$input=e=>p(e.currentTarget.value),D(()=>c.disabled=a()||!d().trim()),D(()=>s.value=d()),e})(),(()=>{var e=Aw(),n=e.firstChild.nextSibling;return n.addEventListener(`change`,e=>void h({projects:Vw(e.currentTarget.value)})),D(()=>n.disabled=a()),D(()=>n.value=t().projects.join(`
|
|
18
|
-
`)),e})(),(()=>{var e=jw();return I(e,n(o,{get each(){return Eu().filter(e=>!e.hidden).slice(0,200)},children:e=>(()=>{var t=Lw();return D(()=>L(t,`label`,e.title)),D(()=>t.value=e.id),t})()})),e})(),(()=>{var e=Mw(),n=e.firstChild.nextSibling;return n.addEventListener(`change`,e=>void h({mutedProjects:Vw(e.currentTarget.value)})),D(()=>n.disabled=a()),D(()=>n.value=t().mutedProjects.join(`
|
|
19
|
-
`)),e})()]}}),null),e})()}P([`input`,`click`]);var Uw=q(`<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.`),Ww=q(`<button type=button class="btn small">Retry`),Gw=q(`<p class="small muted"data-concierge-load>`),Kw=q(`<button type=button class="btn small">Restart`),qw=q(`<button type=button class="btn small danger">Turn off`),Jw=q(`<button type=button class="btn small primary">Turn on`),Yw=q(`<p class="small muted"data-concierge-problem>`),Xw=q(`<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).`),Zw=q(`<div class="row concierge-notice err"role=alert data-concierge-suspended><span class=grow>Stopped: </span><button type=button class="btn small">Restart`),Qw=q(`<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`),$w=q(`<li class="small muted">No machines yet.`),eT=q(`<li class=row><label class="check grow"><input type=radio name=concierge-machine><span><span class="small muted"> · `),tT=q(`<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…`),nT=q(`<button type=button class="btn small">Renew`),rT=q(`<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`),iT=q(`<optgroup label=Projects>`),aT=q(`<optgroup label="Workspace roots">`),oT=q(`<input class=mono aria-describedby=concierge-directory-hint>`),sT=q(`<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>`),cT=q(`<option>`),lT=q(`<input class=mono aria-label="Other model (provider/model)"aria-describedby=concierge-model-hint placeholder=provider/model>`),uT=q(`<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>`),dT=q(`<optgroup>`),fT=q(`<p class="field-error small"role=alert>`),pT=q(`<label class=text-field><span class=field-title></span><span class="field-desc muted small"></span><textarea rows=2>`),mT=q(`<p class="small warn"role=note data-shell-warning>`),hT=q(`<p class=error role=alert data-error=form>`),gT=q(`<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`),_T=q(`<label class=check><input type=checkbox><span class="mono small">`),vT=q(`<label class=check><input type=checkbox><span>`),yT=q(`<button type=button class="btn small">Turn off quiet hours`),bT=q(`<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`),xT=q(`<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`),ST=q(`<li class="small muted">No digests.`),CT=q(`<li class=row><input type=time><span class=digest-days></span><button type=button class="btn small danger">Remove`),wT=q(`<label class="check small"><input type=checkbox><span>`),TT=`/api/agent/concierge`;async function ET(){let e=ms(await z(TT));if(!e)throw Error(`The hub answered an unexpected Concierge view`);return e}async function DT(e){if(!e)return;let{grants:t}=await z(`/api/agent/grants`);return t?.find(t=>t.id===e)}function OT(){let[e,{refetch:t,mutate:r}]=f(ET),i=()=>e.error?void 0:e(),[a,{refetch:s}]=f(()=>i()?.settings.grantID,DT),[c,l]=x(!1),[d,p]=x(!1),[m,_]=x({}),[v,y]=x(),b=()=>ou()??i()?.status,S=0,w;C(h(()=>e.error,e=>{if(clearTimeout(w),!e)return void(S=0);S>=4||(w=setTimeout(()=>void t(),1e3*2**S++))})),C(h(()=>ou()?.state,()=>e.error&&void t(),{defer:!0})),j(()=>clearTimeout(w));let T=async(e,n)=>{l(!0);try{let t=await(await n()).json(),a=i();a&&t.settings&&r({...a,settings:t.settings}),K(e)}catch(e){K(U(e),`err`)}finally{l(!1),t(),s()}},E=(e,t=`Saved`,n={})=>{let r=i().settings;return T(t,()=>W(`${TT}/settings`,{method:`PUT`,json:{...Bs(r,e),...n}}))},ee=()=>T(`Concierge on`,()=>W(`${TT}/enable`,{method:`POST`,json:{expectedRevision:i().settings.revision,timeZone:g()}})),te=async()=>{if(await Ce(`Turn the Concierge off? Its session stops and its grant is revoked; notes and watchlist are kept.`,`Turn off`,{danger:!0}))return T(`Concierge off`,()=>W(`${TT}/disable`,{method:`POST`,json:{expectedRevision:i().settings.revision}}))},O=()=>T(`Restarting the Concierge`,()=>W(`${TT}/restart`,{method:`POST`,json:{}}));return(()=>{var l=Uw();return l.firstChild,I(l,n(u,{get when(){return i()},get fallback(){return(()=>{var r=Gw();return I(r,(()=>{var t=V(()=>!!e.error);return()=>t()?`Could not load: ${U(e.error)} `:`Loading…`})(),null),I(r,n(u,{get when(){return e.error},get children(){var e=Ww();return e.$$click=()=>(S=0,void t()),e}}),null),r})()},children:e=>{let l=()=>e().settings,f=()=>Ts(e().machines),h=()=>Ds(l(),e().machines),x=()=>e().machines.find(e=>e.id===l().machineID);return(()=>{var S=Qw(),C=S.firstChild,w=C.firstChild.firstChild.nextSibling,T=C.nextSibling,ne=T.firstChild.nextSibling.nextSibling,re=T.nextSibling,ie=re.nextSibling,ae=ie.firstChild.nextSibling,k=ie.nextSibling;return k.firstChild,I(w,()=>ws(b(),e().machines,F())),I(C,n(u,{get when(){return l().enabled},get children(){return[(()=>{var e=Kw();return e.$$click=()=>void O(),D(()=>e.disabled=c()),e})(),(()=>{var e=qw();return e.$$click=()=>void te(),D(()=>e.disabled=c()),e})()]}}),null),I(C,n(u,{get when(){return!l().enabled},get children(){var e=Jw();return e.$$click=()=>void ee(),D(t=>{var n=c()||h()!==void 0,r=h()??``;return n!==t.e&&(e.disabled=t.e=n),r!==t.t&&L(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e}}),null),I(S,n(u,{get when(){return V(()=>!l().enabled)()&&h()},get children(){var e=Yw();return I(e,h),e}}),T),I(S,n(u,{get when(){return!l().enabled},get children(){return Xw()}}),T),I(S,n(u,{get when(){return V(()=>!!(l().enabled&&b()?.state===`failed`))()&&b()?.reason},get children(){var e=Zw(),t=e.firstChild;t.firstChild;var n=t.nextSibling;return I(t,()=>b().reason,null),n.$$click=()=>void O(),D(()=>n.disabled=c()),e}}),T),I(ne,n(o,{get each(){return f()},get fallback(){return $w()},children:e=>(()=>{var t=eT(),n=t.firstChild.firstChild,r=n.nextSibling,i=r.firstChild;return i.firstChild,n.addEventListener(`change`,()=>{let t=m()[e.id];y(t===void 0&&l().model!==void 0?e.id:void 0),E(Ks(l(),e,Y.machines,t))}),I(r,()=>e.name,i),I(i,()=>e.note,null),D(r=>{var i=e.id,a=e.eligible?`yes`:`no`,o=!e.selectable||c();return i!==r.e&&L(t,`data-concierge-machine`,r.e=i),a!==r.t&&L(t,`data-eligible`,r.t=a),o!==r.a&&(n.disabled=r.a=o),r},{e:void 0,t:void 0,a:void 0}),D(()=>n.checked=l().machineID===e.id),t})()})),I(S,n(kT,{get settings(){return l()},get machine(){return x()},get busy(){return c()},save:E}),re),I(S,n(AT,{get settings(){return l()},get machine(){return x()},get busy(){return c()},save:E,onModels:(e,t)=>{if(_({...m(),[e]:t}),v()!==e||l().machineID!==e)return;y(void 0);let n=qs(l(),t);n!==l()&&E(n,`Model back to ${x()?.name??`the machine`}'s default`)}}),re),ae.addEventListener(`change`,e=>{let t=e.currentTarget.value.trim()||g(),n=l().quietHours;E({...l(),timeZone:t,...n?{quietHours:{...n,timeZone:t}}:{}})}),I(S,n(MT,{get settings(){return l()},get busy(){return c()},save:E}),k),I(S,n(NT,{get settings(){return l()},get busy(){return c()},save:E}),k),I(S,n(Hw,{}),k),I(k,n(u,{get when(){return l().grant},get fallback(){return(()=>{var e=tT(),t=e.firstChild.nextSibling,n=t.nextSibling;return t.$$click=()=>void E({...l(),grant:Os([l().directory])},`Grant set`),n.$$click=()=>p(!0),D(e=>{var r=c()||!l().directory,i=c()||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})()},children:e=>(()=>{var t=rT(),r=t.firstChild,i=r.firstChild,o=i.nextSibling,s=o.nextSibling,f=s.firstChild,m=r.nextSibling,h=m.nextSibling;return I(i,()=>Ls(e()).head),I(o,()=>Ls(e()).permissions),I(s,()=>e().maxActionsPerHour,f),I(s,(()=>{var e=V(()=>!!a());return()=>e()?` · ${a().state===`active`?Rs(a().expiresAt,F()):a().state}`:l().enabled?``:` · created when you turn it on`})(),null),m.$$click=()=>p(!0),I(t,n(u,{get when(){return l().enabled},get children(){var t=nT();return t.$$click=()=>void E(l(),`Grant renewed`,{grant:e()}),D(()=>t.disabled=c()),t}}),h),h.$$click=()=>void E({...l(),grant:void 0},`Grant removed`),D(e=>{var t=c()||d(),n=c();return t!==e.e&&(m.disabled=e.e=t),n!==e.t&&(h.disabled=e.t=n),e},{e:void 0,t:void 0}),t})()}),null),I(k,n(u,{get when(){return d()},get children(){return n(jT,{get spec(){return l().grant},get directory(){return l().directory},get machineID(){return l().machineID},get revision(){return l().revision},onClose:()=>p(!1),onSaved:e=>{let n=i();n&&r({...n,settings:e}),p(!1),K(`Grant saved`),t(),s()}})}}),null),D(()=>L(S,`data-concierge-state`,b()?.state??`disabled`)),D(()=>ae.value=l().timeZone),S})()}}),null),l})()}function kT(e){let t=()=>Us(e.machine,Y.machines),r=()=>[...t().projects,...t().roots],[i,a]=x(!1);C(h(()=>e.machine?.id,()=>a(!1),{defer:!0}));let s=()=>i()?Vs:Gs(e.settings.directory,r()),c=t=>{t!==e.settings.directory&&e.save({...e.settings,directory:t})},l=()=>t().roots,d=()=>Ws(e.machine,t());return(()=>{var r=sT(),i=r.firstChild,f=i.firstChild.nextSibling,p=f.firstChild.nextSibling,m=i.nextSibling;return f.addEventListener(`change`,e=>{let t=e.currentTarget.value;if(t===`__other__`)return a(!0);a(!1),c(t||void 0)}),I(f,n(u,{get when(){return t().projects.length},get children(){var e=iT();return I(e,n(o,{get each(){return t().projects},children:e=>(()=>{var t=cT();return t.value=e,I(t,e),t})()})),e}}),p),I(f,n(u,{get when(){return l().length},get children(){var e=aT();return I(e,n(o,{get each(){return l()},children:e=>(()=>{var t=cT();return t.value=e,I(t,e),t})()})),e}}),p),p.value=Vs,I(m,d),I(r,n(u,{get when(){return s()===Vs},get children(){var t=oT();return t.addEventListener(`change`,e=>c(e.currentTarget.value.trim()||void 0)),D(n=>{var r=`Other folder on ${e.machine?.name??`the machine`}`,i=e.machine?.roots[0]?`${e.machine.roots[0].replace(/\/+$/,``)}/…`:`/path/to/repo`,a=e.busy;return r!==n.e&&L(t,`aria-label`,n.e=r),i!==n.t&&L(t,`placeholder`,n.t=i),a!==n.a&&(t.disabled=n.a=a),n},{e:void 0,t:void 0,a:void 0}),D(()=>t.value=e.settings.directory??``),t}}),null),D(()=>f.disabled=!e.machine||e.busy),D(()=>f.value=s()),r})()}function AT(e){let t=()=>Xs(e.machine),[r,{refetch:i}]=f(()=>e.machine&&!t()?e.machine.id:void 0,async e=>({id:e,options:Ys(await z(`${TT}/machines/${encodeURIComponent(e)}/models`))})),a=()=>r.error||r.loading?void 0:r()?.id===e.machine?.id?r():void 0;C(h(a,t=>t&&e.onModels(t.id,t.options.map(e=>e.value))));let s=()=>a()?.options??[],c=()=>[...new Set(s().map(e=>e.provider))],[l,d]=x(!1);C(h(()=>e.machine?.id,()=>d(!1),{defer:!0}));let p=()=>!a()&&!r.error&&e.settings.model?e.settings.model:void 0,m=()=>l()?Vs:p()??Gs(e.settings.model,s().map(e=>e.value)),g=t=>{t!==e.settings.model&&e.save({...e.settings,model:t})},_=()=>t()?t():r.loading?`Loading ${e.machine?.name??`the machine`}'s models…`:r.error?`Could not load the models: ${U(r.error)}`:!a()||s().length?``:`Its OpenCode reports no models: type one, or keep the machine default.`;return(()=>{var t=uT(),a=t.firstChild,l=a.firstChild.nextSibling,f=l.firstChild.nextSibling,h=a.nextSibling.nextSibling;return l.addEventListener(`change`,e=>{let t=e.currentTarget.value;if(t===`__other__`)return d(!0);d(!1),g(t||void 0)}),I(l,n(u,{get when(){return p()},children:e=>(()=>{var t=cT();return I(t,e),D(()=>t.value=e()),t})()}),f),I(l,n(o,{get each(){return c()},children:e=>(()=>{var t=dT();return L(t,`label`,e),I(t,n(o,{get each(){return s().filter(t=>t.provider===e)},children:e=>(()=>{var t=cT();return I(t,()=>e.label),D(()=>t.value=e.value),t})()})),t})()}),f),f.value=Vs,I(h,_,null),I(h,n(u,{get when(){return r.error},get children(){return[` `,(()=>{var e=Ww();return e.$$click=()=>void i(),e})()]}}),null),I(t,n(u,{get when(){return m()===Vs},get children(){var t=lT();return t.addEventListener(`change`,e=>g(e.currentTarget.value.trim()||void 0)),D(()=>t.disabled=e.busy),D(()=>t.value=e.settings.model??``),t}}),null),D(t=>{var n=e.busy,i=r.loading?`true`:`false`;return n!==t.e&&(l.disabled=t.e=n),i!==t.t&&L(l,`aria-busy`,t.t=i),t},{e:void 0,t:void 0}),D(()=>l.value=m()),t})()}function jT(t){let[r,i]=x(As(t.spec,t.directory)),[a,s]=x({}),[c,l]=x(``),[d,f]=x(!1),[p,m]=x(``),h=(e,t)=>i({...r(),[e]:t}),g=()=>(Y.machines??[]).find(e=>e.id===t.machineID),_=()=>Is(g(),t.directory,r().projects),v=async n=>{n.preventDefault(),l(``);let i=Ns(r());if(!i.ok)return s(i.errors);s({}),f(!0);try{let e=await(await W(`${TT}/settings`,{method:`PUT`,json:{grant:i.body,expectedRevision:t.revision}})).json();t.onSaved(e.settings)}catch(t){let n=U(t),r=t instanceof e&&t.status===400?Fs(n):void 0;r?s({[r]:n}):l(n)}finally{f(!1)}},y=e=>n(u,{get when(){return a()[e.field]},get children(){var t=fT();return I(t,()=>a()[e.field]),D(()=>L(t,`data-error`,e.field)),t}}),b=e=>(()=>{var t=pT(),i=t.firstChild,a=i.nextSibling,o=a.nextSibling;return I(i,()=>e.label),I(a,()=>e.hint),o.$$input=t=>h(e.field,t.currentTarget.value),I(t,n(y,{get field(){return e.field}}),null),D(t=>{var n=e.label,r=e.placeholder??``;return n!==t.e&&L(o,`aria-label`,t.e=n),r!==t.t&&L(o,`placeholder`,t.t=r),t},{e:void 0,t:void 0}),D(()=>o.value=r()[e.field]),t})();return(()=>{var e=gT(),i=e.firstChild,a=i.firstChild.nextSibling.nextSibling,s=a.firstChild,l=s.nextSibling,f=i.nextSibling;f.firstChild;var g=f.nextSibling,x=g.firstChild,S=x.firstChild.nextSibling.nextSibling,C=x.nextSibling,w=C.firstChild.nextSibling.nextSibling,T=g.nextSibling,E=T.firstChild,ee=E.nextSibling;return e.addEventListener(`submit`,e=>void v(e)),I(i,n(o,{get each(){return _()},children:e=>(()=>{var t=_T(),n=t.firstChild,i=n.nextSibling;return n.addEventListener(`change`,t=>h(`projects`,t.currentTarget.checked?[...r().projects,e]:r().projects.filter(t=>t!==e))),L(n,`aria-label`,e),I(i,e),D(()=>n.checked=r().projects.includes(e)),t})()}),a),s.$$input=e=>m(e.currentTarget.value),l.$$click=()=>(h(`projects`,[...r().projects,p().trim()]),m(``)),I(i,n(y,{field:`projects`}),null),I(f,n(o,{each:ks,children:e=>(()=>{var t=vT(),n=t.firstChild,i=n.nextSibling;return n.addEventListener(`change`,t=>h(`allow`,t.currentTarget.checked?[...r().allow,e]:r().allow.filter(t=>t!==e))),L(n,`aria-label`,e),I(i,e),D(()=>n.checked=r().allow.includes(e)),t})()}),null),I(e,n(y,{field:`allow`}),g),I(e,n(b,{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`}),g),I(e,n(u,{get when(){return Ps(r().permit)},get children(){var e=mT();return I(e,()=>Ps(r().permit)),e}}),g),I(e,n(b,{field:`never`,label:`Never`,hint:`Patterns it may never approve, one per line; never wins.`,placeholder:`shell:rm *`}),g),S.$$input=e=>h(`expires`,e.currentTarget.value),I(x,n(y,{field:`expires`}),null),w.$$input=e=>h(`maxActionsPerHour`,e.currentTarget.value),I(C,n(y,{field:`maxActionsPerHour`}),null),I(e,n(u,{get when(){return c()},get children(){var e=hT();return I(e,c),e}}),T),ke(ee,`click`,t.onClose,!0),D(e=>{var t=!p().trim(),n=d();return t!==e.e&&(l.disabled=e.e=t),n!==e.t&&(E.disabled=e.t=n),e},{e:void 0,t:void 0}),D(()=>s.value=p()),D(()=>S.value=r().expires),D(()=>w.value=r().maxActionsPerHour),e})()}function MT(e){let[t,r]=x(e.settings.quietHours?.start??``),[i,a]=x(e.settings.quietHours?.end??``);return(()=>{var o=bT(),s=o.firstChild.nextSibling,c=s.firstChild,l=s.nextSibling,d=l.firstChild,f=d.firstChild.nextSibling,p=d.nextSibling,m=p.firstChild.nextSibling,h=p.nextSibling,g=l.nextSibling.firstChild;return I(s,(()=>{var t=V(()=>!!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.`})(),c),f.$$input=e=>r(e.currentTarget.value),m.$$input=e=>a(e.currentTarget.value),h.$$click=()=>void e.save({...e.settings,quietHours:{start:t(),end:i(),timeZone:e.settings.timeZone}},`Quiet hours saved`),I(h,()=>e.settings.quietHours?`Save quiet hours`:`Turn on quiet hours`),I(l,n(u,{get when(){return e.settings.quietHours},get children(){var t=yT();return t.$$click=()=>void e.save({...e.settings,quietHours:void 0},`Quiet hours off`),D(()=>t.disabled=e.busy),t}}),null),g.addEventListener(`change`,t=>void e.save({...e.settings,quietAllowsUrgent:t.currentTarget.checked})),D(n=>{var r=e.busy||!t()||!i(),a=e.busy;return r!==n.e&&(h.disabled=n.e=r),a!==n.t&&(g.disabled=n.t=a),n},{e:void 0,t:void 0}),D(()=>f.value=t()),D(()=>m.value=i()),D(()=>g.checked=e.settings.quietAllowsUrgent),o})()}function NT(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=xT(),s=a.firstChild.nextSibling,c=s.firstChild.nextSibling;c.nextSibling;var l=s.nextSibling,u=l.nextSibling.firstChild;return I(s,()=>e.settings.timeZone,c),I(l,n(o,{get each(){return t()},get fallback(){return ST()},children:(a,s)=>(()=>{var c=CT(),l=c.firstChild,u=l.nextSibling,d=u.nextSibling;return l.addEventListener(`change`,e=>e.currentTarget.value&&i(s(),{at:e.currentTarget.value})),I(u,n(o,{each:_c,children:(t,n)=>(()=>{var r=wT(),o=r.firstChild,c=o.nextSibling;return o.addEventListener(`change`,e=>{let t=vc(a.days,n(),e.currentTarget.checked);JSON.stringify(t)===JSON.stringify(a.days)?e.currentTarget.checked=!0:i(s(),{days:t})}),I(c,t),D(n=>{var r=`Digest ${s()+1} on ${t}`,i=e.busy;return r!==n.e&&L(o,`aria-label`,n.e=r),i!==n.t&&(o.disabled=n.t=i),n},{e:void 0,t:void 0}),D(()=>o.checked=!a.days||a.days.includes(n())),r})()})),d.$$click=()=>r(t().filter((e,t)=>t!==s()),`Digest removed`),D(t=>{var n=s(),r=`Digest ${s()+1} time`,i=e.busy,a=e.busy,o=`Remove digest ${s()+1}`;return n!==t.e&&L(c,`data-digest`,t.e=n),r!==t.t&&L(l,`aria-label`,t.t=r),i!==t.a&&(l.disabled=t.a=i),a!==t.o&&(d.disabled=t.o=a),o!==t.i&&L(d,`aria-label`,t.i=o),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),D(()=>l.value=a.at),c})()})),u.$$click=()=>r([...t(),{at:`08:00`}],`Digest added`),D(()=>u.disabled=e.busy||t().length>=4),a})()}P([`click`,`input`]);function PT(e,t){let n=Math.max(0,Math.ceil((e-t)/1e3));return`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}`}function FT(e,t){return t.find(t=>!e.has(t.id))}function IT(e,t,n){let r=t?Date.parse(t):NaN;return Number.isFinite(r)?n+Math.max(0,e-r-1e3):e}var LT={L:0,M:1,Q:2,H:3},RT={L:1,M:0,Q:3,H:2},zT=[[-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]],BT=[[-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]],VT=(e,t)=>!!(e>>>t&1);function HT(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 UT(e,t){let n=LT[t];return Math.floor(HT(e)/8)-zT[n][e]*BT[n][e]}function WT(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 GT(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]=WT(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=WT(n,2)}return t}function KT(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]^=WT(t,e))}return n}function qT(e,t,n){let r=LT[n],i=BT[r][t],a=zT[r][t],o=Math.floor(HT(t)/8),s=i-o%i,c=Math.floor(o/i),l=GT(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=KT(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 JT(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=UT(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 YT=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=RT[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,VT(r,e));this.set(8,7,VT(r,6)),this.set(8,8,VT(r,7)),this.set(7,8,VT(r,8));for(let e=9;e<15;e++)this.set(14-e,8,VT(r,e));for(let e=0;e<8;e++)this.set(i-1-e,8,VT(r,e));for(let e=8;e<15;e++)this.set(8,i-15+e,VT(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,VT(t,e)),this.set(r,n,VT(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]=VT(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 XT(e,t={}){let n=t.ecc??`M`,r=new TextEncoder().encode(e),i=1;for(;4+(i<=9?8:16)+r.length*8>UT(i,n)*8;)if(++i>40)throw Error(`Text too long for a QR code`);let a=new YT(i,n);a.codewords(qT(JT(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 ZT(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 QT=.8,$T=1.8,eE=.05,tE=`hub.fontScale`,nE=e=>Math.min($T,Math.max(QT,e)),rE=(e,t)=>Number((Math.round(e/t)*t).toFixed(2));function iE(e){return Number.isFinite(e)?rE(nE(e),eE):1}function aE(e){return e?iE(Number(e)):1}function oE(e,t,n){return iE(!(t>0)||!(n>0)?e:n/t*e)}function sE(e,t){let n=nE((Number.isFinite(e)?e:1)*Math.exp(-t*.01));return Number(n.toFixed(3))}var cE=e=>`${Math.round(e*100)}%`;function lE(e){try{return aE(e.getItem(tE))}catch{return 1}}function uE(e,t){let n=iE(t);try{n===1?e.removeItem(tE):e.setItem(tE,String(n))}catch{}return n}var dE=()=>typeof localStorage>`u`?void 0:localStorage,[fE,pE]=x(dE()?lE(dE()):1),mE=fE;function hE(e){document.documentElement.style.setProperty(`--font-scale`,String(e))}var gE;function _E(e,t={}){let n=t.settle===!1?e:iE(e);pE(n),hE(n),clearTimeout(gE);let r=()=>{let e=dE();if(!e)return;let t=uE(e,n);t!==fE()&&(pE(t),hE(t))};t.settle===!1?gE=setTimeout(r,250):r()}var vE=`.scroller, .home-scroll`,yE=e=>e instanceof Element&&e.closest(vE)!==null;function bE(e=document){hE(fE());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`&&yE(e.target)&&(t.set(e.pointerId,{x:e.clientX,y:e.clientY}),t.size===2&&(n={scale:fE(),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=oE(n.scale,n.distance,r());e!==fE()&&_E(e,{settle:!1})}},o=e=>{t.delete(e.pointerId)&&t.size<2&&n&&(n=void 0,_E(fE()))},s=e=>{e.touches.length>=2&&yE(e.target)&&e.preventDefault()},c=e=>{e.ctrlKey&&yE(e.target)&&(e.preventDefault(),_E(sE(fE(),e.deltaMode===1?e.deltaY*16:e.deltaY),{settle:!1}))},l,u=e=>{yE(e.target)&&(e.preventDefault(),e.type===`gesturestart`?l=fE():e.type===`gesturechange`&&l!==void 0&&e.scale?_E(oE(l,1,e.scale),{settle:!1}):e.type===`gestureend`&&(l=void 0,_E(fE())))},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 xE=[`light`,`system`,`dark`],SE=`hub.theme`;function CE(e){return e===`light`||e===`dark`||e===`system`?e:`system`}function wE(e){return e===`system`?void 0:e}function TE(){try{return CE(localStorage.getItem(SE))}catch{return`system`}}var[EE,DE]=x(TE());function OE(e){let t=wE(e);t?document.documentElement.dataset.theme=t:delete document.documentElement.dataset.theme;try{e===`system`?localStorage.removeItem(SE):localStorage.setItem(SE,e)}catch{}DE(e)}var kE=q(`<h3 class=section-title>`),AE=q(`<section class=settings-section>`),jE=q(`<div class=settings-search role=search><input type=search placeholder="Search settings"aria-label="Search settings">`),ME=q(`<nav class=settings-nav aria-label="Settings sections">`),NE=q(`<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`),PE=q(`<a>`),FE=q(`<ul class=settings-results aria-label="Search results">`),IE=q(`<p class="muted settings-empty">No settings match.`),LE=q(`<li><a><span class=name></span><span class="small muted"> · `),RE=q(`<ul class=settings-list aria-label="Settings sections">`),zE=q(`<li><a><span class=grow><span class=name></span><span class="small muted">`),BE=q(`<div class=settings-page><p class=muted>No such settings section.</p><a class="btn small"href=/settings>All settings`),VE=q(`<div class=settings-page><h2 class=settings-page-title>`),HE=q(`<span class=badge-pill>`),UE=q(`<div class="small muted">`),WE=q(`<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`),GE=q(`<h3>Notify me when`),KE=q(`<p class="small notify-summary"data-notify-summary>`),qE=q(`<p class="small warn">These apply once this device is subscribed.`),JE=q(`<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.`),YE=q(`<h4>When`),XE=q(`<ul class=switches><li id=quiet-hours><label class=switch><span>Quiet hours</span><input type=checkbox>`),ZE=q(`<p class="small muted"> muted (⋯ menu of a session → Unmute notifications).`),QE=q(`<p class="small muted">Checking this device…`),$E=q(`<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>`),eD=q(`<button type=button class="btn small primary">Enable notifications on this device`),tD=q(`<button type=button class="btn small">Turn off on this device`),nD=q(`<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`),rD=q(`<div class=row-actions>`),iD=q(`<option>`),aD=q(`<p data-test-result>`),oD=q(`<details class=notify-group><summary><h4></h4><span class="small muted notify-group-summary"data-group-summary></span></summary><ul class=switches>`),sD=q(`<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.`),cD=q(`<li><label class=switch><span class=notify-kind><span></span><span class="small muted"></span></span><input type=checkbox>`),lD=q(`<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.`),uD=q(`<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`),dD=q(`<p class="small muted">On this device. Pinch the conversation or the session list to change it too (a trackpad pinch works on desktop).`),fD=q(`<button type=button role=radio class=theme-choice><span>`),pD=q(`<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-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.`),mD=q(`<button type=button class=chip role=radio>`),hD=q(`<h3>Waiting for approval`),gD=q(`<ul class=list>`),_D=q(`<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`),vD=q(`<p class="small muted">None. In OpenCode run /hub → Connect to a hub….`),yD=q(`<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`),bD=q(`<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`),xD=q(`<p class="small muted">`),SD=q(`<span class=muted> · this device`),CD=q(`<li><div class=grow><div class=name></div><div class="small muted">last seen </div></div><button type=button class="btn small danger">`),wD=q(`<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>`),TD=q(`<p class="small muted">Expires in <span class=add-app-countdown></span> · single use`),ED=q(`<div class=row><code class="add-app-link grow"></code><button type=button class="btn small">Copy</button><a class="btn small">Open`),DD=q(`<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.`),OD=q(`<div class=add-app-expired><p class="small warn">This code expired.</p><button type=button class="btn small primary">New code`),kD=q(`<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`),AD=q(`<p class="small muted">How your <a href=/teams>teams</a> work with the rest of your sessions.`),jD=q(`<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>`),MD=q(`<div class=chips role=group aria-label="Admin sections">`),ND=q(`<p class=error role=alert>`),PD=q(`<div id=admin-machines>`),FD=q(`<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=…).`),ID=q(`<div id=admin-audit>`),LD=q(`<span class=count>`),RD=q(`<button type=button class=chip>`),zD=q(`<p class=muted>No machines are waiting for approval.`),BD=q(`<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">`),VD=q(`<p class=muted>`),HD=q(`<li class=muted>No users match.`),UD=q(`<span class=badge-pill>Admin`),WD=q(`<span class="badge-pill off">Disabled`),GD=q(`<span class=badge-pill>You`),KD=q(`<li><div class=grow><div class=name></div><div class="small muted"> · <!> · seen `),qD=q(`<button type=button>`),JD=q(`<p class=muted>No machines are connected to this hub yet.`),YD=q(`<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`),XD=q(`<ol class="list audit">`),ZD=q(`<p class=muted>Nothing recorded yet.`),QD=q(`<li><div class=grow><div class=name></div><div class="small muted"></div></div><time class="small muted">`);function $D(e){return(()=>{var t=AE();return pe(t,ce({get id(){return e.id}},()=>e.title?{"aria-labelledby":`h-${e.id}`}:{"aria-label":e.label??e.id}),!1,!0),I(t,n(u,{get when(){return e.title},get children(){var t=kE();return I(t,()=>e.title),D(()=>L(t,`id`,`h-${e.id}`)),t}}),null),I(t,()=>e.children,null),t})()}var eO=2400,tO=3e3;function nO(e){if(!e)return;let t=Date.now()+tO,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`),eO)}};requestAnimationFrame(n)}var rO=e=>we(!0).find(t=>t.id===e)?.label,iO=!1;function aO(){let e=()=>gt(X()),r=()=>{let e=Kx();return e.name===`settings`?e.section:void 0},i=()=>E(r(),{admin:e(),phone:Z()}),[s,c]=x(``),l=()=>Ee(s(),t(e()));C(h(ie,e=>nO(decodeURIComponent(e.hash.slice(1)))));let d=()=>{iO?(iO=!1,history.back()):a(`/settings`)},f=()=>(()=>{var e=jE(),t=e.firstChild;return t.$$keydown=e=>{e.key===`Escape`&&c(``);let t=l()[0];e.key===`Enter`&&t&&(c(``),a(`/settings/${t.section}#${t.id}`))},t.$$input=e=>c(e.currentTarget.value),D(()=>t.value=s()),e})();return(()=>{var t=NE(),r=t.firstChild,a=r.firstChild,p=r.nextSibling,m=p.firstChild,h=m.firstChild,g=h.firstChild.nextSibling;return g.nextSibling,I(r,n(u,{get when(){return Z()},get children(){return n(u,{get when(){return i()!==`list`},get fallback(){return n(R,{icon:`menu`,label:`Open sidebar`,onClick:Tp})},get children(){return n(R,{icon:`back`,label:`All settings`,onClick:d})}})}}),a),I(a,(()=>{var e=V(()=>!!(Z()&&i()!==`list`));return()=>e()?rO(i())??`Settings`:`Settings`})()),I(p,n(u,{get when(){return!Z()},get children(){var t=ME();return I(t,f,null),I(t,n(o,{get each(){return we(e())},children:e=>(()=>{var t=PE();return t.$$click=()=>c(``),I(t,()=>e.label),D(n=>{var r=`/settings/${e.id}`,a=i()===e.id&&!s()?`page`:void 0;return r!==n.e&&L(t,`href`,n.e=r),a!==n.t&&L(t,`aria-current`,n.t=a),n},{e:void 0,t:void 0}),t})()}),null),t}}),m),I(m,n(u,{get when(){return V(()=>!!Z())()&&i()===`list`},get children(){return f()}}),h),I(m,n(u,{get when(){return!s()},get fallback(){return n(oO,{get results(){return l()},onPick:()=>c(``)})},get children(){return n(ee,{get fallback(){return n(cO,{})},get children(){return[n(A,{get when(){return i()===`list`},get children(){return n(sO,{onPick:()=>iO=!0})}}),n(A,{get when(){return V(()=>i()!==`list`)()&&i()},keyed:!0,children:e=>n(lO,{id:e})})]}})}}),h),I(h,()=>X()?.publicURL??location.origin,g),I(h,()=>X()?.version??`?`,null),t})()}function oO(e){return n(u,{get when(){return e.results.length},get fallback(){return IE()},get children(){var t=FE();return I(t,n(o,{get each(){return e.results},children:t=>(()=>{var n=LE(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild;return ke(r,`click`,e.onPick,!0),I(i,()=>t.label),I(a,()=>rO(t.section),o),I(a,()=>t.description,null),D(()=>L(r,`href`,`/settings/${t.section}#${t.id}`)),n})()})),t}})}function sO(e){return(()=>{var t=RE();return I(t,n(o,{get each(){return we(gt(X()))},children:t=>(()=>{var r=zE(),i=r.firstChild,a=i.firstChild.firstChild,o=a.nextSibling;return ke(i,`click`,e.onPick,!0),I(a,()=>t.label),I(o,()=>t.description),I(i,n(H,{name:`chevron`}),null),D(()=>L(i,`href`,`/settings/${t.id}`)),r})()})),t})()}function cO(){return BE()}function lO(e){return(()=>{var t=VE(),r=t.firstChild;return I(r,()=>rO(e.id)),I(t,n(ee,{get children(){return[n(A,{get when(){return e.id===`general`},get children(){return[n(dO,{}),n(pO,{}),n(SO,{})]}}),n(A,{get when(){return e.id===`notifications`},get children(){return n(fO,{})}}),n(A,{get when(){return e.id===`voice`},get children(){return[n(hO,{}),n(aC,{}),n($D,{id:`speech`,title:`Speech`,get children(){return n(zS,{})}})]}}),n(A,{get when(){return e.id===`machines`},get children(){return[n(vO,{}),n(yO,{})]}}),n(A,{get when(){return e.id===`agents`},get children(){return n(mw,{})}}),n(A,{get when(){return e.id===`concierge`},get children(){return n(OT,{})}}),n(A,{get when(){return e.id===`teams`},get children(){return n(wO,{})}}),n(A,{get when(){return V(()=>e.id===`admin`)()&>(X())},get children(){return n(DO,{})}})]}}),null),D(()=>L(t,`data-settings-section`,e.id)),t})()}async function uO(){if(_t(X()).mode!==`pairing`||await Ce(`Sign out this device? You will need a new pairing code.`,`Sign out`,{danger:!0})){await(await Ef().catch(()=>void 0))?.unsubscribe().catch(()=>{}),await W(`/api/logout`,{method:`POST`,json:{}}).catch(()=>{});try{xs(localStorage)}catch{}td(),location.href=`/`}}function dO(){let e=()=>_t(X());return n($D,{id:`account`,title:`Account`,get children(){var t=WE(),r=t.firstChild,i=r.nextSibling,a=i.firstChild,o=a.firstChild,s=a.nextSibling;s.firstChild;var c=i.nextSibling;return I(r,()=>e().initial),I(o,()=>e().title),I(a,n(u,{get when(){return e().badge},get children(){var t=HE();return I(t,()=>e().badge),t}}),null),I(i,n(u,{get when(){return e().subtitle},get children(){var t=UE();return I(t,()=>e().subtitle),t}}),s),I(s,()=>X()?.device?.name??`paired`,null),c.$$click=()=>void uO(),D(()=>G(r,`avatar large${e().badge?` admin`:``}`)),t}})}function fO(){let[e,{refetch:t}]=f(bf,()=>Of()),[r,i]=x(!1),[a,c]=x(),[l,p]=x(``),[m,h]=x(),[_,v]=x(null),[y,C]=x(),T=()=>y()??ee()?.activityMinutes??5,E=()=>e()?b(e().env):void 0,ee=()=>e()?.view,O=()=>m()??ee()?.prefs,re=()=>m()?_():ee()?.quietHours??null,ie=async(e,n)=>{i(!0);try{await e(),n&&K(n)}catch(e){K(U(e),`err`)}finally{i(!1),h(void 0),t()}},ae=async e=>{try{let t=await(await W(`/api/push/prefs`,{method:`PUT`,json:e})).json();h(t.prefs),v(t.quietHours??null),t.activityMinutes!==void 0&&C(t.activityMinutes)}catch(e){K(U(e),`err`)}},k=async()=>{c(void 0);try{c(d(await Mf(l()||void 0)))}catch(e){c({ok:!1,text:U(e)})}};return n($D,{id:`notifications`,label:`Notifications`,get children(){return[n(u,{get when(){return E()},get fallback(){return QE()},children:t=>[(()=>{var n=$E(),r=n.firstChild,i=r.nextSibling.firstChild.nextSibling.firstChild.nextSibling,a=i.nextSibling.nextSibling,o=a.nextSibling.nextSibling;return I(r,()=>t().message),I(i,(()=>{var t=V(()=>!!e().env.supported);return()=>t()?e().env.permission:`unsupported`})()),I(a,()=>e().env.worker?`registered`:`not registered`),I(o,()=>e().env.hubSubscribed?`yes`:`no`),D(e=>{var n=t().warn?`notify-status warn`:`notify-status ok`,i=t().state;return n!==e.e&&G(r,e.e=n),i!==e.t&&L(r,`data-state`,e.t=i),e},{e:void 0,t:void 0}),n})(),(()=>{var i=rD();return I(i,n(u,{get when(){return t().action===`enable`},get children(){var e=eD();return e.$$click=()=>void ie(Af,`Notifications are on for this device`),D(()=>e.disabled=r()),e}}),null),I(i,n(u,{get when(){return t().action===`disable`},get children(){var e=tD();return e.$$click=()=>void ie(jf,`Notifications are off for this device`),D(()=>e.disabled=r()),e}}),null),I(i,n(u,{get when(){return e().env.hubSubscriptions>0},get children(){var e=nD(),t=e.firstChild;t.firstChild;var r=t.nextSibling;return t.addEventListener(`change`,e=>p(e.currentTarget.value)),I(t,n(o,{each:te,children:e=>(()=>{var t=iD();return I(t,()=>e.label),D(()=>t.value=e.key),t})()}),null),r.$$click=()=>void k(),D(()=>t.value=l()),e}}),null),i})(),n(u,{get when(){return a()},children:e=>(()=>{var t=aD();return I(t,()=>e().text),D(()=>G(t,e().ok?`small ok`:`small err`)),t})()})]}),n(u,{get when(){return O()},get children(){return[GE(),(()=>{var e=KE();return I(e,()=>ne(O())),e})(),n(u,{get when(){return V(()=>!!E())()&&E().state!==`on`},get children(){return qE()}}),n(u,{get when(){return V(()=>`activity`in O()&&!O().activity)()&&!O().done},get children(){return JE()}}),n(o,{get each(){return w.filter(e=>e.kinds.some(e=>e.key in O()))},children:e=>(()=>{var t=oD(),r=t.firstChild,i=r.firstChild,a=i.nextSibling,c=r.nextSibling;return I(i,()=>e.title),I(a,()=>s(e.kinds,O())),I(c,n(o,{get each(){return e.kinds.filter(e=>e.key in O())},children:e=>(()=>{var t=cD(),r=t.firstChild.firstChild,i=r.firstChild,a=i.nextSibling,s=r.nextSibling;return I(i,()=>e.label),I(a,()=>e.description),s.addEventListener(`change`,t=>void ae({[e.key]:t.currentTarget.checked})),I(t,n(u,{get when(){return V(()=>e.key===`activity`)()&&O().activity},get children(){var e=sD(),t=e.firstChild.firstChild.nextSibling;return t.addEventListener(`change`,e=>void ae({activityMinutes:Number(e.currentTarget.value)})),I(t,n(o,{each:S,children:e=>(()=>{var t=iD();return I(t,e===1?`minute`:`${e} minutes`),D(()=>t.value=String(e)),t})()})),D(()=>t.value=String(T())),e}}),null),D(n=>{var r=`pref-${e.key}`,i=e.key;return r!==n.e&&L(t,`id`,n.e=r),i!==n.t&&L(s,`data-pref`,n.t=i),n},{e:void 0,t:void 0}),D(()=>s.checked=!!O()[e.key]),t})()})),D(()=>L(t,`data-notify-group`,e.title)),t})()}),YE(),(()=>{var e=XE(),t=e.firstChild,r=t.firstChild.firstChild.nextSibling;return r.addEventListener(`change`,e=>void ae({quietHours:e.currentTarget.checked?{start:`22:00`,end:`07:00`,timeZone:g()}:null})),I(t,n(u,{get when(){return re()},children:e=>(()=>{var t=lD(),n=t.firstChild,r=n.firstChild.nextSibling,i=n.nextSibling,a=i.firstChild.nextSibling,o=i.nextSibling,s=o.firstChild;return r.addEventListener(`change`,t=>void ae({quietHours:{...e(),start:t.currentTarget.value,timeZone:g()}})),a.addEventListener(`change`,t=>void ae({quietHours:{...e(),end:t.currentTarget.value,timeZone:g()}})),I(o,()=>e().timeZone,s),D(()=>r.value=e().start),D(()=>a.value=e().end),t})()}),null),D(()=>r.checked=!!re()),e})(),n(u,{get when(){return Sf().size},get children(){var e=ZE(),t=e.firstChild;return I(e,()=>dt(Sf().size,`session`),t),e}})]}})]}})}function pO(){return n($D,{id:`appearance`,title:`Appearance`,get children(){return[(()=>{var e=uD(),t=e.firstChild,r=t.firstChild.nextSibling,i=t.nextSibling.firstChild.nextSibling,a=i.nextSibling,s=a.nextSibling;return I(r,n(o,{each:xE,children:e=>(()=>{var t=fD(),n=t.firstChild;return t.$$click=()=>OE(e),I(t,e===`light`?`☀`:e===`dark`?`☾`:`▣`,n),I(n,()=>e[0].toUpperCase()+e.slice(1)),D(()=>L(t,`aria-checked`,EE()===e)),t})()})),i.$$input=e=>_E(Number(e.currentTarget.value)),L(i,`min`,QT),L(i,`max`,$T),L(i,`step`,eE),I(a,()=>cE(mE())),s.$$click=()=>_E(1),D(e=>{var t=cE(mE()),n=mE()===1;return t!==e.e&&L(i,`aria-valuetext`,e.e=t),n!==e.t&&(s.disabled=e.t=n),e},{e:void 0,t:void 0}),D(()=>i.value=mE()),e})(),dD()]}})}var mO={low:`Low`,normal:`Normal`,high:`High`};function hO(){let[e,t]=x(Iy.speed),[r,i]=x(Iy.sensitivity);return n($D,{id:`voice`,title:`Voice`,get children(){var a=pD(),s=a.firstChild,c=s.firstChild.nextSibling,l=c.nextSibling,u=s.nextSibling,d=u.firstChild.firstChild.nextSibling,f=u.nextSibling,p=f.firstChild.firstChild.nextSibling,m=f.nextSibling.firstChild.firstChild.nextSibling;return c.$$input=e=>{Iy.speed=Number(e.currentTarget.value),t(Iy.speed)},L(c,`min`,no),L(c,`max`,2),L(c,`step`,ro),I(l,()=>ao(e())),I(d,n(o,{each:jv,children:e=>(()=>{var t=mD();return t.$$click=()=>{Iy.sensitivity=e,i(e)},I(t,()=>mO[e]),D(n=>{var i=r()===e,a=r()===e;return i!==n.e&&L(t,`aria-checked`,n.e=i),a!==n.t&&L(t,`aria-pressed`,n.t=a),n},{e:void 0,t:void 0}),t})()})),p.addEventListener(`change`,e=>Iy.cues=e.currentTarget.checked),m.addEventListener(`change`,e=>Iy.background=e.currentTarget.checked),D(()=>L(c,`aria-valuetext`,ao(e()))),D(()=>c.value=e()),D(()=>p.checked=Iy.cues),D(()=>m.checked=Iy.background),a}})}async function gO(e,t){try{await W(`/api/enrollments/${B(e.userCode)}/${t}`,{method:`POST`,json:{}}),K(t===`approve`?`${e.machineName} approved; it belongs to you`:`Request denied`)}catch(e){K(U(e),`err`)}vd()}function _O(){return n(u,{get when(){return Zl().length},get children(){return[hD(),(()=>{var e=gD();return I(e,n(o,{get each(){return Zl()},children:e=>(()=>{var t=_D(),n=t.firstChild,r=n.firstChild,i=r.nextSibling,a=i.firstChild.nextSibling;a.nextSibling;var o=n.nextSibling,s=o.nextSibling;return I(r,()=>e.machineName),I(i,()=>e.userCode,a),I(i,()=>Be(e.created,F()),null),o.$$click=()=>void gO(e,`approve`),s.$$click=()=>void gO(e,`deny`),t})()})),e})()]}})}function vO(){let e=async e=>{if(await Ce(`Revoke ${e.name}? Its OpenCode processes disconnect and it must be connected again.`,`Revoke`,{danger:!0}))try{await W(`/api/machines/${B(e.id)}`,{method:`DELETE`}),K(`${e.name} revoked`)}catch(e){K(U(e),`err`)}};return n($D,{id:`machines`,title:`Machines`,get children(){return[n(_O,{}),n(u,{get when(){return(Y.machines??[]).length},get fallback(){return vD()},get children(){var t=gD();return I(t,n(o,{get each(){return Y.machines},children:t=>(()=>{var n=yD(),r=n.firstChild,i=r.firstChild,a=i.firstChild;a.nextSibling;var o=i.nextSibling,s=r.nextSibling;return I(i,()=>t.name,null),I(o,(()=>{var e=V(()=>!!t.online);return()=>e()?`online · ${dt(t.processes.length,`OpenCode process`)}`:`offline · seen ${Be(t.lastSeen,F())}`})()),s.$$click=()=>void e(t),D(e=>{var n=`online-dot${t.online?` on`:``}`,r=`Revoke machine ${t.name}`;return n!==e.e&&G(a,e.e=n),r!==e.t&&L(s,`aria-label`,e.t=r),e},{e:void 0,t:void 0}),n})()})),t}})]}})}function yO(){let[e,{refetch:t,mutate:r}]=f(()=>z(`/api/devices`).then(e=>e.devices)),[i,a]=x(!1),s=async e=>{if(e.current)return void uO();if(await Ce(`Revoke ${e.name}?`,`Revoke`,{danger:!0})){try{await W(`/api/devices/${B(e.id)}`,{method:`DELETE`}),K(`${e.name} revoked`)}catch(e){K(U(e),`err`)}t()}};return n($D,{id:`devices`,title:`Devices`,get children(){return[(()=>{var e=bD(),t=e.firstChild.nextSibling;return t.$$click=()=>a(!0),e})(),n(u,{get when(){return i()},get children(){return n(xO,{get known(){return new Set((e()??[]).map(e=>e.id))},onLinked:e=>r(e),onClose:()=>{a(!1),t()}})}}),n(u,{get when(){return e()},get fallback(){return(()=>{var t=xD();return I(t,(()=>{var t=V(()=>!!e.error);return()=>t()?U(e.error):`Loading…`})()),t})()},get children(){var t=gD();return I(t,n(o,{get each(){return e()},children:e=>(()=>{var t=CD(),r=t.firstChild,i=r.firstChild,a=i.nextSibling;a.firstChild;var o=r.nextSibling;return I(i,()=>e.name,null),I(i,n(u,{get when(){return e.current},get children(){return SD()}}),null),I(a,()=>Be(e.lastSeen,F()),null),o.$$click=()=>void s(e),I(o,()=>e.current?`Sign out`:`Revoke`),t})()})),t}})]}})}var bO=2e3;function xO(e){let[t,r]=x(),[i,a]=x(``),[o,s]=x(Date.now()),c=async()=>{a(``);try{let e=await W(`/api/devices/link`,{method:`POST`,json:{}}),t=await e.json(),n=Date.now();s(n),r({...t,expiresAt:IT(t.expiresAt,e.headers.get(`date`),n)})}catch(e){a(U(e))}},l=()=>(t()?.expiresAt??0)<=o(),d=()=>{let e=t();return e?XT(e.url,{ecc:`M`}):void 0},f=setInterval(()=>s(Date.now()),1e3),p=!1,m=setInterval(async()=>{if(!(p||!t()||l())){p=!0;try{let t=(await z(`/api/devices`)).devices,n=FT(e.known,t);n&&(e.onLinked(t),K(`${n.name} linked`),e.onClose())}catch{}finally{p=!1}}},bO);return j(()=>{clearInterval(f),clearInterval(m)}),c(),n(ze,{open:!0,title:`Add the Hub app`,get onClose(){return e.onClose},class:`add-app`,get children(){return n(u,{get when(){return t()},get fallback(){return(()=>{var e=xD();return I(e,()=>i()||`Creating a link code…`),e})()},children:e=>(()=>{var t=DD(),r=t.firstChild,i=r.firstChild.nextSibling.nextSibling.nextSibling,a=r.nextSibling;return I(i,()=>e().hub),I(t,n(u,{get when(){return!l()},get fallback(){return(()=>{var e=OD(),t=e.firstChild.nextSibling;return t.$$click=()=>void c(),e})()},get children(){return[(()=>{var e=wD(),t=e.firstChild.nextSibling;return D(n=>{var r=`0 0 ${d().size+8} ${d().size+8}`,i=ZT(d(),4);return r!==n.e&&L(e,`viewBox`,n.e=r),i!==n.t&&L(t,`d`,n.t=i),n},{e:void 0,t:void 0}),e})(),(()=>{var t=TD(),n=t.firstChild.nextSibling;return I(n,()=>PT(e().expiresAt,o())),t})(),(()=>{var t=ED(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling;return I(n,()=>e().url),r.$$click=()=>void navigator.clipboard?.writeText(e().url).then(()=>K(`Link copied`),()=>K(`Copy failed`,`err`)),D(()=>L(i,`href`,e().url)),t})()]}}),a),t})()})}})}function SO(){let[e,t]=x(),r=async()=>{try{t(new Set((await z(`/api/devices`)).devices.map(e=>e.id)))}catch(e){K(U(e),`err`)}};return n($D,{id:`add-app`,title:`Add the Hub app`,get children(){return[(()=>{var e=kD(),t=e.firstChild.nextSibling;return t.$$click=()=>void r(),e})(),n(u,{get when(){return e()},children:e=>n(xO,{get known(){return e()},onLinked:()=>{},onClose:()=>t(void 0)})})]}})}var CO=`/api/agent/team-settings`;function wO(){let[t,{mutate:r,refetch:i}]=f(()=>z(CO).then(e=>e.settings)),[a,o]=x(!1),s=async n=>{let a=t();if(!a)return;let s=n.checked;o(!0);try{let e=await(await W(CO,{method:`PUT`,json:{teamIsolation:s,expectedRevision:a.revision}})).json();r(e.settings),K(s?`Team isolation is on`:`Team isolation is off`)}catch(t){n.checked=!s,t instanceof e&&t.status===409?(K(`Team settings changed elsewhere. Showing the current setting; try again.`,`err`),i()):K(U(t),`err`)}finally{o(!1)}};return n($D,{id:`teams`,label:`Teams`,get children(){return[AD(),n(u,{get when(){return t()},get fallback(){return(()=>{var e=xD();return I(e,(()=>{var e=V(()=>!!t.error);return()=>e()?`Could not load: ${U(t.error)}`:`Loading…`})()),e})()},children:e=>(()=>{var t=jD(),n=t.firstChild.firstChild.firstChild.nextSibling;return n.addEventListener(`change`,e=>void s(e.currentTarget)),D(()=>n.disabled=a()),D(()=>n.checked=e().teamIsolation),t})()})]}})}var TO=(e,t)=>Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[],EO=e=>e.id===`local`?`Hub owner (pairing)`:e.name||e.email||e.id;function DO(){let e=()=>yt(X()),[t,r]=x(e()[0]?.[0]??`machines`),[i,a]=x(``);C(()=>{let t=ie().hash,n=t===`#admin-machines`?`machines`:t===`#admin-audit`?`audit`:void 0;n&&e().some(([e])=>e===n)&&r(n)});let s=async(e,t)=>{try{return await e(),a(``),K(t),!0}catch(e){return a(Mt(e)),K(i(),`err`),!1}};return n($D,{id:`admin`,label:`Admin`,get children(){return[(()=>{var i=MD();return I(i,n(o,{get each(){return e()},children:([e,i])=>(()=>{var o=RD();return o.$$click=()=>(r(e),a(``)),I(o,i,null),I(o,n(u,{get when(){return e===`approvals`&&Zl().length},get children(){var e=LD();return I(e,()=>Zl().length),e}}),null),D(()=>L(o,`aria-pressed`,t()===e)),o})()})),i})(),n(u,{get when(){return i()},get children(){var e=ND();return I(e,i),e}}),n(u,{get when(){return t()===`users`},get children(){return n(OO,{change:s})}}),n(u,{get when(){return t()===`machines`},get children(){var e=PD();return I(e,n(kO,{change:s})),e}}),n(u,{get when(){return t()===`approvals`},get children(){return[FD(),n(u,{get when(){return Zl().length},get fallback(){return zD()},get children(){return n(_O,{})}})]}}),n(u,{get when(){return t()===`audit`},get children(){var e=ID();return I(e,n(AO,{})),e}})]}})}function OO(e){let[t,{refetch:r}]=f(()=>z(`/api/admin/users`).then(e=>TO(e,`users`))),[i,a]=x(``),[s,c]=x(`all`),[l,d]=x(`role`),p=async(t,n)=>{await Ce(n.confirm,n.label,{danger:!!n.danger})&&(await e.change(()=>W(`/api/admin/users/${B(t.id)}`,{method:`PUT`,json:n.change}),`${EO(t)}: ${n.label.toLowerCase()} done`)&&t.id===X()?.user?.id&&(Kl(void 0),await Fu().catch(()=>!1)),r())};return(()=>{var e=BD(),r=e.firstChild.firstChild,f=r.nextSibling,m=f.nextSibling;return r.$$input=e=>a(e.currentTarget.value),f.addEventListener(`change`,e=>c(e.currentTarget.value)),I(f,n(o,{each:mt,children:([e,t])=>(()=>{var n=iD();return n.value=e,I(n,t),n})()})),m.addEventListener(`change`,e=>d(e.currentTarget.value)),I(m,n(o,{each:pt,children:([e,t])=>(()=>{var n=iD();return n.value=e,I(n,t),n})()})),I(e,n(u,{get when(){return t()},get fallback(){return(()=>{var e=VD();return I(e,(()=>{var e=V(()=>!!t.error);return()=>e()?`Could not load: ${Mt(t.error)}`:`Loading…`})()),e})()},get children(){var e=gD();return I(e,n(o,{get each(){return At(t(),{query:i(),filter:s(),sort:l()})},get fallback(){return HD()},children:e=>(()=>{var r=KD(),i=r.firstChild,a=i.firstChild,s=a.nextSibling,c=s.firstChild,l=c.nextSibling;return l.nextSibling,I(a,()=>EO(e),null),I(a,n(u,{get when(){return e.role===`admin`},get children(){return UD()}}),null),I(a,n(u,{get when(){return e.disabled},get children(){return WD()}}),null),I(a,n(u,{get when(){return e.id===X()?.user?.id},get children(){return GD()}}),null),I(i,n(u,{get when(){return V(()=>!!e.name)()&&e.email},get children(){var t=UE();return I(t,()=>e.email),t}}),s),I(s,()=>dt(e.machines??0,`machine`),c),I(s,()=>dt(e.devices??0,`device`),l),I(s,()=>Be(e.lastSeen,F())||`never`,null),I(r,n(o,{get each(){return jt(e,t(),X()?.user?.id)},children:t=>(()=>{var n=qD();return n.$$click=()=>void p(e,t),I(n,()=>t.label),D(()=>G(n,`btn small${t.danger?` danger`:``}`)),n})()}),null),D(()=>G(r,e.disabled?`disabled`:``)),r})()})),e}}),null),D(()=>r.value=i()),D(()=>f.value=s()),D(()=>m.value=l()),e})()}function kO(e){let[t,{refetch:r}]=f(()=>z(`/api/admin/machines`).then(e=>TO(e,`machines`)));return n(u,{get when(){return t()},get fallback(){return(()=>{var e=VD();return I(e,(()=>{var e=V(()=>!!t.error);return()=>e()?`Could not load: ${Mt(t.error)}`:`Loading…`})()),e})()},get children(){return n(u,{get when(){return t().length},get fallback(){return JD()},get children(){var i=gD();return I(i,n(o,{get each(){return t()},children:t=>{let n=t.ownerEmail??(t.ownerID===`local`?`hub owner`:t.ownerID)??`unknown`;return(()=>{var i=YD(),a=i.firstChild,o=a.firstChild,s=o.firstChild;s.nextSibling;var c=o.nextSibling,l=c.firstChild,u=a.nextSibling;return I(o,()=>t.name,null),I(c,n,l),I(c,()=>t.ownerID===X()?.user?.id?` (you)`:``,l),I(c,(()=>{var e=V(()=>!!t.online);return()=>e()?`online`:`offline · seen ${Be(t.lastSeen,F())}`})(),null),u.$$click=async()=>{await Ce(`Revoke ${t.name} (${n})? Its OpenCode processes disconnect and it must be connected again.`,`Revoke`,{danger:!0})&&(await e.change(()=>W(`/api/admin/machines/${B(t.id)}`,{method:`DELETE`}),`${t.name} revoked`),r())},D(()=>G(s,`online-dot${t.online?` on`:``}`)),i})()}})),i}})}})}function AO(){let[e]=f(async()=>{let[e,t,n]=await Promise.all([z(`/api/admin/audit`),z(`/api/admin/users`).then(e=>TO(e,`users`),()=>[]),z(`/api/admin/machines`).then(e=>TO(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 Ot(TO(e,`audit`).length?TO(e,`audit`):TO(e,`entries`),r)});return n(u,{get when(){return e()},get fallback(){return(()=>{var t=VD();return I(t,(()=>{var t=V(()=>!!e.error);return()=>t()?`Could not load: ${Mt(e.error)}`:`Loading…`})()),t})()},get children(){return n(u,{get when(){return e().length},get fallback(){return ZD()},get children(){var t=XD();return I(t,n(o,{get each(){return e()},children:e=>(()=>{var t=QD(),n=t.firstChild,r=n.firstChild,i=r.nextSibling,a=n.nextSibling;return I(r,()=>e.action),I(i,()=>e.actor,null),I(i,(()=>{var t=V(()=>!!e.target);return()=>t()?` → ${e.target}`:``})(),null),I(i,(()=>{var t=V(()=>!!e.detail);return()=>t()?` · ${e.detail}`:``})(),null),I(a,()=>Be(e.at,F())),D(t=>{var n=new Date(e.at).toISOString(),r=new Date(e.at).toLocaleString();return n!==t.e&&L(a,`datetime`,t.e=n),r!==t.t&&L(a,`title`,t.t=r),t},{e:void 0,t:void 0}),t})()})),t}})}})}P([`input`,`keydown`,`click`]);var jO=q(`<a href=/settings/voice#recording title="This conversation is recorded on this hub (Settings → Voice → Recording)"><span class=recording-dot aria-hidden=true>`),MO=q(`<span class="recording-note small"data-recording-note>`),NO=q(`<span class=sr-only role=status aria-live=polite data-recording-status>`);function PO(){let[e,t]=x(El.get());return j(El.subscribe(()=>t(El.get()))),e}function FO(e){let t=PO(),r=t=>e.sessionID===void 0||t.sessionID===void 0||t.sessionID===e.sessionID,i=()=>t().on&&r(t()),a=i(),[o,s]=x(``);return j(El.subscribe(()=>{let e=El.get(),t=e.on&&r(e);t!==a&&(a=t,s(t?`Recording on`:`Recording off`))})),[n(u,{get when(){return i()},get children(){var e=jO();return e.firstChild,I(e,()=>Dl(t()),null),D(n=>{var r=`recording-indicator${t().audio?``:` no-audio`}`,i=t().audio?`on`:`no-audio`,a=`${Dl(t())}: this conversation is recorded on the hub. Open the recording settings`;return r!==n.e&&G(e,n.e=r),i!==n.t&&L(e,`data-recording-indicator`,n.t=i),a!==n.a&&L(e,`aria-label`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),e}}),n(u,{get when(){return V(()=>!(i()||!t().note))()&&r(t())},get children(){var e=MO();return I(e,()=>t().note),e}}),n(u,{get when(){return e.announce},get children(){var e=NO();return I(e,o),e}})]}var IO=q(`<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 LO(){let e=()=>fb().sessionID??``;return(()=>{var t=IO(),r=t.firstChild,i=r.firstChild.nextSibling,a=r.nextSibling;return I(t,n(H,{name:`wave`}),r),I(i,pb),I(t,n(FO,{announce:!0,get sessionID(){return e()}}),a),a.$$click=()=>void nb.end(),D(n=>{var i=`voice-pill ${fb().voice}`,a=`Voice mode is on in ${pb()}`,o=k(e());return i!==n.e&&G(t,n.e=i),a!==n.t&&L(t,`aria-label`,n.t=a),o!==n.a&&L(r,`href`,n.a=o),n},{e:void 0,t:void 0,a:void 0}),t})()}P([`click`]);var RO=`/api/agent/workspaces`,zO=50,BO=4e3,VO=t=>t instanceof e?{status:t.status,...t.code?{code:t.code}:{},message:t.message,...t.details?{details:t.details}:{}}:{status:0,message:t instanceof be||t instanceof Error?t.message:String(t)},HO=e=>Dm(VO(e));function UO(){let[t,n]=x(`loading`),[r,i]=x(),[a,o]=x([]),[s,c]=mi({}),[l,u]=x(),[d,f]=x(new Set),p=new Map,m=new Map,h=!1;async function g(){try{let e=pm(await z(`${RO}?state=active&limit=${zO}`));o(e.items),i(void 0),n(`ready`)}catch(t){t instanceof e&&(t.status===404||t.code===`unsupported`)?n(`unavailable`):t instanceof e&&t.status===403?n(`forbidden`):(i(HO(t)),n(`error`))}}async function _(e){p.set(e,Date.now()),c(e,e=>({...e??{},loading:!0}));try{let t=fm(await z(`${RO}/${B(e)}/board`));if(!t)throw Error(`The hub sent a board this console can't read.`);return c(e,e=>({...e,board:t,loading:!1,error:void 0})),t}catch(t){c(e,e=>({...e,loading:!1,error:HO(t)}));return}}async function v(){try{u(Zn(await z(`/api/agent/grants`)))}catch{u(`error`)}}function y(e){if(m.has(e))return;let t=Math.max(0,(p.get(e)??0)+BO-Date.now());m.set(e,setTimeout(()=>{m.delete(e),d().has(e)&&document.visibilityState!==`hidden`&&_(e)},t))}function b(){h||(h=!0,g(),Tu(e=>{if(e.type===`resync`&&g(),e.type===`catalog`||e.type===`resync`)for(let e of d())y(e)}))}function S(e){let t=new Set(d());t.has(e)?t.delete(e):(t.add(e),_(e),l()===void 0&&v()),f(t)}let C=(e,t)=>c(e,e=>({...e??{loading:!1},notice:t}));async function w(e,t){await W(`${RO}/${B(e)}/supervision`,{method:`PUT`,json:t})}async function T(e,t,n){let r=s[e]?.board;if(!r||s[e]?.saving)return;let i=gm(r,t);if(i)i!==`unchanged`&&C(e,{text:Tm(i),kind:`warn`});else{c(e,e=>({...e,saving:!0,notice:{text:`Saving: ${n}…`,kind:``}}));try{await E(e,t,Cm(t,r.revision),n)}finally{c(e,e=>({...e,saving:!1}))}}}async function E(t,n,r,i){try{await w(t,r),await _(t),C(t,{text:`Done: ${i}.`,kind:``});return}catch(n){if(!(n instanceof e&&n.status===409&&n.code===`conflict`)){C(t,{text:HO(n),kind:`err`}),_(t);return}}let a=await _(t);if(!a)return C(t,{text:`The workspace changed elsewhere and could not be reloaded. Your change is kept: ${i}.`,kind:`warn`,pending:n});let o=Em(n,a);if(o.kind===`done`)return C(t,{text:`Already done elsewhere: ${i}.`,kind:``});if(o.kind===`dropped`)return C(t,{text:o.reason,kind:`warn`});try{await w(t,o.body),await _(t),C(t,{text:`The workspace changed elsewhere; re-applied your change: ${i}.`,kind:``})}catch(r){_(t),r instanceof e&&r.status===409?C(t,{text:`The workspace keeps changing elsewhere. Your change is kept: ${i}.`,kind:`warn`,pending:n}):C(t,{text:HO(r),kind:`err`})}}return{availability:t,listError:r,workspaces:a,boards:s,grants:l,expanded:d,start:b,loadList:g,loadBoard:_,toggle:S,move:T,notify:C}}var WO=_(UO),GO=`hub.sidebar.sections.collapsed`;function KO(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 qO(e,t){let n=KO(e);n.has(t)?n.delete(t):n.add(t);try{e.setItem(GO,JSON.stringify([...n]))}catch{}return n}var JO=e=>e!==`results`;function YO(e,t,n){if(t&&JO(e)){if(e===`needs`)return{text:String(t),label:`${dt(t,`session`)} ${t===1?`needs`:`need`} you`};if(n)return{text:String(t),label:dt(t,e===`workspaces`?`workspace`:`session`)}}}var XO=q(`<button type=button class=side-section-toggle><span class=side-section-title>`),ZO=q(`<div class=side-section-head>`),QO=q(`<span class=side-section-title>`),$O=q(`<span aria-hidden=true data-section-count>`),[ek,tk]=x(KO(localStorage)),nk=(e,t)=>JO(t)&&ek().has(e),rk=e=>`side-sec-${e.replace(/[^A-Za-z0-9_-]/g,`-`)}`;function ik(e){let t=()=>nk(e.id,e.kind),r=()=>YO(e.kind,e.count,t());return(()=>{var i=ZO();return I(i,n(u,{get when(){return JO(e.kind)},get fallback(){return(()=>{var t=QO();return I(t,()=>e.title),t})()},get children(){var i=XO(),a=i.firstChild;return i.$$click=()=>tk(qO(localStorage,e.id)),I(i,n(H,{get name(){return t()?`chevron`:`down`},class:`side-section-caret`}),a),I(a,()=>e.title),I(i,n(u,{get when(){return r()},children:t=>(()=>{var n=$O();return I(n,()=>t().text),D(()=>G(n,`side-count${e.kind===`needs`?` needs`:``}`)),n})()}),null),D(n=>{var a=!t(),o=rk(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&&L(i,`aria-expanded`,n.e=a),o!==n.t&&L(i,`aria-controls`,n.t=o),s!==n.a&&L(i,`data-section-toggle`,n.a=s),c!==n.o&&L(i,`aria-label`,n.o=c),l!==n.i&&L(i,`title`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),i}}),null),I(i,()=>e.children,null),i})()}P([`click`]);var ak=q(`<p class=side-empty>Workspaces are not available to this device.`),ok=q(`<p class=side-empty role=alert>Could not load workspaces: <!> <button type=button class=link-btn>Retry`),sk=q(`<ul class=ws-list>`),ck=q(`<section aria-label=Workspaces data-section=workspaces>`),lk=q(`<p class=ws-goal><span class=sr-only>Goal: `),uk=q(`<div class=ws-panel>`),dk=q(`<li><button type=button class=ws-head><span class=ws-title>`),fk=q(`<p class=ws-notice role=status aria-live=polite>`),pk=q(`<p class=side-empty role=alert>Could not load the board: <!> <button type=button class=link-btn>Retry`),mk=q(`<button type=button class=link-btn>Retry`),hk=q(`<p class=side-empty>Loading…`),gk=q(`<p class=side-empty>No members yet.`),_k=q(`<ul role=tree>`),vk=q(`<div>Drop here: no supervisor`),yk=q(`<p class=ws-keys>Drag to change supervision, or Alt+arrows. Supervision grants nothing.`),bk=q(`<p class=ws-keys>`),xk=q(`<span class="ws-rel ws-spawned"title="Native parent session (unchanged by supervision)">spawned by <a tabindex=-1>`),Sk=q(`<span class="ws-rel ws-supervised"title="Workspace supervision link">supervised by `),Ck=q(`<ul class=ws-assignments>`),wk=q(`<li role=treeitem><div class=ws-row><a class=ws-member tabindex=-1></a></div><p class=ws-meta>`),Tk=q(`<span>`),Ek=q(`<span class=ws-assignment-stale> · stale`),Dk=q(`<li><span class=ws-assignment-title></span> <span class=ws-assignment-status>`),Ok=q(`<ul>`),kk=q(`<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.`),Ak=q(`<p>Could not load your grants.`),jk=q(`<p>Loading…`),Mk=q(`<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.`),Nk=q(`<li> · <!> · <!> <span class=muted>(grant <!>)`),Pk=new Set([`idle`,`working`,`blocked`,`error`]),Fk={open:`open`,in_progress:`in progress`,blocked:`blocked`},Ik={ArrowRight:`indent`,ArrowLeft:`outdent`,ArrowUp:`up`,ArrowDown:`down`};function Lk(e){let t=WO;ue(()=>t.start());let r=()=>{let e=t.availability();return e===`forbidden`||e===`error`||e===`ready`&&t.workspaces().length>0};return n(u,{get when(){return r()},get children(){var r=ck();return I(r,n(ik,{id:`workspaces`,kind:`workspaces`,title:`Workspaces`,get count(){return t.workspaces().length}}),null),I(r,n(u,{get when(){return t.availability()===`forbidden`},get children(){return ak()}}),null),I(r,n(u,{get when(){return t.availability()===`error`},get children(){var e=ok(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling;return I(e,()=>t.listError(),n),r.$$click=()=>void t.loadList(),e}}),null),I(r,n(u,{get when(){return!nk(`workspaces`,`workspaces`)},get children(){var r=sk();return I(r,n(o,{get each(){return t.workspaces()},children:t=>n(Rk,{ws:t,get onPick(){return e.onPick}})})),D(()=>L(r,`id`,rk(`workspaces`))),r}}),null),D(()=>G(r,`side-section ws-section${nk(`workspaces`,`workspaces`)?` collapsed`:``}`)),r}})}function Rk(e){let t=WO,r=()=>t.expanded().has(e.ws.id),i=`ws-panel-${e.ws.id}`;return(()=>{var a=dk(),o=a.firstChild,s=o.firstChild;return o.$$click=()=>t.toggle(e.ws.id),L(o,`aria-controls`,i),I(o,n(H,{get name(){return r()?`down`:`chevron`}}),s),I(s,()=>e.ws.title),I(a,n(u,{get when(){return e.ws.goal},get children(){var t=lk();return t.firstChild,I(t,()=>e.ws.goal,null),D(()=>L(t,`title`,e.ws.goal)),t}}),null),I(a,n(u,{get when(){return r()},get children(){var t=uk();return L(t,`id`,i),I(t,n(Vk,{get ws(){return e.ws},get onPick(){return e.onPick}})),t}}),null),D(t=>{var n=`ws-item${r()?` open`:``}`,i=e.ws.id,s=r();return n!==t.e&&G(a,t.e=n),i!==t.t&&L(a,`data-workspace`,t.t=i),s!==t.a&&L(o,`aria-expanded`,t.a=s),t},{e:void 0,t:void 0,a:void 0}),a})()}var zk=(e,t)=>{let n=e.members.find(e=>e.memberID===t);if(!n)return`a member`;let r=km(Y.machines,n.sessionID);return r.found?r.title:n.session?.name??n.sessionID};function Bk(e,t,n){let r=zk(e,t.memberID);return t.supervisorMemberID===null?`${r} has no supervisor`:n===`reorder`?`${r} reordered`:`${r} supervised by ${zk(e,t.supervisorMemberID)}`}function Vk(e){let t=WO,r=()=>e.ws.id,i=()=>t.boards[r()],s=()=>i()?.board,c=T(()=>s()?hm(s()):void 0),[l,d]=x(),[f,p]=x(),[m,h]=x(),g,_,v=()=>{let e=c();if(e?.flat.length)return e.flat.some(e=>e.member.memberID===l())?l():e.flat[0].member.memberID},y=e=>{d(e),g?.querySelector(`[data-member="${CSS.escape(e)}"]`)?.focus()};C(()=>{if(c(),_){let e=_;queueMicrotask(()=>{g?.querySelector(`[data-member="${CSS.escape(e)}"]`)&&(_=void 0,y(e))})}});let b=(e,n,i=!1)=>{let a=s();e&&a&&(i&&(_=e.memberID),t.move(r(),e,Bk(a,e,n)))},S=(n,i,o)=>{let s=o.flat.indexOf(i);if(n.altKey&&Ik[n.key]){n.preventDefault();let e=Ik[n.key],a=Sm(o,i.member.memberID,e);return a?b(a,e===`up`||e===`down`?`reorder`:`supervise`,!0):t.notify(r(),{text:`No move that way.`,kind:`warn`})}if(n.altKey||n.ctrlKey||n.metaKey)return;let c=n.key===`ArrowDown`?o.flat[s+1]:n.key===`ArrowUp`?o.flat[s-1]:n.key===`Home`?o.flat[0]:n.key===`End`?o.flat[o.flat.length-1]:void 0;c?(n.preventDefault(),y(c.member.memberID)):n.key===`Enter`&&n.target===n.currentTarget&&(n.preventDefault(),e.onPick?.(),a(k(i.member.sessionID)))},w=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`},E=(e,t)=>{let n=s(),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=Sm(t,r,e);s&&!gm(n,s)&&i.push({label:a,hint:o,run:()=>b(s,e===`up`||e===`down`?`reorder`:`supervise`,!0)})}let a=t.flat.filter(e=>e.member.memberID!==r&&!gm(n,xm(t,r,{memberID:e.member.memberID,position:`inside`})));if(a.length){i.push({section:`Supervised by`});for(let e of a)i.push({label:zk(n,e.member.memberID),run:()=>b(xm(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=fk();return I(e,()=>i()?.notice?.text??``,null),I(e,n(u,{get when(){return i()?.notice?.pending},children:e=>(()=>{var t=mk();return t.$$click=()=>b(e(),`supervise`),t})()}),null),e})(),n(u,{get when(){return i()?.error},get children(){var e=pk(),n=e.firstChild.nextSibling,a=n.nextSibling.nextSibling;return I(e,()=>i().error,n),a.$$click=()=>void t.loadBoard(r()),e}}),n(u,{get when(){return c()},get fallback(){return n(u,{get when(){return!i()?.error},get children(){return hk()}})},children:a=>[n(u,{get when(){return!a().flat.length},get children(){return gk()}}),(()=>{var c=_k(),l=g;return typeof l==`function`?ge(l,c):g=c,I(c,n(o,{get each(){return a().flat},children:i=>{let c=()=>km(Y.machines,i.member.sessionID),l=()=>zk(s(),i.member.memberID),g=()=>i.supervisorMemberID?a().flat.find(e=>e.member.memberID===i.supervisorMemberID)?.children??[]:a().roots,_=()=>Am(i,s(),Y.machines),y=()=>Pk.has(i.member.session?.state??``)?i.member.session.state:`idle`,x=()=>s().workspace.state===`active`&&!t.boards[r()]?.saving;return(()=>{var t=wk(),r=t.firstChild,s=r.firstChild,C=r.nextSibling;return t.addEventListener(`drop`,e=>{let t=f();if(!t)return;e.preventDefault(),e.stopPropagation();let n=w(e);p(void 0),h(void 0),b(xm(a(),t,{memberID:i.member.memberID,position:n}),n===`inside`?`supervise`:`reorder`)}),t.addEventListener(`dragleave`,e=>{e.currentTarget.contains(e.relatedTarget)||h(void 0)}),t.addEventListener(`dragover`,e=>{let t=f();t&&t!==i.member.memberID&&(e.preventDefault(),e.stopPropagation(),h(`${i.member.memberID}:${w(e)}`))}),t.addEventListener(`dragend`,()=>{qp(),p(void 0),h(void 0)}),t.addEventListener(`dragstart`,e=>{Kp(e,{target:{sessionID:i.member.sessionID},label:l()}),e.dataTransfer?.setData(`text/plain`,i.member.memberID),e.dataTransfer&&(e.dataTransfer.effectAllowed=`move`),p(i.member.memberID)}),t.$$keydown=e=>S(e,i,a()),t.addEventListener(`focus`,e=>e.target===e.currentTarget&&d(i.member.memberID)),I(r,n(_e,{get state(){return y()}}),s),s.$$click=()=>e.onPick?.(),L(s,`draggable`,!1),I(s,l),I(r,n(me,{get label(){return`Move ${l()}`},class:`icon-btn small row-more`,items:()=>E(i,a())}),null),I(C,n(o,{get each(){return Mm(i.member,c())},children:e=>(()=>{var t=Tk();return I(t,()=>e.label),D(n=>{var r=`ws-badge ${e.kind}`,i=e.title;return r!==n.e&&G(t,n.e=r),i!==n.t&&L(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),null),I(C,n(u,{get when(){return _().spawnedBy},get children(){var e=xk(),t=e.firstChild.nextSibling;return I(t,()=>_().spawnedBy.title),D(()=>L(t,`href`,k(_().spawnedBy.sessionID))),e}}),null),I(C,n(u,{get when(){return _().supervisedBy},get children(){var e=Sk();return e.firstChild,I(e,()=>_().supervisedBy.title,null),e}}),null),I(t,n(u,{get when(){return i.assignments.length},get children(){var e=Ck();return I(e,n(o,{get each(){return i.assignments},children:e=>(()=>{var t=Dk(),r=t.firstChild,i=r.nextSibling.nextSibling;return I(r,()=>e.title),I(i,()=>Fk[e.status]??e.status),I(t,n(u,{get when(){return e.stale?.length},get children(){var t=Ek();return D(()=>L(t,`title`,e.stale.join(`, `))),t}}),null),D(()=>G(t,`ws-assignment ${e.status}`)),t})()})),D(()=>L(e,`aria-label`,`Assignments of ${l()}`)),e}}),null),I(t,n(u,{get when(){return _().supervisedBy},children:e=>n(Hk,{get supervisorSessionID(){return e().sessionID},get supervisorTitle(){return e().title},get memberDirectory(){return c().directory}})}),null),D(e=>{var n=i.depth+1,r=g().length,a=g().indexOf(i)+1,o=v()===i.member.memberID,c=`${l()}${i.member.master?`, master`:``}${_().supervisedBy?`, supervised by ${_().supervisedBy.title}`:``}`,u=v()===i.member.memberID?0:-1,d=i.member.memberID,p=`ws-node${i.member.presence===`online`?``:` away`}${f()===i.member.memberID?` dragged`:``}${m()?.startsWith(`${i.member.memberID}:`)?` drop-${m().split(`:`)[1]}`:``}`,h=String(i.depth),y=x()&&!i.member.master,b=k(i.member.sessionID);return n!==e.e&&L(t,`aria-level`,e.e=n),r!==e.t&&L(t,`aria-setsize`,e.t=r),a!==e.a&&L(t,`aria-posinset`,e.a=a),o!==e.o&&L(t,`aria-selected`,e.o=o),c!==e.i&&L(t,`aria-label`,e.i=c),u!==e.n&&L(t,`tabindex`,e.n=u),d!==e.s&&L(t,`data-member`,e.s=d),p!==e.h&&G(t,e.h=p),h!==e.r&&Se(t,`--ws-depth`,e.r=h),y!==e.d&&L(t,`draggable`,e.d=y),b!==e.l&&L(s,`href`,e.l=b),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}),t})()}})),D(t=>{var n=`ws-tree${f()?` dragging`:``}`,a=`Supervision in ${e.ws.title}`,o=`ws-keys-${r()}`,s=i()?.saving?`true`:void 0;return n!==t.e&&G(c,t.e=n),a!==t.t&&L(c,`aria-label`,t.t=a),o!==t.a&&L(c,`aria-describedby`,t.a=o),s!==t.o&&L(c,`aria-busy`,t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),c})(),n(u,{get when(){return f()},get children(){var e=vk();return e.addEventListener(`drop`,e=>{e.preventDefault();let t=f();p(void 0),h(void 0),t&&b(xm(a(),t,{root:!0}),`supervise`)}),e.addEventListener(`dragleave`,()=>h(void 0)),e.addEventListener(`dragover`,e=>{e.preventDefault(),h(`root`)}),D(()=>G(e,`ws-root-drop${m()===`root`?` over`:``}`)),e}}),(()=>{var e=yk();return D(()=>L(e,`id`,`ws-keys-${r()}`)),e})(),n(u,{get when(){return a().staleLinks||s().membersTruncated||s().linksTruncated},get children(){var e=bk();return I(e,n(u,{get when(){return a().staleLinks},get children(){return[V(()=>a().staleLinks),` link(s) to departed members not shown. `]}}),null),I(e,n(u,{get when(){return s().membersTruncated||s().linksTruncated},children:`Some members are not shown (limit).`}),null),e}})]})]}function Hk(e){let t=WO,r=()=>{let n=t.grants();return Array.isArray(n)?Fm(n,e.supervisorSessionID,e.memberDirectory,Date.now()):n};return(()=>{var t=kk(),i=t.firstChild.nextSibling;return I(t,n(u,{get when(){return r()!==`error`},get fallback(){return Ak()},get children(){return n(u,{get when(){return Array.isArray(r())},get fallback(){return jk()},get children(){return n(u,{get when(){return r().length},get fallback(){return(()=>{var t=Mk(),n=t.firstChild;return I(t,()=>e.supervisorTitle,n),t})()},get children(){var e=Ok();return I(e,n(o,{get each(){return r()},children:e=>(()=>{var t=Nk(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling.nextSibling,a=i.nextSibling.nextSibling,o=a.firstChild.nextSibling;return o.nextSibling,I(t,()=>e.verbs.join(`, `),n),I(t,(()=>{var t=V(()=>e.covers===void 0);return()=>t()?`folder unknown`:e.covers?`covers this session's folder`:`not this session's folder`})(),r),I(t,()=>Rs(e.expiresAt,Date.now()),i),I(a,()=>e.grantID,o),t})()})),e}})}})}}),i),t})()}P([`click`,`keydown`]);var Uk=q(`<nav aria-label=Primary><ul>`),Wk=q(`<a>`),Gk=q(`<li>`),Kk=q(`<a class="side-link nav-link disabled"aria-disabled=true>`),qk=q(`<div class=nav-rail>`),Jk=()=>({signedIn:!!X(),concierge:ou()?.state});function Yk(e){let t=()=>se(ie().pathname);return(()=>{var r=Uk(),i=r.firstChild;return I(i,n(o,{get each(){return m(Jk())},children:r=>(()=>{var i=Gk();return I(i,n(u,{get when(){return r.enabled},get fallback(){return(()=>{var t=Kk();return I(t,n(H,{get name(){return r.dest.icon}}),null),I(t,n(u,{get when(){return!e.compact},get children(){return r.dest.label}}),null),D(n=>{var i=`${r.dest.label} isn't available`,a=e.compact?r.dest.label:void 0;return i!==n.e&&L(t,`title`,n.e=i),a!==n.t&&L(t,`aria-label`,n.t=a),n},{e:void 0,t:void 0}),t})()},get children(){var i=Wk();return i.$$click=()=>e.onPick?.(),I(i,n(H,{get name(){return r.dest.icon}}),null),I(i,n(u,{get when(){return!e.compact},get children(){return r.dest.label}}),null),D(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&&G(i,n.e=a),o!==n.t&&L(i,`href`,n.t=o),s!==n.a&&L(i,`aria-current`,n.a=s),c!==n.o&&L(i,`aria-label`,n.o=c),l!==n.i&&L(i,`title`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),i}})),i})()})),D(()=>G(r,e.compact?`nav-rail-links`:`feature-nav`)),r})()}function Xk(e){return(()=>{var t=qk();return I(t,n(R,{icon:`sidebar`,label:`Show sidebar (⌘B)`,get onClick(){return e.onExpand}}),null),I(t,n(Yk,{compact:!0}),null),t})()}P([`click`]);var Zk=q(`<span class=concierge-btn-text>Concierge`),Qk=q(`<span aria-hidden=true>`),$k=q(`<button type=button>`),eA=q(`<a href=/settings/concierge data-concierge-button=disabled data-indicator=off>`),tA;function nA(){let e=tA;return tA=void 0,e}function rA(e){let t=()=>Ue().name===`concierge`,r=()=>e.labelled?Zk():null,i=e=>n(u,{get when(){return e.indicator!==`running`},get children(){var t=Qk();return I(t,(()=>{var t=V(()=>e.indicator===`attention`);return()=>t()?e.count??`!`:``})()),D(()=>G(t,`concierge-ind ind-${e.indicator}`)),t}});return n(u,{get when(){return ou()},children:o=>{let s=()=>dc(o(),pu(),t(),Date.now(),ic($l(),o(),{tiers:`all`}).length,new Set($l().filter(e=>e.state===`open`).map(e=>e.id)));return n(u,{get when(){return lc(o())===!0},get fallback(){return(()=>{var t=eA();return t.$$click=()=>e.onPick?.(),I(t,n(H,{name:`spark`}),null),I(t,r,null),I(t,()=>i(s()),null),D(n=>{var r=`icon-btn concierge-btn off ind-off${e.labelled?` labelled`:``}`,i=s().label,a=s().title;return r!==n.e&&G(t,n.e=r),i!==n.t&&L(t,`aria-label`,n.t=i),a!==n.a&&L(t,`title`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()},get children(){var c=$k();return c.$$click=n=>{if(e.onPick?.(),t())return he(`/`);tA=n.currentTarget,a(`/concierge`)},I(c,n(H,{name:`spark`}),null),I(c,r,null),I(c,()=>i(s()),null),D(n=>{var r=`icon-btn concierge-btn state-${o().state} ind-${s().indicator}${t()?` on`:``}${e.labelled?` labelled`:``}`,i=s().label,a=t(),l=s().title,u=o().state,d=s().indicator;return r!==n.e&&G(c,n.e=r),i!==n.t&&L(c,`aria-label`,n.t=i),a!==n.a&&L(c,`aria-expanded`,n.a=a),l!==n.o&&L(c,`title`,n.o=l),u!==n.i&&L(c,`data-concierge-button`,n.i=u),d!==n.n&&L(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}})}})}P([`click`]);var iA=q(`<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>`),aA=q(`<span class=badge title="Machines waiting for approval">`),oA=q(`<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><a class=account href=/settings><span aria-hidden=true></span><span class=account-name>`),sA=q(`<p class=side-empty>`),cA=q(`<a class="icon-btn small">`),lA=q(`<ul class=side-list>`),uA=q(`<section>`),dA=q(`<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`),fA=q(`<span class=jobs-badge>`),pA=q(`<span class=unread-dot role=img aria-label=Unread>`),mA=q(`<a class=side-row-link><span class=side-title>`),hA=q(`<li>`),gA=q(`<span class=side-row-link>`),_A=`hub.sidebar.groupBy`,vA=`hub.sidebar.sort`;function yA(e){let[t,r]=x(``),[i,a]=x(localStorage.getItem(_A)===`machine`?`machine`:`project`),[s,c]=x(localStorage.getItem(vA)===`title`?`title`:`recent`),l=T(()=>Za(Eu(),{query:t(),groupBy:i(),sortBy:s()})),d=()=>{let e=Kx();return e.name===`session`?e.id:void 0},f=()=>_t(X()),p=(e,t)=>{e&&(a(e),localStorage.setItem(_A,e)),t&&(c(t),localStorage.setItem(vA,t))};return(()=>{var a=oA(),c=a.firstChild,m=c.firstChild,h=m.firstChild,g=m.nextSibling,_=c.nextSibling,v=_.firstChild,y=_.nextSibling,b=y.firstChild,x=y.nextSibling,S=x.firstChild;S.firstChild;var C=S.nextSibling,w=x.nextSibling.firstChild,T=w.firstChild,E=T.nextSibling;return m.$$click=()=>e.phone&&e.onClose(),I(m,n(Bd,{class:`brand-mark`}),h),I(g,n(rA,{labelled:!0,onPick:()=>e.phone&&e.onClose()}),null),I(g,n(u,{get when(){return e.phone},get fallback(){return n(R,{icon:`sidebar`,label:`Collapse sidebar (⌘B)`,get onClick(){return e.onCollapse}})},get children(){return n(R,{icon:`close`,label:`Close sidebar`,get onClick(){return e.onClose}})}}),null),I(_,n(H,{name:`search`}),v),v.$$keydown=e=>e.key===`Escape`&&r(``),v.$$input=e=>r(e.currentTarget.value),y.$$click=()=>e.phone&&e.onClose(),I(y,n(H,{name:`plus`}),b),I(a,n(Yk,{onPick:()=>e.phone&&e.onClose()}),x),I(S,n(me,{label:`Group and sort`,items:()=>[{section:`Group by`},{label:`Project`,checked:i()===`project`,run:()=>p(`project`,void 0)},{label:`Server`,checked:i()===`machine`,run:()=>p(`machine`,void 0)},{section:`Sort by`},{label:`Recent activity`,checked:s()===`recent`,run:()=>p(void 0,`recent`)},{label:`Title`,checked:s()===`title`,run:()=>p(void 0,`title`)}]}),null),I(C,n(u,{get when(){return $l().length},get children(){var t=iA(),n=t.firstChild.firstChild.firstChild,r=n.firstChild.nextSibling;return n.$$click=()=>e.phone&&e.onClose(),I(r,(()=>{var e=V(()=>$l().length===1);return()=>e()?`A Decision waits for you`:`${$l().length} Decisions wait for you`})()),D(()=>L(n,`href`,ic($l(),ou(),{tiers:`all`}).length===$l().length?`/concierge`:`/`)),t}}),null),I(C,n(u,{get when(){return l().length},get fallback(){return(()=>{var e=sA();return I(e,()=>t()?`No sessions match.`:`No sessions yet.`),e})()},get children(){return n(o,{get each(){return l()},children:t=>(()=>{var r=uA();return I(r,n(ik,{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(u,{get when(){return V(()=>t.kind===`group`)()&&t.machineID},get children(){var e=cA();return I(e,n(H,{name:`plus`})),D(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&&L(e,`aria-label`,n.e=r),i!==n.t&&L(e,`title`,n.t=i),a!==n.a&&L(e,`href`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),e}})}}),null),I(r,n(u,{get when(){return!nk(t.id,t.kind)},get children(){var r=lA();return I(r,n(o,{get each(){return t.rows},children:t=>n(bA,{row:t,get active(){return d()===t.id},onPick:()=>e.phone&&e.onClose()})})),D(()=>L(r,`id`,rk(t.id))),r}}),null),D(e=>{var n=`side-section ${t.kind}${nk(t.id,t.kind)?` collapsed`:``}`,i=t.title,a=t.id;return n!==e.e&&G(r,e.e=n),i!==e.t&&L(r,`aria-label`,e.t=i),a!==e.a&&L(r,`data-section`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),r})()})}}),null),I(C,n(Lk,{onPick:()=>e.phone&&e.onClose()}),null),w.$$click=()=>e.phone&&e.onClose(),I(T,()=>f().initial),I(E,()=>f().title),I(w,n(u,{get when(){return Zl().length},get children(){var e=aA();return I(e,()=>Zl().length),e}}),null),I(w,n(H,{name:`settings`}),null),D(e=>{var t=`Settings (${f().title})`,n=`avatar${f().badge?` admin`:``}`;return t!==e.e&&L(w,`aria-label`,e.e=t),n!==e.t&&G(T,e.t=n),e},{e:void 0,t:void 0}),D(()=>v.value=t()),a})()}function bA(e){let t=()=>e.row,r=()=>fb().phase!==`off`&&fb().sessionID===t().id;return(()=>{var i=hA();return I(i,n(u,{get when(){return!xh(t().id,`sidebar`)},get fallback(){return(()=>{var e=gA();return I(e,n(_e,{get state(){return t().state}}),null),I(e,n(jg,{get id(){return t().id},get title(){return t().title},place:`sidebar`,class:`side-title`,children:null}),null),e})()},get children(){var r=mA(),i=r.firstChild;return ke(r,`dragend`,qp),r.addEventListener(`dragstart`,e=>Kp(e,{target:{sessionID:t().id},label:t().title})),ke(r,`click`,e.onPick,!0),I(r,n(_e,{get state(){return t().state}}),i),I(r,n(u,{get when(){return eo(t(),fb())},get children(){return n(Oe,{})}}),i),I(i,()=>t().title),I(r,n(Mg,{get id(){return t().id}}),null),I(r,n(u,{get when(){return t().error},children:e=>n(Me,{get text(){return e()}})}),null),I(r,n(u,{get when(){return t().waitingInTerminal},get children(){return dA()}}),null),I(r,n(u,{get when(){return t().jobs},get children(){var e=fA();return I(e,()=>t().jobs),D(n=>{var r=Na(t().jobs),i=Na(t().jobs);return r!==n.e&&L(e,`title`,n.e=r),i!==n.t&&L(e,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),e}}),null),I(r,n(u,{get when(){return t().unread},get children(){return pA()}}),null),D(n=>{var i=k(t().id),a=e.active?`page`:void 0,o=`${t().title} · ${t().where} · ${t().machineName}${t().error?` · ${t().error}`:``}`,s=!Z();return i!==n.e&&L(r,`href`,n.e=i),a!==n.t&&L(r,`aria-current`,n.t=a),o!==n.a&&L(r,`title`,n.a=o),s!==n.o&&L(r,`draggable`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),r}}),null),I(i,n(me,{get label(){return`More actions for ${t().title}`},class:`icon-btn small row-more`,items:()=>Ch(t(),{open:!1,place:`sidebar`})}),null),D(()=>G(i,`side-row${e.active?` active`:``}${t().unread?` unread`:``}${r()?` voice-here`:``}`)),i})()}P([`click`,`input`,`keydown`]);var xA={cycle:`F6`,close:`Control+Alt+W`,moveEarlier:`Control+Alt+Shift+ArrowLeft`,moveLater:`Control+Alt+Shift+ArrowRight`,focus:e=>`Control+Alt+${e}`},SA=new Set([`ArrowLeft`,`ArrowUp`]),CA=new Set([`ArrowRight`,`ArrowDown`]);function wA(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 SA.has(e.key)?{type:`move`,step:-1}:CA.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<=lt?{type:`focus`,index:n-1}:void 0}var TA=`hub.paneSizes.v1`,EA={cols:280,rows:160},DA=[`vertical`,`horizontal`,`grid`];function OA(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 kA(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 AA(e){return e>0?Array.from({length:e},()=>1/e):[]}function jA(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 MA(e,t,n,r,i,a,o){let s=r?64:16,[c,l]=o===`cols`?[`ArrowRight`,`ArrowLeft`]:[`ArrowDown`,`ArrowUp`];if(n===c)return jA(e,t,s,i,a);if(n===l)return jA(e,t,-s,i,a);if(n===`Home`)return jA(e,t,-2*i,i,a);if(n===`End`)return jA(e,t,2*i,i,a)}var NA=(e,t,n)=>`${e}:${t}:${n}`;function PA(e){let[t,n,r,...i]=e.split(`:`),a=Number(n);if(i.length||!DA.includes(t)||!Number.isInteger(a)||a<2||a>lt||r!==`cols`&&r!==`rows`)return;let o=OA(t,a)[r];return o>1?o:void 0}function FA(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 IA(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=PA(e),i=n===void 0?void 0:FA(t,n);i&&(r[e]=i)}return r}function LA(e,t,n,r,i,a){let o=NA(n,r,i),s=PA(o),c=s===void 0?void 0:FA(a,s);if(!c)return t;let l={...t,[o]:c};try{e?.setItem(TA,JSON.stringify({v:1,sizes:l}))}catch{}return l}function RA(e,t,n){let r=OA(t,n),i=i=>{let a=e[NA(t,n,i)];return a&&a.length===r[i]?a:AA(r[i])};return{cols:i(`cols`),rows:i(`rows`)}}function zA(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 BA=200,VA=10,HA=e=>e instanceof Error?e.message:String(e),UA=e=>e&&typeof e==`object`&&typeof e.status==`number`?e.status:void 0,WA=class{timeline;fetch;options;state=`idle`;error;cursor;invalid=!1;generation=0;loading;constructor(e,t,n={}){this.timeline=e,this.fetch=t,this.options=n}get hasOlder(){return this.cursor!==void 0}get limit(){return this.options.limit??80}changed(){this.options.onChange?.()}async first(){let e=this.begin(),t=await this.fetch({limit:this.limit,order:`desc`});e===this.generation&&await this.show(t,e)}async resync(){let e=this.begin(),t=await this.fetch({limit:this.limit,order:`desc`});if(e!==this.generation)return;let n=t.items??[],r=t.older===void 0||n.some(e=>this.timeline.fromHistory(e?.key));t.cursor===void 0&&r?(this.timeline.load(n),this.state===`loading`&&(this.state=this.cursor===void 0?`done`:`idle`),this.changed()):(this.timeline.forgetHistory(),await this.show(t,e))}older(){if(this.loading)return this.loading;if(this.state!==`idle`||this.cursor===void 0)return Promise.resolve();let e=this.generation,t=this.cursor;this.state=`loading`,this.changed();let n=(async()=>{try{let n=await this.fetch({limit:this.limit,before:t});if(e!==this.generation)return;this.timeline.load(n.items,{older:!0}),this.cursor=n.older,this.state=n.older===void 0?`done`:`idle`,this.error=void 0}catch(t){if(e!==this.generation)return;this.state=`error`,this.error=HA(t),this.invalid=UA(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=HA(t),this.invalid=!0,this.changed()}}else return this.state=`idle`,this.error=void 0,this.older()}}begin(){return this.loading=void 0,++this.generation}async show(e,t){if(this.timeline.load(e.items),this.error=void 0,this.invalid=!1,e.cursor!==void 0&&e.older===void 0){let n=e.cursor;for(let e=1;n!==void 0&&e<VA;e++){let e=await this.fetch({limit:BA,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()}},GA=[`native`,`hooks`,`rpc`,`screen`],KA={opencode:`OpenCode`,"claude-code":`Claude Code`,codex:`Codex`},qA=e=>KA[e]??e;function JA(e){let t=e?.harness||`opencode`;if(t===`opencode`)return{native:!0,harness:t,harnessName:`OpenCode`,evidence:`native`,turn:!0,steer:!0,interrupt:!0,stop:!0,permission:!0,form:!0,models:!0,timeline:!0,summary:!0,voice:!0,queued:!1};let n=GA.includes(e?.evidence??``)?e.evidence:`unknown`,r=e?.features?new Set(e.features):void 0,i=e=>!r||r.has(e);return{native:!1,harness:t,harnessName:qA(t),evidence:n,turn:i(`turn`),steer:i(`steer`),interrupt:i(`interrupt`),stop:i(`stop`),permission:i(`permission`),form:i(`form`),models:i(`models`),timeline:i(`timeline`),summary:i(`summary`),voice:i(`conversation`)&&i(`steer`),queued:n===`hooks`||n===`screen`||n===`unknown`}}var YA={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 XA(e){if(e.native)return;let t=YA[e.evidence];return{level:e.evidence,label:t.label,detail:t.detail(e.harnessName)}}function ZA(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 QA(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 $A={queued:`queued`,retained:`held`,pending:`pending`,dropped:`not delivered`};function ej(e){return typeof e==`string`?$A[e]:void 0}function tj(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 nj=/data:([\w.+-]+\/[\w.+-]+)?((?:;[\w.+-]+=[^;,\s"'<>]*)*);base64,([A-Za-z0-9+/_-]+={0,2})/gi,rj=/^[A-Za-z0-9+/_-]+={0,2}$/,ij=[`mime`,`mimeType`,`media_type`,`mediaType`];function aj(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 oj(e,t){return`[${e||`data`}, ${aj(t)} — not shown]`}function sj(e){return e.includes(`base64,`)?e.replace(nj,(e,t,n,r)=>oj(t?.toLowerCase(),r)):e}function cj(e){if(typeof e.data!=`string`||!rj.test(e.data))return;let t=ij.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 lj(e){return uj(e)}function uj(e){if(typeof e==`string`)return sj(e);if(Array.isArray(e))return e.map(uj);if(!e||typeof e!=`object`)return e;let t=e,n=cj(t),r={};for(let[e,i]of Object.entries(t))r[e]=e===`data`&&n?oj(n,i):uj(i);return r}var dj=(e,t,n)=>`/api/sessions/${encodeURIComponent(e)}/timeline/messages/${encodeURIComponent(t)}/files/${n}`;function fj(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=Yg(n.mime)&&typeof e.sessionID==`string`&&typeof e.messageID==`string`;t.push({key:`${e.key}:${n.index}`,name:typeof n.name==`string`&&n.name?n.name:n.mime.startsWith(`image/`)?`image`:`file`,mime:n.mime,...r?{src:dj(e.sessionID,e.messageID,n.index)}:{}})}return t}function pj(e,t={}){let n=[];for(let r of e)if(!((r.depth??0)>0))switch(r.kind){case`user`:{let e=fj(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`:r.text&&n.push({type:`assistant`,key:r.key,text:r.text,live:r.live===!0});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),r.state===`failed`&&i.failed++,r.state===`running`&&i.running++,t||n.push(i);break}case`message`:n.push(_j(r));break;case`error`:n.push(r.declined===!0?{type:`error`,key:r.key,label:`${t.denied?.(r)??`Denied`}: the turn stopped`,denied:!0}:hj(r));break;case`retry`:n.push({type:`retry`,key:r.key,...mj(`attempt`,r.attempt),...mj(`next`,r.next),...typeof r.errorType==`string`?{errorType:r.errorType}:{},...mj(`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 mj=(e,t)=>typeof t==`number`&&Number.isFinite(t)?{[e]:t}:{};function hj(e){let t=typeof e.text==`string`&&e.text.trim()?e.text.trim():void 0,n=ha(e.errorType),r=_a(e.errorStatus);return{type:`error`,key:e.key,label:n??t??`Error`,...n&&t?{message:t}:{},...r?{status:r}:{}}}function gj(e,t){return{text:Ca(e,t),waiting:va(e.next,t)!==void 0}}function _j(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=ej(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 vj=`The model didn't share its reasoning text (only an encrypted summary).`;function yj(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…`:vj,muted:!0}}function bj(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 xj(e,t){return JSON.stringify(lj(e??{summary:t.summary||void 0,error:t.error}),null,2)}var Sj=q(`<p class=composer-error role=alert>`),Cj=q(`<p class="composer-hint muted small">`),wj=q(`<li class="attachment busy"aria-label="Preparing image"><span class="spinner small">`),Tj=q(`<ul class=attachments aria-label="Attached images">`),Ej=q(`<div><button type=button class=split-main>`),Dj=q(`<button type=button class="btn stop"aria-label="Stop the session and its subagents"> Stop`),Oj=q(`<span class=sr-only>`),kj=q(`<button type=button class=model-chip title="Voice model (the orchestrator you talk to)">Voice: `),Aj=q(`<button type=button class=model-chip title="Worker model (subagents that do the work)">Worker: `),jj=q(`<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>`),Mj=q(`<li class=attachment><img><button type=button class=attachment-remove title=Remove>`),Nj=q(`<span class="spinner small">`),Pj=q(`<button type=button class=split-chev aria-label="Choose microphone"aria-haspopup=dialog>`),Fj=q(`<p class="error small pad">`),Ij=q(`<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>`),Lj=q(`<button type=button class=menu-item role=menuitemradio><span class=menu-check></span><span class=menu-label>`),Rj=q(`<span class=muted> · “<!>…”`),zj=q(`<span class=voice-ignored title="Heard as background noise, not sent"> · ignored: “<!>”`),Bj=q(`<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`),Vj=q(`<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`),Hj=q(`<span>`);function Uj(e){let t,r,[i,a]=x(!1),s=()=>e.images.length>=Wg.maxImages,c=()=>{t.style.height=`auto`,t.style.height=`${Math.min(t.scrollHeight,280)}px`};C(()=>{e.draft,queueMicrotask(c)});let l=()=>e.view.primary===`steer`?`Steer`:`Send`;return(()=>{var c=jj(),d=c.firstChild,f=d.firstChild,p=f.nextSibling,m=p.nextSibling,h=m.firstChild,g=h.nextSibling.nextSibling,_=g.nextSibling,v=d.nextSibling,y=v.firstChild;y.nextSibling,c.addEventListener(`drop`,t=>{let n=vx(t.dataTransfer);a(!1),n.length&&(t.preventDefault(),e.onAttach(n))}),c.addEventListener(`dragleave`,e=>{e.currentTarget.contains(e.relatedTarget)||a(!1)}),c.addEventListener(`dragover`,e=>{[...e.dataTransfer?.types??[]].includes(`Files`)&&(e.preventDefault(),a(!0))}),c.addEventListener(`submit`,t=>{t.preventDefault(),e.view.canSubmit&&!e.attaching&&e.onSubmit()}),I(c,n(u,{get when(){return e.error},get children(){var t=Sj();return I(t,()=>e.error),t}}),d),I(c,n(u,{get when(){return e.view.hint},get children(){var t=Cj();return I(t,()=>e.view.hint),t}}),d),I(d,n(u,{get when(){return e.images.length||e.attaching},get children(){var t=Tj();return I(t,n(o,{get each(){return e.images},children:t=>(()=>{var r=Mj(),i=r.firstChild,a=i.nextSibling;return a.$$click=()=>e.onDetach(t.id),I(a,n(H,{name:`close`})),D(e=>{var n=t.preview,r=t.name,o=t.name,s=`Remove ${t.name}`;return n!==e.e&&L(i,`src`,e.e=n),r!==e.t&&L(i,`alt`,e.t=r),o!==e.a&&L(i,`title`,e.a=o),s!==e.o&&L(a,`aria-label`,e.o=s),e},{e:void 0,t:void 0,a:void 0,o:void 0}),r})()}),null),I(t,n(u,{get when(){return e.attaching},get children(){return wj()}}),null),t}}),f),f.$$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())},f.addEventListener(`paste`,t=>{let n=vx(t.clipboardData);n.length&&(t.preventDefault(),e.onAttach(n))}),f.$$input=t=>e.onInput(t.currentTarget.value);var b=t;typeof b==`function`?ge(b,f):t=f,p.addEventListener(`change`,t=>{let n=[...t.currentTarget.files??[]];t.currentTarget.value=``,n.length&&e.onAttach(n)});var x=r;return typeof x==`function`?ge(x,p):r=p,h.$$click=()=>r.click(),I(h,n(H,{name:`plus`})),ke(g,`click`,e.onDictate,!0),I(g,n(u,{get when(){return!e.transcribing},get fallback(){return Nj()},get children(){return n(H,{get name(){return e.dictating===!1?`mic`:`stop`}})}})),I(m,n(u,{get when(){return e.showVoice!==!1},get children(){var t=Ej(),r=t.firstChild;return ke(r,`click`,e.onVoice,!0),I(r,n(H,{name:`wave`})),I(t,n(Wj,{}),null),D(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&&G(t,n.e=i),a!==n.t&&L(r,`aria-pressed`,n.t=a),o!==n.a&&L(r,`aria-label`,n.a=o),s!==n.o&&L(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}}),_),I(m,n(u,{get when(){return e.view.showStop},get children(){var t=Dj(),r=t.firstChild;return ke(t,`click`,e.onStop,!0),I(t,n(H,{name:`stop`}),r),D(()=>t.disabled=!e.view.canStop),t}}),_),I(_,n(u,{get when(){return e.view.primary===`send`},get fallback(){return l()},get children(){return[n(H,{name:`send`}),(()=>{var e=Oj();return I(e,l),e})()]}})),I(y,()=>e.metaLeft),I(v,n(u,{get when(){return e.showModels!==!1},get children(){return[(()=>{var t=kj();return t.firstChild,t.$$click=()=>e.onModel(`voice`),I(t,()=>e.voiceModel,null),t})(),(()=>{var t=Aj();return t.firstChild,t.$$click=()=>e.onModel(`worker`),I(t,()=>e.workerModel,null),t})()]}}),null),D(t=>{var n=`composer${i()?` dragging`:``}`,r=e.voiceOn?`Voice mode is on — talk, or type here`:e.view.primary===`steer`?`Steer the running session…`:`Reply…`,a=Ug.join(`,`),o=s()?`At most ${Wg.maxImages} images per message`:`Attach images (or paste / drop them here)`,l=s()||e.attaching,u=`icon-btn${e.dictating===!1?``:` recording`}`,d=e.dictating===!1?`Dictate`:`Stop dictation`,m=e.voiceBlocked??(e.dictating===!1?`Dictate`:`Stop dictation (${e.dictating}s left)`),v=!!e.voiceBlocked||e.transcribing||e.voiceOn,y=`btn primary send ${e.view.primary}`,b=!e.view.canSubmit||e.attaching;return n!==t.e&&G(c,t.e=n),r!==t.t&&L(f,`placeholder`,t.t=r),a!==t.a&&L(p,`accept`,t.a=a),o!==t.o&&L(h,`title`,t.o=o),l!==t.i&&(h.disabled=t.i=l),u!==t.n&&G(g,t.n=u),d!==t.s&&L(g,`aria-label`,t.s=d),m!==t.h&&L(g,`title`,t.h=m),v!==t.r&&(g.disabled=t.r=v),y!==t.d&&G(_,t.d=y),b!==t.l&&(_.disabled=t.l=b),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0}),D(()=>f.value=e.draft),c})()}function Wj(){let[e,t]=x(!1),[r,i]=x([]),[a,s]=x(0),[c,l]=x(``),d,f,p,[m,h]=x({right:0,bottom:0}),g=async()=>{p?.(),p=void 0;try{p=await Uy(zy(),s),l(``)}catch(e){l(e.name===`NotAllowedError`?`Microphone permission was denied.`:`Microphone: ${e.message}`)}},_=async()=>{let e=d.getBoundingClientRect();if(h({right:window.innerWidth-e.right,bottom:window.innerHeight-e.top+6}),t(!0),!navigator.mediaDevices)return l(`This browser cannot use the microphone here (it needs HTTPS).`);i(await Hy().catch(()=>[])),g()},v=()=>{t(!1),p?.(),p=void 0,s(0)},y=t=>e()&&!d.contains(t.target)&&!f?.contains(t.target)&&v(),b=t=>e()&&t.key===`Escape`&&!xe(f)&&v();return document.addEventListener(`mousedown`,y),document.addEventListener(`keydown`,b),j(()=>{document.removeEventListener(`mousedown`,y),document.removeEventListener(`keydown`,b),v()}),[(()=>{var t=Pj();t.$$click=()=>e()?v():void _();var r=d;return typeof r==`function`?ge(r,t):d=t,I(t,n(H,{name:`down`})),D(()=>L(t,`aria-expanded`,e())),t})(),n(u,{get when(){return e()},get children(){return n(ve,{get children(){var e=Ij(),t=e.firstChild.nextSibling,i=t.firstChild,s=f;return typeof s==`function`?ge(s,e):f=e,I(e,n(o,{get each(){return[{deviceId:``,label:`System default`},...r().filter(e=>e.deviceId&&e.deviceId!=="default")]},children:(e,t)=>(()=>{var n=Lj(),r=n.firstChild,i=r.nextSibling;return n.$$click=()=>{Vy(e.deviceId),g()},I(r,()=>zy()===e.deviceId?`✓`:``),I(i,()=>e.label||`Microphone ${t()}`),D(()=>L(n,`aria-checked`,zy()===e.deviceId)),n})()}),t),I(e,n(u,{get when(){return c()},get children(){var e=Fj();return I(e,c),e}}),null),D(n=>{var r=`${m().right}px`,o=`${m().bottom}px`,s=Math.round(a()*100),c=`${Math.round(a()*100)}%`;return r!==n.e&&Se(e,`right`,n.e=r),o!==n.t&&Se(e,`bottom`,n.t=o),s!==n.a&&L(t,`aria-valuenow`,n.a=s),c!==n.o&&Se(i,`width`,n.o=c),n},{e:void 0,t:void 0,a:void 0,o:void 0}),e}})}})]}var Gj={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 Kj(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(`
|
|
20
|
-
`):void 0}function qj(e){let t=()=>e.state===`listening`&&e.working?`Thinking`:Gj[e.state],r=[.5,.8,1,.7,.45];return(()=>{var i=Vj(),a=i.firstChild,s=a.nextSibling,c=s.nextSibling,l=c.nextSibling,d=l.nextSibling,f=d.nextSibling;return I(a,n(o,{each:r,children:t=>(()=>{var n=Hj();return D(r=>Se(n,`transform`,`scaleY(${Math.max(.15,Math.min(1,(e.state===`speaking`?.6:e.level)*t*1.6))})`)),n})()})),I(s,t,null),I(s,n(u,{get when(){return e.held},get children(){var t=Rj(),n=t.firstChild.nextSibling;return n.nextSibling,I(t,()=>e.held,n),t}}),null),I(s,n(u,{get when(){return e.ignored},get children(){var t=zj(),n=t.firstChild.nextSibling;return n.nextSibling,I(t,()=>e.ignored,n),t}}),null),I(i,n(FO,{announce:!0}),c),ke(l,`click`,e.onModel,!0),I(l,()=>e.model),ke(d,`click`,e.onMute,!0),I(d,n(H,{get name(){return e.state===`paused`?`muted`:`mic`}})),ke(f,`click`,e.onEnd,!0),I(i,n(u,{get when(){return e.notifyHint},get children(){var t=Bj(),n=t.firstChild.nextSibling;return n.$$click=()=>e.onAllowNotifications?.(),t}}),null),D(t=>{var n=`voice-bar ${e.state}`,r=e.detector?.mode,a=Kj(e.timing,e.detector),o=`icon-btn${e.state===`paused`?` on`:``}`,c=e.state===`paused`,l=e.state===`paused`?`Unmute`:`Mute`,u=e.state===`paused`?`Unmute`:`Mute`;return n!==t.e&&G(i,t.e=n),r!==t.t&&L(i,`data-vad`,t.t=r),a!==t.a&&L(s,`title`,t.a=a),o!==t.o&&G(d,t.o=o),c!==t.i&&L(d,`aria-pressed`,t.i=c),l!==t.n&&L(d,`aria-label`,t.n=l),u!==t.s&&L(d,`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})()}P([`input`,`keydown`,`click`]);var Jj=()=>({query:``,active:0}),Yj=e=>[void 0,...(e.variants??[]).filter(e=>e!=="default")];function Xj(e,t,n=100){if(t.chosen)return{mode:`variants`,model:t.chosen,rows:Yj(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 Zj=(e,t)=>({...e,query:t,active:0}),Qj=(e,t)=>({providerID:e.providerID,modelID:e.modelID,...t?{variant:t}:{}});function $j(e,t,n){let r=Xj(e,t);if(r.mode===`variants`)return n<0||n>=r.rows.length?{state:t}:{state:t,pick:Qj(r.model,r.rows[n])};let i=r.rows[n];return i?Yj(i).length>1?{state:{...t,chosen:i,active:0}}:{state:t,pick:Qj(i)}:{state:t}}function eM(e,t,n,{inSearch:r}){let i=Xj(e,t).rows.length;if(n===`ArrowDown`||n===`ArrowUp`)return{state:{...t,active:Math.max(0,Qx(t.active,n===`ArrowDown`?1:-1,i))},handled:!0};if(n===`Enter`)return{...$j(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}:{...$j(e,t,r),handled:!0}}return{state:t,handled:!1}}var tM=(e,t)=>({[e]:t}),nM=q(`<div>`),rM=q(`<p class="error small"role=alert>Couldn't load models: `),iM=q(`<p class="muted small">Loading models…`),aM=q(`<input type=search class=picker-search placeholder="Search models"aria-label="Search models"autofocus>`),oM=q(`<p class="muted small"role=status>`),sM=q(`<ul class=picker-list role=listbox aria-label=Models>`),cM=q(`<li class="muted small">No models match.`),lM=q(`<div class="picker-group muted small">`),uM=q(`<span class="po-id muted">variants ›`),dM=q(`<span class=po-mark>✓`),fM=q(`<kbd>`),pM=q(`<li><button type=button role=option><span class=po-name></span><span class="po-id muted">`),mM=q(`<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>`),hM=q(`<li><button type=button role=option><span class=po-name></span><kbd>`);function gM(e,t){let n=e?.prefs[t]??e?.defaults[t];return n?`${n.modelID}${n.variant?` · ${n.variant}`:``}`:`default`}function _M(e){let[t,n]=x(),[r,i]=x(``),[a,o]=x();return{prefs:t,error:r,load:async()=>{try{n(await z(`${N(e())}/model-prefs`)),i(``)}catch(e){i(U(e))}},loadCatalog:async()=>{if(a())return a();let{models:t}=await z(`${N(e())}/models`),n=new Ft(t);return o(n),n},save:async(t,r)=>{try{n(await(await W(`${N(e())}/model-prefs`,{method:`PUT`,json:tM(t,r)})).json()),K(`${t===`voice`?`Voice`:`Worker`} model applies to the next ${t===`voice`?`turn`:`task`}.`)}catch(e){K(`Couldn't set the ${t===`voice`?`Voice`:`Worker`} model: ${U(e)}`,`err`)}}}}function vM(e){let[t,r]=x(Jj()),[i,a]=x(),[s,c]=x(``),l=()=>e.kind!==void 0,d=()=>e.kind?e.models.prefs()?.prefs[e.kind]??e.models.prefs()?.defaults[e.kind]:void 0,f=e=>d()?.providerID===e.providerID&&d()?.modelID===e.modelID,p=()=>{r(Jj()),c(``),e.models.loadCatalog().then(a,e=>c(U(e)))},m=T(()=>i()?Xj(i(),t()):void 0),g=t=>{if(r(t.state),!t.pick||!e.kind)return;let n=e.kind;e.onClose(),e.models.save(n,t.pick)},_=e=>i()&&g($j(i(),t(),e)),v=e=>{if(!i()||e.altKey||e.ctrlKey||e.metaKey)return;let n=eM(i(),t(),e.key,{inSearch:e.target instanceof HTMLInputElement});if(!n.handled)return;e.preventDefault(),g(n);let r=e.currentTarget;queueMicrotask(()=>r.querySelector(`.picker-opt.active`)?.scrollIntoView({block:`nearest`}))};return C(h(l,e=>e&&p())),n(ze,{get open(){return l()},get title(){return`${e.kind===`voice`?`Voice`:`Worker`} model`},get onClose(){return e.onClose},class:`picker`,get children(){var e=nM();return e.$$keydown=v,I(e,n(u,{get when(){return!s()},get fallback(){return(()=>{var e=rM();return e.firstChild,I(e,s,null),e})()},get children(){return n(u,{get when(){return m()},get fallback(){return iM()},children:e=>n(u,{get when(){return V(()=>e().mode===`models`)()&&e()},get fallback(){return n(yM,{get view(){return e()},get active(){return t().active},get current(){return d()},onPick:_,onBack:()=>r(e=>({...e,chosen:void 0,active:0}))})},children:e=>[(()=>{var e=aM();return e.$$input=e=>r(t=>Zj(t,e.currentTarget.value)),D(()=>e.value=t().query),e})(),(()=>{var t=oM();return I(t,(()=>{var t=V(()=>e().total===1);return()=>t()?`1 model`:`${e().total} models`})(),null),I(t,(()=>{var t=V(()=>!!e().more);return()=>t()?` · showing ${e().rows.length}, search to narrow`:``})(),null),t})(),(()=>{var r=sM();return I(r,n(o,{get each(){return e().rows},get fallback(){return cM()},children:(r,i)=>(()=>{var a=pM(),o=a.firstChild,s=o.firstChild,c=s.nextSibling;return I(a,n(u,{get when(){return i()===0||e().rows[i()-1].group!==r.group},get children(){var e=lM();return I(e,()=>r.group),e}}),o),o.$$click=()=>_(i()),I(s,()=>r.name||r.modelID),I(c,()=>r.modelID),I(o,n(u,{get when(){return(r.variants??[]).some(e=>e!=="default")},get children(){return uM()}}),null),I(o,n(u,{get when(){return f(r)},get children(){return dM()}}),null),I(o,n(u,{get when(){return i()<9},get children(){var e=fM();return I(e,()=>i()+1),e}}),null),D(e=>{var n=`picker-opt${t().active===i()?` active`:``}`,a=f(r);return n!==e.e&&G(o,e.e=n),a!==e.t&&L(o,`aria-selected`,e.t=a),e},{e:void 0,t:void 0}),a})()})),r})()]})})}})),e}})}function yM(e){let t;ue(()=>t?.focus());let r=()=>e.current?.providerID===e.view.model.providerID&&e.current?.modelID===e.view.model.modelID;return(()=>{var i=mM(),a=i.firstChild,s=a.firstChild,c=s.nextSibling;c.firstChild;var l=a.nextSibling;return ke(s,`click`,e.onBack,!0),I(c,()=>e.view.model.name||e.view.model.modelID,null),I(l,n(o,{get each(){return e.view.rows},children:(i,a)=>(()=>{var o=hM(),s=o.firstChild,c=s.firstChild,l=c.nextSibling;return s.$$click=()=>e.onPick(a()),ge(e=>a()===0&&(t=e),s),I(c,i??`Default`),I(s,n(u,{get when(){return V(()=>!!r())()&&e.current?.variant===i},get children(){return dM()}}),l),I(l,()=>a()+1),D(t=>{var n=`picker-opt${e.active===a()?` active`:``}`,o=r()&&e.current?.variant===i;return n!==t.e&&G(s,t.e=n),o!==t.t&&L(s,`aria-selected`,t.t=o),t},{e:void 0,t:void 0}),o})()})),i})()}P([`keydown`,`input`,`click`]);var bM=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;function xM(e){let t=[],n=0,r=0,i=!1;for(let a of String(e??``).replace(/\r\n?/g,`
|
|
21
|
-
`).split(`
|
|
22
|
-
`)){let e=bM.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 SM=new Set([`user`,`launch`,`self`,`prompt`,`title`]),CM=e=>`/api/agent/sessions/${encodeURIComponent(e)}/intent`,wM=e=>e.replace(/\s+/g,` `).trim();function TM(e){let t=Array.from(wM(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 EM=(e,t)=>({text:e===null?null:wM(e),expectedRevision:t});function DM(e){if(e?.source===`user`)return{text:null,expectedRevision:e.revision};if(e?.source===`prompt`)return{source:`prompt`,text:null,expectedRevision:e.revision}}function OM(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 kM(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`||!SM.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 AM(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 jM(e,t,n){return e.type===`intent`&&e.sessionID===t&&e.revision!==n}var MM=q(`<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`),NM=q(`<div class=intent-field>`),PM=q(`<button type=button class="btn small">Retry`),FM=q(`<button type=button class="btn small">Clear`),IM=q(`<div class=row><button type=button class="btn small">Edit`),LM=q(`<p class="muted small intent-error">Could not load the intent.`),RM=q(`<p class="muted small">Loading…`),zM=q(`<p class="muted small">No intent yet.`),BM=q(`<p class="small intent-text">`),VM=q(`<p class="muted small">`),HM=q(`<p class=field-error>`);function UM(t){let[r,{refetch:i,mutate:a}]=f(()=>t.sessionID,async e=>kM(await z(CM(e)))),[o,s]=x(!1),[c,l]=x(``),[d,p]=x(!1),[m,h]=x(``),g=()=>TM(c()),_=()=>r.error?void 0:r.loading?r.latest:r();j(Tu(e=>{!o()&&jM(e,t.sessionID,_()?.revision)&&i()}));let v=()=>{l(_()?.source===`title`?``:_()?.text??``),h(``),s(!0)},y=async n=>{if(d()||n!==null&&g())return;let o=n===null?DM(_()):EM(n,_()?.revision??0);if(o){p(!0),h(``);try{let e=kM(await(await W(CM(t.sessionID),{method:`PUT`,json:o})).json());r.error?i():a(e),s(!1)}catch(t){let n=AM(t instanceof e?{status:t.status,...t.code?{code:t.code}:{},message:t.message}:{message:U(t)},{loaded:!r.error});h(n.text),n.reload&&(s(!1),i())}finally{p(!1)}}};return(()=>{var e=NM();return I(e,n(u,{get when(){return o()},get fallback(){return[n(u,{get when(){return!r.error},get fallback(){return LM()},get children(){return n(u,{get when(){return!r.loading||_()},get fallback(){return RM()},get children(){return n(u,{get when(){return _()},get fallback(){return zM()},children:e=>[(()=>{var t=BM();return I(t,()=>e().text),t})(),(()=>{var t=VM();return I(t,()=>OM(e())),t})()]})}})}}),(()=>{var e=IM(),t=e.firstChild;return t.$$click=v,I(e,n(u,{get when(){return r.error},get children(){var e=PM();return e.$$click=()=>void i(),e}}),null),I(e,n(u,{get when(){return DM(_())},get children(){var e=FM();return e.$$click=()=>void y(null),D(t=>{var n=d(),r=_()?.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&&L(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e}}),null),D(()=>t.disabled=r.loading&&!r.error),e})()]},get children(){var e=MM(),r=e.firstChild,i=r.nextSibling,a=i.nextSibling,o=a.firstChild,f=o.nextSibling;return ge(e=>queueMicrotask(()=>e.focus()),i),i.$$keydown=e=>{e.key===`Enter`&&y(c()),e.key===`Escape`&&s(!1)},i.$$input=e=>l(e.currentTarget.value),L(i,`maxlength`,560),I(e,n(u,{get when(){return V(()=>!!c())()&&g()},children:e=>(()=>{var t=HM();return I(t,e),t})()}),a),o.$$click=()=>void y(c()),f.$$click=()=>s(!1),D(e=>{var n=`intent-${t.sessionID}`,a=`intent-${t.sessionID}`,s=d()||!!g(),c=d();return n!==e.e&&L(r,`for`,e.e=n),a!==e.t&&L(i,`id`,e.t=a),s!==e.a&&(o.disabled=e.a=s),c!==e.o&&(f.disabled=e.o=c),e},{e:void 0,t:void 0,a:void 0,o:void 0}),D(()=>i.value=c()),e}}),null),I(e,n(u,{get when(){return m()},children:e=>(()=>{var t=HM();return I(t,e),t})()}),null),e})()}P([`input`,`keydown`,`click`]);var WM=q(`<section><h3><button type=button class=card-toggle><span>`),GM=q(`<ul class=job-list>`),KM=q(`<ul class=mcp-list>`),qM=q(`<aside class=rail aria-label="Session details"><div class=rail-head><span class=rail-title>Details`),JM=q(`<p class="rail-error small"><strong>`),YM=q(`<p class="muted small">`),XM=q(`<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>`),ZM=q(`<span class=muted>`),QM=q(`<p class="small retry-note">`),$M=q(`<li><span aria-hidden=true></span><span class="job-command mono"></span><span class="muted small">`),eN=q(`<div class=meter role=meter aria-valuemin=0 aria-valuemax=100 aria-label="Context used"><span>`),tN=q(`<p class=small><strong></strong><span class=muted> `),nN=q(`<li><span aria-hidden=true></span><span class=mcp-name></span><span class="muted small">`),rN=q(`<span class=diffstat><span class=add>+</span> <span class=del>−`),iN=q(`<ul class=file-list>`),aN=q(`<p class="muted small">No changes.`),oN=q(`<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>−`),sN=q(`<p class="muted small more-files">+<!> more <!> (only the most-changed files are listed)`),cN=q(`<table class=diff><tbody>`),lN=q(`<p class="muted small pad">The diff is too large to show completely (512 KB).`),uN=q(`<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>`),dN=q(`<option>`),fN=q(`<p class="muted small pad">Loading diff…`),pN=q(`<p class="muted small pad">`),mN=q(`<p class="muted small pad">No textual changes (binary file, or a rename).`),hN=q(`<tr><td class=ln></td><td class=ln></td><td class=code-line><span class=sign>`),gN=e=>e.truncated&&e.totalFiles?Math.max(0,e.totalFiles-e.files.length):0,[_N,vN]=x(cx(localStorage));function yN(e){let t=()=>!_N().has(e.id);return(()=>{var r=WM(),i=r.firstChild,a=i.firstChild,o=a.firstChild;return a.$$click=()=>vN(lx(localStorage,e.id)),I(a,n(H,{name:`chevron`,class:`card-chevron`}),o),I(o,()=>e.title),I(i,()=>e.extra,null),I(r,n(u,{get when(){return t()},get children(){return e.children}}),null),D(n=>{var i=`rail-card${t()?``:` collapsed`}`,o=e.label??e.title,s=e.domID,c=e.id,l=t();return i!==n.e&&G(r,n.e=i),o!==n.t&&L(r,`aria-label`,n.t=o),s!==n.a&&L(r,`id`,n.a=s),c!==n.o&&L(r,`data-card`,n.o=c),l!==n.i&&L(a,`aria-expanded`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),r})()}var bN=e=>e>=1e3?`${(e/1e3).toFixed(e>=1e5?0:1)}k`:String(e);function xN(e){let t=()=>e.found?.session,r=()=>t()?.open?t()?.terminal?.source===`herdr`?`herdr`:`tui`:`background`,i=()=>Aa(t()?.status,F()),a=()=>i().filter(e=>e.status===`running`).length,s=()=>t()?.state===`working`||t()?.status?.some(e=>e.state===`working`)?Pa(t()?.status,t()?.id,Fe()):void 0,c=()=>Ta(t()?.status,t()?.id),l=()=>{let t=e.summary?.mcp;return t?.length?`Connectors · ${t.filter(e=>e.status===`connected`).length} connected`:`Connectors`};return(()=>{var d=qM(),f=d.firstChild;return f.firstChild,I(f,n(R,{icon:`close`,label:`Close details`,get onClick(){return e.onClose}}),null),I(d,n(u,{get when(){return c()},children:e=>(()=>{var n=JM(),r=n.firstChild;return I(r,()=>e().label),I(n,(()=>{var t=V(()=>!!e().status);return()=>t()?` · ${e().status}`:``})(),null),I(n,(()=>{var n=V(()=>!!(e().title&&e().sessionID!==t()?.id));return()=>n()?` · ${e().title}`:``})(),null),D(()=>L(n,`title`,e().text)),n})()}),null),I(d,n(yN,{id:`environment`,title:`Environment`,get children(){return n(u,{get when(){return e.found},get fallback(){return(()=>{var e=YM();return I(e,()=>Y.machines?`Not reported by any connected machine.`:`Loading…`),e})()},children:i=>(()=>{var a=XM(),o=a.firstChild.nextSibling,s=o.firstChild,c=s.nextSibling,l=c.nextSibling;l.firstChild;var u=o.nextSibling.nextSibling,d=u.nextSibling.nextSibling,f=d.firstChild,p=f.firstChild,m=d.nextSibling.nextSibling,h=m.nextSibling.nextSibling;return I(o,()=>i().machine.name,c),I(l,(()=>{var e=V(()=>Y.connection!==`live`);return()=>e()?`Connecting`:i().machine.online?`online`:`offline`})(),null),I(u,()=>ye(e.summary?.directory??i().session.directory)),I(p,()=>e.summary?.directory??i().session.directory),I(d,n(R,{icon:`copy`,label:`Copy the directory`,onClick:()=>{let t=e.summary?.directory??i().session.directory;navigator.clipboard.writeText(t).then(()=>K(`Directory copied`),()=>K(`Could not copy the directory`,`err`))}}),null),I(m,()=>e.summary?.branch??(()=>{var t=ZM();return I(t,()=>e.loading?`…`:`—`),t})()),I(h,()=>Ne[r()],null),I(h,(()=>{var e=V(()=>!!t()?.terminal?.workspace);return()=>e()?` · ${t().terminal.workspace}`:``})(),null),D(t=>{var n=`online-dot${i().machine.online&&Y.connection===`live`?` on`:``}`,r=e.summary?.directory??i().session.directory,a=e.summary?.directory??i().session.directory;return n!==t.e&&G(s,t.e=n),r!==t.t&&L(u,`title`,t.t=r),a!==t.a&&L(f,`title`,t.a=a),t},{e:void 0,t:void 0,a:void 0}),a})()})}}),null),I(d,n(u,{get when(){return t()?.id},children:e=>n(yN,{id:`intent`,title:`Intent`,label:`Session intent`,get children(){return n(UM,{get sessionID(){return e()}})}})}),null),I(d,n(u,{get when(){return i().length||s()},get children(){return n(yN,{id:`jobs`,get title(){return`Jobs${a()?` · ${a()} running`:``}`},label:`Background jobs`,get children(){return[n(u,{get when(){return s()},children:e=>(()=>{var t=QM();return I(t,e),t})()}),(()=>{var e=GM();return I(e,n(o,{get each(){return i()},children:e=>(()=>{var n=$M(),r=n.firstChild,i=r.nextSibling,a=i.nextSibling;return I(i,()=>e.command??e.id),I(a,()=>Ma(e,F()),null),I(a,(()=>{var n=V(()=>!!(e.sessionID!==t()?.id&&e.sessionTitle));return()=>n()?` · ${e.sessionTitle}`:``})(),null),D(t=>{var i=`job ${e.status}`,a=e.command??e.id,o=`job-dot ${e.status===`running`?`on`:e.exit?`bad`:``}`;return i!==t.e&&G(n,t.e=i),a!==t.t&&L(n,`title`,t.t=a),o!==t.a&&G(r,t.a=o),t},{e:void 0,t:void 0,a:void 0}),n})()})),e})()]}})}}),null),I(d,n(yN,{id:`context`,title:`Context`,get children(){return n(u,{get when(){return e.summary?.context},get fallback(){return(()=>{var t=YM();return I(t,()=>e.loading?`Loading…`:`No usage reported yet.`),t})()},children:e=>[(()=>{var t=eN(),n=t.firstChild;return D(r=>{var i=e().percent??0,a=`${e().percent??0}%`,o=(e().percent??0)>80?`hot`:``;return i!==r.e&&L(t,`aria-valuenow`,r.e=i),a!==r.t&&Se(n,`width`,r.t=a),o!==r.a&&G(n,r.a=o),r},{e:void 0,t:void 0,a:void 0}),t})(),(()=>{var t=tN(),n=t.firstChild,r=n.nextSibling;return r.firstChild,I(n,(()=>{var t=V(()=>e().percent!==void 0);return()=>t()?`${e().percent}%`:bN(e().used)})()),I(r,(()=>{var t=V(()=>!!e().limit);return()=>t()?`${bN(e().used)} / ${bN(e().limit)} tokens`:`tokens`})(),null),I(r,(()=>{var t=V(()=>!!e().model);return()=>t()?` · ${e().model}`:``})(),null),t})()]})}}),null),I(d,n(yN,{id:`mcp`,get title(){return l()},label:`MCP servers`,get children(){return n(u,{get when(){return e.summary?.mcp?.length},get fallback(){return(()=>{var t=YM();return I(t,()=>e.loading?`Loading…`:`No MCP servers.`),t})()},get children(){var t=KM();return I(t,n(o,{get each(){return e.summary.mcp},children:e=>(()=>{var t=nN(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling;return I(r,()=>e.name),I(i,()=>e.status.replace(`_`,` `)),D(r=>{var i=e.error??e.status,a=`mcp-dot ${e.status}`;return i!==r.e&&L(t,`title`,r.e=i),a!==r.t&&G(n,r.t=a),r},{e:void 0,t:void 0}),t})()})),t}})}}),null),I(d,n(yN,{id:`changes`,title:`Changes`,domID:`rail-changes`,get extra(){return n(u,{get when(){return e.summary?.changes},children:e=>(()=>{var t=rN(),n=t.firstChild;n.firstChild;var r=n.nextSibling.nextSibling;return r.firstChild,I(n,()=>e().additions,null),I(r,()=>e().deletions,null),t})()})},get children(){return n(u,{get when(){return e.summary?.changes},get fallback(){return(()=>{var t=YM();return I(t,(()=>{var t=V(()=>!!e.loading);return()=>t()?`Loading…`:e.summaryError||`No working-tree changes reported (not a git repository, or OpenCode is still warming up).`})()),t})()},children:t=>n(u,{get when(){return t().files.length},get fallback(){return aN()},get children(){return[(()=>{var r=iN();return I(r,n(o,{get each(){return t().files},children:t=>(()=>{var n=oN(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild,s=a.nextSibling.firstChild;s.firstChild;var c=s.nextSibling.nextSibling;return c.firstChild,r.$$click=()=>e.onFile(t.file),I(i,()=>t.status[0].toUpperCase()),I(o,()=>t.file),I(s,()=>t.additions,null),I(c,()=>t.deletions,null),D(e=>{var n=t.file,a=`file-status ${t.status}`;return n!==e.e&&L(r,`title`,e.e=n),a!==e.t&&G(i,e.t=a),e},{e:void 0,t:void 0}),n})()})),r})(),n(u,{get when(){return gN(t())},children:e=>(()=>{var t=sN(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,I(t,e,n),I(t,()=>e()===1?`file`:`files`,r),t})()})]}})})}}),null),d})()}function SN(e){let[t]=f(()=>e.file,async t=>z(`${N(e.sessionID)}/diff?file=${B(t)}`)),[r,i]=x(!1);return(()=>{var a=uN(),s=a.firstChild,c=s.firstChild,l=c.nextSibling,d=l.firstChild,f=s.nextSibling;return I(s,n(H,{name:`diff`}),c),c.addEventListener(`change`,t=>e.onFile(t.currentTarget.value)),I(c,n(o,{get each(){return e.files},children:e=>(()=>{var t=dN();return t.value=e,I(t,e),t})()})),I(s,n(u,{get when(){return t()},children:e=>(()=>{var t=rN(),n=t.firstChild;n.firstChild;var r=n.nextSibling.nextSibling;return r.firstChild,I(n,()=>e().additions,null),I(r,()=>e().deletions,null),t})()}),l),d.addEventListener(`change`,e=>i(e.currentTarget.checked)),I(s,n(R,{icon:`close`,label:`Close diff`,get onClick(){return e.onClose}}),null),I(f,n(u,{get when(){return!t.loading},get fallback(){return fN()},get children(){return n(u,{get when(){return!t.error},get fallback(){return(()=>{var e=pN();return I(e,(()=>{var e=V(()=>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(u,{get when(){return t()?.patch},get fallback(){return mN()},get children(){return[(()=>{var e=cN(),r=e.firstChild;return I(r,n(o,{get each(){return xM(t().patch).filter(e=>e.type!==`meta`)},children:e=>(()=>{var t=hN(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.firstChild;return I(n,()=>e.oldNo??``),I(r,()=>e.newNo??``),I(a,(()=>{var t=V(()=>e.type===`add`);return()=>t()?`+`:e.type===`del`?`−`:` `})()),I(i,()=>e.text,null),D(()=>G(t,e.type)),t})()})),e})(),n(u,{get when(){return t().truncated},get children(){return lN()}})]}})}})}})),D(t=>{var n=`Changes in ${e.file}`,i=`diff-body${r()?` wrap`:``}`;return n!==t.e&&L(a,`aria-label`,t.e=n),i!==t.t&&G(f,t.t=i),t},{e:void 0,t:void 0}),D(()=>c.value=e.file),D(()=>d.checked=r()),a})()}P([`click`]);function CN(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 wN(e,t){return e&&(e.type===`number`||e.type===`integer`)&&typeof t==`string`&&t.trim()?Number(t):typeof t==`string`?t.trim():t}function TN(e,t){let n=new Map(e.map(e=>[e.key,e]));return e.filter(e=>(e.when??[]).every(e=>{let r=wN(n.get(e.key),t[e.key])===e.value;return e.op===`eq`?r:!r}))}var EN=e=>typeof e==`string`?e.trim():``;function DN(e,t){let n={};for(let r of TN(e,t)){let e=ON(r,t[r.key]);e&&(n[r.key]=e)}return n}function ON(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=EN(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=EN(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 kN(e,t){let n={};for(let r of TN(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=EN(e);if(!t)continue;n[r.key]=r.type===`number`||r.type===`integer`?Number(t):t}}}return n}var AN=q(`<p class="muted small"data-answer-unavailable> can't take this answer from the hub; answer it in the terminal.`),jN=q(`<p class="blocker-recommendation small"data-recommendation>`),MN=q(`<p class=blocker-text>`),NN=q(`<div role=group><p class=blocker-head><strong>`),PN=q(`<p class="muted small">This question has nothing to fill in here; answer it in the terminal.`),FN=q(`<p class="answered-by small muted"data-answered-by>`),IN=q(`<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`),LN=q(`<form class=form-card novalidate><fieldset><div class=row><button type=submit class="btn small primary"></button><button type=button class="btn small">Dismiss`),RN=q(`<p class="field-error small"role=alert>`),zN=q(`<div>`),BN=q(`<span class=field-title>`),VN=q(`<span class="field-desc muted small">`),HN=q(`<a class="btn small"target=_blank rel="noopener noreferrer">Open link`),UN=q(`<label class=check><input type=checkbox>`),WN=q(`<input type=text placeholder="Other (comma separated)">`),GN=q(`<div role=group class=choice-group>`),KN=q(`<input type=text placeholder="Type your own answer">`),qN=q(`<div role=radiogroup class=choice-group>`),JN=q(`<label class=text-field>`),YN=q(`<input type=text>`),XN=q(`<span class="muted small"> — `),ZN=q(`<label class=choice><input type=checkbox><span>`),QN=q(`<label class=choice><input type=radio><span>`);function $N(t,n){return!(t instanceof e)||t.status!==409||t.code!==`gone`?!1:(K(`Already answered or expired`),n(),!0)}function eP(e){let[t,r]=x(!1),i=()=>e.blocker,a=()=>i().sessionID&&i().sessionID!==e.rootID?` (${i().sessionTitle||`subagent`})`:``,o=()=>i().kind===`permission`?`Permission request`:`Question`;return n(u,{get when(){return!t()},get children(){var t=NN(),s=t.firstChild,c=s.firstChild;return I(c,(()=>{var e=V(()=>i().kind===`permission`);return()=>e()?`Permission`:i().question?`Question`:`Form`})()),I(s,a,null),I(t,n(ee,{get fallback(){return PN()},get children(){return[n(A,{get when(){return e.canAnswer===!1},get children(){return[n($h,{get class(){return`blocker-text${i().kind===`permission`?` mono`:``}`},get text(){return i().summary},what:`the request`,get reveal(){return i().kind===`permission`}}),(()=>{var t=AN(),n=t.firstChild;return I(t,()=>e.harnessName??`This harness`,n),t})()]}}),n(A,{get when(){return i().kind===`permission`},get children(){return[n($h,{class:`blocker-text mono`,get text(){return i().summary},what:`the request`,reveal:!0}),n(u,{get when(){return Yr(i().recommendation,Mu)},get children(){var e=jN();return I(e,()=>Yr(i().recommendation,Mu)),e}}),n(tP,{get sessionID(){return e.sessionID},get blocker(){return i()},onGone:()=>r(!0)})]}}),n(A,{get when(){return V(()=>i().kind===`form`)()&&i().fields?.length},get children(){return[n(u,{get when(){return!i().question||i().summary!==`Questions`},get children(){var e=MN();return I(e,()=>i().summary),e}}),n(nP,{get sessionID(){return e.sessionID},get blocker(){return i()},get fields(){return i().fields},onGone:()=>r(!0)})]}})]}}),null),I(t,n(u,{get when(){return Br(_u(),i().id,Mu,Cu)},children:e=>(()=>{var t=FN();return I(t,()=>e().text),D(()=>L(t,`title`,e().title)),t})()}),null),D(e=>{var n=`card blocker ${i().kind}`,r=`${o()}: ${i().summary}`;return n!==e.e&&G(t,e.e=n),r!==e.t&&L(t,`aria-label`,e.t=r),e},{e:void 0,t:void 0}),t}})}function tP(e){let[t,n]=x(!1),r=async t=>{n(!0);try{await W(`${N(e.sessionID)}/permission`,{method:`POST`,json:{requestID:e.blocker.id,decision:t}}),K(t===`reject`?`Denied`:`Allowed`)}catch(t){$N(t,e.onGone)||K(tj(t)??U(t),`err`),n(!1)}};return(()=>{var e=IN(),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`),D(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 nP(e){let[t,r]=x(CN(e.fields)),[i,a]=x({}),[s,c]=x(!1),[l,d]=x(!1),f=T((n=[])=>{let r=TN(e.fields,t()).map(e=>e.key);return r.length===n.length&&r.every((e,t)=>e===n[t])?n:r}),p=t=>e.fields.find(e=>e.key===t),m=(e,t)=>{r(n=>({...n,[e]:t})),i()[e]&&a(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e)))},h=async(t,n)=>{c(!0);try{await W(`${N(e.sessionID)}/form`,{method:`POST`,json:{formID:e.blocker.id,...t}}),d(!0),K(n)}catch(t){$N(t,e.onGone)||K(tj(t)??U(t),`err`),c(!1)}},g=n=>{n.preventDefault();let r=DN(e.fields,t());if(a(r),Object.keys(r).length)return;let i=kN(e.fields,t());e.blocker.question&&!Object.values(i).some(e=>Array.isArray(e)?e.length>0:e!==``&&e!==!1)?K(`Pick or type an answer first (Dismiss skips the questions)`,`err`):h({answer:i},`Answer sent`)},_=()=>s()||l();return(()=>{var r=LN(),a=r.firstChild,s=a.firstChild,c=s.firstChild,d=c.nextSibling;return r.addEventListener(`submit`,g),I(a,n(o,{get each(){return f()},children:r=>n(u,{get when(){return p(r)},children:a=>(()=>{var o=zN();return L(o,`data-key`,r),I(o,n(rP,{get field(){return a()},get value(){return t()[r]},onChange:e=>m(r,e),get formID(){return e.blocker.id}}),null),I(o,n(u,{get when(){return i()[r]},get children(){var e=RN();return I(e,()=>i()[r]),e}}),null),D(()=>G(o,`form-field ${a().type}`)),o})()})}),s),I(c,()=>l()?`Sent`:`Submit`),d.$$click=()=>void h({cancel:!0},`Dismissed`),D(()=>a.disabled=_()),r})()}function rP(e){let t=()=>e.field,r=()=>`f-${e.formID}-${t().key}`,i=()=>t().title||t().key,a=()=>typeof e.value==`string`?e.value:``,s=()=>Array.isArray(e.value)?e.value:[],c=()=>new Set((t().options??[]).map(e=>e.value)),l=()=>[(()=>{var e=BN();return I(e,i,null),I(e,()=>t().required?` *`:``,null),e})(),n(u,{get when(){return t().description},get children(){var e=VN();return I(e,()=>t().description),e}})];return n(ee,{get children(){return[n(A,{get when(){return t().type===`external`},get children(){return[n(l,{}),(()=>{var e=HN();return D(()=>L(e,`href`,t().url)),e})()]}}),n(A,{get when(){return t().type===`boolean`},get children(){var t=UN(),r=t.firstChild;return r.addEventListener(`change`,t=>e.onChange(t.currentTarget.checked)),I(t,n(l,{}),null),D(()=>r.checked=e.value===!0),t}}),n(A,{get when(){return t().type===`multiselect`},get children(){var r=GN();return I(r,n(l,{}),null),I(r,n(o,{get each(){return t().options??[]},children:t=>(()=>{var r=ZN(),i=r.firstChild,a=i.nextSibling;return i.addEventListener(`change`,n=>e.onChange(n.currentTarget.checked?[...s(),t.value]:s().filter(e=>e!==t.value))),I(a,()=>t.label),I(r,n(u,{get when(){return t.description},get children(){var e=XN();return e.firstChild,I(e,()=>t.description,null),e}}),null),D(()=>i.checked=s().includes(t.value)),r})()}),null),I(r,n(u,{get when(){return t().custom},get children(){var t=WN();return t.addEventListener(`change`,t=>e.onChange([...s().filter(e=>c().has(e)),...t.currentTarget.value.split(`,`).map(e=>e.trim()).filter(Boolean)])),D(()=>L(t,`aria-label`,`${i()}: other`)),D(()=>t.value=s().filter(e=>!c().has(e)).join(`, `)),t}}),null),D(()=>L(r,`aria-label`,i())),r}}),n(A,{get when(){return V(()=>t().type===`string`)()&&t().options?.length},get children(){var s=qN();return I(s,n(l,{}),null),I(s,n(o,{get each(){return t().options??[]},children:t=>(()=>{var i=QN(),o=i.firstChild,s=o.nextSibling;return o.addEventListener(`change`,()=>e.onChange(t.value)),I(s,()=>t.label),I(i,n(u,{get when(){return t.description},get children(){var e=XN();return e.firstChild,I(e,()=>t.description,null),e}}),null),D(()=>L(o,`name`,r())),D(()=>o.checked=a()===t.value),i})()}),null),I(s,n(u,{get when(){return t().custom},get children(){var t=KN();return t.$$input=t=>e.onChange(t.currentTarget.value),D(()=>L(t,`aria-label`,`${i()}: your own answer`)),D(()=>t.value=c().has(a())?``:a()),t}}),null),D(()=>L(s,`aria-label`,i())),s}}),n(A,{when:!0,get children(){return[(()=>{var e=JN();return I(e,n(l,{})),D(()=>L(e,`for`,r())),e})(),(()=>{var n=YN();return n.$$input=t=>e.onChange(t.currentTarget.value),D(e=>{var i=r(),a=t().type===`number`||t().type===`integer`?`decimal`:void 0,o=t().placeholder??``;return i!==e.e&&L(n,`id`,e.e=i),a!==e.t&&L(n,`inputmode`,e.t=a),o!==e.a&&L(n,`placeholder`,e.a=o),e},{e:void 0,t:void 0,a:void 0}),D(()=>n.value=a()),n})()]}})]}})}P([`click`,`input`]);var iP=/^(\s{0,3})(`{3,}|~{3,})\s*([^\s`]*)/,aP=/^\s{0,3}(#{1,6})(?:\s+(.*))?$/,oP=/^\s{0,3}(={2,}|-{3,})\s*$/,sP=/^\s{0,3}([-*_])(\s*\1){2,}\s*$/,cP=/^\s{0,3}>\s?(.*)$/,lP=/^(\s*)([-*+]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/,uP=/^\[([ xX])\](?:\s+(.*))?$/,dP=/^:?-+:?$/,fP=e=>e.length-e.trimStart().length,pP=(e,t)=>e.slice(Math.min(t,fP(e))),mP=e=>iP.test(e),hP=e=>mP(e)||aP.test(e)||sP.test(e)||cP.test(e)||lP.test(e);function gP(e,t={}){let n=String(e??``).replace(/\r\n?/g,`
|
|
23
|
-
`).split(`
|
|
24
|
-
`).map(e=>e.replace(/^[ \t]+/,e=>e.replace(/\t/g,` `))),r=!!t.streaming,i=_P(n,{streaming:r},!0).blocks;return wP(i,r?CP(i):void 0)}function _P(e,t,n){let r=[],i=[],a=!1,o=!1,s=!1,c=()=>{a&&o&&(s=!0),a=!1,o=!0},l=()=>{i.length&&r.push({type:`paragraph`,text:i.join(`
|
|
25
|
-
`)}),i=[]};for(let o=0;o<e.length;o++){let s=e[o];if(!s.trim()){l(),a=!0;continue}let u=iP.exec(s);if(u){l(),c();let[,t,n]=u,i=[];for(o++;o<e.length;o++){let r=/^\s*(`{3,}|~{3,})\s*$/.exec(e[o]);if(r&&r[1][0]===n[0]&&r[1].length>=n.length)break;i.push(pP(e[o],t.length))}r.push({type:`code`,lang:u[3]??``,text:i.join(`
|
|
26
|
-
`)});continue}if(i.length){let e=oP.exec(s);if(e){r.push({type:`heading`,level:e[1][0]===`=`?1:2,text:i.join(`
|
|
27
|
-
`)}),i=[];continue}}let d=aP.exec(s);if(d){l(),c(),r.push({type:`heading`,level:d[1].length,text:(d[2]??``).replace(/(^|\s+)#+\s*$/,``).trim()});continue}if(sP.test(s)){l(),c(),r.push({type:`rule`});continue}let f=SP(e,o,t.streaming&&n);if(f){l(),c(),r.push(f.block),o=f.end-1;continue}if(cP.test(s)){l(),c();let i=[],a=o;for(;a<e.length;a++){let t=cP.exec(e[a]);if(t)i.push(t[1]);else if(e[a].trim()&&i.at(-1)?.trim()&&!hP(e[a]))i.push(e[a]);else break}r.push({type:`quote`,blocks:_P(i,t,n&&a===e.length).blocks}),o=a-1;continue}let p=lP.exec(s);if(p&&(!i.length||vP(p[2]))){l(),c();let i=yP(e,o,t,n);r.push(i.block),o=i.end-1,i.trailingBlank&&(a=!0)}else i.length||c(),i.push(s.trim())}return l(),{blocks:r,loose:s,trailingBlank:a}}var vP=e=>!/\d/.test(e)||/^0*1[.)]$/.test(e);function yP(e,t,n,r){let i=lP.exec(e[t]),a=/\d/.test(i[2]),o=i[2].slice(-1),s=[],c=!1,l=!1,u=t;for(;u<e.length;){let t=lP.exec(e[u]);if(!t||/\d/.test(t[2])!==a||t[2].slice(-1)!==o)break;s.length&&l&&(c=!0);let i=t[1].length,d=t[3]?.replace(/\t/g,` `).length??0,f=i+t[2].length+(d>=1&&d<=4?d:1),p=[d>4?`${` `.repeat(d-1)}${t[4]??``}`.trim():t[4]??``],m,h=e=>{if(m){let t=/^\s*(`{3,}|~{3,})\s*$/.exec(e);t&&t[1][0]===m[0]&&t[1].length>=m.length&&(m=void 0)}else{let t=iP.exec(e);t&&(m=t[2])}};h(p[0]);let g=u+1,_=0;for(;g<e.length;g++){let t=e[g];if(!t.trim()){_++;continue}let n=fP(t),r;if(r=m?!0:_?n>=Math.min(f,i+2):n>=f?!0:lP.test(t)?n>=i+2:n>i||!hP(t)&&!mP(p.at(-1)),!r)break;for(;_;_--)p.push(``);let a=pP(t,f);p.push(a),h(a)}l=_>0;let v=uP.exec(p[0]),y=_P(v?[v[2]??``,...p.slice(1)]:p,n,r&&g===e.length);y.loose&&(c=!0),s.push({...v?{checked:v[1]!==` `}:{},blocks:y.blocks}),u=g}let d=a?Number(i[2].slice(0,-1)):void 0;return{block:{type:`list`,ordered:a,...a?{start:d}:{},loose:c,items:s},end:u,trailingBlank:l}}function bP(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 xP=e=>{let t=e.trim(),n=t.startsWith(`:`),r=t.length>1&&t.endsWith(`:`);return n&&r?`center`:r?`right`:n?`left`:null};function SP(e,t,n){let r=e[t];if(!r.includes(`|`))return;let i=bP(r),a=e[t+1],o;if(a!==void 0){let r=bP(a),s=t+1===e.length-1;r.length===i.length&&r.every(e=>dP.test(e))?o=r.map(xP):s&&/^[\s|:-]*$/.test(a)&&(a.includes(`-`)||n)&&a.includes(`|`)&&r.length<=i.length&&(o=i.map((e,t)=>r[t]&&dP.test(r[t])?xP(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(`|`)||mP(t)||cP.test(t)||aP.test(t))break;s.push(bP(t).slice(0,i.length))}return{block:{type:`table`,align:o,head:i,rows:s},end:Math.min(c,e.length)}}function CP(e){let t=e.at(-1);if(t){if(t.type===`paragraph`||t.type===`heading`)return{node:t};if(t.type===`quote`)return CP(t.blocks);if(t.type===`list`)return CP(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 wP(e,t){let n=e=>t?.node===e;return e.map(e=>{switch(e.type){case`paragraph`:return{type:`paragraph`,children:RP(e.text,{streaming:n(e)})};case`heading`:return{type:`heading`,level:e.level,children:RP(e.text,{streaming:n(e)})};case`quote`:return{type:`quote`,blocks:wP(e.blocks,t)};case`list`:return{...e,items:e.items.map(e=>({...e.checked===void 0?{}:{checked:e.checked},blocks:wP(e.blocks,t)}))};case`table`:{let r=(r,i,a)=>RP(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 TP(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 EP=/[!-/:-@[-`{-~]/,DP=/\s/,OP=/[\p{L}\p{N}_]/u,kP={"**":`strong`,__:`strong`,"~~":`del`,"==":`mark`},AP=(e,t,n)=>{let r=0;for(;e[t+r]===n;)r++;return r};function jP(e,t,n){for(let r=t;r<e.length;r++){if(e[r]!=="`")continue;let t=AP(e,r,"`");if(t===n)return r;r+=t-1}return-1}function MP(e,t,n,r){for(let i=t;i<=e.length-n.length;i++){let t=e[i];if(t===`\\`)i++;else if(t==="`"&&n!=="`"){let t=AP(e,i,"`"),n=jP(e,i+t,t);i=(n>=0?n:i)+t-1}else if(e.startsWith(n,i)&&r(i))return i}return-1}function NP(e,t){let n=0;for(let r=t+1;r<e.length;r++){let t=e[r];if(t===`\\`)r++;else if(t==="`"){let t=AP(e,r,"`"),n=jP(e,r+t,t);r=(n>=0?n:r)+t-1}else if(t===`[`)n++;else if(t===`]`){if(n===0)return r;n--}}return-1}function PP(e,t){let n=0;for(let r=t;r<e.length;r++)if(e[r]===`(`)n++;else if(e[r]===`)`){if(n===0)return r;n--}else if(e[r]===`
|
|
28
|
-
`)return-1;return-1}function FP(e){let t=e.trim();return t.startsWith(`<`)?t.slice(1,t.indexOf(`>`)>0?t.indexOf(`>`):void 0):t.split(/\s+/)[0]??``}var IP=e=>e.map(e=>e.type===`text`||e.type===`code`?e.text:e.type===`image`?e.alt:e.type===`br`?` `:IP(e.children)).join(``);function LP(e,t){let n=/^https?:\/\/[^\s<>]+/i.exec(e.slice(t,t+2048));if(!n)return;let r=n[0];for(;;){let e=r.at(-1);if(/[.,:;!?'"*_~]/.test(e))r=r.slice(0,-1);else if(e===`)`&&(r.match(/\(/g)?.length??0)<(r.match(/\)/g)?.length??0))r=r.slice(0,-1);else if(e===`]`&&(r.match(/\[/g)?.length??0)<(r.match(/\]/g)?.length??0))r=r.slice(0,-1);else break}return/^https?:\/\/[^/]/i.test(r)?r:void 0}function RP(e,t={}){let n=String(e??``),r=!!t.streaming,i=[],a=``,o=(...e)=>{a&&i.push({type:`text`,text:a}),a=``,i.push(...e)},s=0;for(;s<n.length;){let e=n[s],i=n[s+1];if(e===`\\`){if(i===`
|
|
29
|
-
`){o({type:`br`}),s+=2;continue}if(i!==void 0&&EP.test(i)){a+=i,s+=2;continue}}if(e===`
|
|
30
|
-
`){a=a.replace(/ +$/,``),o({type:`br`}),s++;continue}if(e==="`"){let e=AP(n,s,"`"),t=jP(n,s+e,e);if(t>=0||r){let r=n.slice(s+e,t>=0?t:void 0);r.length>2&&r.startsWith(` `)&&r.endsWith(` `)&&r.trim()&&(r=r.slice(1,-1)),o({type:`code`,text:r}),s=t>=0?t+e:n.length;continue}a+=n.slice(s,s+e),s+=e;continue}let c=n.slice(s,s+2),l=kP[c];if(l&&i!==void 0&&n[s+2]!==void 0&&!DP.test(n[s+2])&&n[s+2]!==e&&(e!==`_`||s===0||!OP.test(n[s-1]))){let i=MP(n,s+3,c,t=>!DP.test(n[t-1])&&(e!==`_`||!OP.test(n[t+2]??``)));if(i>0||r){o({type:l,children:RP(n.slice(s+2,i>0?i:void 0),{inLink:t.inLink,streaming:i<0})}),s=i>0?i+2:n.length;continue}}if((e===`*`||e===`_`)&&i!==void 0&&i!==e&&!DP.test(i)&&(e===`*`||s===0||!OP.test(n[s-1]))){let i=MP(n,s+1,e,t=>n[t+1]===e||n[t-1]===e?!1:!DP.test(n[t-1])&&(e!==`_`||!OP.test(n[t+1]??``)));if(i>s+1||r){o({type:`em`,children:RP(n.slice(s+1,i>s?i:void 0),{inLink:t.inLink,streaming:i<0})}),s=i>s?i+1:n.length;continue}}let u=e===`!`&&i===`[`;if(e===`[`||u){let e=u?s+1:s,i=NP(n,e);if(i>0&&n[i+1]===`(`){let a=PP(n,i+2),c=RP(n.slice(e+1,i),{inLink:!0});if(a>0){let e=TP(FP(n.slice(i+2,a)));u?o({type:`image`,alt:IP(c),...e?{href:e}:{}}):e&&!t.inLink?o({type:`link`,href:e,children:c}):o(...c),s=a+1;continue}if(r&&!n.slice(i).includes(`
|
|
31
|
-
`)){o(...u?[{type:`text`,text:IP(c)}]:c),s=n.length;continue}}}if(e===`<`&&!t.inLink){let e=/^<([a-zA-Z][a-zA-Z0-9+.-]{1,31}:[^\s<>]*)>/.exec(n.slice(s,s+2048)),t=/^<([^\s<>@\\]+@[^\s<>@\\]+\.[^\s<>@\\]+)>/.exec(n.slice(s,s+512)),r=e??t;if(r){let t=TP(e?r[1]:`mailto:${r[1]}`);t?o({type:`link`,href:t,children:[{type:`text`,text:r[1]}]}):a+=r[0],s+=r[0].length;continue}}if((e===`h`||e===`H`)&&!t.inLink&&(s===0||!/[\p{L}\p{N}_/]/u.test(n[s-1]))&&n.slice(s-2,s)!==`](`){let e=LP(n,s),t=e&&TP(e);if(e&&t){o({type:`link`,href:t,children:[{type:`text`,text:e}]}),s+=e.length;continue}}a+=e,s++}return a&&i.push({type:`text`,text:a}),i}var zP=`modulepreload`,BP=function(e){return`/`+e},VP={},HP=function(e){return e.pathname.endsWith(`.css`)},UP=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw e[t]=void 0,n});return e[t]=i,i},WP=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=BP(t,n);let r=s(t),i=HP(r);return UP(VP,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let t=document.createElement(`link`);if(t.rel=i?`stylesheet`:zP,i||(t.as=`script`),t.crossOrigin=``,t.href=r.href,a&&t.setAttribute(`nonce`,a),document.head.appendChild(t),i)return new Promise((e,n)=>{t.addEventListener(`load`,e),t.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${r}`)))})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},GP=q(`<br>`),KP=q(`<code class=inline-code>`),qP=q(`<a rel="noopener noreferrer">`),JP=q(`<a class=md-image target=_blank rel="noopener noreferrer"title="Image (opens in a new tab)">`),YP=q(`<span class=md-image>`),XP=q(`<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>`),ZP=q(`<span>`),QP=q(`<hr>`),$P=q(`<p>`),eF=q(`<input type=checkbox disabled>`),tF=q(`<li>`),nF=q(`<blockquote>`),rF=q(`<div class=table-wrap><table><thead><tr></tr></thead><tbody>`),iF=q(`<th>`),aF=q(`<tr>`),oF=q(`<td>`),sF=q(`<div class=md>`),[cF,lF]=x(),uF=!1;function dF(){uF||(uF=!0,WP(()=>import(`./highlight-y4rJE6Tt.js`).then(e=>lF({run:e.highlight,languageOf:e.languageOf}),()=>uF=!1),[]))}var fF=65536;function pF(e,t){dF();let n=cF();return!n||!e||t.length>fF||!n.languageOf(e)?[{text:t}]:n.run(t,e)}function mF(e){return n(We,{get each(){return e.nodes},children:e=>n(ee,{get children(){return[n(A,{get when(){return V(()=>e().type===`text`)()&&e()},children:e=>V(()=>e().text)}),n(A,{get when(){return e().type===`br`},get children(){return GP()}}),n(A,{get when(){return V(()=>e().type===`code`)()&&e()},children:e=>(()=>{var t=KP();return I(t,()=>e().text),t})()}),n(A,{get when(){return V(()=>e().type===`link`)()&&e()},children:e=>(()=>{var t=qP();return I(t,n(mF,{get nodes(){return e().children}})),D(n=>{var r=e().href,i=e().href.startsWith(`/`)?void 0:`_blank`;return r!==n.e&&L(t,`href`,n.e=r),i!==n.t&&L(t,`target`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(A,{get when(){return V(()=>e().type===`image`)()&&e()},children:e=>n(u,{get when(){return e().href},get fallback(){return(()=>{var t=YP();return I(t,()=>e().alt||`image`),t})()},get children(){var t=JP();return I(t,()=>e().alt||`image`),D(()=>L(t,`href`,e().href)),t}})}),n(A,{get when(){return V(()=>`children`in e())()&&e()},children:e=>n(Re,{get component(){return{strong:`strong`,em:`em`,del:`del`,mark:`mark`}[e().type]??`span`},get children(){return n(mF,{get nodes(){return e().children}})}})})]}})})}async function hF(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 gF(e){let[t,r]=x(!1),[i,a]=x(!1),o;j(()=>clearTimeout(o)),dF();let s=T(()=>{let t=cF();return!t||!e.lang||e.text.length>fF||!t.languageOf(e.lang)?[{text:e.text}]:t.run(e.text,e.lang)}),c=()=>e.lang||`text`;return(()=>{var l=XP(),d=l.firstChild,f=d.firstChild,p=f.nextSibling,m=p.nextSibling,h=d.nextSibling,g=h.firstChild;return I(f,c),p.$$click=()=>a(!i()),I(p,()=>i()?`No wrap`:`Wrap`),m.$$click=async()=>{await hF(e.text)&&(r(!0),clearTimeout(o),o=setTimeout(()=>r(!1),1500))},I(m,()=>t()?`Copied`:`Copy`),I(g,n(We,{get each(){return s()},children:e=>n(u,{get when(){return e().kind},get fallback(){return e().text},get children(){var t=ZP();return I(t,()=>e().text),D(()=>G(t,`tok-${e().kind}`)),t}})})),D(n=>{var r=`code-block${i()?` wrap`:``}`,a=i(),o=i()?`Scroll long lines`:`Wrap long lines`,s=t()?`Copied`:`Copy ${c()} code`,u=e.lang||void 0;return r!==n.e&&G(l,n.e=r),a!==n.t&&L(p,`aria-pressed`,n.t=a),o!==n.a&&L(p,`title`,n.a=o),s!==n.o&&L(m,`aria-label`,n.o=s),u!==n.i&&L(h,`data-lang`,n.i=u),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),l})()}var _F={left:`left`,center:`center`,right:`right`};function vF(e){return n(We,{get each(){return e.blocks},children:e=>n(ee,{get children(){return[n(A,{get when(){return V(()=>e().type===`paragraph`)()&&e()},children:e=>(()=>{var t=$P();return I(t,n(mF,{get nodes(){return e().children}})),t})()}),n(A,{get when(){return V(()=>e().type===`heading`)()&&e()},children:e=>n(Re,{get component(){return`h${Math.min(6,e().level+2)}`},get children(){return n(mF,{get nodes(){return e().children}})}})}),n(A,{get when(){return V(()=>e().type===`list`)()&&e()},children:e=>n(Re,{get component(){return e().ordered?`ol`:`ul`},get start(){return V(()=>!!(e().ordered&&e().start!==1))()?e().start:void 0},get class(){return e().loose?`loose`:void 0},get children(){return n(We,{get each(){return e().items},children:e=>(()=>{var t=tF();return I(t,n(u,{get when(){return e().checked!==void 0},get children(){var t=eF();return D(()=>L(t,`aria-label`,e().checked?`Done`:`Not done`)),D(()=>t.checked=e().checked),t}}),null),I(t,n(vF,{get blocks(){return e().blocks}}),null),D(()=>G(t,e().checked===void 0?void 0:`task`)),t})()})}})}),n(A,{get when(){return V(()=>e().type===`code`)()&&e()},children:e=>n(gF,{get lang(){return e().lang},get text(){return e().text}})}),n(A,{get when(){return V(()=>e().type===`quote`)()&&e()},children:e=>(()=>{var t=nF();return I(t,n(vF,{get blocks(){return e().blocks}})),t})()}),n(A,{get when(){return V(()=>e().type===`table`)()&&e()},children:e=>(()=>{var t=rF(),r=t.firstChild.firstChild,i=r.firstChild,a=r.nextSibling;return I(i,n(We,{get each(){return e().head},children:(t,r)=>(()=>{var i=iF();return I(i,n(mF,{get nodes(){return t()}})),D(t=>He(i,e().align[r]?{"text-align":_F[e().align[r]]}:void 0,t)),i})()})),I(a,n(We,{get each(){return e().rows},children:t=>(()=>{var r=aF();return I(r,n(We,{get each(){return t()},children:(t,r)=>(()=>{var i=oF();return I(i,n(mF,{get nodes(){return t()}})),D(t=>He(i,e().align[r]?{"text-align":_F[e().align[r]]}:void 0,t)),i})()})),r})()})),t})()}),n(A,{get when(){return e().type===`rule`},get children(){return QP()}})]}})})}function yF(e){let t=T(()=>gP(e.text,{streaming:e.streaming}));return(()=>{var e=sF();return I(e,n(vF,{get blocks(){return t()}})),e})()}P([`click`]);var bF=q(`<a class=msg-image target=_blank rel=noopener><img loading=lazy>`,!0,!1,!1),xF=q(`<span class=file-chip> `),SF=q(`<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>`),CF=q(`<div class=msg-images>`),wF=q(`<div class=pill>`),TF=q(`<p class="msg-note muted small"data-answered-note>`),EF=q(`<div><div class=user-body>`),DF=q(`<div class=msg-tools role=toolbar aria-label="Copy, fork, revert">`),OF=q(`<span>`),kF=q(`<div class=transcript aria-label=Conversation>`),AF=q(`<div>`),jF=q(`<p class="note sys turn-denied">`),MF=q(`<span class=turn-error-status>`),NF=q(`<div class=turn-error-message>`),PF=q(`<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>`),FF=q(`<p><span class=turn-retry-mark aria-hidden=true>↻</span><span>`),IF=q(`<a><span class=sub-mark aria-hidden=true></span><span class=sub-label>Subagent · <strong></strong></span><span class="sub-state muted">`),LF=q(`<span class=spinner>`),RF=q(`<span class=hub-msg-kind>`),zF=q(`<span class="hub-msg-state muted">`),BF=q(`<span class="hub-msg-delivery muted"title="Not delivered into a turn yet: the recipient's harness takes it at its next step">`),VF=q(`<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>`),HF=q(`<div class="fold-body hub-msg-text">`),UF=q(`<div><button type=button class=fold-head><span class=hub-msg-mark aria-hidden=true>⇄</span><span>`),WF=q(`<a>`),GF=q(`<span class="spinner small">`),KF=q(`<div class="fold thought"><button type=button class=fold-head><span>`),qF=q(`<ul class="fold-body tool-list">`),JF=q(`<div><button type=button class=fold-head><span>`),YF=q(`<pre class=code>`),XF=q(`<div class=tool-detail>`),ZF=q(`<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">`),QF=q(`<span class="muted small">Loading full details…`),$F=q(`<span class="error small">`),eI=q(`<span class="muted small">No details for this call yet.`),tI={pending:[`…`,`Sending`],sent:[`✓`,`Sent`],queued:[`◷`,`Queued: the harness takes it at its next step`],heard:[`✓✓`,`Heard by the agent`],failed:[`!`,`Not sent`]};function nI(e){let[t,r]=x(!1);return n(u,{get when(){return V(()=>!!e.image.src)()&&!t()},get fallback(){return(()=>{var t=xF(),r=t.firstChild;return I(t,n(H,{name:`file`}),r),I(t,()=>e.image.name,null),D(()=>L(t,`title`,e.image.mime)),t})()},get children(){var t=bF(),n=t.firstChild;return n.addEventListener(`error`,()=>r(!0)),D(r=>{var i=e.image.src,a=e.image.name,o=e.image.src,s=e.image.name;return i!==r.e&&L(t,`href`,r.e=i),a!==r.t&&L(t,`title`,r.t=a),o!==r.a&&L(n,`src`,r.a=o),s!==r.o&&L(n,`alt`,r.o=s),r},{e:void 0,t:void 0,a:void 0,o:void 0}),t}})}var rI=500;function iI(e){let[t,r]=x(!1),i,a=()=>clearTimeout(i),s=t=>{t.pointerType===`touch`&&e.actions&&(a(),i=setTimeout(()=>r(!0),rI))},c=(e,t)=>()=>{r(!1),e.enabled&&t()};return(()=>{var i=EF(),l=i.firstChild;return pe(i,ce({get class(){return`msg user${t()?` tools-open`:``}`},get"data-key"(){return e.block.key}},()=>e.block.messageID?{"data-message":e.block.messageID}:{},{onPointerDown:s,onPointerUp:a,onPointerCancel:a,onPointerLeave:a,onFocusOut:e=>!e.currentTarget.contains(e.relatedTarget)&&r(!1),onKeyDown:e=>{if(e.key!==`Escape`)return;let n=e.target?.closest?.(`.msg-tools`);(t()||n)&&(r(!1),n&&e.currentTarget.querySelector(`.msg-more`)?.focus(),e.stopPropagation())}}),!1,!0),I(i,n(u,{get when(){return e.actions},get children(){var i=SF();return i.$$click=e=>{let n=!t(),i=e.currentTarget;r(n),n&&e.detail===0&&queueMicrotask(()=>i.closest(`.msg`)?.querySelector(`.msg-tools button`)?.focus())},I(i,n(H,{name:`more`})),D(n=>{var r=t(),a=`msg-tools-${e.block.key}`;return r!==n.e&&L(i,`aria-expanded`,n.e=r),a!==n.t&&L(i,`aria-controls`,n.t=a),n},{e:void 0,t:void 0}),i}}),l),I(l,n(u,{get when(){return e.block.images?.length},get children(){var t=CF();return I(t,n(o,{get each(){return e.block.images},children:e=>n(nI,{image:e})})),t}}),null),I(l,n(u,{get when(){return e.block.text},get children(){var t=wF();return I(t,()=>e.block.text),t}}),null),I(l,n(u,{get when(){return e.block.note},get children(){var t=TF();return I(t,()=>e.block.note),t}}),null),I(l,n(u,{get when(){return e.actions},children:t=>(()=>{var i=DF();return I(i,n(R,{icon:`copy`,label:`Copy`,"data-action":`copy`,onClick:()=>(r(!1),t().onCopy(e.block.text))}),null),I(i,n(u,{get when(){return e.block.messageID},children:r=>[n(R,{icon:`fork`,get label(){return V(()=>!!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 c(t().fork,()=>t().onFork(r(),e.block.text))}}),n(u,{get when(){return t().onForkBeside},children:i=>n(R,{icon:`split`,get label(){return V(()=>!!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 c(t().fork,()=>i()(r(),e.block.text))}})}),n(R,{icon:`undo`,get label(){return V(()=>!!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 c(t().revert,()=>t().onRevert(r(),e.block.text))}})]}),null),D(()=>L(i,`id`,`msg-tools-${e.block.key}`)),i})()}),null),I(i,n(u,{get when(){return e.tick},children:e=>(()=>{var t=OF();return I(t,()=>tI[e()][0]),D(n=>{var r=`tick ${e()}`,i=tI[e()][1],a=tI[e()][1];return r!==n.e&&G(t,n.e=r),i!==n.t&&L(t,`aria-label`,n.t=i),a!==n.a&&L(t,`title`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),i})()}function aI(e){return(()=>{var t=kF();return I(t,n(o,{get each(){return e.blocks},children:t=>n(ee,{get children(){return[n(A,{get when(){return t.type===`user`&&t},children:t=>n(iI,{get block(){return t()},get tick(){return e.ticks[t().key]},get actions(){return e.actions}})}),n(A,{get when(){return t.type===`assistant`&&t},children:e=>(()=>{var t=AF();return I(t,n(yF,{get text(){return e().text},get streaming(){return e().live}})),D(n=>{var r=`msg assistant${e().live?` live`:``}`,i=e().key;return r!==n.e&&G(t,n.e=r),i!==n.t&&L(t,`data-key`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(A,{get when(){return t.type===`thought`&&t},children:t=>n(sI,{get block(){return t()},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})}),n(A,{get when(){return t.type===`tools`&&t},children:t=>n(cI,{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(A,{get when(){return t.type===`message`&&t},children:t=>n(oI,{get block(){return t()},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})}),n(A,{get when(){return t.type===`error`&&t.denied&&t},children:e=>(()=>{var t=jF();return I(t,()=>e().label),D(()=>L(t,`data-key`,e().key)),t})()}),n(A,{get when(){return t.type===`error`&&t},children:e=>(()=>{var t=PF(),r=t.firstChild.nextSibling,i=r.firstChild,a=i.firstChild;return I(a,()=>e().label),I(i,n(u,{get when(){return e().status},get children(){var t=MF();return I(t,()=>e().status),t}}),null),I(r,n(u,{get when(){return e().message},get children(){var t=NF();return I(t,()=>e().message),t}}),null),D(n=>{var r=e().key,i=`Error: ${e().label}`;return r!==n.e&&L(t,`data-key`,n.e=r),i!==n.t&&L(t,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(A,{get when(){return t.type===`retry`&&t},children:e=>{let t=()=>gj(e(),Fe());return(()=>{var n=FF(),r=n.firstChild.nextSibling;return I(r,()=>t().text),D(r=>{var i=`msg turn-retry${t().waiting?` waiting`:``}`,a=e().key;return i!==r.e&&G(n,r.e=i),a!==r.t&&L(n,`data-key`,r.t=a),r},{e:void 0,t:void 0}),n})()}}),n(A,{get when(){return t.type===`subagent`&&t},children:e=>(()=>{var t=IF(),r=t.firstChild,i=r.nextSibling,a=i.firstChild.nextSibling,o=i.nextSibling;return I(r,(()=>{var t=V(()=>e().state===`working`);return()=>t()?LF():`◆`})()),I(a,()=>e().label),I(o,()=>e().state),I(t,n(H,{name:`chevron`,class:`chev`}),null),D(n=>{var r=`subagent ${e().state}`,i=k(e().sessionID),a=e().key;return r!==n.e&&G(t,n.e=r),i!==n.t&&L(t,`href`,n.t=i),a!==n.a&&L(t,`data-key`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})]}})})),t})()}function oI(e){let t=()=>!!e.expanded[e.block.key];return n(u,{get when(){return V(()=>!e.block.primer)()&&!e.block.summary},get fallback(){return(()=>{var r=UF(),i=r.firstChild,a=i.firstChild.nextSibling;return pe(r,ce({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),i.$$click=()=>e.onToggle(e.block.key,!t()),I(a,()=>e.block.summary??e.block.label),I(i,n(H,{name:`chevron`,class:`chev`}),null),I(r,n(u,{get when(){return t()},get children(){var t=HF();return I(t,()=>e.block.text),t}}),null),D(n=>{var r=t(),a=e.block.summary?`Sent by the hub, not by you: show the full update`:void 0;return r!==n.e&&L(i,`aria-expanded`,n.e=r),a!==n.t&&L(i,`title`,n.t=a),n},{e:void 0,t:void 0}),r})()},get children(){var t=VF(),r=t.firstChild,i=r.firstChild,a=i.nextSibling,s=r.nextSibling;return I(i,()=>e.block.direction===`out`?`↗`:`↘`),I(r,n(u,{get when(){return e.block.kind!==`msg`},get children(){var t=RF();return I(t,()=>e.block.kind),t}}),a),I(a,()=>Mn(e.block.label,Mu)),I(r,n(u,{get when(){return e.block.state===`open`||e.block.state===`answered`||e.block.state===`declined`||e.block.state===`expired`},get children(){var t=zF();return I(t,()=>e.block.state),t}}),null),I(r,n(u,{get when(){return e.block.delivery},get children(){var t=BF();return I(t,()=>e.block.delivery),D(()=>L(t,`data-delivery`,e.block.delivery)),t}}),null),I(s,n(u,{get when(){return e.block.parts},get fallback(){return e.block.text},children:e=>n(o,{get each(){return e()},children:e=>e.href?(()=>{var t=WF();return I(t,()=>e.text),D(()=>L(t,`href`,e.href)),t})():e.text})})),D(n=>{var r=`msg hub-msg ${e.block.direction}`,i=e.block.key,o=`Hub ${e.block.kind} ${Mn(e.block.label,Mu)}`,s=e.block.label;return r!==n.e&&G(t,n.e=r),i!==n.t&&L(t,`data-key`,n.t=i),o!==n.a&&L(t,`aria-label`,n.a=o),s!==n.o&&L(a,`title`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t}})}function sI(e){let t=()=>!!e.expanded[e.block.key],r=t=>e.onToggle(e.block.key,t),i=()=>yj(e.block);return(()=>{var a=KF(),o=a.firstChild,s=o.firstChild;return o.$$click=()=>r(!t()),I(o,n(u,{get when(){return e.block.running},get children(){return GF()}}),s),I(s,()=>i().label),I(o,n(H,{name:`chevron`,class:`chev`}),null),I(a,n(u,{get when(){return t()},get children(){var e=AF();return I(e,()=>i().body),D(()=>G(e,`fold-body reasoning${i().muted?` hidden-reasoning`:``}`)),e}}),null),D(n=>{var r=e.block.key,i=t();return r!==n.e&&L(a,`data-key`,n.e=r),i!==n.t&&L(o,`aria-expanded`,n.t=i),n},{e:void 0,t:void 0}),a})()}function cI(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=JF(),s=i.firstChild,c=s.firstChild;return s.$$click=()=>r(!t()),I(s,n(u,{get when(){return e.block.running},get children(){return GF()}}),c),I(c,a),I(s,n(H,{name:`chevron`,class:`chev`}),null),I(i,n(u,{get when(){return t()},get children(){var t=qF();return I(t,n(o,{get each(){return e.block.items},children:t=>n(lI,{row:t,get sessionID(){return e.sessionID},get onDetail(){return e.onDetail},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})})),t}}),null),D(n=>{var r=`fold tools${e.block.failed?` has-failed`:``}`,a=e.block.key,o=t();return r!==n.e&&G(i,n.e=r),a!==n.t&&L(i,`data-key`,n.t=a),o!==n.a&&L(s,`aria-expanded`,n.a=o),n},{e:void 0,t:void 0,a:void 0}),i})()}function lI(e){let t=()=>!!e.expanded[`tool:${e.row.key}`],r=t=>e.onToggle(`tool:${e.row.key}`,t),[i,a]=x(!1),[o,s]=x(``),c=()=>e.row,l=()=>c().completed&&c().at?lo(c().completed-c().at):``,d=async()=>{let n=!t();if(r(n),n&&c().detail===void 0&&c().messageID&&c().partID!==void 0){a(!0),s(``);try{let t=await z(`${N(e.sessionID)}/timeline/messages/${B(c().messageID)}/parts/${B(String(c().partID))}`);e.onDetail(c().key,t.detail)}catch(e){s(U(e))}finally{a(!1)}}},f=()=>typeof c().summary==`string`?c().summary:``;return(()=>{var e=ZF(),r=e.firstChild,a=r.firstChild,s=a.nextSibling,p=s.nextSibling,m=p.nextSibling;return r.$$click=d,I(a,(()=>{var e=V(()=>c().state===`running`);return()=>e()?GF():c().state===`failed`?`✕`:`✓`})()),I(s,()=>c().name??`tool`),I(p,f),I(m,l),I(e,n(u,{get when(){return t()},get children(){var e=XF();return I(e,n(u,{get when(){return!i()},get fallback(){return QF()},get children(){return n(u,{get when(){return!o()},get fallback(){return(()=>{var e=$F();return I(e,o),e})()},get children(){return n(u,{get when(){return c().detail!==void 0||f()||c().error},get fallback(){return eI()},get children(){var e=YF();return I(e,()=>xj(c().detail,{summary:f(),error:c().error})),e}})}})}})),e}}),null),D(n=>{var i=`tool ${c().state??``}`,o=t(),s=c().state??``;return i!==n.e&&G(e,n.e=i),o!==n.t&&L(r,`aria-expanded`,n.t=o),s!==n.a&&L(a,`aria-label`,n.a=s),n},{e:void 0,t:void 0,a:void 0}),e})()}P([`click`]);var uI={profilesPerUser:200,versionsPerProfile:100,skillsPerProfile:32,commandsPerProfile:64,instructionsChars:32e3,skillChars:32e3,commandChars:8e3,versionBytes:524288,projectsPerProfile:16},dI=[`pending`,`applied`,`partial`,`rejected`,`unsupported`,`restart_required`];function fI(e){if(!O(e))return`content must be an object`;if(e.instructions!==void 0&&!v(e.instructions,uI.instructionsChars))return`instructions must be at most ${uI.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,uI.skillsPerProfile,uI.skillChars,`body`,`skills`],[e.commands,uI.commandsPerProfile,uI.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(!O(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),!y(n.description,300))return`${a}.${n.name}.description must be 1–300 characters`;if(!v(n[i],r)||n[i].trim()===``)return`${a}.${n.name}.${i} must be 1–${r} characters`}}if(new TextEncoder().encode(JSON.stringify(e)).length>uI.versionBytes)return`profile version is too large`}function pI(e){if(e===void 0)return;let t=uI.projectsPerProfile;if(!Array.isArray(e)||e.length>t||!e.every(e=>y(e))||new Set(e).size!==e.length)return`projects must be at most ${t} unique project names`}function mI(e){return O(e)?Ie(e.name)?y(e.title)?e.description!==void 0&&!v(e.description,4e3)?`description must be at most ${le} characters`:M(e.tags)??de(e.metadata)??pI(e.projects)??fI(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 hI(e){return Array.isArray(e)?`[${e.map(hI).join(`,`)}]`:O(e)?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${hI(e[t])}`).join(`,`)}}`:JSON.stringify(e)}var gI=/^[a-z][a-z0-9_]{0,39}$/,_I=/^[A-Z][A-Z0-9_]{0,63}$/,vI=`secret:`;function yI(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(vI)){if(!_I.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(!gI.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 Q=e=>typeof e==`object`&&!!e&&!Array.isArray(e),$=e=>typeof e==`string`,bI=e=>typeof e==`number`&&Number.isFinite(e),xI=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=1,SI=e=>Array.isArray(e)?e.filter($):[];function CI(e,t){return{items:Q(e)&&Array.isArray(e.items)?e.items.map(t).filter(e=>e!==void 0):[],...Q(e)&&$(e.cursor)?{cursor:e.cursor}:{}}}function wI(e){if(Q(e)&&$(e.id)&&$(e.name)&&$(e.title)&&xI(e.latestVersion)&&bI(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:SI(e.tags),metadata:Q(e.metadata)?Object.fromEntries(Object.entries(e.metadata).filter(e=>$(e[1]))):{},projects:SI(e.projects),latestVersion:e.latestVersion,revision:e.revision,updatedAt:bI(e.updatedAt)?e.updatedAt:0}}var TI=e=>CI(e,wI),EI=[`sessions`,`online`,`olderVersion`,`teamRoles`,`staffedSeats`,`launches`,`liveLaunches`];function DI(e){if(!Q(e))return;let t={};for(let n of EI)bI(e[n])&&(t[n]=e[n]);return Array.isArray(e.teams)&&(t.teams=SI(e.teams)),Array.isArray(e.harnesses)&&(t.harnesses=SI(e.harnesses)),t}function OI(e){if(Q(e)&&xI(e.version)&&bI(e.skills)&&bI(e.commands))return{version:e.version,skills:e.skills,commands:e.commands,instructions:e.instructions===!0}}function kI(e){let t=TI(e),n=Q(e)&&Q(e.usage)?e.usage:void 0,r=Q(e)&&Q(e.summaries)?e.summaries:void 0;return{items:t.items.map(e=>{let t=n?DI(n[e.id]):void 0,i=r?OI(r[e.id]):void 0;return{profile:e,...t?{usage:t}:{},...i?{summary:i}:{}}}),...t.cursor?{cursor:t.cursor}:{}}}var AI=e=>!!e&&((e.sessions??0)>0||(e.teamRoles??0)>0||(e.launches??0)>0);function jI(e){if(!e)return[];let t=[];e.sessions&&t.push(dt(e.sessions,`session`)),e.teamRoles&&t.push(dt(e.teamRoles,`team role`)),e.launches&&t.push(dt(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 MI=e=>[...new Set(e)].sort();function NI(e){return{tags:MI(e.flatMap(e=>e.profile.tags)),projects:MI(e.flatMap(e=>e.profile.projects)),teams:MI(e.flatMap(e=>e.usage?.teams??[])),harnesses:MI(e.flatMap(e=>e.usage?.harnesses??[]))}}function PI(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`===AI(e.usage)))}var FI=e=>(e?.sessions??0)+(e?.teamRoles??0)+(e?.launches??0),II=(e,t)=>e.profile.name<t.profile.name?-1:+(e.profile.name>t.profile.name);function LI(e,t){let n=[...e];return t===`updated`?n.sort((e,t)=>t.profile.updatedAt-e.profile.updatedAt||II(e,t)):t===`usage`?n.sort((e,t)=>FI(t.usage)-FI(e.usage)||II(e,t)):n.sort(II)}var RI=[`sessions`,`teams`,`launches`,`workspaces`];function zI(e){if(!Q(e)||!$(e.sessionID)||!xI(e.version)||!bI(e.revision))return;let t=Q(e.effective)&&xI(e.effective.version)?e.effective.version:void 0,n=Q(e.ack)&&dI.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,...bI(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:Q(e.ack)&&e.ack.offline===!0}}function BI(e){if(!Q(e)||!$(e.profileID)||!xI(e.latestVersion))return;let t=e=>Array.isArray(e)?e.filter(Q):[],n=Q(e.sessions)?e.sessions:void 0;return{profileID:e.profileID,latestVersion:e.latestVersion,counts:{...DI(e.counts),...Q(e.counts)&&bI(e.counts.workspaces)?{workspaces:e.counts.workspaces}:{}},sessions:(n&&Array.isArray(n.items)?n.items:[]).flatMap(e=>zI(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}:{},...xI(e.version)?{version:e.version}:{},...bI(e.staffed)?{staffed:e.staffed}:{}})),launches:t(e.launches).filter(e=>$(e.id)&&$(e.state)&&xI(e.version)).map(e=>({id:e.id,state:e.state,...$(e.outcome)?{outcome:e.outcome}:{},version:e.version,...$(e.sessionID)?{sessionID:e.sessionID}:{},created:bI(e.created)?e.created:0,updated:bI(e.updated)?e.updated:0})),workspaces:t(e.workspaces).filter(e=>$(e.workspaceID)).map(e=>({workspaceID:e.workspaceID,...$(e.title)?{title:e.title}:{},sessions:bI(e.sessions)?e.sessions:0})),projects:SI(e.projects),hidden:SI(e.hidden).filter(e=>RI.includes(e)),truncated:SI(e.truncated)}}var VI=(e,t)=>t?`/teams/${encodeURIComponent(e)}`:`/watchtower?group=team&team=${encodeURIComponent(e)}`;function HI(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=de(n)??pI(r);return i?{ok:!1,error:i}:{ok:!0,patch:{metadata:Object.keys(n).length?n:null,projects:r.length?r:null}}}function UI(e){if(!Q(e)||!$(e.profileID)||!xI(e.version)||!$(e.digest))return;let t=e=>Q(e)&&$(e.name)?{name:e.name,description:$(e.description)?e.description:``}:void 0;return{profileID:e.profileID,version:e.version,digest:e.digest,createdAt:bI(e.createdAt)?e.createdAt:0,bytes:bI(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:SI(e.params)}]:[]}),secretRefs:SI(e.secretRefs)}}function WI(e){if(Q(e)&&xI(e.version)&&$(e.digest))return{version:e.version,digest:e.digest,bytes:bI(e.bytes)?e.bytes:0,createdAt:bI(e.createdAt)?e.createdAt:0}}var GI=e=>CI(e,WI);function KI(e){let t=Q(e)?e.version:void 0;if(!Q(t)||!$(t.profileID)||!xI(t.version)||!$(t.digest)||!Q(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=>Q(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=>Q(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:bI(t.createdAt)?t.createdAt:0,content:r}}function qI(e){if(Q(e)&&dI.includes(e.status)&&$(e.digest))return{status:e.status,digest:e.digest,notes:SI(e.notes),at:bI(e.at)?e.at:0,offline:e.offline===!0}}function JI(e){if(Q(e)&&$(e.profileID)&&xI(e.version)&&$(e.digest)&&(e.status===`applied`||e.status===`partial`))return{profileID:e.profileID,version:e.version,digest:e.digest,status:e.status,at:bI(e.at)?e.at:0}}function YI(e){if(!Q(e)||!$(e.sessionID)||!$(e.profileID)||!xI(e.version)||!bI(e.revision))return;let t=qI(e.ack),n=JI(e.effective);return{sessionID:e.sessionID,profileID:e.profileID,version:e.version,revision:e.revision,...t?{ack:t}:{},...n?{effective:n}:{}}}function XI(e){if(!Q(e)||!(`assignment`in e))return;if(e.assignment===null)return{assignment:null};let t=YI(e.assignment);if(!t)return;let n=wI(e.profile),r=UI(e.version);return{assignment:t,...n?{profile:n}:{},...r?{version:r}:{}}}var ZI={pending:`Pending`,applied:`Applied`,partial:`Partly applied`,rejected:`Rejected`,unsupported:`Unsupported`,restart_required:`Restart required`},QI={applied:`ok`,partial:`warn`,restart_required:`warn`,pending:`pending`,unsupported:`err`,rejected:`err`};function $I(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:QI[r],detail:`${e.profile?.title??n} v${t.version}: ${ZI[r]}${t.ack?.offline?` (machine offline)`:``}${s?` · v${s} available`:``}`,requested:t.version,...a===void 0?{}:{effective:a},...s?{upgrade:s}:{}}}function eL(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 tL=`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.`,nL={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.`},rL=e=>nL[e]??`This harness reports what took effect after you pin; presets can't apply profiles.`,iL=()=>({instructions:``,model:``,skills:[],commands:[]}),aL=e=>({instructions:e.instructions??``,model:e.model??``,skills:e.skills.map(e=>({...e})),commands:e.commands.map(e=>({...e}))});function oL(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=fI(r);if(i)return{ok:!1,error:i};for(let e of r.commands){let t=yI(e.template);if(typeof t==`string`)return{ok:!1,error:`commands.${e.name}: ${t}`}}return{ok:!0,content:r}}function sL(e,t){let n=oL(e);return!n.ok||hI(n.content)!==hI(t)}function cL(e,t){let n=oL(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=mI(a);return o?{ok:!1,error:o}:{ok:!0,body:a}}function lL(e){let t=yI(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 uL=4e3;function dL(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 ${uL} characters`};n[r]=e}return{ok:!0,body:{params:n}}}function fL(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 pL=`Control+Alt+P`,mL=e=>e.ctrlKey&&e.altKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyP`,hL=(e,t)=>e?e.endsWith(`
|
|
32
|
-
`)?e+t:`${e}\n${t}`:t,gL=(e,t,n)=>({profileID:e,version:t,expectedRevision:n.assignment?.revision??0});function _L(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 vL=e=>!!e.assignment&&(e.assignment.ack?.status??`pending`)===`pending`,yL=15e3,bL=16,xL=e=>e>=bL?void 0:Math.min(yL,1e3*2**e);function SL(e){let t=e,n=t?.message??String(e);switch(t?.code){case`conflict`:return`Changed elsewhere meanwhile${bI(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 CL=encodeURIComponent,wL=`/api/agent`,TL={list:(e=`active`,t=!0)=>`${wL}/profiles?state=${e}&limit=200${t?`&include=usage,summary`:``}`,usage:(e,t)=>`${wL}/profiles/${CL(e)}/usage?limit=200${t?`&cursor=${CL(t)}`:``}`,create:()=>`${wL}/profiles`,one:e=>`${wL}/profiles/${CL(e)}`,versions:e=>`${wL}/profiles/${CL(e)}/versions`,version:(e,t)=>`${wL}/profiles/${CL(e)}/versions/${t}`,session:e=>`${wL}/sessions/${CL(e)}/profile`,unpin:(e,t)=>`${wL}/sessions/${CL(e)}/profile?expectedRevision=${t}`,render:(e,t)=>`${wL}/sessions/${CL(e)}/profile/commands/${CL(t)}/render`},EL=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,DL=async e=>e.json().catch(()=>({})),OL=async(e=`active`)=>TI(await z(TL.list(e,!1))),kL=async(e=`active`)=>kI(await z(TL.list(e)));async function AL(e,t){let n=BI(await z(TL.usage(e,t)));if(!n)throw Error(`The hub sent an unreadable usage answer`);return n}async function jL(e,t){let n=wI((await DL(await W(TL.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 ML(e){let t=await z(TL.one(e)),n=wI(t.profile);if(!n)throw Error(`The hub sent an unreadable profile`);return{profile:n,latest:UI(t.latest)}}var NL=async e=>GI(await z(`${TL.versions(e)}?limit=200`));async function PL(e,t){let n=KI(await z(TL.version(e,t)));if(!n)throw Error(`The hub sent an unreadable version`);return n}async function FL(e,t){let n=wI((await DL(await W(TL.create(),{method:`POST`,json:e,headers:{"idempotency-key":t}}))).profile);if(!n)throw Error(`The hub sent an unreadable profile`);return n}async function IL(e,t,n){let r=wI((await DL(await W(TL.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 LL(e,t){let n=wI((await DL(await W(TL.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 RL(e){let t=XI(await z(TL.session(e)));if(!t)throw Error(`The hub sent an unreadable profile pin`);return t}async function zL(e,t){await W(TL.session(e),{method:`PUT`,json:t})}async function BL(e,t){await W(TL.unpin(e,t),{method:`DELETE`})}async function VL(e,t,n){let r=await DL(await W(TL.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 HL=q(`<p class="error small"role=alert>`),UL=q(`<input type=search role=combobox aria-label="Search commands"aria-controls=prof-commands aria-expanded=true placeholder="Type a command…"autofocus>`),WL=q(`<ul class=prof-commands id=prof-commands role=listbox aria-label=Commands>`),GL=q(`<p class=prof-note>Inserted text goes into this session's composer; review it, then send.`),KL=q(`<p class="muted small">No profile is pinned to this session, so it has no commands. Pin one from the session's profile chip.`),qL=q(`<p class="muted small">Loading commands…`),JL=q(`<p class="muted small">`),YL=q(`<li role=option class=prof-command><strong>/</strong><span class=prof-sub>`),XL=q(`<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.`),ZL=q(`<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`),QL=q(`<label><textarea>`);function $L(e){let t=e.view.assignment,[r]=f(async()=>{if(!t)return[];let n=e.view.version?.commands??[];try{return(await PL(t.profileID,t.version)).content.commands.map(e=>{let t=lL(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:[]}))}}),[i,a]=x(``),[s,c]=x(0),[l,d]=x(),[p,m]=x({}),[h,g]=x(``),[_,v]=x(!1),y=T(()=>fL(r()??[],i())),b=e=>{e&&(d(e),m({}),g(``),e.params.length?requestAnimationFrame(()=>document.querySelector(`.prof-palette [data-param]`)?.focus()):S(e))},S=async t=>{let n=dL(t.params,p());if(!n.ok)return g(n.error);v(!0),g(``);try{let{prompt:r}=await VL(e.sessionID,t.name,n.body);mb.set(e.sessionID,hL(mb.get(e.sessionID),r)),e.onInserted()}catch(e){g(SL(e))}finally{v(!1)}},C=e=>{let t=y().length;e.key===`ArrowDown`&&t?(e.preventDefault(),c((s()+1)%t)):e.key===`ArrowUp`&&t?(e.preventDefault(),c((s()-1+t)%t)):e.key===`Enter`&&(e.preventDefault(),b(y()[s()]))},w=t=>`prof-cmd-${e.sessionID}-${t}`;return n(ze,{open:!0,get title(){return`Commands · ${e.title}`},get onClose(){return e.onClose},class:`prof-dialog prof-palette`,get children(){return[n(u,{get when(){return l()},get fallback(){return n(u,{when:t,get fallback(){return KL()},get children(){return[(()=>{var e=UL();return e.$$keydown=C,e.$$input=e=>(a(e.currentTarget.value),c(0)),D(()=>L(e,`aria-activedescendant`,y().length?w(s()):void 0)),D(()=>e.value=i()),e})(),n(u,{get when(){return r()},get fallback(){return qL()},get children(){return n(u,{get when(){return y().length},get fallback(){return(()=>{var n=JL();return I(n,(()=>{var n=V(()=>!!r().length);return()=>n()?`No command matches.`:`${e.view.profile?.name??`This profile`} v${t.version} has no commands.`})()),n})()},get children(){var e=WL();return I(e,n(o,{get each(){return y()},children:(e,t)=>(()=>{var n=YL(),r=n.firstChild;r.firstChild;var i=r.nextSibling;return n.addEventListener(`pointerenter`,()=>c(t())),n.$$click=()=>b(e),I(r,()=>e.name,null),I(i,()=>e.description,null),I(i,(()=>{var t=V(()=>!!e.params.length);return()=>t()?` · asks for ${e.params.join(`, `)}`:``})(),null),I(i,(()=>{var t=V(()=>!!e.secrets.length);return()=>t()?` · uses secret ${e.secrets.join(`, `)}`:``})(),null),D(e=>{var r=w(t()),i=t()===s();return r!==e.e&&L(n,`id`,e.e=r),i!==e.t&&L(n,`aria-selected`,e.t=i),e},{e:void 0,t:void 0}),n})()})),e}})}}),GL()]}})},children:e=>(()=>{var t=ZL(),r=t.firstChild,i=r.firstChild;i.firstChild;var a=i.nextSibling.nextSibling,s=r.nextSibling,c=s.firstChild,l=c.nextSibling;return t.addEventListener(`submit`,t=>(t.preventDefault(),void S(e()))),I(i,()=>e().name,null),I(a,()=>e().description),I(t,n(o,{get each(){return e().params},children:e=>(()=>{var t=QL(),n=t.firstChild;return I(t,e,n),n.$$input=t=>m({...p(),[e]:t.currentTarget.value}),L(n,`data-param`,e),L(n,`rows`,e===`arguments`?3:1),D(()=>n.value=p()[e]??``),t})()}),s),I(t,n(u,{get when(){return e().secrets.length},get children(){var t=XL(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return I(t,()=>e().secrets.join(`, `),n),I(r,()=>`{{secret:${e().secrets[0]}}}`),t}}),s),I(t,n(u,{get when(){return h()},get children(){var e=HL();return I(e,h),e}}),s),l.$$click=()=>d(void 0),D(()=>c.disabled=_()),t})()}),n(u,{get when(){return V(()=>!l())()&&h()},get children(){var e=HL();return I(e,h),e}})]}})}P([`input`,`keydown`,`click`]);var eR=q(`<span class=prof-up aria-hidden=true>↑v`),tR=q(`<button type=button>`),nR=q(`<section aria-label="Pinned profile"><h3>Pinned`),rR=q(`<label>Profile<select aria-label=Profile>`),iR=q(`<label>Version<select aria-label=Version>`),aR=q(`<div class=row><button type=button class="btn small primary">`),oR=q(`<section aria-label="Pin a profile"><h3></h3><p class=prof-note>`),sR=q(`<p class="error small"role=alert>`),cR=q(`<p class="muted small">No profile is pinned to this session.`),lR=q(`<div class=prof-status><span></span><strong class=small>`),uR=q(`<ul class=prof-guidance aria-label="What took effect">`),dR=q(`<p class=prof-note>`),fR=q(`<div class=row><button type=button class="btn small">Unpin</button><button type=button class="btn small">Commands… (Ctrl+Alt+P)`),pR=q(`<li>`),mR=q(`<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`),hR=q(`<p class="muted small">`),gR=q(`<p class="muted small">No active profiles. Create one under Agent profiles (/profiles).`),_R=q(`<option> (<!>)`),vR=q(`<option>v`),yR=e=>{let t=Du(e)?.session.title;return typeof t==`string`&&t?t:`this session`};function bR(t){let[r,i]=x(),[a,o]=x(!0),[s,c]=x(!1),[l,d]=x(!1),f,p,m=0,h=!0,g=async()=>{try{let e=await RL(t.sessionID);if(!h)return;i(e),o(!0),_()}catch(t){if(!h)return;t instanceof e&&(t.status===404||t.status===403)&&o(!1)}},_=()=>{clearTimeout(p);let e=r();if(!e||!vL(e))return void(m=0);let t=xL(m++);t!==void 0&&(p=setTimeout(()=>void g(),t))},v=async()=>{m=0,await g()};ue(()=>void g()),j(()=>{h=!1,clearTimeout(p)}),ue(()=>{let e=e=>{mL(e)&&t.takesInput()&&a()&&r()&&(e.preventDefault(),d(!0))};document.addEventListener(`keydown`,e),j(()=>document.removeEventListener(`keydown`,e))});let y=()=>$I(r()??{assignment:null}),b=()=>f?.closest(`.session-layout`)?.querySelector(`textarea[aria-label="Message"]`)?.focus();return n(u,{get when(){return V(()=>!!a())()&&r()},get children(){return[(()=>{var e=tR();e.$$click=()=>{c(!0),g()};var t=f;return typeof t==`function`?ge(t,e):f=e,L(e,`aria-keyshortcuts`,pL),I(e,(()=>{var e=V(()=>!!r().assignment);return()=>e()?y().label:`Profile`})(),null),I(e,n(u,{get when(){return y().upgrade},get children(){var e=eR();return e.firstChild,I(e,()=>y().upgrade,null),e}}),null),D(t=>{var n=`prof-chip ${y().tone}`,i=r().assignment?.ack?.status??`none`,a=`${y().detail}. Commands: ${pL}`,o=r().assignment?`Agent profile: ${y().label}, ${ZI[r().assignment.ack?.status??`pending`]}${y().upgrade?`, v${y().upgrade} available`:``}`:`Agent profile: none`;return n!==t.e&&G(e,t.e=n),i!==t.t&&L(e,`data-profile-status`,t.t=i),a!==t.a&&L(e,`title`,t.a=a),o!==t.o&&L(e,`aria-label`,t.o=o),t},{e:void 0,t:void 0,a:void 0,o:void 0}),e})(),n(u,{get when(){return s()},get children(){return n(xR,{get sessionID(){return t.sessionID},get harness(){return t.harness},get view(){return r()},onClose:()=>c(!1),onChanged:()=>void v(),onCommands:()=>{c(!1),d(!0)}})}}),n(u,{get when(){return l()},get children(){return n($L,{get sessionID(){return t.sessionID},get title(){return yR(t.sessionID)},get view(){return r()},onClose:()=>d(!1),onInserted:()=>{d(!1),requestAnimationFrame(b)}})}})]}})}function xR(e){let[t]=f(()=>OL(`active`).then(e=>e.items)),[r,i]=x(e.view.assignment?.profileID??``),[a,s]=x(0),[c,l]=x(``),[d,p]=x(!1);C(()=>{let e=t.error?void 0:t();e?.length&&!e.some(e=>e.id===r())&&i(e[0].id)});let[m]=f(()=>r()||void 0,e=>NL(e).then(e=>e.items));C(h([()=>m.error?void 0:m(),()=>e.view.assignment?.profileID,()=>e.view.assignment?.version],([t])=>{if(!t?.length)return;let n=e.view.assignment;s(n&&n.profileID===r()&&t.some(e=>e.version===n.version)?n.version:t[0].version)}));let g=()=>$I(e.view),_=()=>eL(e.view),v=()=>_L(e.view,r(),a()),y=async(t,n,r)=>{p(!0),l(``);try{await zL(e.sessionID,gL(t,n,e.view)),K(r),e.onChanged()}catch(t){l(SL(t)),e.onChanged()}finally{p(!1)}},b=async()=>{let t=e.view.assignment;if(t){p(!0),l(``);try{await BL(e.sessionID,t.revision),K(`Unpinned. What the session already applied stays until it restarts.`),e.onChanged()}catch(t){l(SL(t)),e.onChanged()}finally{p(!1)}}};return n(ze,{open:!0,get title(){return`Agent profile · ${yR(e.sessionID)}`},get onClose(){return e.onClose},class:`prof-dialog`,get children(){return[(()=>{var t=nR();return t.firstChild,I(t,n(u,{get when(){return e.view.assignment},get fallback(){return cR()},children:t=>[(()=>{var e=lR(),n=e.firstChild,r=n.nextSibling;return I(n,()=>g().label),I(r,()=>ZI[t().ack?.status??`pending`],null),I(r,()=>t().ack?.offline?` · machine offline`:``,null),D(e=>{var i=`prof-chip ${g().tone}`,a=t().ack?.status??`pending`;return i!==e.e&&G(n,e.e=i),a!==e.t&&L(r,`data-ack`,e.t=a),e},{e:void 0,t:void 0}),e})(),(()=>{var e=uR();return I(e,n(o,{get each(){return _()},children:e=>(()=>{var t=pR();return I(t,e),t})()})),e})(),n(u,{get when(){return g().upgrade},children:n=>(()=>{var r=mR(),i=r.firstChild,a=i.firstChild.nextSibling,o=a.nextSibling.nextSibling,s=o.nextSibling.nextSibling;s.nextSibling;var c=i.nextSibling;return c.firstChild,I(i,n,a),I(i,()=>e.view.profile?.name??`this profile`,o),I(i,()=>t().version,s),c.$$click=()=>void y(t().profileID,n(),`Upgrading to v${n()}…`),I(c,n,null),D(()=>c.disabled=d()),r})()}),(()=>{var e=dR();return I(e,tL),e})(),(()=>{var t=fR(),n=t.firstChild,r=n.nextSibling;return n.$$click=()=>void b(),ke(r,`click`,e.onCommands,!0),L(r,`aria-keyshortcuts`,pL),D(()=>n.disabled=d()),t})()]}),null),t})(),(()=>{var c=oR(),l=c.firstChild,f=l.nextSibling;return I(l,()=>e.view.assignment?`Change the pin`:`Pin a profile`),I(f,()=>rL(e.harness)),I(c,n(u,{get when(){return V(()=>!t.error)()&&t()},get fallback(){return(()=>{var e=hR();return I(e,(()=>{var e=V(()=>!!t.error);return()=>e()?SL(t.error):`Loading profiles…`})()),e})()},get children(){return n(u,{get when(){return t().length},get fallback(){return gR()},get children(){return[(()=>{var e=rR(),a=e.firstChild.nextSibling;return a.addEventListener(`change`,e=>i(e.currentTarget.value)),I(a,n(o,{get each(){return t()},children:e=>(()=>{var t=_R(),n=t.firstChild,r=n.nextSibling;return r.nextSibling,I(t,()=>e.title,n),I(t,()=>e.name,r),D(()=>t.value=e.id),t})()})),D(()=>a.value=r()),e})(),(()=>{var e=iR(),t=e.firstChild.nextSibling;return t.addEventListener(`change`,e=>s(Number(e.currentTarget.value))),I(t,n(o,{get each(){return V(()=>!!m.error)()?[]:m()??[]},children:(e,t)=>(()=>{var n=vR();return n.firstChild,I(n,()=>e.version,null),I(n,()=>t()===0?` (latest)`:``,null),D(()=>n.value=String(e.version)),n})()})),D(()=>t.disabled=!!m.error||!m()),D(()=>t.value=String(a())),e})(),(()=>{var e=aR(),t=e.firstChild;return t.$$click=()=>void y(r(),a(),`${v().label}: sent to the session`),I(t,()=>v().label),D(()=>t.disabled=d()||!r()||!a()),e})()]}})}}),null),D(()=>L(f,`data-harness`,e.harness)),c})(),n(u,{get when(){return c()},get children(){var e=sR();return I(e,c),e}})]}})}P([`click`]);var SR=10;function CR(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 ${qA(t)} sessions yet`};return{fork:r(`fork`,`Fork`),revert:r(`revert`,`Revert`)}}var wR=e=>Number.isSafeInteger(e)&&e>=0?e:0;function TR(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:wR(t.hidden),...typeof t.at==`number`&&Number.isFinite(t.at)?{at:t.at}:{},files:n,filesTotal:Math.max(wR(t.filesTotal),n.length),...ER(t.stagedAt)?{stagedAt:t.stagedAt}:{}}}var ER=e=>typeof e==`number`&&Number.isFinite(e);function DR(e){let t=e?.revertCommitted;if(t&&typeof t==`object`&&typeof t.messageID==`string`&&t.messageID&&ER(t.until)&&ER(t.at))return{messageID:t.messageID,...ER(t.from)?{from:t.from}:{},until:t.until,at:t.at}}function OR(e){let t=DR(e);return`${TR(e)?.messageID??``}|${t?`${t.messageID}@${t.at}`:``}`}function kR(e){let t=Math.max(e.filesTotal,e.files.length);return{text:`${dt(e.hidden,`message`)} reverted`,...t?{files:`${dt(t,`file`)} restored`}:{}}}function AR(e){let t=Math.max(e.filesTotal,e.files.length);if(!t)return;let n=e.files.slice(0,SR).map(e=>e.file),r=t-n.length;return[`Revert ${dt(e.hidden,`message`)}?`,``,`The session changed ${dt(t,`file`)} since then; ${t===1?`it goes`:`they go`} back to how ${t===1?`it was`:`they were`}:`,n.join(`
|
|
33
|
-
`)+(r>0?`\nand ${r} more`:``),``,`Restore undoes the revert until you send the next message.`].join(`
|
|
34
|
-
`)}function jR(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 MR(e,t){return t===void 0?e:e.trim()===t.trim()?``:e}var NR=new Map;function PR(e,t){t.length&&NR.set(e,t)}function FR(e){let t=NR.get(e)??[];return NR.delete(e),t}var IR=q(`<button type=button class="btn small changes"aria-label="Show changes"><span class=add>+</span> <span class=del>−`),LR=q(`<div class="banner warn">No connected OpenCode process reports this session. It is read-only until its machine reconnects.`),RR=q(`<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.`),zR=q(`<div class=history-sentinel aria-hidden=true>`),BR=q(`<p class="history-edge loading muted small"role=status><span class="spinner small"></span> Loading earlier messages…`),VR=q(`<p class="history-edge muted small">Beginning of conversation`),HR=q(`<p class="history-edge error small"role=alert>Couldn't load earlier messages: <!> <button type=button class="btn small">Retry`),UR=q(`<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.`),WR=q(`<p class="working-line muted"role=status><span class="spinner small"></span> `),GR=q(`<p class="idle-line muted small"> · last activity `),KR=q(`<button type=button class="btn primary tap-to-start">Tap to start Voice mode`),qR=q(`<p class="note err voice-error"role=alert>Voice mode: `),JR=q(`<div class=sheet-backdrop>`),YR=q(`<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>`),XR=q(`<a class="crumb muted"> <span class=crumb-sep aria-hidden=true>/`),ZR=q(`<h1 class=title>`),QR=q(`<h1 class=title><button type=button class=title-btn>`),$R=q(`<span class=chip-server><span aria-hidden=true></span><span class=place-sep aria-hidden=true>·</span><span class=place-where>`),ez=q(`<span> · `),tz=q(`<span class=place-branch>`),nz=q(`<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>`),rz=q(`<span class=session-error-status>`),iz=q(`<span class="session-error-where muted">in subagent `),az=q(`<div class=session-error-message>`),oz=q(`<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>`),sz=q(`<p class="muted pad">Loading conversation…`),cz=q(`<p class="muted pad empty-session">No messages yet. Type below, or start Voice mode.`),lz=q(`<p>`),uz=q(`<p class="answered-by small muted">`),dz=q(`<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`),fz=q(`<span class=muted> · `),pz=q(`<button type=button class="btn stop"aria-label="Stop the session and its subagents"> Stop`),mz=q(`<div class=composer-unavailable data-no-prompt><p class="muted small">`),hz=q(`<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`),gz=3e4,_z=80,vz=100,yz=2e3,bz;function xz(t){let r=t.id,i=zc(r,t.visible);j(()=>i.release()),C(()=>t.focused?.()&&i.focus());let s=()=>xp()&&(t.rail?.()??!0),c,l=()=>{let e=c??s();c=void 0,wp(!e)},d=()=>document.visibilityState===`visible`&&(t.visible?.()??!0),f=()=>Du(r),m=()=>Eu().find(e=>e.id===r),g=()=>{let e=f();return e?la(e.machine.name,e.session,ft()?.branch):void 0},_=()=>f()?.session.status,v=()=>Io(O()?_()?.filter(e=>ne().has(e.id)):_()),y=()=>!f(),b=T(()=>JA(f()?.process)),S=()=>XA(b()),w=()=>!!f()&&!b().timeline,E=()=>f()?.session.exposed!==!1,te=()=>typeof f()?.session.rootID==`string`?f().session.rootID:r,O=()=>te()!==r;C(()=>{let e=f()?.session;if(!Z()||!e)return;let t=te()===r?e.parentID:te();zA(window.history,location.pathname+location.search+location.hash,typeof t==`string`?t:void 0)});let ne=T(()=>Fo(_(),r)),re=(e,t)=>e===te()&&(!O()||typeof t==`string`&&ne().has(t)),ie=()=>{let e=f()?.session.parentID;if(typeof e==`string`&&e)return{id:e,title:_()?.find(t=>t.id===e)?.title||Du(e)?.session.title||`Parent session`}},[ae,oe]=x(),se=()=>{let e=ae();return e?e.value:TR(f()?.session)};C(()=>{let e=ae();e&&TR(f()?.session)?.messageID===e.value?.messageID&&oe(void 0)});let ce=T(()=>CR(f()?.process)),le,M=new Ht,[de,fe]=x(0),pe=()=>fe(e=>e+1),[he,ve]=x(!1),[ye,P]=x(!1),[xe,Se]=x([]),[we,Te]=x({}),Ee=0,Oe=(e,t=``,n)=>Se(r=>[...r.slice(-20),{key:`n${++Ee}`,text:e,kind:t,...n?{denial:n}:{}}]),[ke,Ae]=x([]),je=!1,Me=()=>{let e=_u(),t=ke();return t.length?[...e,...t.filter(t=>!e.some(e=>e.seq===t.seq))]:e},B=e=>typeof e.sessionID==`string`?Ur(Me(),e.sessionID,bj(M.rows(),e),Cu):void 0,Ne=T(()=>(de(),new Set(M.rows().flatMap(e=>e.kind===`error`&&e.declined===!0?[B(e)?.key??``]:[]).filter(Boolean)))),Pe=new Map,Fe=T(()=>{de(),M.status(_(),r);let e=new Map,t=se(),n=DR(f()?.session),i=pj(t||n?M.rows().filter(e=>!jR(e,t,n)):M.rows(),{denied:e=>B(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,i}),[Ie,Re]=mi({}),ze,Ve=!0,He=()=>requestAnimationFrame(()=>ze&&(ze.scrollTop=ze.scrollHeight));C(h(Fe,()=>Ve&&He())),C(h(Fe,e=>{!je&&e.some(e=>e.type===`error`&&e.denied&&e.label===`Denied: the turn stopped`)&&(je=!0,z(`/api/agent/audit?limit=${vz}`).then(e=>Ae(lr(e).entries)).catch(()=>{}))}));let[Ue,We]=x(0),Ge=e=>new URLSearchParams(Object.entries(e).flatMap(([e,t])=>t===void 0?[]:[[e,String(t)]])).toString(),Ke=new WA(M,e=>z(`${N(r)}/timeline?${Ge(e)}`),{limit:_z,onChange:()=>{qe(()=>De(()=>{We(e=>e+1),pe()})),Ke.state===`idle`&&Xe()}}),q=()=>(Ue(),{state:Ke.state,error:Ke.error});function qe(e){let t=ze;if(!t||Ve)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 Je,Ye;function Xe(){Ye&&ze&&typeof IntersectionObserver<`u`&&(Je??=new IntersectionObserver(e=>e.some(e=>e.isIntersecting)&&void Ke.older(),{root:ze,rootMargin:`${Math.round(window.innerHeight*1.5)}px 0px 0px 0px`}),Je.unobserve(Ye),Je.observe(Ye))}j(()=>Je?.disconnect());let Ze=e=>{Ye=e,requestAnimationFrame(()=>requestAnimationFrame(Xe))},Qe=()=>`${se()?.messageID??``}|${OR({revertCommitted:DR(f()?.session)})}`,$e=p(Qe),et=!1;C(h(Qe,e=>{if(e===$e)return;let t=e.split(`|`)[0]===$e.split(`|`)[0];$e=e,t&&et?et=!1:he()&&tt()}));async function tt(){M.clear(),pe();try{await Ke.first(),await rt(),Ve=!0,He()}catch(e){Oe(`Could not refresh the conversation: ${U(e)}`,`err`)}}async function nt(){if(w())return ve(!0);try{await Ke.first(),ve(!0),pe(),He()}catch(t){t instanceof e&&t.status===404&&!f()?P(!0):w()||tj(t)||Oe(t instanceof e&&t.status===409?`No OpenCode process for this session is connected; history is unavailable until it reconnects.`:`Could not load the conversation: ${U(t)}`,`err`),ve(!0)}}async function rt(){try{let{messages:e}=await z(`${N(r)}/messages?limit=200`);for(let t of e??[]){let e=Gt(r,t);e&&M.hubMessage(e)}pe()}catch{}}async function it(){try{let e=await z(N(r)),t=Hl.feed(te());t.load(e.activity??[]),e.status&&t.status(e.status)}catch{}}let at=p(()=>_()),ot=Tu(e=>{if(e.type===`resync`){he()?Ke.resync().catch(e=>Oe(`Could not refresh the conversation: ${U(e)}`,`err`)).then(rt):nt().then(rt),it(),xt();return}let t=typeof e.rootID==`string`?e.rootID:e.sessionID;if(e.type===`activity`&&re(t,e.sessionID)&&e.item&&e.item.kind!==`thinking`)M.activity(e.sessionID,e.item),pe();else if(e.type===`reasoning`&&re(t,e.sessionID)&&typeof e.messageID==`string`&&typeof e.delta==`string`)M.appendReasoning({sessionID:e.sessionID,messageID:e.messageID,delta:e.delta}),pe();else if(e.type===`delta`&&re(t,e.sessionID)&&typeof e.messageID==`string`&&typeof e.text==`string`)M.appendText({sessionID:e.sessionID,messageID:e.messageID,...Number.isInteger(e.ordinal)?{ordinal:e.ordinal}:{},delta:e.text}),pe();else if(e.type===`message`){let t=Gt(r,e.message);t&&(M.hubMessage(t),pe())}else if(e.type===`turn`&&e.sessionID===r&&Jt){let{sub:t,sentAt:n}=Jt;Jt=void 0,Zt(e,t,n)}else if(e.type===`status`&&e.sessionID===te()){for(let t of Dv(at,e.sessions,r))Oe(t,`sys`);let t=Io(at);if(at=e.sessions,!Io(e.sessions)){for(let e of M.rows())e.live&&M.upsert({key:e.key,live:!1});M.endReasoning(void 0),t&&i.streamed()===!1&&he()&&Ke.resync().catch(()=>{}).then(rt)}pe(),St()}}),st;C(h(()=>f()?.session.updated,()=>{clearTimeout(st),st=setTimeout(()=>d()&&void id(r),400)}));let ct=(e,t=!1)=>W(`${N(r)}/presence`,{method:`POST`,json:{visible:e},keepalive:t}).catch(()=>{}),lt=()=>{ct(d(),document.visibilityState!==`visible`),d()&&id(r)};C(h(()=>t.visible?.()??!0,()=>lt(),{defer:!0}));let ut=p(i.streamed);C(h(i.streamed,e=>{if(e===void 0)return;let t=ut===!1&&e;ut=e,t&&he()&&Ke.resync().catch(()=>{}).then(rt)}));let dt,[ft,pt]=x(),[mt,ht]=x(``),[gt,_t]=x(!0),vt=0,yt,bt=0;async function xt(){if(vt=Date.now(),f()&&!b().summary)return ht(`Details aren't available for ${b().harnessName} sessions.`),_t(!1);try{let e=await z(`${N(r)}/summary`);pt(e),ht(``),(!e.branch||!e.changes)&&bt<2&&(bt++,clearTimeout(yt),yt=setTimeout(xt,4e3))}catch(t){ht(t instanceof e&&t.status===409?`The machine is disconnected.`:`Could not load details: ${U(t)}`)}finally{_t(!1)}}function St(){clearTimeout(yt),yt=setTimeout(xt,Math.max(0,yz-(Date.now()-vt)))}let[Ct,wt]=x(),Tt=_M(()=>r),[Et,Dt]=x(),[Ot,kt]=x({...t_(),draft:mb.get(r)}),At=e=>{kt(t=>n_(t,e)),mb.set(r,Ot().draft)};j(mb.subscribe(e=>{e===r&&mb.get(r)!==Ot().draft&&kt(e=>n_(e,{type:`input`,text:mb.get(r)}))}));let jt=()=>ZA(b(),v()),Mt=()=>{let e=r_(Ot(),{running:v(),offline:y()}),t=jt();return{...e,canSubmit:e.canSubmit&&t.allowed,showStop:e.showStop&&b().stop,...!e.hint&&t.hint?{hint:t.hint}:{}}},Nt=0,[Pt,Ft]=x(!1),It=Promise.resolve();function Lt(e){It=It.then(async()=>{Ft(!0);try{for(let t of e)try{At({type:`attach`,image:await fx(t,Ot().images)})}catch(e){At({type:`attachError`,message:U(e)})}}finally{Ft(!1)}})}async function Rt(e,t,n){let r=[];for(let i of n)if(Yg(i.mime))try{let n=await(await W(dj(e,t,i.index))).blob();r.push(await fx(new File([n],i.name||`image`,{type:i.mime}),r))}catch{}return r}async function zt(e){try{await navigator.clipboard.writeText(e),K(`Copied`)}catch{K(`Could not copy: the browser refused`,`err`)}}async function Bt(e,t=!1){try{let n=await(await W(`${N(r)}/fork`,{method:`POST`,json:{messageID:e}})).json();n.text&&mb.set(n.sessionID,n.text),PR(n.sessionID,await Rt(r,e,n.attachments??[])),K(t?`Forked into a new session beside this one`:`Forked into a new session`),t?Wf(n.sessionID):a(k(n.sessionID))}catch(e){K(tj(e)??`Could not fork: ${U(e)}`,`err`)}}async function Vt(e){if(v())return K(`Wait for the session to finish (or stop it) before reverting`,`warn`);try{let t=AR(await z(`${N(r)}/revert/preview?messageID=${encodeURIComponent(e)}`));if(t&&!await Ce(t,`Revert`,{danger:!0}))return;let n=await(await W(`${N(r)}/revert`,{method:`POST`,json:{messageID:e,files:!0}})).json();oe({value:TR({revert:n.revert})}),De(()=>{for(let e of Ot().images)At({type:`detach`,id:e.id});At({type:`input`,text:n.text??``})}),le=n.text??``;for(let t of await Rt(r,e,n.attachments??[]))At({type:`attach`,image:t})}catch(e){K(tj(e)??`Could not revert: ${U(e)}`,`err`)}}async function Ut(){try{await W(`${N(r)}/revert/restore`,{method:`POST`,json:{}}),oe({value:void 0}),At({type:`input`,text:MR(Ot().draft,le)}),le=void 0}catch(e){K(`Could not restore: ${U(e)}`,`err`)}}async function Wt(){if(!se())return!0;try{return await W(`${N(r)}/revert/commit`,{method:`POST`,json:{}}),et=!0,oe({value:void 0}),le=void 0,!0}catch(e){return K(`Could not send: the revert could not be completed (${U(e)})`,`err`),!1}}let Kt=()=>{let e=ce();return{fork:e.fork,revert:e.revert.enabled&&v()?{enabled:!1,reason:`Wait for the session to finish (or stop it) before reverting`}:e.revert,onCopy:e=>void zt(e),onFork:e=>void Bt(e),onForkBeside:e=>void Bt(e,!0),onRevert:e=>void Vt(e)}};async function qt(){let t=Ot().draft.trim(),n=Ot().images;if(!t&&!n.length||se()&&!await Wt())return;if(rn()&&!n.length){At({type:`input`,text:``}),nb.sendTyped(r,t);return}let i=++Nt,a=`local:${i}`,o=v(),s=Date.now();De(()=>{At({type:`submit`,id:i}),M.upsert({key:a,kind:`user`,text:t,at:s,...n.length?{images:n.map(({name:e,mime:t,preview:n})=>({name:e,mime:t,preview:n}))}:{}}),Te(e=>({...e,[a]:`pending`})),pe()}),Ve=!0,He();try{let e={text:t,...n.length?{images:n.map(({mime:e,data:t,name:n})=>({mime:e,data:t,name:n}))}:{}},o=await W(`${N(r)}/turn`,{method:`POST`,json:e,headers:{prefer:`respond-async`}}),c=await o.json().catch(()=>({})),l=i_(o.status,c);At({type:`accepted`,id:i});let u=QA(b(),l);Te(e=>({...e,[a]:u.tick})),u.toast&&K(u.toast),l===`accepted`?Jt={sub:i,sentAt:s}:Zt(c,i,s)}catch(t){if(t instanceof be&&!o&&await o_(v)){At({type:`accepted`,id:i}),Te(e=>({...e,[a]:`sent`})),Oe(`Lost the connection to the hub after sending; the session is working on your message and its reply will appear here.`,`sys`);return}let n=tj(t);n&&K(n,`err`);let r=n??(t instanceof e&&t.status===504?`OpenCode did not answer in time. The session may still be working.`:U(t));De(()=>{At({type:`rejected`,id:i,message:r}),M.upsert({key:a,kind:`user`,text:``,images:[]}),pe()})}}let Jt,[Yt,Xt]=x(new Set);function Zt(e,t,n){let i=M.rows().some(e=>e.kind===`assistant`&&(e.at??0)>=n&&e.text);e.reply&&!i&&M.upsert({key:`reply:${t}`,kind:`assistant`,text:e.reply,at:Date.now()});let a=Hr(_u(),new Set([r,...ne()]),Date.now(),void 0,Cu),o=a_(e,{denied:a?.text});o&&Oe(o.text,o.kind,a&&o.text.startsWith(a.text)?a.key:void 0),a&&o?.text.startsWith(a.text)&&Xt(e=>new Set([...e,a.key])),pe()}async function $t(){At({type:`stop`});try{let{stopped:e}=await(await W(`${N(r)}/stop`,{method:`POST`,json:{}})).json(),t=Array.isArray(e)?e.length:0;K(t?`Stopped ${t} session${t===1?``:`s`}`:`Nothing was running`)}catch(e){K(tj(e)??`Could not stop: ${U(e)}`,`err`)}finally{At({type:`stopped`})}}let en=()=>vb(r),tn=()=>i.takesInput()?hb.toggle(r):i.focus(),nn=fb,rn=()=>nn().phase!==`off`&&nn().sessionID===r,an=()=>nn().phase!==`off`&&nn().sessionID!==void 0&&nn().sessionID!==r,on=()=>nn().error?.sessionID===r&&!nn().error.gesture?nn().error.message:void 0,sn=()=>nn().error?.sessionID===r&&nn().error.gesture===!0,cn=()=>Oo(Yl()??void 0,X()?.publicURL)?.micBlocked?`Set up speech in Settings to use the microphone`:void 0;j(nb.attach(r,{user:e=>{let t=`voice:${++Ee}`;return M.upsert({key:t,kind:`user`,text:e,at:Date.now()}),Te(e=>({...e,[t]:`pending`})),pe(),t},tick:(e,t)=>Te(n=>({...n,[e]:t})),agent:e=>{let t=e.messageID?M.liveTextKey(e.messageID):`say:${++Ee}`,{mode:n,text:r}=Ev(M.get(t)?.text??``,e.text);n!==`keep`&&(M.upsert({key:t,messageID:e.messageID,kind:`assistant`,text:r,at:M.get(t)?.at??Date.now()}),pe())},note:(e,t)=>Oe(e,t??`sys`)}));async function ln(){if(!rn()&&!i.takesInput())return i.focus();rn()||(Ry(),hb.cancel()),await nb.toggle(r),nb.isOn(r)&&nb.state.phase===`on`&&Oe(`Voice mode on${nb.state.agent?` (${nb.state.agent} agent)`:``}. Speak naturally; say “stop” to interrupt, “pause listening” to end.`,`sys`)}let un=Bv(location.href);un.voice&&(bz=r,a(un.path,{replace:!0})),C(()=>{bz===r&&f()&&!cn()&&(bz=void 0,rn()||ln())}),ue(()=>{for(let e of FR(r))At({type:`attach`,image:e});let e=xx(r);e&&(De(()=>{At({type:`input`,text:e.text});for(let t of e.images)At({type:`attach`,image:t})}),qt()),it(),id(r),ct(d()),dt=setInterval(()=>d()&&void ct(!0),gz),document.addEventListener(`visibilitychange`,lt)});let dn=!1;C(()=>{!dn&&Y.machines&&(dn=!0,p(()=>{nt().then(rt),xt(),(!f()||b().models)&&Tt.load()}))});let fn=()=>void ct(!1,!0);window.addEventListener(`pagehide`,fn),j(()=>{ot(),clearInterval(dt),clearTimeout(yt),clearTimeout(st),document.removeEventListener(`visibilitychange`,lt),window.removeEventListener(`pagehide`,fn),fn()});let pn=!1;C(()=>{if(f())pn=!0;else if(pn&&Y.machines){if(t.onGone)return t.onGone();K(`That session is gone (deleted, or its machine was revoked).`,`warn`),a(`/`,{replace:!0})}});let mn=()=>Ei(f()?.session).filter(e=>!O()||e.sessionID!==void 0&&ne().has(e.sessionID)),hn=T(()=>new Map(mn().map(e=>[`${e.kind}:${e.id}`,e]))),gn=T((e=[])=>{let t=[...hn().keys()];return t.length===e.length&&t.every((t,n)=>t===e[n])?e:t}),_n=T(()=>{de();let e;for(let t of M.rows())t.kind===`user`&&(t.depth??0)===0&&typeof t.at==`number`&&(e===void 0||t.at>e)&&(e=t.at);return e}),vn=()=>{let e=new Set(mn().map(e=>e.id));return Vr(_u(),new Set([r,...ne()]),bn(),_n(),new Set([...Yt(),...Ne()]),Mu,Cu).filter(t=>!e.has(t.key))},yn=()=>(Gl(),F(),Hl.has(te())?Hl.feed(te()).pulse():void 0),[bn,xn]=x(Date.now()),Sn=setInterval(()=>xn(Date.now()),1e3);j(()=>clearInterval(Sn));let Cn=()=>{if(O()){let e=_()?.find(e=>e.id===r);return e?.state===`working`?(bn(),`Working${e.since?` · ${lo(Date.now()-e.since)}`:``}`):void 0}let e=yn();if(!v()||!e?.busy)return;bn();let t=Pa(_(),r),n=ka(_());return`${t??e.label}${e.since?` · ${lo(Date.now()-e.since)}`:``}${n?` · ${Na(n)}`:``}`},wn=()=>Ta(_(),r),Tn=()=>{let e=f()?.session;if(!e)return`Not connected`;let t=mn().length;return b().voice?`${rn()&&nn().agent?`${nn().agent} agent`:e.conversation?`Voice agent`:`Session agent`} · ${t?`${t} request${t===1?``:`s`} waiting`:E()?`Voice on`:`Voice off`}`:t?`${t} request${t===1?``:`s`} waiting`:`${b().harnessName} session`},En=()=>ft()?.changes?.files.map(e=>e.file)??[];return(()=>{var e=YR(),a=e.firstChild,d=a.firstChild,p=d.firstChild,h=d.nextSibling,_=h.firstChild,x=h.nextSibling.firstChild;e.$$pointerdown=()=>i.focus(),e.$$focusin=()=>i.focus(),I(d,n(u,{get when(){return Z()},get children(){return n(R,{icon:`menu`,label:`Open sidebar`,onClick:Tp})}}),p),I(p,n(u,{get when(){return ie()},children:e=>(()=>{var t=XR(),r=t.firstChild,i=r.nextSibling;return I(t,n(H,{name:`chevron`,class:`crumb-chev`}),r),I(t,()=>e().title,i),D(n=>{var r=k(e().id),i=`Back to ${e().title}`,a=`Back to ${e().title}`;return r!==n.e&&L(t,`href`,n.e=r),i!==n.t&&L(t,`title`,n.t=i),a!==n.a&&L(t,`aria-label`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),I(p,n(u,{get when(){return m()},get fallback(){return(()=>{var e=ZR();return I(e,()=>f()?.session.title||(Y.machines?`Session`:`Loading…`)),e})()},children:e=>[n(_e,{get state(){return e().state}}),n(jg,{get id(){return e().id},get title(){return e().title},place:`topbar`,class:`title`,get children(){var t=QR(),n=t.firstChild;return n.$$click=()=>bh({id:e().id,place:`topbar`}),I(n,()=>e().title),D(()=>L(n,`title`,`${e().title} · click to rename`)),t}}),n(Mg,{get id(){return e().id}}),n(me,{label:`Session actions`,class:`icon-btn small`,items:()=>Ch(e(),{open:!1,place:`topbar`})})]}),null),I(d,n(u,{get when(){return g()},children:e=>(()=>{var t=$R(),r=t.firstChild,i=r.nextSibling,a=i.nextSibling;return I(t,()=>e().machine,i),I(a,()=>e().where),I(t,n(u,{get when(){return e().branch},get children(){return[n(H,{name:`branch`}),V(()=>e().branch)]}}),null),D(n=>{var i=`${e().text} · ${f().session.directory}`,a=`Runs on ${e().text}`,o=`online-dot${f().machine.online?` on`:``}`;return i!==n.e&&L(t,`title`,n.e=i),a!==n.t&&L(t,`aria-label`,n.t=a),o!==n.a&&G(r,n.a=o),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),I(d,n(u,{get when(){return S()},children:e=>(()=>{var t=ez(),n=t.firstChild;return I(t,()=>b().harnessName,n),I(t,()=>e().label,null),D(n=>{var r=`chip-evidence ${e().level}`,i=e().level,a=e().detail,o=`${b().harnessName} · evidence: ${e().label}. ${e().detail}`;return r!==n.e&&G(t,n.e=r),i!==n.t&&L(t,`data-evidence`,n.t=i),a!==n.a&&L(t,`title`,n.a=a),o!==n.o&&L(t,`aria-label`,n.o=o),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),null),I(d,n(bR,{sessionID:r,get harness(){return b().harness},get takesInput(){return i.takesInput}}),null),I(d,n(u,{get when(){return ft()?.changes?.files.length},get children(){var e=IR(),t=e.firstChild;t.firstChild;var n=t.nextSibling.nextSibling;return n.firstChild,e.$$click=()=>wt(En()[0]),I(t,()=>ft().changes.additions,null),I(n,()=>ft().changes.deletions,null),e}}),null),I(d,n(u,{get when(){return an()},get children(){return n(LO,{})}}),null),I(d,n(u,{get when(){return Z()},get children(){return n(rA,{})}}),null),I(d,n(R,{icon:`rail`,get label(){return s()?`Hide details`:`Show details`},get"aria-pressed"(){return s()},onPointerDown:()=>c=s(),onClick:l}),null),I(d,()=>t.paneTools,null),I(a,n(u,{get when(){return V(()=>!!Z())()&&g()},children:e=>(()=>{var t=nz(),r=t.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return I(i,()=>e().machine),I(a,()=>e().where),I(t,n(u,{get when(){return e().branch},get children(){return[n(H,{name:`branch`}),(()=>{var t=tz();return I(t,()=>e().branch),t})()]}}),null),D(n=>{var i=f().session.directory,a=`Runs on ${e().text}`,o=`online-dot${f().machine.online?` on`:``}`;return i!==n.e&&L(t,`title`,n.e=i),a!==n.t&&L(t,`aria-label`,n.t=a),o!==n.a&&G(r,n.a=o),n},{e:void 0,t:void 0,a:void 0}),t})()}),h),I(a,n(u,{get when(){return wn()},children:e=>(()=>{var t=oz(),i=t.firstChild.nextSibling,a=i.firstChild,o=a.firstChild;return I(o,()=>e().label),I(a,n(u,{get when(){return e().status},get children(){var t=rz();return I(t,()=>e().status),t}}),null),I(a,n(u,{get when(){return V(()=>e().sessionID!==r)()&&e().title},get children(){var t=iz();return t.firstChild,I(t,()=>e().title,null),t}}),null),I(i,n(u,{get when(){return V(()=>!!e().message)()&&e().message!==e().label},get children(){var t=az();return I(t,()=>e().message),t}}),null),I(t,n(R,{icon:`close`,label:`Dismiss error`,class:`session-error-dismiss`,onClick:()=>void Ld(e().sessionID)}),null),D(()=>L(t,`data-error-session`,e().sessionID)),t})()}),h),I(a,n(u,{get when(){return V(()=>!!y())()&&Y.machines},get children(){return LR()}}),h),h.addEventListener(`scroll`,e=>Ve=e.currentTarget.scrollHeight-e.currentTarget.scrollTop-e.currentTarget.clientHeight<80);var C=ze;return typeof C==`function`?ge(C,h):ze=h,I(_,n(u,{get when(){return!ye()},get fallback(){return n(Sz,{})},get children(){return[n(u,{get when(){return he()},get fallback(){return sz()},get children(){return[n(u,{get when(){return w()},get children(){var e=RR(),t=e.firstChild.nextSibling;return t.nextSibling,I(e,()=>b().harnessName,t),e}}),n(u,{get when(){return Fe().length||xe().length},get fallback(){return n(u,{get when(){return!w()},get children(){return cz()}})},get children(){return[(()=>{var e=zR();return ge(Ze,e),e})(),n(ee,{get children(){return[n(A,{get when(){return q().state===`loading`},get children(){return BR()}}),n(A,{get when(){return V(()=>q().state===`done`)()&&Fe().length},get children(){return VR()}}),n(A,{get when(){return q().state===`error`},get children(){var e=HR(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return I(e,()=>q().error,t),n.$$click=()=>void Ke.retry(),e}})]}}),n(aI,{sessionID:r,get blocks(){return Fe()},get ticks(){return we()},get actions(){return Kt()},expanded:Ie,onToggle:(e,t)=>Re(e,t),onDetail:(e,t)=>{M.detail(e,t),pe()}})]}})]}}),n(o,{get each(){return Wr(xe(),Ne())},children:e=>(()=>{var t=lz();return I(t,()=>e.text),D(n=>{var r=`note ${e.kind}`,i=e.kind===`err`?`alert`:void 0;return r!==n.e&&G(t,n.e=r),i!==n.t&&L(t,`role`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(Eg,{get decisions(){return Qt($l(),r)}}),n(o,{get each(){return gn()},children:e=>n(u,{get when(){return hn().get(e)},children:e=>n(eP,{sessionID:r,get blocker(){return e()},rootID:r,get canAnswer(){return V(()=>e().kind===`permission`)()?b().permission:b().form},get harnessName(){return b().harnessName}})})}),n(o,{get each(){return vn()},children:e=>(()=>{var t=uz();return I(t,()=>e.text),D(n=>{var r=e.key,i=e.title;return r!==n.e&&L(t,`data-answered-by`,n.e=r),i!==n.t&&L(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(u,{get when(){return V(()=>!!v())()&&i.streamed()===!1},get children(){return UR()}}),n(u,{get when(){return Cn()},get children(){var e=WR();return e.firstChild.nextSibling,I(e,Cn,null),e}}),n(u,{get when(){return V(()=>!(v()||!f()))()&&m()},get children(){var e=GR(),t=e.firstChild;return I(e,()=>Le[m().state],t),I(e,()=>Be(m().updated,F()),null),e}})]}})),I(x,n(u,{get when(){return rn()},get children(){return n(qj,{get state(){return nn().voice},get level(){return nn().level},get held(){return nn().held},get ignored(){return nn().ignored},get working(){return v()},get model(){return gM(Tt.prefs(),`voice`)},onMute:()=>nb.mute(),onEnd:()=>void nb.end(),onModel:()=>Dt(`voice`),get notifyHint(){return ub()},onAllowNotifications:()=>void db(),get timing(){return nn().timing},get detector(){return nn().detector}})}}),null),I(x,n(u,{get when(){return sn()},get children(){var e=KR();return e.$$click=()=>void ln(),e}}),null),I(x,n(u,{get when(){return on()},get children(){var e=qR();return e.firstChild,I(e,on,null),e}}),null),I(x,n(u,{get when(){return se()},children:e=>(()=>{var t=dz(),r=t.firstChild,i=r.firstChild,a=r.nextSibling;return I(t,n(H,{name:`undo`}),r),I(r,()=>kR(e()).text,i),I(r,n(u,{get when(){return kR(e()).files},children:e=>(()=>{var t=fz();return t.firstChild,I(t,e,null),t})()}),i),a.$$click=()=>void Ut(),D(()=>L(t,`data-revert`,e().messageID)),t})()}),null),I(x,n(u,{get when(){return jt().show},get fallback(){return(()=>{var e=mz(),t=e.firstChild;return I(t,()=>jt().hint),I(e,n(u,{get when(){return Mt().showStop},get children(){var e=pz(),t=e.firstChild;return e.$$click=()=>void $t(),I(e,n(H,{name:`stop`}),t),D(()=>e.disabled=!Mt().canStop),e}}),null),e})()},get children(){return n(Uj,{get draft(){return Ot().draft},get images(){return Ot().images},get attaching(){return Pt()},get view(){return Mt()},get error(){return Ot().error},get voiceOn(){return rn()},get voiceBlocked(){return cn()},get dictating(){return en().recording},get transcribing(){return en().transcribing},get metaLeft(){return Tn()},get voiceModel(){return V(()=>!!Tt.error())()?`unavailable`:gM(Tt.prefs(),`voice`)},get workerModel(){return V(()=>!!Tt.error())()?`unavailable`:gM(Tt.prefs(),`worker`)},onInput:e=>At({type:`input`,text:e}),onAttach:Lt,onDetach:e=>{let t=Ot().images.find(t=>t.id===e);t?.preview.startsWith(`blob:`)&&URL.revokeObjectURL(t.preview),At({type:`detach`,id:e})},onSubmit:()=>void qt(),onStop:()=>void $t(),onDictate:()=>void tn(),onVoice:()=>void ln(),onModel:e=>Dt(e),get showModels(){return b().models},get showVoice(){return b().voice}})}}),null),I(a,n(u,{get when(){return Ct()},get children(){return n(SN,{sessionID:r,get file(){return Ct()},get files(){return V(()=>!!En().length)()?En():[Ct()]},onFile:wt,onClose:()=>wt(void 0)})}}),null),I(e,n(u,{get when(){return s()},get children(){return[n(u,{get when(){return Z()},get children(){var e=JR();return e.$$click=()=>wp(!1),e}}),n(u,{get when(){return!Z()},get children(){return n(Zb,{panel:`rail`,label:`Resize details`})}}),n(xN,{get found(){return f()},get summary(){return ft()},get summaryError(){return mt()},get loading(){return gt()},onFile:e=>wt(e),onClose:()=>wp(!1)})]}}),null),I(e,n(vM,{get kind(){return Et()},models:Tt,onClose:()=>Dt(void 0)}),null),D(t=>{var n=`session-layout${s()?` with-rail`:``}`,r=i.paneID,a=i.takesInput()?``:void 0;return n!==t.e&&G(e,t.e=n),r!==t.t&&L(e,`data-pane`,t.t=r),a!==t.a&&L(e,`data-pane-focused`,t.a=a),t},{e:void 0,t:void 0,a:void 0}),e})()}function Sz(){return hz()}P([`focusin`,`pointerdown`,`click`]);var Cz=q(`<span class=pane-drop-label>`),wz=q(`<div class=pane-drop-area><span class=pane-drop-hint>`),Tz=q(`<div aria-hidden=true>`),Ez=q(`<div class=pane-dock-map>`),Dz=q(`<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.`),Oz={left:`Split left`,right:`Split right`,top:`Stack above`,bottom:`Stack below`,center:`Replace`};function kz(e,t){let n=Yp(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: ${Oz[t].replace(`Split `,``).replace(`Stack `,``)}`,refused:!1}:n===`added`&&`empty`in e?{text:`Open in a pane`,refused:!1}:{text:Oz[t],refused:!1}}function Az(e){let[t,r]=x(),i=t=>e.index===void 0?{empty:!0}:{index:e.index,zone:t},a=t=>{if(!Jp(t))return;t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getBoundingClientRect(),i=e.index===void 0?`center`:Jf(t.clientX-n.left,t.clientY-n.top,n.width,n.height);r(i),t.dataTransfer&&(t.dataTransfer.dropEffect=Wp()?.move||t.dataTransfer.effectAllowed===`move`?`move`:`copy`)},o=()=>t()?kz(i(t()),t()):void 0;return(()=>{var s=Tz();return s.addEventListener(`drop`,e=>{if(!Jp(e))return;e.preventDefault(),e.stopPropagation();let n=t()??`center`;r(void 0),Zp(e,i(n))}),s.addEventListener(`dragleave`,e=>!e.currentTarget.contains(e.relatedTarget)&&r(void 0)),s.addEventListener(`dragover`,a),s.addEventListener(`dragenter`,a),I(s,n(u,{get when(){return e.label},get children(){var t=Cz();return I(t,()=>e.label),t}}),null),I(s,n(u,{get when(){return t()},get children(){var e=wz(),n=e.firstChild;return I(n,()=>o()?.text),D(()=>L(e,`data-zone`,t())),e}}),null),D(n=>{var r=`pane-drop${e.class?` ${e.class}`:``}`,i=e.style,a=t(),c=o()?.refused?``:void 0;return r!==n.e&&G(s,n.e=r),n.t=He(s,i,n.t),a!==n.a&&L(s,`data-zone`,n.a=a),c!==n.o&&L(s,`data-refused`,n.o=c),n},{e:void 0,t:void 0,a:void 0,o:void 0}),s})()}var jz=e=>{if(Xe(e)!==void 0)return`Artifact`;let t=Du(e.sessionID)?.session.title,n=typeof t==`string`&&t?t:`Session`;return e.sideChatID?`Side chat: ${n}`:n};function Mz(){let e=Vf,t=()=>e().panes.length,r=()=>OA(e().split,t()),i=n=>{let r=kA(e().split,t(),n);return{"grid-column":`${r.col+1} / span ${r.colSpan}`,"grid-row":`${r.row+1}`}};return(()=>{var a=Dz(),s=a.firstChild,c=s.firstChild,l=c.nextSibling;return I(c,(()=>{var e=V(()=>!!Wp()?.label);return()=>e()?`Open “${Wp().label}” in a pane`:`Open in a pane`})()),I(s,n(u,{get when(){return t()},get fallback(){return n(Az,{class:`pane-dock-empty`,label:`No panes open: drop here`})},get children(){var t=Ez();return I(t,n(o,{get each(){return e().panes},children:(e,t)=>n(Az,{get index(){return t()},get label(){return jz(e)},class:`pane-dock-pane`,get style(){return i(t())}})})),D(e=>{var n=`repeat(${r().cols}, 1fr)`,i=`repeat(${r().rows}, 1fr)`;return n!==e.e&&Se(t,`grid-template-columns`,e.e=n),i!==e.t&&Se(t,`grid-template-rows`,e.t=i),e},{e:void 0,t:void 0}),t}}),l),a})()}var Nz=q(`<div role=separator tabindex=0>`);function Pz(e){let[t,n]=x(!1),r=[],i=0,a=0,o,s=()=>EA[e.axis],c=t=>e.axis===`cols`?t.clientX:t.clientY,l=e=>Math.round(e*100),u=()=>{let t=e.sizes(),n=(t[e.index]??0)+(t[e.index+1]??0),r=Math.min(s()/Math.max(1,e.total()),n/2);return{min:l(r),max:l(n-r)}},d=()=>{a&&cancelAnimationFrame(a),a=0,n(!1),document.documentElement.classList.remove(`resizing`,`resizing-rows`)},f=(t,n)=>{t.hasPointerCapture(n)&&t.releasePointerCapture(n);let r=o;o=void 0,d(),r&&e.onChange(r,!0)};return j(d),(()=>{var d=Nz();return d.$$keydown=t=>{let n=MA(e.sizes(),e.index,t.key,t.shiftKey,e.total(),s(),e.axis);n&&(t.preventDefault(),e.onChange(n,!0))},d.$$dblclick=()=>e.onChange(AA(e.sizes().length),!0),d.addEventListener(`pointercancel`,e=>t()&&f(e.currentTarget,e.pointerId)),d.$$pointerup=e=>t()&&f(e.currentTarget,e.pointerId),d.$$pointermove=n=>{t()&&(o=jA(r,e.index,c(n)-i,e.total(),s()),a||=requestAnimationFrame(()=>{a=0,o&&e.onChange(o,!1)}))},d.$$pointerdown=t=>{t.button===0&&(t.preventDefault(),t.stopPropagation(),t.currentTarget.setPointerCapture(t.pointerId),r=e.sizes(),i=c(t),n(!0),document.documentElement.classList.add(e.axis===`cols`?`resizing`:`resizing-rows`))},D(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=l(e.sizes()[e.index]??0),c=u().min,f=u().max,p=e.style;return r!==n.e&&G(d,n.e=r),i!==n.t&&L(d,`data-axis`,n.t=i),a!==n.a&&L(d,`aria-orientation`,n.a=a),o!==n.o&&L(d,`aria-label`,n.o=o),s!==n.i&&L(d,`aria-valuenow`,n.i=s),c!==n.n&&L(d,`aria-valuemin`,n.n=c),f!==n.s&&L(d,`aria-valuemax`,n.s=f),n.h=He(d,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}),d})()}P([`pointerdown`,`pointermove`,`pointerup`,`dblclick`,`keydown`]);var Fz=q(`<span role=status>Send this to the main session? It is queued and arrives after its current turn; nothing is interrupted.`),Iz=q(`<button type=submit class="btn small primary">Send`),Lz=q(`<button type=button class="btn small">Back`),Rz=q(`<form class=sidechat-send><label class=muted>Message for </label><textarea rows=3></textarea><div class=sidechat-row>`),zz=q(`<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…`),Bz=q(`<p class="muted sidechat-note">`),Vz=q(`<span role=status>`),Hz=q(`<ol class=sidechat-context aria-label="Copied context">`),Uz=q(`<li><span class=muted></span><div class=sidechat-context-text>`),Wz=q(`<p class="muted sidechat-problem"role=alert>`),Gz=q(`<button type=submit class="btn small">Review`),Kz=q(`<button type=button class=btn>Close pane`),qz=q(`<div class=empty><p class=display>Side chat</p><p class=muted role=status>`),Jz=e=>{let t=Du(e)?.session.title;return typeof t==`string`&&t?t:`the main session`};function Yz(t){let[r,i]=x(),[a,s]=x(),[c,l]=x(!1),[d,f]=x(!1),[p,m]=x(!1),[h,g]=x(!1),[_,v]=x(``),[y,b]=x(Date.now()),S,C=0,w=!0,T=e=>{i(e),b(Date.now()),clearTimeout(S),Hm(e).kind===`launching`?S=setTimeout(E,Zm(C++)):C=0};async function E(){try{let e=await z(Xm.one(t.sideChatID));if(!w)return;let n=Vm(e.sideChat);if(!n)return s(`The hub answered a side chat this console can't read.`);s(void 0),T(n)}catch(t){if(!w)return;s(t instanceof e&&t.status===404?`This side chat is gone, or it isn't yours.`:U(t))}}ue(E),j(()=>{w=!1,clearTimeout(S)});async function ee(){let t=r();if(t&&!c()){l(!0);try{let e=await(await W(Xm.refresh(t),{method:`POST`,json:{expectedRevision:t.revision}})).json(),n=Vm(e.sideChat);n&&T(n),K(Gm(e.delivery))}catch(t){t instanceof e&&t.code===`conflict`?(K(`The side chat changed meanwhile. It was reloaded; refresh again.`,`warn`),await E()):K(`Couldn't refresh: ${U(t)}`,`err`)}finally{l(!1)}}}async function te(){let e=r();if(!(!e||c()||qm(_()))){l(!0);try{await W(Xm.send(e),{method:`POST`,json:{text:_(),confirmed:!0}}),K(`Sent to the main session. It arrives after its current turn.`),v(``),g(!1),m(!1)}catch(e){K(`Couldn't send: ${U(e)}`,`err`)}finally{l(!1)}}}let O=()=>{let e=r();return e?Hm(e):void 0},ne=()=>{let e=O();return e?.kind===`ready`?e.sessionID:void 0},re=()=>{let e=r();return e?Wm(e,y()):void 0};return[(()=>{var e=zz(),i=e.firstChild.firstChild.nextSibling;i.firstChild;var a=i.nextSibling,s=a.firstChild,l=s.nextSibling,y=l.nextSibling;return I(i,()=>Jz(r()?.sourceSessionID??``),null),s.$$click=()=>f(!d()),l.$$click=ee,y.$$click=()=>(m(!p()),g(!1)),I(a,()=>t.paneTools,null),I(a,n(u,{get when(){return!t.paneTools},get children(){return n(R,{icon:`close`,class:`small`,label:`Close pane`,title:`Close pane (the side chat keeps running)`,onClick:()=>t.onClose()})}}),null),I(e,n(u,{get when(){return re()},children:e=>(()=>{var t=Bz();return I(t,()=>e().summary,null),I(t,n(u,{get when(){return e().stale},children:e=>[` · `,(()=>{var t=Vz();return I(t,e),t})()]}),null),t})()}),null),I(e,n(u,{get when(){return V(()=>!!d())()&&r()},children:e=>(()=>{var t=Hz();return I(t,n(o,{get each(){return e().snapshot.items},children:e=>(()=>{var t=Uz(),n=t.firstChild,r=n.nextSibling;return I(n,()=>e.role,null),I(n,()=>e.changed?` · changed`:``,null),I(n,()=>e.stale?` · no longer in the main session (earlier copy)`:``,null),I(n,()=>e.clipped?` · shortened`:``,null),I(r,()=>e.text),t})()})),t})()}),null),I(e,n(u,{get when(){return p()},get children(){var e=Rz(),i=e.firstChild;i.firstChild;var a=i.nextSibling,o=a.nextSibling;return e.addEventListener(`submit`,e=>{e.preventDefault(),h()?te():qm(_())||g(!0)}),I(i,()=>Jz(r()?.sourceSessionID??``),null),a.$$input=e=>v(e.currentTarget.value),I(e,n(u,{get when(){return V(()=>!!_())()&&qm(_())},children:e=>(()=>{var t=Wz();return I(t,e),t})()}),o),I(o,n(u,{get when(){return h()},get fallback(){return(()=>{var e=Gz();return D(()=>e.disabled=!!qm(_())),e})()},get children(){return[Fz(),(()=>{var e=Iz();return D(()=>e.disabled=c()),e})(),(()=>{var e=Lz();return e.$$click=()=>g(!1),D(()=>e.disabled=c()),e})()]}})),D(e=>{var n=`sidechat-send-${t.sideChatID}`,r=`sidechat-send-${t.sideChatID}`,o=h()||c();return n!==e.e&&L(i,`for`,e.e=n),r!==e.t&&L(a,`id`,e.t=r),o!==e.a&&(a.disabled=e.a=o),e},{e:void 0,t:void 0,a:void 0}),D(()=>a.value=_()),e}}),null),D(e=>{var t=d(),n=!r(),i=!r()||c(),a=p(),o=!r();return t!==e.e&&L(s,`aria-expanded`,e.e=t),n!==e.t&&(s.disabled=e.t=n),i!==e.a&&(l.disabled=e.a=i),a!==e.o&&L(y,`aria-expanded`,e.o=a),o!==e.i&&(y.disabled=e.i=o),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),e})(),n(u,{get when(){return ne()},keyed:!0,get fallback(){return(()=>{var e=qz(),r=e.firstChild.nextSibling;return I(r,()=>a()??(O()&&O().kind!==`ready`?O().text:`Loading…`)),I(e,n(u,{get when(){return a()},get children(){var e=Kz();return e.$$click=()=>t.onClose(),e}}),null),e})()},children:e=>n(xz,{id:e,get visible(){return t.visible},get focused(){return t.focused},get onGone(){return t.onGone},get rail(){return t.rail}})})]}P([`click`,`input`]);var Xz=()=>{try{return globalThis.localStorage}catch{return}},[Zz,Qz]=x(IA(Xz())),[$z,eB]=x();function tB(e,t){let n=RA(Zz(),e,t),r=$z();if(!r)return n;let[i,a,o]=r.key.split(`:`);return i===e&&Number(a)===t?{...n,[o]:r.sizes}:n}function nB(e,t,n,r,i=!0){if(!i)return void eB({key:`${e}:${t}:${n}`,sizes:r});eB(void 0),Qz(i=>LA(Xz(),i,e,t,n,r))}var rB=q(`<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>`),iB=q(`<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.`),aB=q(`<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`),oB=q(`<div class=pane-tabs role=tablist aria-label="Open sessions">`),sB=q(`<div><div class=pane-grid>`),cB=q(`<button type=button>`),lB=q(`<div role=presentation><button type=button role=tab>`),uB=q(`<section class=pane tabindex=-1>`),dB=q(`<p class="muted cmp-empty">Loading the artifact…`),fB=i(()=>WP(()=>import(`./ArtifactPane-XTnwXl-Y.js`).then(e=>({default:e.ArtifactPane})),__vite__mapDeps([0,1,2,3,4]))),pB=6,mB=[{split:`vertical`,label:`Side by side`,icon:`split`},{split:`horizontal`,label:`Stacked`,icon:`stack`},{split:`grid`,label:`Grid`,icon:`grid`}],hB=e=>{let t=Xe(e);return t===void 0?e.sideChatID?`${e.sessionID}#${e.sideChatID}`:e.sessionID:`!${t}`},gB=e=>e.startsWith(`!`)?e.slice(1):void 0,_B=e=>e.split(`#`)[0],vB=e=>encodeURIComponent(e).replace(/%/g,`_`),yB=e=>{let t=Du(e)?.session.title;return typeof t==`string`&&t?t:`Session`},bB=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function xB(e){let[t,r]=x(!1);Te(h(()=>e.routed,e=>{if(e===void 0)return void r(!1);let t=!0;Hf(n=>{let r=ct(n,{sessionID:e});return t=r.outcome!==`invalid`,r.layout}),r(!t)})),Te(()=>{let e=gu();e.size&&Hf(t=>bc(t,e))});let i=Vf,s=()=>i().panes.length,l=T(()=>i().panes.map(hB),[],{equals:bB}),d=e=>l().indexOf(e),f=()=>l()[i().focused],m=()=>i().split,g=()=>Z()&&s()>1,[_,v]=x({}),y=e=>{let t=gB(e);return t===void 0?e.includes(`#`)?`Side chat: ${yB(_B(e))}`:yB(_B(e)):`Artifact: ${_()[t]??`…`}`},b=()=>!Z()&&s()>1,S=()=>!!Wp()&&!Z();C(h(()=>i().panes[i().focused]?.sideChatID?void 0:i().panes[i().focused]?.sessionID,n=>{n&&!t()&&n!==p(()=>e.routed)&&a(k(n),{replace:!0})}));let w=()=>requestAnimationFrame(()=>{let e=document.querySelector(`section.pane[data-focused]`);e&&!e.contains(document.activeElement)&&(e.querySelector(`textarea:not([disabled])`)??e).focus()}),E=e=>Hf(t=>tt(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))},te=e=>{let t=i().focused;ee(()=>Hf(n=>at(n,t,t+e))),w()},O=e=>{e<0||e>=s()||(Hf(t=>it(t,e)),s()||a(`/`,{replace:!0}))},ne=e=>{K(s()>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`),O(d(e))};ue(()=>{let e=e=>{if(t()||e.defaultPrevented||s()<2||e.getModifierState?.(`AltGraph`))return;let n=wA(e);if(n){if(e.preventDefault(),n.type===`cycle`)Hf(e=>st(e,n.step));else if(n.type===`focus`)E(Math.min(n.index,s()-1));else if(n.type===`move`)return te(n.step);else return O(i().focused);g()||w()}};document.addEventListener(`keydown`,e),j(()=>document.removeEventListener(`keydown`,e))});let re,[ie,ae]=x({w:0,h:0});ue(()=>{if(!re||typeof ResizeObserver>`u`)return;let e=new ResizeObserver(()=>re&&ae({w:re.clientWidth,h:re.clientHeight}));e.observe(re),j(()=>e.disconnect())});let A=()=>b()?OA(m(),s()):{cols:1,rows:1},oe=()=>tB(m(),s()),se=e=>(e===`cols`?ie().w:ie().h)-(A()[e]-1)*pB,ce=(e,t)=>t>1?e.map(e=>`minmax(0, ${e}fr)`).join(` ${pB}px `):`minmax(0, 1fr)`,le=()=>({"grid-template-columns":ce(oe().cols,A().cols),"grid-template-rows":ce(oe().rows,A().rows)}),M=e=>{if(!b())return{"grid-column":`1`,"grid-row":`1`};let t=kA(m(),s(),e);return{"grid-column":`${2*t.col+1} / span ${2*t.colSpan-1}`,"grid-row":`${2*t.row+1}`}},de=e=>Array.from({length:Math.max(0,e)},(e,t)=>t),fe=e=>(t,n)=>nB(m(),s(),e,t,n),pe=e=>{let t=s(),n=i().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(),E(r),requestAnimationFrame(()=>document.querySelector(`.pane-tabs [role="tab"][aria-selected="true"]`)?.focus()))},me=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 N(e){let t=()=>d(e.key),r=()=>m()===`horizontal`;return n(u,{get when(){return b()},get children(){var a=rB(),o=a.firstChild;return ke(o,`dragend`,qp),o.addEventListener(`dragstart`,n=>{let r=i().panes[t()];(!r||!Kp(n,{target:r,label:y(e.key),move:!0}))&&n.preventDefault()}),I(o,n(H,{name:`grip`})),I(a,n(R,{icon:`chevron`,class:`small flip`,get label(){return r()?`Move pane up`:`Move pane left`},get"aria-keyshortcuts"(){return xA.moveEarlier},get disabled(){return t()<=0},onClick:()=>(E(t()),te(-1))}),null),I(a,n(R,{icon:`chevron`,class:`small`,get label(){return r()?`Move pane down`:`Move pane right`},get"aria-keyshortcuts"(){return xA.moveLater},get disabled(){return t()>=s()-1},onClick:()=>(E(t()),te(1))}),null),I(a,n(R,{icon:`close`,class:`small`,label:`Close pane`,title:`Close pane (the session keeps running)`,get"aria-keyshortcuts"(){return xA.close},onClick:()=>O(t())}),null),a}})}return n(u,{get when(){return!t()},get fallback(){return n(u,{get when(){return e.routed},keyed:!0,children:e=>n(xz,{id:e})})},get children(){return[n(u,{get when(){return!s()},get children(){var e=iB();return e.firstChild.nextSibling.nextSibling,I(e,n(u,{get when(){return S()},get children(){return n(Az,{label:`Open in a pane`})}}),null),e}}),(()=>{var e=sB(),t=e.firstChild;I(e,n(u,{get when(){return b()},get children(){var e=aB(),t=e.firstChild,r=t.nextSibling,i=r.firstChild,a=i.nextSibling;return a.nextSibling,e.$$keydown=me,I(t,n(o,{each:mB,children:e=>(()=>{var t=cB();return t.$$click=()=>Hf(t=>Ze(t,e.split)),I(t,n(H,{get name(){return e.icon}})),D(n=>{var r=e.label,i=e.label,a=m()===e.split;return r!==n.e&&L(t,`aria-label`,n.e=r),i!==n.t&&L(t,`title`,n.t=i),a!==n.a&&L(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})),I(r,s,i),I(r,lt,a),e}}),t),I(e,n(u,{get when(){return g()},get children(){var e=oB();return e.$$keydown=pe,I(e,n(o,{get each(){return l()},children:e=>{let t=()=>f()===e,r=()=>y(e);return(()=>{var i=lB(),a=i.firstChild;return a.$$click=()=>E(d(e)),I(a,r),I(i,n(R,{icon:`close`,class:`small`,get label(){return`Close ${r()}`},get tabindex(){return t()?0:-1},onClick:()=>O(d(e))}),null),D(n=>{var r=`pane-tab${t()?` selected`:``}`,o=`pane-tab-${vB(e)}`,s=`pane-${vB(e)}`,c=t(),l=t()?0:-1;return r!==n.e&&G(i,n.e=r),o!==n.t&&L(a,`id`,n.t=o),s!==n.a&&L(a,`aria-controls`,n.a=s),c!==n.o&&L(a,`aria-selected`,n.o=c),l!==n.i&&L(a,`tabindex`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),i})()}})),e}}),t);var r=re;return typeof r==`function`?ge(r,t):re=t,I(t,n(o,{get each(){return l()},children:e=>{let t=_B(e),r=()=>d(e),i=()=>f()===e,a=()=>!g()||i();return(()=>{var o=uB();return o.$$pointerdown=()=>E(d(e)),o.$$focusin=()=>E(d(e)),I(o,n(u,{get when(){return gB(e)===void 0},get fallback(){return n(c,{get fallback(){return dB()},get children(){return n(fB,{get artifactID(){return gB(e)},get paneTools(){return n(N,{key:e})},onTitle:t=>v(n=>({...n,[gB(e)]:t}))})}})},get children(){return n(u,{get when(){return!e.includes(`#`)},get fallback(){return n(Yz,{get sideChatID(){return e.slice(e.indexOf(`#`)+1)},visible:a,focused:i,onGone:()=>ne(e),onClose:()=>O(d(e)),rail:()=>!b()||i(),get paneTools(){return n(N,{key:e})}})},get children(){return n(xz,{id:t,visible:a,focused:i,onGone:()=>ne(e),rail:()=>!b()||i(),get paneTools(){return n(N,{key:e})}})}})}})),D(t=>{var n=`pane-${vB(e)}`,c=g()?`tabpanel`:`region`,l=g()?`pane-tab-${vB(e)}`:void 0,u=g()?void 0:`Pane ${r()+1} of ${s()}: ${y(e)}`,d=i()?``:void 0,f=!a(),p=M(r());return n!==t.e&&L(o,`id`,t.e=n),c!==t.t&&L(o,`role`,t.t=c),l!==t.a&&L(o,`aria-labelledby`,t.a=l),u!==t.o&&L(o,`aria-label`,t.o=u),d!==t.i&&L(o,`data-focused`,t.i=d),f!==t.n&&(o.hidden=t.n=f),t.s=He(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),I(t,n(u,{get when(){return S()},get children(){return n(o,{get each(){return l()},children:e=>n(Az,{get index(){return d(e)},get style(){return M(d(e))}})})}}),null),I(t,n(o,{get each(){return de(A().cols-1)},children:e=>n(Pz,{axis:`cols`,index:e,sizes:()=>oe().cols,total:()=>se(`cols`),get onChange(){return fe(`cols`)},get style(){return{"grid-column":`${2*e+2}`,"grid-row":m()===`grid`&&s()%2==1?`1`:`1 / -1`}}})}),null),I(t,n(o,{get each(){return de(A().rows-1)},children:e=>n(Pz,{axis:`rows`,index:e,sizes:()=>oe().rows,total:()=>se(`rows`),get onChange(){return fe(`rows`)},style:{"grid-row":`${2*e+2}`,"grid-column":`1 / -1`}})}),null),D(n=>{var r=`workspace${b()?` ws-split`:``}${g()?` ws-tabs`:``}`,i=m(),a=le();return r!==n.e&&G(e,n.e=r),i!==n.t&&L(e,`data-split`,n.t=i),n.a=He(t,a,n.a),n},{e:void 0,t:void 0,a:void 0}),e})()]}})}P([`keydown`,`click`,`focusin`,`pointerdown`]);var SB={artifacts:i(()=>WP(()=>import(`./Library-CZSSHvOJ.js`),__vite__mapDeps([5,1,3,6]))),teams:i(()=>WP(()=>import(`./TeamsPage-DJt-Kk84.js`),__vite__mapDeps([7,1,8,9,10]))),watchtower:i(()=>WP(()=>import(`./Watchtower-BXaUaXO1.js`).then(e=>e.t),__vite__mapDeps([11,1,9,8,10,12]))),profiles:i(()=>WP(()=>import(`./ProfilesDestination-dZa3vioh.js`),__vite__mapDeps([13,1,8])))},CB=q(`<div class=feature-page><header class=topbar><h1 class=title></h1></header><div class=feature-scroll><div class=feature-body>`);function wB(e){return(()=>{var t=CB(),r=t.firstChild,i=r.firstChild,a=r.nextSibling.firstChild;return I(r,n(u,{get when(){return Z()},get children(){return n(R,{icon:`menu`,label:`Open sidebar`,onClick:Tp})}}),i),I(i,()=>e.title),I(r,()=>e.actions,null),I(a,()=>e.children),t})()}var TB=q(`<p class=feature-note> isn't available yet. <a href=/>Back to All sessions`),EB=q(`<p class=muted>Loading…`);function DB(e){let t=T(()=>r.find(t=>t.id===e.id)),i=T(()=>{let e=t();return e&&oe(e,{signedIn:!!X()})===`ok`?SB[e.id]:void 0});return n(u,{get when(){return i()},get fallback(){return n(wB,{get title(){return t()?.label??`Not found`},get children(){var e=TB(),n=e.firstChild;return I(e,()=>t()?.label??`This page`,n),e}})},children:r=>n(c,{get fallback(){return n(wB,{get title(){return t().label},get children(){return EB()}})},get children(){return n(Re,{get component(){return r()},get rest(){return e.rest}})}})})}var OB=q(`<span class="badge-pill armed-left"role=timer title="How long this stays armed for a spoken answer">`),kB=q(`<p class="muted small armed-why">Why: `),AB=q(`<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">`),jB=q(`<button type=button>`);function MB(e){let t=()=>e.decision,[r,i]=x(!1),[a,s]=x(Date.now()),c=setInterval(()=>s(Date.now()),1e3);j(()=>clearInterval(c));let l=()=>{let e=pu()?.expiresAt;return e===void 0?``:nn(e,a())},d=async e=>{i(!0);try{await eb(t().id,e)}catch(e){K(U(e),`err`),i(!1)}};return(()=>{var e=AB(),i=e.firstChild,a=i.firstChild.nextSibling.nextSibling;a.firstChild;var s=i.nextSibling,c=s.nextSibling,f=c.nextSibling;return I(a,()=>Pn(t(),Mu,gu()),null),I(i,n(u,{get when(){return l()},get children(){var e=OB();return I(e,l),e}}),null),I(s,()=>In(t(),Mu,gu())),I(e,n(lg,{get decision(){return t()}}),c),I(e,n(u,{get when(){return V(()=>!!t().recommendation?.why)()&&t().recommendation.why!==ug(t())},get children(){var e=kB();return e.firstChild,I(e,()=>t().recommendation.why,null),e}}),c),I(c,n(o,{get each(){return t().options},children:e=>(()=>{var t=jB();return t.$$click=()=>void d(e.id),I(t,()=>e.label),D(n=>{var i=`btn${e.safe||e.id===`always`?``:` primary`}`,a=r();return i!==n.e&&G(t,n.e=i),a!==n.t&&(t.disabled=n.t=a),n},{e:void 0,t:void 0}),t})()})),I(f,()=>pc(!!Yl()&&!Yl().reason)),D(n=>{var r=t().id,i=t().id,o=Fn(t()),c=t().question;return r!==n.e&&L(e,`data-armed-decision`,n.e=r),i!==n.t&&L(e,`data-decision`,n.t=i),o!==n.a&&L(a,`title`,n.a=o),c!==n.o&&L(s,`title`,n.o=c),n},{e:void 0,t:void 0,a:void 0,o:void 0}),e})()}P([`click`]);var NB=q(`<button type=button class="btn small"aria-label="Restart the Concierge"title="Restart the Concierge (a new session)">Restart`),PB=q(`<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">`),FB=q(`<p role=status data-concierge-notice>`),IB=q(`<div class=concierge-asked aria-label="Decisions from the Concierge"role=group>`),LB=q(`<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>`),RB=q(`<div class=concierge-idle><form class=concierge-composer><textarea rows=1 aria-label="Ask the Concierge"placeholder="The Concierge is not running"disabled>`),zB=q(`<aside class="concierge-panel side"aria-label=Concierge tabindex=-1>`),BB=q(`<section class="concierge-panel page"aria-label=Concierge tabindex=-1>`),VB=q(`<p class="working-line muted small"role=status><span class="spinner small"></span> Working…`),HB=q(`<div class=concierge-scroll>`),UB=q(`<p class="note err"role=alert>Voice: `),WB=q(`<button type=button>`),GB=q(`<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)">`),KB=q(`<p class="muted small pad">Loading…`),qB=q(`<p class="muted small pad">`),JB=q(`<p>`),YB=3e4,XB=80,ZB=/^#decision-(dec_[A-Za-z0-9]{1,64})$/,QB=new Set([`starting`,`running`,`waiting_machine`,`backoff`,`failed`]),$B=()=>!!Yl()&&!Yl().reason;function eV(e){let t=ou,r=()=>(Y.machines??[]).map(e=>({id:e.id,name:e.name,online:e.online===!0})),i=()=>r().find(e=>e.id===t()?.machineID),o=()=>hc(t(),i()),s=()=>t()?.state===`running`&&!!t()?.sessionID&&i()?.online!==!1,c=T(()=>Qy()),l=T(()=>wc($l(),t(),c())),[d,f]=x(!1),[p,m]=x(),g,_=nA(),v=()=>he(`/`);async function y(){f(!0);try{await W(`/api/agent/concierge/restart`,{method:`POST`,json:{}}),K(`Restarting the Concierge`)}catch(e){K(`Could not restart: ${U(e)}`,`err`)}finally{f(!1)}}ue(()=>{if(e.mode!==`side`)return;let t=e=>{e.key!==`Escape`||e.defaultPrevented||xe(g)||document.querySelector(`.menu-pop, [role='menu']`)||(e.preventDefault(),v())};document.addEventListener(`keydown`,t),j(()=>document.removeEventListener(`keydown`,t)),requestAnimationFrame(()=>g&&!g.contains(document.activeElement)&&g.focus())});function b(e){let t=()=>requestAnimationFrame(()=>{let t=g?.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})):K(`That Decision is no longer available`)});if(g?.querySelector(`[data-decision="${e}"]`))return t();hd(e).then(e=>{e&&e.state!==`open`&&m(e),t()})}C(h(ie,e=>{let t=ZB.exec(e.hash)?.[1];t&&(a(`/concierge`,{replace:!0}),b(t))})),ue(()=>{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&&ZB.exec(new URL(t.getAttribute(`href`)??``,location.origin).hash)?.[1];n&&t.getAttribute(`href`).startsWith(`/concierge#`)&&(e.preventDefault(),b(n))};g?.addEventListener(`click`,e),j(()=>g?.removeEventListener(`click`,e))}),j(()=>{_?.isConnected&&_.focus()});let S=()=>[(()=>{var i=PB(),a=i.firstChild,o=a.firstChild.nextSibling,s=a.nextSibling;return I(i,n(u,{get when(){return e.mode===`page`},get children(){return n(R,{icon:`back`,label:`Back`,onClick:v})}}),a),I(i,n(H,{name:`spark`,class:`concierge-mark`}),a),I(o,()=>ws(t(),r(),F()),null),I(o,n(u,{get when(){return t()?.sessionID},get children(){return n(FO,{get sessionID(){return t().sessionID}})}}),null),I(i,n(u,{get when(){return V(()=>!!t())()&&QB.has(t().state)},get children(){var e=NB();return e.$$click=()=>void y(),D(()=>e.disabled=d()),e}}),s),I(s,n(H,{name:`settings`})),I(i,n(u,{get when(){return e.mode===`side`},get children(){return n(R,{icon:`close`,label:`Close the Concierge (Esc)`,onClick:v})}}),null),D(()=>L(o,`data-concierge-panel-status`,t()?.state??`none`)),i})(),n(u,{get when(){return o()},get children(){var e=FB();return I(e,o),D(()=>G(e,`concierge-notice${t()?.state===`failed`?` err`:``}`)),e}}),n(u,{get when(){return c()},children:e=>n(MB,{get decision(){return e()}})}),n(u,{get when(){return l().length},get children(){var e=IB();return I(e,n(Eg,{get decisions(){return l()}})),e}}),n(u,{get when(){return p()},keyed:!0,children:e=>(()=>{var t=LB(),r=t.firstChild,i=r.firstChild.nextSibling.nextSibling;i.nextSibling;var a=r.nextSibling,o=a.nextSibling;return I(i,()=>e.state),I(r,n(R,{icon:`close`,label:`Close this Decision`,onClick:()=>m(void 0)}),null),I(a,()=>In(e,Mu,gu())),I(t,n(lg,{decision:e}),o),I(o,()=>is(e)),D(n=>{var r=`Decision (${e.state}): ${e.question}`,i=e.id,o=e.id,s=e.question;return r!==n.e&&L(t,`aria-label`,n.e=r),i!==n.t&&L(t,`data-decision`,n.t=i),o!==n.a&&L(t,`data-closed-decision`,n.a=o),s!==n.o&&L(a,`title`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),n(u,{get when(){return V(()=>!!s())()&&t()?.sessionID},keyed:!0,get fallback(){return(()=>{var e=RB();return e.firstChild.addEventListener(`submit`,e=>e.preventDefault()),e})()},children:t=>n(tV,{id:t,get autofocus(){return e.mode===`side`}})})];return n(u,{get when(){return e.mode===`side`},get fallback(){return(()=>{var e=BB(),t=g;return typeof t==`function`?ge(t,e):g=e,I(e,S),e})()},get children(){var e=zB(),t=g;return typeof t==`function`?ge(t,e):g=e,I(e,S),e}})}function tV(t){let r=t.id,i=()=>Du(r),a=()=>i()?.session.status,s=()=>Io(a()),c=new Ht,[l,d]=x(0),f=()=>d(e=>e+1),[p,m]=x(!1),[g,_]=x({}),[v,y]=x([]),b=0,S=(e,t=`sys`)=>y(n=>[...n.slice(-10),{key:`n${++b}`,text:e,kind:t}]),w=T(()=>(l(),c.status(a(),r),pj(c.rows()))),E=T(()=>rV(w())),[ee,te]=mi({}),O,ne=!0,re=()=>requestAnimationFrame(()=>O&&(O.scrollTop=O.scrollHeight));C(h(E,()=>ne&&re())),C(()=>{for(let e of cs(w(),ru()))hd(e)});let ie=e=>new URLSearchParams(Object.entries(e).flatMap(([e,t])=>t===void 0?[]:[[e,String(t)]])).toString(),ae=new WA(c,e=>z(`${N(r)}/timeline?${ie(e)}`),{limit:XB,onChange:f});async function k(){try{let{messages:e}=await z(`${N(r)}/messages?limit=200`);for(let t of e??[]){let e=Gt(r,t);e&&c.hubMessage(e)}f()}catch{}}async function A(){try{await ae.first()}catch(e){S(`Could not load the conversation: ${U(e)}`,`err`)}m(!0),await k(),re()}let oe,se=s(),ce=Tu(e=>{let t=typeof e.rootID==`string`?e.rootID:e.sessionID;if(e.type===`resync`)ae.resync().catch(()=>{}).then(k);else if(t!==r)return;else if(e.type===`activity`&&e.item&&e.item.kind!==`thinking`)c.activity(e.sessionID,e.item);else if(e.type===`reasoning`&&typeof e.messageID==`string`&&typeof e.delta==`string`)c.appendReasoning({sessionID:e.sessionID,messageID:e.messageID,delta:e.delta});else if(e.type===`delta`&&typeof e.messageID==`string`&&typeof e.text==`string`)c.appendText({sessionID:e.sessionID,messageID:e.messageID,...Number.isInteger(e.ordinal)?{ordinal:e.ordinal}:{},delta:e.text});else if(e.type===`message`){let t=Gt(r,e.message);t&&c.hubMessage(t)}else if(e.type===`turn`&&oe){let{sentAt:t}=oe;oe=void 0,Ce(e,t)}else if(e.type===`status`){let t=Io(e.sessions),n=se&&!t;if(se=t,t)return;for(let e of c.rows())e.live&&c.upsert({key:e.key,live:!1});c.endReasoning(void 0),n&&ae.resync().catch(()=>{}).then(k)}else return;f()}),le=()=>document.visibilityState===`visible`,M=(e,t=!1)=>(Zy(e),W(`${N(r)}/presence`,{method:`POST`,json:{visible:e},keepalive:t}).catch(()=>{})),de=()=>void M(le(),!le()),fe=()=>void M(!1,!0),pe,me=fb,he=()=>me().phase!==`off`&&me().sessionID===r,_e=()=>me().error?.sessionID===r?me().error.message:void 0;j(nb.attach(r,{user:e=>{let t=`voice:${++b}`;return c.upsert({key:t,kind:`user`,text:e,at:Date.now()}),_(e=>({...e,[t]:`pending`})),f(),t},tick:(e,t)=>_(n=>({...n,[e]:t})),agent:e=>{let t=e.messageID?c.liveTextKey(e.messageID):`say:${++b}`,{mode:n,text:r}=Ev(c.get(t)?.text??``,e.text);n!==`keep`&&(c.upsert({key:t,messageID:e.messageID,kind:`assistant`,text:r,at:c.get(t)?.at??Date.now()}),f())},note:(e,t)=>S(e,t??`sys`)}));async function ve(){he()||(Ry(),hb.cancel()),await nb.toggle(r),nb.isOn(r)&&nb.state.phase===`on`&&S(`Voice on. Talk to the Concierge; say “yes” or “no” to answer the Decision it is asking about.`)}let[ye,P]=x(``),[be,F]=x(!1),xe,Se=()=>{xe&&(xe.style.height=`auto`,xe.style.height=`${Math.min(xe.scrollHeight,200)}px`)};function Ce(e,t){let n=e.reply?.trim(),r=c.rows().some(e=>e.kind===`assistant`&&(e.at??0)>=t&&e.text?.trim()===n);e.reply&&!r&&c.upsert({key:`reply:${++b}`,kind:`assistant`,text:e.reply,at:Date.now()});let i=a_(e);i&&S(i.text,i.kind),f()}async function R(){let t=ye().trim();if(!t||be())return;let n=Qy(),i=oc(t,n);if(i.kind===`answer`){F(!0);try{await eb(i.decisionID,i.option,`text`),P(``),c.upsert({key:`answered:${++b}`,kind:`user`,text:t,at:Date.now(),note:cc(n,i.option)}),f(),ne=!0,re()}catch(t){K(`Not answered: ${U(t)}${t instanceof e&&t.status===403?`. Tap an option on the card.`:``}`,`err`)}finally{F(!1)}return}if(P(``),queueMicrotask(Se),he()){nb.sendTyped(r,t);return}let a=`local:${++b}`,o=Date.now();De(()=>{c.upsert({key:a,kind:`user`,text:t,at:o}),_(e=>({...e,[a]:`pending`})),f()}),ne=!0,re();try{let e=await W(`${N(r)}/turn`,{method:`POST`,json:{text:t},headers:{prefer:`respond-async`}}),n=await e.json().catch(()=>({})),i=i_(e.status,n);_(e=>({...e,[a]:i===`steered`?`queued`:`sent`})),i===`accepted`?oe={sentAt:o}:Ce(n,o)}catch(e){_(e=>({...e,[a]:`failed`})),S(`Could not send: ${U(e)}`,`err`),ye()||P(t)}}return ue(()=>{A(),M(le()),pe=setInterval(()=>le()&&void M(!0),YB),document.addEventListener(`visibilitychange`,de),window.addEventListener(`pagehide`,fe),t.autofocus&&requestAnimationFrame(()=>xe?.focus())}),j(()=>{ce(),clearInterval(pe),document.removeEventListener(`visibilitychange`,de),window.removeEventListener(`pagehide`,fe),fe()}),[(()=>{var e=HB();e.addEventListener(`scroll`,e=>ne=e.currentTarget.scrollHeight-e.currentTarget.scrollTop-e.currentTarget.clientHeight<80);var t=O;return typeof t==`function`?ge(t,e):O=e,I(e,n(u,{get when(){return p()},get fallback(){return KB()},get children(){return n(u,{get when(){return E().length},get fallback(){return(()=>{var e=qB();return I(e,()=>fc($B())),e})()},get children(){return n(aI,{sessionID:r,get blocks(){return E()},get ticks(){return g()},expanded:ee,onToggle:(e,t)=>te(e,t),onDetail:(e,t)=>{c.detail(e,t),f()}})}})}}),null),I(e,n(o,{get each(){return v()},children:e=>(()=>{var t=JB();return I(t,()=>e.text),D(n=>{var r=`note ${e.kind}`,i=e.kind===`err`?`alert`:void 0;return r!==n.e&&G(t,n.e=r),i!==n.t&&L(t,`role`,n.t=i),n},{e:void 0,t:void 0}),t})()}),null),I(e,n(u,{get when(){return s()},get children(){return VB()}}),null),e})(),(()=>{var e=GB(),t=e.firstChild,r=t.firstChild,i=r.nextSibling;I(e,n(u,{get when(){return he()},get children(){return n(qj,{get state(){return me().voice},get level(){return me().level},get held(){return me().held},get ignored(){return me().ignored},get working(){return s()},model:`Concierge`,onMute:()=>nb.mute(),onEnd:()=>void nb.end(),onModel:()=>K(`The Concierge keeps its own model: change it in Settings → Concierge`),get notifyHint(){return ub()},onAllowNotifications:()=>void db(),get timing(){return me().timing},get detector(){return me().detector}})}}),t),I(e,n(u,{get when(){return _e()},get children(){var e=UB();return e.firstChild,I(e,_e,null),e}}),t),t.addEventListener(`submit`,e=>{e.preventDefault(),R()}),r.$$keydown=e=>{e.key===`Enter`&&!e.shiftKey&&!e.isComposing&&!(Z()&&`ontouchstart`in window)&&(e.preventDefault(),R())},r.$$input=e=>{P(e.currentTarget.value),Se()};var a=xe;return typeof a==`function`?ge(a,r):xe=r,I(t,n(u,{get when(){return $B()||he()},get children(){var e=WB();return e.$$click=()=>void ve(),I(e,n(H,{name:`wave`})),D(t=>{var n=`icon-btn concierge-voice${he()?` on`:``}`,r=he(),i=he()?`Stop talking to the Concierge`:`Talk to the Concierge`,a=he()?`End Voice with the Concierge`:`Talk to the Concierge (Voice)`;return n!==t.e&&G(e,t.e=n),r!==t.t&&L(e,`aria-pressed`,t.t=r),i!==t.a&&L(e,`aria-label`,t.a=i),a!==t.o&&L(e,`title`,t.o=a),t},{e:void 0,t:void 0,a:void 0,o:void 0}),e}}),i),I(i,n(H,{name:`send`})),D(e=>{var t=he()?`Voice is on: talk, or type here`:`Ask the Concierge…`,n=!ye().trim()||be();return t!==e.e&&L(r,`placeholder`,e.e=t),n!==e.t&&(i.disabled=e.t=n),e},{e:void 0,t:void 0}),D(()=>r.value=ye()),e})()]}var nV={unknown:`link`};function rV(e){let t=Ou,n=[...ru().values()].map(e=>({...e,question:Mn(e.question,Mu)})),r=[];for(let i of e)if(!(i.type===`message`&&i.primer)){if(i.type===`message`&&i.direction===`in`&&Vo(i.from)){let e=Jo(i.text,t);r.push(e?{...i,summary:e}:i)}else i.type===`message`&&i.text.includes(`dec_`)?r.push({...i,parts:es(i.text,n,nV)}):i.type===`assistant`&&i.text.includes(`dec_`)?r.push({...i,text:ts(i.text,n,nV)}):i.type===`tools`?r.push({...i,items:i.items.map(e=>typeof e.summary==`string`&&e.summary.includes(`ses_`)?{...e,summary:rs(e.summary,t)}:e)}):r.push(i)}return r}P([`click`,`input`,`keydown`]);var iV=q(`<main class=entry><p></p><button type=button class=btn>Retry`),aV=q(`<main class=entry><p class=muted>Loading…`),oV=q(`<div class=drawer-backdrop>`),sV=q(`<div class=voice-strip>`),cV=q(`<div class=conn-banner role=status>Reconnecting to the hub…`),lV=q(`<div role=status aria-live=polite>`),uV=q(`<p class="muted cmp-empty"data-concierge-wait>Loading…`),dV=q(`<div><main class=main>`),fV=q(`<button type=button class="btn small">`),pV=q(`<div role=status aria-live=polite><span>`),mV=q(`<header class=topbar><span class="title display grow">Hub`),hV=q(`<div class=home-shell><div class=home-scroll>`),gV=()=>Ue().name===`concierge`&&!Z(),_V=()=>{let e=Kx();return e.name===`session`?vs(e.id,ou(),fu(),Y.machines,cu(),cu()?[]:hu()):void 0},vV=()=>{let e=Kx();return _V()===`session`?e.id:void 0},yV=()=>kc(Rc(fb().phase===`off`,vV()),Ue().name===`concierge`?ou()?.sessionID:void 0);function bV(){qu(()=>fb().phase!==`off`),C(()=>Ju(yV()));let[e,t]=x(``),[r,i]=x(!1),o=async()=>{t(``);try{if(!await Fu())return;Zu(yV()),yd(),Pf(),i(!0)}catch(e){t(`Cannot reach the hub: ${e.message}`)}};return C(h(()=>Ue().name,e=>{e!==`pair`&&!r()&&o(),Z()&&bp(!1)})),C(()=>{!X()&&r()&&Ue().name!==`pair`&&i(!1)}),C(()=>{let e=Ue();e.name===`session`&&gu().has(e.id)&&a(`/concierge`,{replace:!0})}),C(()=>hb.viewing(Lc()??vV())),ue(()=>j(bE())),ue(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`b`&&(e.preventDefault(),Tp())};document.addEventListener(`keydown`,e),j(()=>document.removeEventListener(`keydown`,e))}),C(()=>Fp(gV())),C(()=>{let e=Ip(),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`)}),C(()=>{r()&&location.hash===`#speech`&&Ue().name!==`settings`&&a(`/settings/voice#speech`,{replace:!0})}),[n(ee,{get children(){return[n(A,{get when(){return V(()=>Ue().name===`pair`)()&&Ue()},children:e=>n(pf,{get next(){return e().next},get error(){return e().error}})}),n(A,{get when(){return e()},get children(){var t=iV(),n=t.firstChild,r=n.nextSibling;return I(n,e),r.$$click=()=>void o(),t}}),n(A,{get when(){return!r()},get children(){return aV()}}),n(A,{get when(){return V(()=>Ue().name===`approve`)()&&Ue()},children:e=>n(hf,{get code(){return e().code}})}),n(A,{when:!0,get children(){var e=dV(),t=e.firstChild;return I(e,n(u,{get when(){return!Z()||yp()},get children(){return[n(u,{get when(){return Z()},get children(){var e=oV();return e.$$click=()=>bp(!1),e}}),n(u,{get when(){return!_p()||Z()},get children(){return[n(yA,{get phone(){return Z()},onClose:()=>bp(!1),onCollapse:Tp}),n(u,{get when(){return!Z()},get children(){return n(Zb,{panel:`side`,label:`Resize sidebar`})}})]}})]}}),t),I(e,n(u,{get when(){return V(()=>!!_p())()&&!Z()},get children(){return n(Xk,{onExpand:Tp})}}),t),I(t,n(u,{get when(){return V(()=>fb().phase!==`off`)()&&Kx().name!==`session`},get children(){var e=sV();return I(e,n(LO,{})),e}}),null),I(t,n(u,{get when(){return Y.connection===`down`},get children(){return cV()}}),null),I(t,n(u,{get when(){return V(()=>Y.connection!==`down`)()&&Hu()},get children(){var e=lV();return I(e,()=>Hu()===`reconnecting`?`Reconnecting…`:`Updated`),D(()=>G(e,`sync-note ${Hu()}`)),e}}),null),I(t,n(u,{get when(){return V(()=>!(!Wp()||Z()||vV()))()&&Kx().name!==`panes`},get children(){return n(Mz,{})}}),null),I(t,n(ee,{get children(){return[n(A,{get when(){return V(()=>!fu())()&&(Kx().name===`session`||Kx().name===`panes`)||_V()===`wait`},get children(){return uV()}}),n(A,{get when(){return vV()||Kx().name===`panes`},get children(){return n(xB,{get routed(){return vV()}})}}),n(A,{get when(){return V(()=>Kx().name===`new`)()&&Kx()},children:e=>n(Ux,ce(()=>e()))}),n(A,{get when(){return V(()=>Kx().name===`feature`)()&&Kx()},children:e=>n(DB,ce(()=>e()))}),n(A,{get when(){return Kx().name===`settings`},get children(){return n(aO,{})}}),n(A,{get when(){return Kx().name===`concierge`},get children(){return n(eV,{mode:`page`})}}),n(A,{when:!0,get children(){return n(xV,{})}})]}}),null),I(e,n(u,{get when(){return gV()},get children(){return n(eV,{mode:`side`})}}),null),D(()=>G(e,`shell${_p()&&!Z()?` collapsed`:``}${Z()?` phone`:``}${yp()?` drawer`:``}`)),e}})]}}),n(hh,{}),n(Ae,{}),n(u,{get when(){return fe()},children:e=>(()=>{var t=pV(),r=t.firstChild;return I(r,()=>e().text),I(t,n(u,{get when(){return e().action},get children(){var t=fV();return t.$$click=()=>{e().action.run(),Ve()},I(t,()=>e().action.label),t}}),null),D(()=>G(t,`toast ${e().kind}`)),t})()})]}function xV(){return(()=>{var e=hV(),t=e.firstChild;return I(e,n(u,{get when(){return Z()},get children(){var e=mV(),t=e.firstChild;return I(e,n(R,{icon:`menu`,label:`Open sidebar`,onClick:Tp}),t),I(e,n(rA,{}),null),e}}),t),I(t,n(Gb,{})),e})()}P([`click`]),je(()=>n(bV,{}),document.getElementById(`root`)),Ff();export{pF as A,Wf as B,SL as C,uI as D,jI as E,qp as F,Tu as H,Kp as I,Z as L,qA as M,EE as N,yF as O,mh as P,Tp as R,HI as S,VI as T,Eu as U,Y as V,oL as _,ML as a,PI as b,zL as c,jL as d,NL as f,sL as g,cL as h,PL as i,WP as j,hF as k,AL as l,lL as m,IL as n,kL as o,ZI as p,FL as r,EL as s,wB as t,LL as u,aL as v,LI as w,NI as x,iL as y,Kf as z};
|