@huynle/hub 0.8.0 → 0.8.2
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 +326 -1
- package/README.md +85 -16
- package/package.json +1 -1
- package/packages/claude-code/package.json +1 -1
- package/packages/claude-code/src/paths.ts +3 -3
- package/packages/cli/dist/hub-cli.js +723 -281
- package/packages/cli/package.json +1 -1
- package/packages/cli/src/artifact-jobs-mcp.ts +10 -9
- package/packages/cli/src/artifacts-mcp.ts +8 -7
- package/packages/cli/src/bootstrap/adapters/node-services/render.ts +2 -2
- package/packages/cli/src/bootstrap/discovery/host.ts +15 -1
- package/packages/cli/src/bootstrap/discovery/probe.ts +1 -1
- package/packages/cli/src/bootstrap/enrollment/enroll.ts +3 -3
- package/packages/cli/src/bootstrap/enrollment/policy.ts +13 -0
- package/packages/cli/src/cli.ts +3 -3
- package/packages/cli/src/http.ts +1 -0
- package/packages/cli/src/launches.ts +9 -3
- package/packages/cli/src/login.ts +2 -2
- package/packages/cli/src/mcp.ts +9 -4
- package/packages/cli/src/messaging.ts +4 -2
- package/packages/cli/src/profiles-mcp.ts +301 -0
- package/packages/cli/src/setup/commands.ts +20 -2
- package/packages/cli/src/spoke-services.ts +1 -1
- package/packages/cli/src/team-intake-mcp.ts +8 -7
- package/packages/cli/src/teams-mcp.ts +61 -3
- package/packages/cli/src/tool-args.ts +6 -0
- package/packages/cli/src/watchlist.ts +5 -4
- package/packages/codex/package.json +1 -1
- package/packages/codex/src/paths.ts +3 -3
- package/packages/node/package.json +1 -1
- package/packages/node/src/config.ts +10 -2
- package/packages/node/src/opencode-warm.ts +27 -8
- package/packages/node/src/run.ts +3 -2
- package/packages/preset/package.json +1 -1
- package/packages/protocol/package.json +1 -1
- package/packages/protocol/src/concierge.ts +4 -1
- package/packages/protocol/src/embedded-media.ts +59 -0
- package/packages/protocol/src/index.ts +90 -7
- package/packages/protocol/src/launch.ts +14 -0
- package/packages/protocol/src/wire.ts +1 -0
- package/packages/runtime-openshell/package.json +1 -1
- package/packages/runtime-sdk/package.json +1 -1
- package/packages/sdk/package.json +1 -1
- package/packages/sdk/src/client.ts +3 -1
- package/packages/sdk/src/errors.ts +1 -0
- package/packages/sdk/src/index.ts +1 -0
- package/packages/sdk/src/types.ts +22 -2
- package/packages/sdk/src/wake.ts +20 -0
- package/packages/spoke-sdk/package.json +1 -1
- package/packages/spoke-sdk/src/connection.ts +13 -1
- package/src/central/agent/acting-routes.ts +3 -2
- package/src/central/agent/acting.ts +70 -12
- package/src/central/agent/audit.ts +1 -1
- package/src/central/agent/decisions.ts +58 -2
- package/src/central/agent/delivery.ts +111 -28
- package/src/central/agent/errors.ts +2 -0
- package/src/central/agent/escalation.ts +39 -10
- package/src/central/agent/events.ts +7 -1
- package/src/central/agent/launch-engine.ts +173 -30
- package/src/central/agent/launch-routes.ts +20 -9
- package/src/central/agent/launch-spec.ts +60 -17
- package/src/central/agent/launch-store.ts +55 -2
- package/src/central/agent/message-limits.ts +89 -11
- package/src/central/agent/message-routes.ts +8 -3
- package/src/central/agent/messages.ts +3 -2
- package/src/central/agent/placement.ts +93 -18
- package/src/central/agent/read-routes.ts +3 -0
- package/src/central/agent/routes.ts +11 -2
- package/src/central/agent/webhooks.ts +17 -2
- package/src/central/artifacts/jobs-routes.ts +4 -1
- package/src/central/concierge/board-routes.ts +13 -2
- package/src/central/concierge/context.ts +3 -1
- package/src/central/concierge/inbound.ts +4 -7
- package/src/central/concierge/prompt.ts +10 -6
- package/src/central/concierge/proposals.ts +8 -2
- package/src/central/concierge/routes.ts +62 -2
- package/src/central/concierge/session-routes.ts +62 -6
- package/src/central/concierge/supervisor.ts +34 -7
- package/src/central/concierge/watchlist-routes.ts +4 -2
- package/src/central/config.ts +21 -5
- package/src/central/http.ts +87 -35
- package/src/central/main.ts +1 -1
- package/src/central/registry.ts +49 -4
- package/src/central/revert-windows.ts +66 -0
- package/src/central/spoke-ws.ts +6 -3
- package/src/central/teams/intake.ts +20 -6
- package/src/central/teams/staffing.ts +24 -2
- package/src/central/workspaces/sidechats-routes.ts +1 -1
- package/src/index.ts +63 -30
- package/src/migrate.ts +109 -3
- package/src/spoke/deliver.ts +6 -0
- package/src/spoke/env-inject.ts +8 -1
- package/src/spoke/fork-revert.ts +94 -9
- package/src/spoke/hub-tool.ts +26 -12
- package/src/spoke/launchers.ts +6 -4
- package/src/spoke/listing.ts +18 -6
- package/src/spoke/localhub.ts +14 -4
- package/src/spoke/locations.ts +120 -0
- package/src/spoke/profile-apply.ts +24 -14
- package/src/spoke/session-context.ts +183 -33
- package/src/spoke/spoke.ts +129 -41
- package/src/spoke/timeline.ts +30 -3
- package/src/spoke/tracker.ts +17 -1
- package/src/status.ts +2 -1
- package/web/dist/assets/ArtifactPage-R0ZTpHca.js +1 -0
- package/web/dist/assets/ArtifactPane-C9KrBna8.js +1 -0
- package/web/dist/assets/ArtifactWorkbench-sP2mZccC.js +6 -0
- package/web/dist/assets/Library-BXbJvTUS.js +2 -0
- package/web/dist/assets/ProfilesDestination-D7XyLTJ7.js +1 -0
- package/web/dist/assets/TeamsPage-Dgxt8UI3.js +1 -0
- package/web/dist/assets/Watchtower-DJHx6cWw.js +2 -0
- package/web/dist/assets/index-BabrNDB3.css +1 -0
- package/web/dist/assets/index-g4V9mfSr.js +34 -0
- package/web/dist/assets/live-OgQWPrSY.js +5 -0
- package/web/dist/assets/{pane-layout-CKC4I00k.js → pane-layout-DWXfDU-1.js} +1 -1
- package/web/dist/assets/{renderer2d-CX5j3NcD.js → renderer2d-DjEipyto.js} +1 -1
- package/web/dist/assets/{renderer3d-BXIVOvfi.js → renderer3d-B648jKGO.js} +1 -1
- package/web/dist/assets/{safe-area-DfPsOdWR.js → safe-area-CNLyboIj.js} +1 -1
- package/web/dist/assets/{silero-worker-C8-8vLVS.js → silero-worker-DhlIHyD_.js} +1 -1
- package/web/dist/assets/{source-CvUHTc3O.js → source-CDU04kYw.js} +1 -1
- package/web/dist/assets/ui-Dh1-78Cl.js +3 -0
- package/web/dist/index.html +4 -4
- package/web/dist/assets/ArtifactPage-BS0gVkfu.js +0 -1
- package/web/dist/assets/ArtifactPane-PLYHNs6s.js +0 -1
- package/web/dist/assets/ArtifactWorkbench-LkDyJ5Dv.js +0 -6
- package/web/dist/assets/Library-CtxRqTjo.js +0 -2
- package/web/dist/assets/ProfilesDestination-BYiHKLmc.js +0 -1
- package/web/dist/assets/TeamsPage-BwjsAAUC.js +0 -1
- package/web/dist/assets/Watchtower-C4swrWVs.js +0 -2
- package/web/dist/assets/index-DaH5GUdV.js +0 -31
- package/web/dist/assets/index-WWuKfWxL.css +0 -1
- package/web/dist/assets/live-YyTjE47g.js +0 -5
- package/web/dist/assets/ui-C9Igxzjm.js +0 -1
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ArtifactPane-C9KrBna8.js","assets/ui-Dh1-78Cl.js","assets/ArtifactWorkbench-sP2mZccC.js","assets/source-CDU04kYw.js","assets/ArtifactWorkbench-9eTj1CeW.css","assets/Library-BXbJvTUS.js","assets/Library-DYsFj_5c.css","assets/TeamsPage-Dgxt8UI3.js","assets/plural-Bspvoqfq.js","assets/live-OgQWPrSY.js","assets/live-BUofsQpz.css","assets/Watchtower-DJHx6cWw.js","assets/Watchtower-CTgqHk5g.css","assets/ProfilesDestination-D7XyLTJ7.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 N,a as pe,at as P,b as me,bt as he,c as ge,ct as _e,d as ve,dt as F,et as ye,f as I,ft as L,g as be,gt as xe,h as Se,ht as R,i as z,it as B,j as Ce,jt as we,k as Te,kt as Ee,l as De,lt as Oe,m as ke,mt as Ae,n as je,nt as V,o as Me,ot as Ne,p as Pe,pt as H,q as Fe,r as U,rt as W,s as Ie,st as Le,t as Re,tt as G,u as ze,ut as K,v as Be,vt as Ve,w as He,wt as Ue,x as We,xt as Ge,y as q,yt as J,z as Ke,zt as qe}from"./ui-Dh1-78Cl.js";import{a as Je,c as Ye,d as Xe,f as Ze,g as Qe,h as $e,i as et,l as tt,m as nt,n as rt,o as it,p as at,r as ot,s as st,t as ct,u as lt}from"./pane-layout-DWXfDU-1.js";import{t as ut}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 dt=e=>e==null?``:String(e).trim(),ft=Object.freeze([[`role`,`Admins first`],[`email`,`Email`],[`lastSeen`,`Last seen`]]),pt=Object.freeze([[`all`,`All`],[`admins`,`Admins`],[`active`,`Active`],[`disabled`,`Disabled`]]),mt=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 ht(e){return e?.user?.role===`admin`}function gt(e){let t=e?.user,n=e?.auth===`oidc`?`oidc`:`pairing`,r=ht(e);if(n!==`oidc`)return{mode:n,admin:r,title:`This hub`,initial:`H`};let i=dt(t?.name),a=dt(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 _t=Object.freeze([[`users`,`Users`],[`machines`,`Machines`],[`approvals`,`Approvals`],[`audit`,`Audit log`]]);function vt(e){return ht(e)?_t.filter(([t])=>t!==`users`||e?.auth===`oidc`):[]}function yt(e,t){return ht(e)&&t?.scope===`user`?[`user`,`default`]:[`user`]}function bt(e){return e&&e.startsWith(`/`)&&!e.startsWith(`//`)&&!e.includes(`\\`)?e:`/`}function xt(e,t){if(e?.mode===`oidc`&&typeof e.signIn==`string`&&e.signIn)return`${e.signIn}?next=${encodeURIComponent(bt(t))}`}function St(e){let t=e?.auth===`oidc`?dt(e?.user?.email):``;return t?`This machine will belong to you (${t}).`:`This machine will belong to you.`}var Ct={stt:[`provider`,`model`,`baseURL`,`language`],tts:[`provider`,`model`,`voice`,`baseURL`,`speed`]};function wt(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 Ct[e]){let n=r?s[t]===void 0||s[t]===null:dt(a[t])===dt(o[t]),l=dt(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 Tt(e){return{[e]:Object.fromEntries([...Ct[e],`apiKey`].map(e=>[e,null]))}}function Et(e){let t=dt(e);if(!t)return`Unknown action`;if(mt[t])return mt[t];let n=t.replace(/[._-]+/g,` `).trim().toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)}function Dt(e,t=[]){let n=new Map(t.map(e=>[e.id,dt(e.email)||dt(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:Et(e.action),target:e.target===void 0?void 0:n.get(e.target)??e.target,detail:e.detail}))}var Ot=e=>(dt(e.email)||dt(e.name)||e.id).toLowerCase();function kt(e,{query:t=``,filter:n=`all`,sort:r=`role`}={}){let i=dt(t).toLowerCase(),a=e=>(!i||`${dt(e.email)} ${dt(e.name)}`.toLowerCase().includes(i))&&(n===`admins`?e.role===`admin`:n===`disabled`?!!e.disabled:n!==`active`||!e.disabled),o=(e,t)=>Ot(e).localeCompare(Ot(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 At(e,t,n){let r=dt(e.email)||dt(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 jt(e){let t=dt(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 Mt=e=>String(e??``).normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase(),Nt=e=>`${e.providerID}/${e.modelID}`,Pt=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=Mt(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&&!Mt([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:Nt(e),variants:e.variant?[e.variant]:[],stale:!0}}},Ft=e=>`${e}:reasoning`,It=(e,t)=>t===void 0?`${e}:text`:`${e}:text:${t}`,Lt=e=>`hubmsg:${e}`,Rt=1e3,zt=(e,t)=>`activity:${e}:${t}`,Bt=(e,t)=>e.pos-t.pos||e.live-t.live,Vt=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({...Ht(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(Ft(t)),e.kind===`assistant`&&t&&(typeof e.ordinal==`number`&&n.push(It(t,e.ordinal)),(e.ordinal===void 0||e.ordinal===0)&&n.push(It(t))),e.kind===`tool`&&typeof e.callID==`string`&&typeof e.sessionID==`string`&&n.push(zt(e.sessionID,e.callID)),e.kind===`message`&&t&&n.push(Lt(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(Ft(t));let a=i?.key??Ft(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=It(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=It(e),n=-1;for(let r of this.items.values()){if(r.kind!==`assistant`||r.messageID!==e||this.history.has(r.key))continue;let i=r.key.startsWith(`${e}:text:`)?Number(r.key.slice(e.length+6)):NaN;Number.isInteger(i)&&i>n&&([t,n]=[r.key,i])}return t}activity(e,t){if(!t||typeof t.id!=`string`||t.kind===`thinking`)return;let n=zt(e,t.id),r=this.items.get(n);this.upsert({key:n,sessionID:e,kind:`tool`,callID:t.id,...t.tool?{name:t.tool}:{},...t.summary?{summary:t.summary}:{},...t.error?{error:t.error}:{},...t.childSessionID?{childSessionID:t.childSessionID}:{},state:t.state,at:r?.at??t.at})}endReasoning(e,t=Date.now()){for(let n of this.items.values())n.kind===`reasoning`&&n.state===`running`&&(e===void 0||n.sessionID===e)&&this.upsert({key:n.key,kind:n.kind,state:`done`,completed:t})}upsert(e){e&&typeof e.key==`string`&&(this.places.has(e.key)||this.places.set(e.key,this.livePlace()),this.put(e))}livePlace(){return{pos:this.top,live:++this.liveSeq}}put(e){this.items.set(e.key,{...this.items.get(e.key)??{},...e})}hubMessage(e){if(e&&typeof e.key==`string`&&typeof e.messageID==`string`){for(let[t,n]of this.items)if(t!==e.key&&n.kind===`message`&&n.messageID===e.messageID&&this.history.has(t))return;if(!this.places.has(e.key)){if(typeof e.at==`number`&&Number.isFinite(e.at)){let t=e.at*Rt;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)=>Bt(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)=>Bt(e.place,t.place)).flatMap(e=>e.rows)}};function Ht(e,t){return Object.fromEntries(t.filter(t=>e[t]!==void 0).map(t=>[t,e[t]]))}function Ut(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 Wt(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:Lt(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:Ut(n.from),to:n.to,...typeof n.replyTo==`string`?{replyTo:n.replyTo}:{}},recipient:Ut(n.recipient),...typeof n.state==`string`?{state:n.state}:{},...typeof n.delivery==`string`?{delivery:n.delivery}:{}}}var Gt=new Set([`open`,`answered`,`expired`,`closed`]),Kt=e=>!!e&&typeof e==`object`&&!Array.isArray(e);function qt(e){if(!Kt(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`||!Gt.has(i)||typeof o!=`number`||!Kt(s))return;let c=r.filter(e=>Kt(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 Jt=(e,t)=>t.at-e.at||(e.id<t.id?1:-1);function Yt(e){return e.filter(e=>e.state===`open`).sort(Jt)}function Xt(e,t){return Yt([...e.filter(e=>e.id!==t.id),t])}function Zt(e,t){return e.filter(e=>e.from.kind===`session`&&e.from.sessionID===t||e.about.includes(t))}var Qt=new Set,$t=(e,t=Qt)=>e.as===`concierge`||e.from.kind===`session`&&t.has(e.from.sessionID)?`@@concierge`:Ut(e.from),en=e=>e.tier===`tap`?`Answer here (tap): only a signed-in console can answer this one.`:``;function tn(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 nn(e,t){if(e.deadline===void 0)return``;let n=tn(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 rn(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 an=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)=>Xt(e,t),Yt(t))}fail(e){this.pending.delete(e)}},on=`@@concierge`,sn=/\nThe Concierge's note: ([\s\S]*)$/,cn=/proposes to deny ([\s\S]*) in (?:@[\w-]+|ses_\w+)\.(?:\nThe Concierge's note: [\s\S]*)?$/,ln=/^[\s\S]*? asks to approve( always(?: \(saves [\s\S]*?\))?)? ([\s\S]*)\. Outside its grant: ([\s\S]*)$/,un=`a permission request (details unknown)`,dn=e=>typeof e==`string`&&e?e:void 0;function fn(e){let t=Array.isArray(e.resources)?e.resources.filter(e=>typeof e==`string`):void 0,n=dn(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??dn(e.summary),resources:t??[]}:{action:n??e.summary.slice(0,r),resources:t??[e.summary.slice(r+2)]}}function pn(e){let t=e.indexOf(`: `);return t<0?{action:e,resources:[]}:{action:e.slice(0,t),resources:[e.slice(t+2)]}}function mn(e,t,n){if(e)return{...fn(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 hn=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 gn(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 _n=(e,t)=>({id:t,label:e.label(t)??t}),vn=e=>Array.isArray(e)?e.map(String).join(`, `):typeof e==`object`&&e?JSON.stringify(e):String(e);function yn(e,t){let n=e.action;if(n?.kind===`permission`){let r=$t(e),i=e.from.kind===`session`&&r===e.from.sessionID?t.label(e.from.sessionID)??r:r,a=ln.exec(e.question),o=n.sessionID??n.rootID??e.about[0],s=mn(gn(t,[n.sessionID,n.rootID,...e.about],`permission`,n.requestID),n.request,()=>a&&a[2]!==un?pn(a[2]):void 0),c=dn(n.reason)??a?.[3]?.trim(),l=e.recommendation?.why;return{kind:`permission`,requester:i,...o?{target:_n(t,o)}:{},...hn(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??sn.exec(e.question)?.[1]?.trim(),a={kind:`proposal`,verb:n.verb??`act`,target:_n(t,n.target),always:!1,...i?{purpose:{by:on,text:i}}:{}};switch(n.verb){case`deny`:{let i=dn(r.requestID),o=gn(t,[n.target],`permission`,i),s=cn.exec(e.question)?.[1],c=mn(o,n.request,()=>s&&s!==`permission request ${i}`?pn(s):void 0);return{...a,...hn(c),...i?{requestID:i}:{}}}case`prompt`:return{...a,resources:[],...dn(r.text)?{text:dn(r.text)}:{}};case`answer`:{let e=dn(r.formID),i=gn(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:vn(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=fn(a);return{kind:`ask`,target:_n(t,i),...o.action?{action:o.action}:{},resources:o.resources,always:!1,requestID:a.id,source:`live`}}function bn(e){if(e.action?.kind!==`act`)return e.question;let t=e.question.replace(sn,``);return e.action.verb===`prompt`||e.action.verb===`answer`?t.split(`
|
|
3
|
+
`)[0]:t}var xn=typeof Intl<`u`&&`Segmenter`in Intl?new Intl.Segmenter(void 0,{granularity:`grapheme`}):void 0;function Sn(e){return xn?Array.from(xn.segment(e),e=>e.segment):Array.from(e)}function Cn(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=Sn(r);return o.length>t&&(r=o.slice(0,t).join(``),i=!0),{text:i?`${r}…`:r,cut:i}}var wn=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 Tn(e){return e.replace(wn,(e,t)=>t||`⟨U+${e.codePointAt(0).toString(16).toUpperCase().padStart(4,`0`)}⟩`)}var En=/(?<![\w/.-])ses_[A-Za-z0-9]{1,64}(?![\w])/g,Dn=10,On=e=>e.length>12?`${e.slice(0,Dn)}…`:e,kn=e=>e.replace(/[/\\]+$/,``).split(/[/\\]/).pop()||``;function An(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?kn(t.directory):``;return a?`${a} · ${On(e)}`:On(e)}function jn(e,t){return e.replace(En,e=>t(e))}function Mn(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 Nn(e,t,n=new Set){return $t(e,n)===`@@concierge`?`@@concierge`:Mn(e.from,t)}var Pn=e=>e.from.kind===`session`?e.from.sessionID:e.from.kind===`app`?e.from.tokenID:void 0;function Fn(e,t,n=new Set){let r=e.action;return r?.kind===`permission`&&r.request&&typeof r.request.action==`string`?`${Nn(e,t,n)} asks to approve ${r.request.action}${r.always?` always`:``}`:jn(bn(e),t)}var In=[`approve`,`deny`,`answer`,`prompt`,`stop`,`roles`,`launch`],Ln=new Set([`active`,`expired`,`revoked`]),Rn=e=>!!e&&typeof e==`object`&&!Array.isArray(e),zn=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),Bn=[`sessions:read`,`sessions:manage`,`messages:send`,`messages:read`,`sessions:act`,`sessions:launch`,`events:subscribe`,`profiles:read`,`profiles:manage`,`profiles:assign`,`workspaces:read`,`workspaces:manage`,`artifacts:read`,`artifacts:write`,`artifacts:ai`,`teams:read`,`teams:manage`,`teams:submit`];function Vn(e){if(Rn(e)&&typeof e.id==`string`&&/^[0-9a-f]{16}$/.test(e.id)&&zn(e.scopes))return{id:e.id,...typeof e.label==`string`?{label:e.label}:{},scopes:e.scopes.filter(e=>Bn.includes(e)),...typeof e.created==`number`?{created:e.created}:{}}}function Hn(e){return(Rn(e)&&Array.isArray(e.tokens)?e.tokens:[]).map(Vn).filter(e=>!!e)}function Un(e,t){let n=e.trim();if(!n)return{ok:!1,error:`Give the token a label`};if(!t.length)return{ok:!1,error:`Pick at least one scope`};let r=t.find(e=>!Bn.includes(e));return r?{ok:!1,error:`Unknown scope: ${r}`}:{ok:!0,body:{label:n,scopes:[...new Set(t)]}}}var Wn={"sessions:read":`Read your sessions and their activity`,"sessions:manage":`Name sessions and claim roles`,"messages:send":`Send messages and asks, reply and decline`,"messages:read":`Read messages to it`,"sessions:act":`Approve, deny, answer, prompt and stop sessions (only under a grant)`,"sessions:launch":`Launch sessions (only under a grant with verb launch for the repo)`,"events:subscribe":`Subscribe webhooks to events`,"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`},Gn=e=>Bn.includes(e);function Kn(e){let t=Rn(e)?e.login:void 0;if(Rn(t)&&typeof t.userCode==`string`&&typeof t.clientName==`string`&&zn(t.scopes)&&typeof t.created==`number`&&typeof t.expiresAt==`number`)return{userCode:t.userCode,clientName:t.clientName,scopes:t.scopes.filter(Gn),created:t.created,expiresAt:t.expiresAt}}function qn(e){return Bn.map(t=>{let n=e.scopes.includes(t);return{scope:t,label:Wn[t],requested:n,checked:n}})}function Jn(e){if(!e.length)return{ok:!1,error:`Pick at least one scope`};let t=e.find(e=>!Gn(e));return t?{ok:!1,error:`Unknown scope: ${t}`}:{ok:!0,body:{scopes:[...new Set(e)]}}}function Yn(e){if(!Rn(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`&&Ln.has(u)&&Rn(r)&&zn(r.projects)&&zn(i)&&Rn(a)&&zn(a.allow)&&zn(a.never)&&typeof o==`boolean`&&typeof s==`number`&&typeof c==`number`&&typeof l==`number`)return e}function Xn(e){return(Rn(e)&&Array.isArray(e.grants)?e.grants:[]).map(Yn).filter(e=>!!e)}function Zn(e,t){return e.state===`revoked`||e.revokedAt!==void 0?`revoked`:e.state===`expired`||t>=e.expiresAt?`expired`:`active`}var Qn={active:`Active`,expired:`Expired`,revoked:`Revoked`};function $n(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 er(e,t){let n=Zn(e,t);return{id:e.id,holder:e.holderSessionID?`${e.holder} (${e.holderSessionID})`:e.holder,state:n,stateLabel:Qn[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 ${$n(e.expiresAt,t)}`:Qn[n],editable:n===`active`}}function tr(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 nr=e=>e.split(`
|
|
9
|
+
`).map(e=>e.trim()).filter(Boolean),rr=/^\d+(s|m|h|d)?$/,ir=e=>/^([A-Za-z]:)?[\\/]/.test(e);function ar(e){let t={},n=e.holder.trim();n||(t.holder=`Who holds it: @@orchestrator, @name, ses_… or app:<token id>`);let r=nr(e.projects),i=r.find(e=>!ir(e));r.length?i!==void 0&&(t.projects=`${i} is not an absolute directory`):t.projects=`At least one project directory`;let a=In.filter(t=>e.allow.includes(t));a.length||(t.allow=`Pick at least one action`);let o=e.expires.trim();rr.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:nr(e.permit),never:nr(e.never)},expires:o,maxActionsPerHour:c,allowAlways:e.allowAlways}}}function or(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 sr(e){if(!Rn(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`&&Rn(r)&&typeof r.kind==`string`&&typeof i==`string`&&Rn(a)&&typeof o==`string`&&typeof s==`string`)return e}function cr(e){if(!Rn(e))return{entries:[]};let t=(Array.isArray(e.entries)?e.entries:[]).map(sr).filter(e=>!!e);return typeof e.next==`number`?{entries:t,next:e.next}:{entries:t}}var lr={allow:`allowed`,needs_user:`needs you`,forbidden:`refused`,paused:`paused`,rate_limited:`rate limited`,busy:`hub busy`},ur={ok:`done`,failed:`failed`,gone:`already answered`,offline:`offline`,unsupported:`unsupported`,escalated:`sent to you`,refused:`refused`},dr=new Set([`forbidden`,`paused`,`rate_limited`,`busy`]),fr=new Set([`failed`,`refused`,`offline`,`unsupported`]),pr={"acting.pause":`turned agent actions off`,"acting.resume":`turned agent actions on`},mr={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 $`]},hr={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`]},gr=/^Decision dec_[A-Za-z0-9]{1,64}: (\w+)$/;function _r(e,t,n){let r=hr[gr.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 vr(e,t,n,r){if(e===`propose`)return _r(r,t,n);let i=mr[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 yr=(e,t)=>e.as===`concierge`?`@@concierge`:e.actor.kind===`user`?`you`:t?Mn(e.actor,e=>t(e)??On(e)):Ut(e.actor);function br(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 xr(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 Sr=`Shell, outside folders and tools always need the user's tap`,Cr=`The Concierge never answers “always”: the user decides`,wr={approve:`Approved`,deny:`Denied`,answer:`Answered`,prompt:`Prompted`,stop:`Stopped`},Tr=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`),Er=/[\u061c\u200b-\u200f\u2028-\u202e\u2060-\u206f\ufeff\u{E0000}-\u{E007F}]/gu,Dr=300;function Or(e){let t=Tr(e).replace(Er,``).replace(/«/g,`‹`).replace(/»/g,`›`).replace(/[\u0000-\u001f\u007f-\u009f]/g,` `).replace(/\s+/g,` `).trim(),n=Array.from(t);return`«${n.length>Dr?`${n.slice(0,299).join(``)}…`:t}»`}function kr(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===Sr)return`Needed your tap: shell commands, outside folders and tools always do`;if(t===Cr)return`Needed your tap: the Concierge never answers “always”`;if(e.decision===`needs_user`)return t?`Needed you: ${Tr(t).replace(/ outside the grant\b/,` outside the Concierge's grant`)}`:`Needed you`;let n=wr[e.verb];return n&&e.decision===`allow`&&e.outcome===`ok`?`${n} by the Concierge inside your grant${t?`. Its note: ${Or(t)}`:``}`:Tr(t)}function Ar(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)??On(a):``,s=pr[e.verb]??vr(e.verb,i,o,e.reason),c=pr[e.verb]?void 0:[r,r&&a?`in ${a}`:a].filter(Boolean).join(` `)||void 0,l=lr[e.decision]??e.decision,u=ur[e.outcome]??e.outcome,d=e.decision===`allow`&&e.outcome===`ok`,f=t&&t.state!==`open`?`${u} · ${xr(t)}`:void 0;return{seq:e.seq,at:e.at,who:yr(e,n??(()=>void 0)),what:s,...c?{whatTitle:c}:{},result:d?`done`:f??(l===u?l:`${l} · ${u}`),tone:d||t?.state===`answered`?`ok`:dr.has(e.decision)||fr.has(e.outcome)?`err`:`warn`,grant:e.grant?`grant`:``,...e.grant?{grantTitle:e.grant}:{},reason:kr(e)}}var jr={approve:`Approved`,deny:`Denied`,answer:`Answered`},Mr=3,Nr=3,Pr=e=>e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()||e;function Fr(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(Pr)??[];if(!i.length)return`your grant`;let a=i.slice(0,Nr).join(`, `);return`your grant for ${i.length>Nr?`${a} and ${i.length-Nr} more`:a}`}function Ir(e,t,n){let r=jr[e.verb];if(!r||e.decision!==`allow`||e.outcome!==`ok`)return;let i=`${r} by ${yr(e,t)}`;return e.grant?{text:`${i} · ${Fr(e.grant,e,n)}`,title:e.grant}:{text:i}}function Lr(e,t,n){return Ir(e,t,n)?.text}function Rr(e,t){return[t,...e.filter(e=>e.seq!==t.seq)].sort((e,t)=>t.seq-e.seq).slice(0,100)}function zr(e,t,n,r){for(let i of e){if(i.target.requestID!==t&&i.target.formID!==t)continue;let e=Ir(i,n,r);if(e)return e}}function Br(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>=Mr)break;if(!c.target.sessionID||!t.has(c.target.sessionID)||n-c.at>6e5||r!==void 0&&c.at<r)continue;let e=Ir(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 Vr(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=Lr(a,void 0,i);if(e)return{key:a.target.requestID??a.target.formID??`seq-${a.seq}`,text:e}}}function Hr(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=Lr(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 Ur(e,t){return e.filter(e=>e.denial===void 0||!t.has(e.denial))}function Wr(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 Gr=/^(.*?) asks to approve( always(?: \(saves .*?\))?)? (.*?)\. Outside its grant: (.*)$/s,Kr=`a permission request (details unknown)`;function qr(e){if(e.action?.kind!==`permission`)return;let t={requester:$t(e),always:e.action.always===!0,...e.action.requestID?{requestID:e.action.requestID}:{}},n=Gr.exec(e.question);if(!n)return{...t,action:void 0,resources:[],reason:void 0};let r=n[3],i=r.indexOf(`: `),a=r!==Kr;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 Jr(e,t){return!Rn(e)||typeof e.by!=`string`||e.recommends!==`approve`?``:`${t?jn(e.by,t):e.by} recommends Approve${typeof e.why==`string`&&e.why?`: ${e.why}`:``}`}var Yr=Symbol(`store-raw`),Xr=Symbol(`store-node`),Zr=Symbol(`store-has`),Qr=Symbol(`store-self`);function $r(e){let t=e[Ge];if(!t&&(Object.defineProperty(e,Ge,{value:t=new Proxy(e,si)}),!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 ei(e){let t;return typeof e==`object`&&!!e&&(e[Ge]||!(t=Object.getPrototypeOf(e))||t===Object.prototype||Array.isArray(e))}function ti(e,t=new Set){let n,r,i,a;if(n=e!=null&&e[Yr])return n;if(!ei(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=ti(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=ti(i,t))!==i&&(e[a]=r))}return e}function ni(e,t){let n=e[t];return n||Object.defineProperty(e,t,{value:n=Object.create(null)}),n}function ri(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 ii(e,t){let n=Reflect.getOwnPropertyDescriptor(e,t);return!n||n.get||!n.configurable||t===Ge||t===Xr||(delete n.value,delete n.writable,n.get=()=>e[Ge][t]),n}function ai(e){qe()&&ri(ni(e,Xr),Qr)()}function oi(e){return ai(e),Reflect.ownKeys(e)}var si={get(e,t,n){if(t===Yr)return e;if(t===Ge)return n;if(t===ae)return ai(e),n;let r=ni(e,Xr),i=r[t],a=i?i():e[t];if(t===Xr||t===Zr||t===`__proto__`)return a;if(!i){let n=Object.getOwnPropertyDescriptor(e,t);qe()&&(typeof a!=`function`||Object.prototype.hasOwnProperty.call(e,t))&&!(n&&n.get)&&(a=ri(r,t,a)())}return ei(a)?$r(a):a},has(e,t){return t===Yr||t===Ge||t===ae||t===Xr||t===Zr||t===`__proto__`||(qe()&&ri(ni(e,Zr),t)(),t in e)},set(){return!0},deleteProperty(){return!0},ownKeys:oi,getOwnPropertyDescriptor:ii};function ci(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[Zr]&&e[Zr][t]&&i!==void 0&&e[Zr][t].$()):(e[t]=n,e[Zr]&&e[Zr][t]&&i===void 0&&e[Zr][t].$());let o=ni(e,Xr),s;if((s=ri(o,t,i))&&s.$(()=>n),Array.isArray(e)&&e.length!==a){for(let t=e.length;t<a;t++)(s=o[t])&&s.$();(s=ri(o,`length`,a))&&s.$(e.length)}(s=o[Qr])&&s.$()}function li(e,t){let n=Object.keys(t);for(let r=0;r<n.length;r+=1){let i=n[r];ui(i)||ci(e,i,t[i])}}function ui(e){return e===`__proto__`||e===`constructor`||e===`prototype`}function di(e,t){if(typeof t==`function`&&(t=t(e)),t=ti(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&&ci(e,n,r)}ci(e,`length`,r)}else li(e,t)}function fi(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&&ui(r)))return;if(Array.isArray(r)){for(let i=0;i<r.length;i++)fi(e,[r[i]].concat(t),n);return}if(o&&a===`function`){for(let i=0;i<e.length;i++)r(e[i],i)&&fi(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)fi(e,[r].concat(t),n);return}if(t.length>1){fi(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=ti(a),r===void 0||ei(i)&&ei(a)&&!Array.isArray(a)?li(i,a):ci(e,r,a))}function pi(...[e,t]){let n=ti(e||{}),r=Array.isArray(n),i=$r(n);function a(...e){Ee(()=>{r&&e.length===1?di(n,e[0]):fi(n,e)})}return[i,a]}var mi=Symbol(`store-root`);function hi(e){return e===`__proto__`||e===`constructor`||e===`prototype`}function gi(e,t,n,r,i){if(hi(n))return;let a=t[n];if(e===a)return;let o=Array.isArray(e);if(n!==mi&&(!ei(e)||!ei(a)||o!==Array.isArray(a)||i&&e[i]!==a[i])){ci(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++)gi(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++)ci(a,n,e[n]);for(;n<e.length;n++)ci(a,n,f[n]),gi(e[n],a,n,r,i);a.length>e.length&&ci(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?(ci(a,n,f[n]),gi(e[n],a,n,r,i)):ci(a,n,e[n])}else for(let t=0,n=e.length;t<n;t++)gi(e[t],a,t,r,i);a.length>e.length&&ci(a,`length`,e.length);return}let s=Object.keys(e);for(let t=0,n=s.length;t<n;t++)hi(s[t])||gi(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&&ci(a,c[t],void 0)}function _i(e,t={}){let{merge:n,key:r=`id`}=t,i=ti(e);return e=>{if(!ei(e)||!ei(i))return i;let t=gi(i,{[mi]:e},mi,n,r);return t===void 0?e:t}}var vi=new WeakMap,yi={get(e,t){if(t===Yr)return e;let n=e[t];if(t===Ge||t===ae||t===Xr||t===Zr||t===`__proto__`)return n;let r;return ei(n)?vi.get(n)||(vi.set(n,r=new Proxy(n,yi)),r):n},set(e,t,n){return ci(e,t,ti(n)),!0},deleteProperty(e,t){return ci(e,t,void 0,!0),!0}};function bi(e){return t=>{if(ei(t)){let n;(n=vi.get(t))||vi.set(t,n=new Proxy(t,yi)),e(n)}return t}}var xi={blocked:0,working:1,error:2,idle:3},Si=e=>xi[e]??3,Ci=e=>String(e??``).replace(/(.)[\\/]+$/,`$1`);function wi(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 xi?e.state:`idle`}function Ti(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 Ei(e){let t=`idle`;for(let n of e)Si(n)<xi[t]&&(t=n);return t}function Di(e){if(!e)return;if(e.kind===`thinking`)return`Thinking…`;let t=e.tool||`tool`;return e.summary?`${t} · ${e.summary}`:t}function Oi(e){return String(e??``).normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase()}var ki=e=>Oi(e).split(/\s+/).filter(Boolean);function Ai(e,t){let n=ki(t);if(!n.length)return!0;let r=[e.title||`Untitled`,e.projectName,e.project,e.directory].filter(Boolean).map(Oi);return n.every(e=>r.some(t=>t.includes(e)))}function ji(e,t){let n=Ci(e),r=Ci(t);return n===r?``:n.startsWith(`${r}/`)?n.slice(r.length+1):n}var Mi=e=>String(e??``).replace(/(.)[\\/]+$/,`$1`),Ni=e=>Mi(e).split(/[\\/]/).pop()||String(e??``),Pi=[`hiddenSessions`,`hiddenWorkspaces`,`pinnedSessions`,`pinnedWorkspaces`],Fi=500,Ii=5e3,Li=4096,Ri=e=>e===`hiddenSessions`?Ii:Fi,zi=(e,t=Fi)=>{if(!Array.isArray(e))return[];let n=[...new Set(e.filter(e=>typeof e==`string`&&e.length>0&&e.length<=Li))];return n.length>t?n.slice(n.length-t):n};function Bi(e){let t=e,n=t&&typeof t==`object`&&t.prefs&&typeof t.prefs==`object`?t.prefs:e??{};return Object.fromEntries(Pi.map(e=>[e,zi(n[e],Ri(e))]))}function Vi(e){let t=e.trim();return t?t.length>200?{error:`Title is longer than 200 characters`}:{title:t}:{error:`Enter a title`}}function Hi(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 Ui=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=Wi(e,n);a===r||t-i>this.graceMs?this.pending.delete(n):a!==void 0&&Hi(e,n,r)}}},Wi=(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 Gi(e,t,n,r){if(!Pi.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?zi([...i,...o],Ri(t)):i.filter(e=>!o.has(e));return{prefs:{...e,[t]:s},patch:{[t]:s}}}var Ki=e=>{try{let t=JSON.parse(e??`null`);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}};function qi(e,t,n){let r=e!=null||t!=null,i={};for(let[r,a]of[[`pinnedSessions`,e],[`pinnedWorkspaces`,t]]){let e=n[r]??[],t=Ki(a).filter(t=>!e.includes(t));t.length&&(i[r]=zi([...e,...t]))}return{clear:r,patch:Object.keys(i).length?i:void 0}}var Ji={working:`working`,blocked:`blocked`};function Yi(e){return Ei([wi(e),Ji[e?.terminal?.status??``]??`idle`])}var Xi=e=>!!e?.open&&e.terminal?.source===`herdr`&&!!e.terminal.workspaceID,Zi=e=>Mi(e?.project||e?.directory);function Qi(e){return Xi(e)?`herdr:${e.terminal.workspaceID}`:Zi(e)}var $i=(e,t)=>Zi(e)===t||Mi(e.directory)===t||Xi(e)&&Qi(e)===t;function ea(e,t){if(t.sessions.has(e.id))return!0;for(let n of t.workspaces)if($i(e,n))return!0;return!1}function ta(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 na(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?ta(e,t):t)}return[...r.values()]}function ra(e){let t=ia(e);return e=>ea(e,t)}var ia=e=>({sessions:new Set(e?.hiddenSessions??[]),workspaces:new Set(e?.hiddenWorkspaces??[])}),aa=e=>e?.terminals?.herdr?.workspaces??[];function oa(e){let t=Mi(e.project||e.directory),n=e.project?ji(e.directory,t):``;return`${e.projectName||Ni(t)}${n?` › ${n}`:``}`}function sa(e,t,n){let r=oa(t),i=n?.trim()||void 0;return{machine:e,where:r,...i?{branch:i}:{},text:[e,r,i].filter(Boolean).join(` · `)}}function ca(e,t,n){let r=Xi(e)?e.terminal.workspace||aa(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:Yi(e),blockers:Ti(e),exposed:e.exposed!==!1,pinned:n.has(e.id),nowText:Di(e.now),where:oa(e),workspace:r??(e.projectName||Ni(Zi(e))),machineID:t?.id}}var la=50,ua=200;function da(e){let t=aa(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(Mi))),r=na(e),i=new Map,a=new Map;for(let e of r){let t=Mi(e.directory);t&&(i.set(t,Math.max(i.get(t)??0,e.updated??0)),a.set(t,oa(e)))}for(let e of r){let t=Mi(e.project);if(!t||a.has(t))continue;let n=Math.max(...r.filter(e=>Mi(e.project)===t).map(e=>e.updated??0));i.set(t,n),a.set(t,e.projectName||Ni(t))}let o=[...i.entries()].filter(([e])=>!n.has(e)).sort((e,t)=>t[1]-e[1]).slice(0,la).map(([e])=>({kind:`folder`,key:e,label:a.get(e)??Ni(e),directories:[e]}));return{herdr:!!e?.terminals?.herdr,targets:[...t,...o]}}function fa({target:e,directory:t,title:n,openInHerdr:r}){let i={directory:t},a=String(n??``).trim().slice(0,ua);return a&&(i.title=a),r&&e?.kind===`herdr`&&e.workspaceID&&(i.herdrWorkspace=e.workspaceID),i}function pa(e){if(typeof e==`string`&&e)return e.includes(`budget`)?`Quota exceeded`:ma[e]}var ma={"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 ha(e){return typeof e==`number`&&Number.isInteger(e)&&e>=100&&e<=999?`HTTP ${e}`:void 0}function ga(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 _a=e=>typeof e==`string`&&e.trim()?e.trim():void 0,va=(e,t)=>e.toLowerCase()===t.toLowerCase(),ya=(e,t)=>e&&t&&!va(e,t)?t:void 0;function ba(e){let t=pa(e.errorType),n=_a(e.message),r=ha(e.errorStatus),i=ya(t,n);return`${t??n??`Error`}${r?` (${r})`:``}${i?`: ${i}`:``}`}function xa(e,t){let n=typeof e.attempt==`number`?` (attempt ${e.attempt})`:``,r=ga(e.next,t),i=pa(e.errorType),a=_a(e.message),o=ya(i,a),s=i?o?`${i} — ${o}`:i:a;return`Retrying${n}${r?` · next in ${r}`:``}${s?`: ${s}`:``}`}var Sa=e=>!!e&&typeof e==`object`&&typeof e.id==`string`;function Ca(e,t){let n=Array.isArray(e)?e.filter(Sa):[],r=t?n.find(e=>e.id===t):n[0];if(!r)return;if(r.state===`error`)return wa(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?wa(a):void 0}function wa(e){let t=_a(e.detail),n=ha(e.errorStatus),r=_a(e.title);return{sessionID:e.id,...r?{title:r}:{},label:pa(e.errorType)??t??`Error`,...t?{message:t}:{},...n?{status:n}:{},text:ba({errorType:e.errorType,errorStatus:e.errorStatus,message:t})}}var Ta=e=>Array.isArray(e)?e:[];function Ea(e){return Ta(e).flatMap(e=>(Array.isArray(e.jobs)?e.jobs:[]).map(t=>({...t,sessionID:e.id,sessionTitle:e.title??``})))}function Da(e){return Ea(e).filter(e=>e.status===`running`).length}function Oa(e,t){let n=Ea(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 ka(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 Aa(e,t){if(e.status===`running`)return e.started===void 0?`running`:`running · ${ka(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?ka(e.ended-e.started):void 0;return n?[n,r].filter(Boolean).join(` · `):[r??`ended`,i].filter(Boolean).join(` · `)}function ja(e){return e<=0?``:`${e} job${e===1?``:`s`}`}function Ma(e,t,n=Date.now()){let r=Ta(e),i=(t?r.find(e=>e.id===t&&e.retry):void 0)??r.find(e=>e.retry);return i?.retry?xa(i.retry,n):void 0}function Na(e,t,n,r=new Set){let i=new Set(t.pinnedSessions),a=new Set(t.hiddenSessions),o=ra(t),s=[];for(let t of e??[])for(let e of na(t)){if(r.has(e.id))continue;let c=ca(e,t,i),l=c.open?c.terminal?.source===`herdr`?`herdr`:`tui`:`background`,u=n[c.id],d=c.state===`working`?Ma(e.status,void 0,1/0):void 0,f=c.state===`error`?Ca(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:Qi(e),jobs:Da(e.status),...d?{retry:d}:{},...f?{error:f}:{}})}return s.sort((e,t)=>t.updated-e.updated)}function Pa(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 Fa=Object.freeze({query:``,filters:Object.freeze({status:`all`,source:`all`,machine:``,archived:!1}),sort:Object.freeze({key:`activity`,dir:`desc`})}),Ia=[`status`,`title`,`project`,`server`,`source`,`activity`],La=[`all`,`needs`,`running`,`idle`],Ra=[`all`,`open`,`background`],za=(e,t)=>e.localeCompare(t,void 0,{sensitivity:`base`}),Ba=(e,t)=>t.updated-e.updated,Va={status:(e,t)=>xi[e.state]-xi[t.state]||Ba(e,t),title:(e,t)=>za(e.title,t.title)||Ba(e,t),project:(e,t)=>za(e.workspace,t.workspace)||Ba(e,t),server:(e,t)=>za(e.machineName,t.machineName)||Ba(e,t),source:(e,t)=>za(e.source,t.source)||Ba(e,t),activity:(e,t)=>e.updated-t.updated};function Ha(e,t){let n=t.status===`needs`&&e.state===`blocked`;return!((t.archived?!e.hidden:e.hidden&&!n)||t.status===`needs`&&!Ja(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 Ua(e,t){if(!t.trim()||Ai(e,t))return!0;let n=Oi(t).split(/\s+/).filter(Boolean),r=[e.title,e.workspace,e.where,e.directory,e.machineName].map(Oi);return n.every(e=>r.some(t=>t.includes(e)))}function Wa(e,t){let n=Va[t.sort.key],r=t.sort.key===`activity`?t.sort.dir===`desc`?-1:1:t.sort.dir===`asc`?1:-1;return e.filter(e=>Ha(e,t.filters)&&Ua(e,t.query)).sort((e,t)=>r*n(e,t))}var Ga=(e,t,n)=>t.includes(e)?e:n;function Ka(e){let t;try{if(t=JSON.parse(e??`null`)??{},typeof t!=`object`||Array.isArray(t))return Fa}catch{return Fa}let n=t.filters??{},r=t.sort??{},i=Fa,a=Ga(r.key,Ia,i.sort.key),o=a===r.key?Ga(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:Ga(n.status,La,i.filters.status),source:Ga(n.source,Ra,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?Fa:{query:``,filters:l?i.filters:c,sort:s}}function qa(e){return JSON.stringify({filters:e.filters,sort:e.sort})}var Ja=e=>e.state===`blocked`||e.state===`error`&&!e.hidden;function Ya(e,{query:t,groupBy:n,sortBy:r,recentLimit:i=20}){let a=e.filter(e=>!e.hidden),o=e.filter(Ja),s=r===`title`?(e,t)=>za(e.title,t.title)||Ba(e,t):Ba;if(t.trim())return[{id:`results`,title:`Results`,kind:`results`,rows:a.filter(e=>Ua(e,t)).sort(Ba)}];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(Ba))}),d({id:`running`,title:`Running`,kind:`running`,rows:l(a.filter(e=>!c.has(e.id)&&e.running).sort(Ba))}),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`&&za(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(Ba);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(Ba).slice(0,i)}),u}var Xa=864e5;function Za(e,t,n){if(!Number.isInteger(t)||t<1)return[];let r=n-t*Xa;return e.filter(e=>!e.hidden&&!e.running&&!e.pinned&&!e.open&&e.updated<r)}function Qa(e,t){return t.phase!==`off`&&t.sessionID===e.id||e.conversation===!0}function $a(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 eo=.75,to=.05;function no(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/to)/Math.round(1/to);return Math.min(2,Math.max(eo,Number(n.toFixed(2))))}function ro(e){let t=no(e);return`${Number.isInteger(t)?t.toFixed(1):String(t)}×`}var io={working:`working`,blocked:`blocked`,error:`failed`,idle:`done`},ao=160,oo=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>ao?`…${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=io[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`:co(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 co(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 ${co(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 so(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 co(e){if(e.kind===`thinking`)return`Thinking…`;let t=e.tool||`tool`;return e.summary?`${t} · ${e.summary}`:t}var lo=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 uo(){let e=Object.values(lo),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 fo=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=lo[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}},po=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 fo;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)}]}},mo=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}},ho=new Set([`working`,`blocked`]);function go(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`&&!ho.has(t??``)?i.push(e.id):ho.has(t??``)&&!ho.has(e.state)&&a.push(e.id)}for(let[e,t]of r)ho.has(t)&&a.push(e);return{started:i,finished:a}}function _o(e){return(e??[]).some(e=>e.state===`working`)}var vo=Object.freeze([`openrouter`,`openai-compatible`]),yo={stt:[`provider`,`model`,`baseURL`,`language`],tts:[`provider`,`model`,`voice`,`baseURL`,`speed`]},bo=e=>e==null?``:String(e).trim();function xo(e){let t={};for(let n of[`stt`,`tts`]){let r=e?.[n]??{};t[n]=Object.fromEntries(yo[n].map(e=>[e,bo(r[e])])),t[n].apiKey={action:`keep`,value:``}}return t}function So(e,t){let n={};for(let r of[`stt`,`tts`]){let i=e?.[r]??{},a=t[r],o={};for(let e of yo[r]){if(e===`baseURL`&&bo(a.provider)!==`openai-compatible`)continue;let t=bo(a[e]);t!==bo(i[e])&&(o[e]=t===``?null:e===`speed`?Number(t):t)}a.apiKey?.action===`set`?o.apiKey=bo(a.apiKey.value):a.apiKey?.action===`clear`&&(o.apiKey=null),Object.keys(o).length&&(n[r]=o)}return n}function Co(e){let t={};for(let n of[`stt`,`tts`]){let r=e[n],i=(e,r)=>t[`${n}.${e}`]=r;if(vo.includes(bo(r.provider))||i(`provider`,`Choose a provider.`),bo(r.model)||i(`model`,`Enter a model.`),bo(r.provider)===`openai-compatible`){let e=bo(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`){bo(r.voice)||i(`voice`,`Enter a voice.`);let e=bo(r.speed);e&&!(Number(e)>=.25&&Number(e)<=4)&&i(`speed`,`Use a number from 0.25 to 4.`)}r.apiKey?.action===`set`&&!bo(r.apiKey.value)&&i(`apiKey`,`Paste the new key, or cancel.`)}return t}function wo(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 To=/^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i;function Eo(e,t){if(!e||e.stt&&e.tts)return;let n=!1;try{n=To.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 Do=()=>({machines:void 0,reads:{},prefs:Bi({}),prefsSource:`unknown`,prefsPending:0,prefsStale:!1,connection:`connecting`,enrollmentRev:0}),Oo=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function ko(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 Ao(e,t){if(!Oo(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 ko(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 ko(e.machines,t.sessionID,e=>{e.conversation=t.on,n=!0}),n}case`reads`:return Oo(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=Bi(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 jo(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??Mo(e,t)}function Mo(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=No(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 No(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 Po(e){return(e??[]).some(e=>e.state===`working`||e.state===`blocked`)}var Fo=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 oo(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(!Oo(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 Oo(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 Io(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 Lo=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=Io(e)===Io(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(Io(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 Ro(e,t){return t===`scope`&&e===`live`?{connection:`live`,reconnecting:!1}:{connection:`connecting`,reconnecting:e!==`connecting`}}var zo=e=>e===`app:concierge`||e===`app concierge`,Bo=/^(ses_[A-Za-z0-9]+)(?: \(sub ses_[A-Za-z0-9]+\))? (.*)$/,Vo=/^[!+-] (.*)$/,Ho=/^… (\d+) more updates not listed$/,Uo=2,Wo={permission:`needs a permission`,question:`has a question`};function Go(e,t){let n=/^machine \S+ (online|offline)$/.exec(e);if(n)return`a machine went ${n[1]}`;let r=Bo.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} ${Wo[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 Ko(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=Ho.exec(e);n&&(o+=Number(n[1]));let r=Vo.exec(e);r&&(a.length<Uo?a.push(Go(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 qo=60,Jo=/(`[^`]*`|\]\([^)]*\)|<[a-z][a-z0-9+.-]*:[^>\s]*>|\b[a-z][a-z0-9+.-]*:\/\/[^\s<>()]+)|(?<![\w#/[(])((?:Decision )?)(dec_[A-Za-z0-9]{1,64})(?!\w)/g,Yo=e=>{let t=Intl.Segmenter;return t?Array.from(new t(void 0,{granularity:`grapheme`}).segment(e),e=>e.segment):Array.from(e)},Xo=e=>{let t=e.replace(/\s+/g,` `).trim(),n=Yo(t);return n.length>qo?`${n.slice(0,59).join(``)}…`:t};function Zo(e){if(!e.includes(`dec_`))return[];let t=new Set;for(let n of e.matchAll(Jo))!n[1]&&n[3]&&t.add(n[3]);return[...t]}function Qo(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(Jo)){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 “${Xo(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 $o(e,t,n={}){return Qo(e,t,n).map(e=>e.href?`[${es(e.text)}](${e.href})`:e.text).join(``)}var es=e=>e.replace(/[\\`*_[\]<>~=]/g,`\\$&`);function ts(e,t){return e.replace(/(?<![\w/])ses_[A-Za-z0-9]{1,64}(?!\w)/g,e=>t(e)??e)}function ns(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 rs=2e3,is=6e4,as=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(rs*2**(t-1),is)})}return}finally{this.running--,this.asking.delete(e),this.queue.shift()?.()}}};function os(e,t){let n=new Set;for(let r of e)if((r.type===`assistant`?r.live!==!0:r.type===`message`&&!r.primer&&!zo(r.from))&&typeof r.text==`string`)for(let e of Zo(r.text))t.has(e)||n.add(e);return[...n]}var ss=new Set([`disabled`,`starting`,`running`,`waiting_machine`,`backoff`,`failed`,`stopping`]),cs=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ls=e=>typeof e==`string`,us=e=>typeof e==`number`&&Number.isFinite(e);function ds(e){if(cs(e)&&ls(e.state)&&ss.has(e.state))return{state:e.state,...ls(e.reason)?{reason:e.reason.slice(0,200)}:{},...ls(e.sessionID)?{sessionID:e.sessionID}:{},hiddenSessionIDs:Array.isArray(e.hiddenSessionIDs)?e.hiddenSessionIDs.filter(ls):[],...ls(e.launchID)?{launchID:e.launchID}:{},...ls(e.machineID)?{machineID:e.machineID}:{},generation:us(e.generation)?e.generation:0,since:us(e.since)?e.since:0,...us(e.nextAttemptAt)?{nextAttemptAt:e.nextAttemptAt}:{}}}function fs(e){if(!cs(e)||!cs(e.settings))return;let t=ds(e.status);if(!t)return;let n=Array.isArray(e.machines)?e.machines.filter(cs).filter(e=>ls(e.id)&&ls(e.name)).map(e=>({id:e.id,name:e.name,eligible:e.eligible===!0,online:e.online===!0,...ls(e.reason)?{reason:e.reason}:{},roots:Array.isArray(e.roots)?e.roots.filter(ls):[]})):[];return{settings:e.settings,status:t,machines:n}}function ps(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 ms=4e3,hs=(e,t,n)=>e||t&&n;function gs(e,t,n,r,i,a){return ps(t,r,a).has(e)?`concierge`:!n||i===!1&&!_s(e,r)?`wait`:`session`}var _s=(e,t)=>(t??[]).some(t=>(t.processes??[]).some(t=>(t.sessions??[]).some(t=>t.id===e))),vs=e=>`concierge.hidden.${e??`local`}`;function ys(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 bs(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 xs=e=>e<6e4?`${Math.max(1,Math.ceil(e/1e3))} s`:`${Math.ceil(e/6e4)} min`;function Ss(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 ${xs(e.nextAttemptAt-n)}`;case`failed`:return`Failed${e.reason?`: ${e.reason}`:``}`;case`stopping`:return`Stopping`}}function Cs(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 ws=(e,t)=>{let n=t.replace(/\/+$/,``);return e===n||e.startsWith(`${n}/`)};function Ts(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=>ws(e.directory,t)))return`The directory must be under one of ${n.name}'s workspace roots: ${n.roots.join(`, `)}`}var Es=e=>({allow:[`answer`,`deny`,`approve`],projects:[...e],permissions:{allow:[`read`,`edit`],never:[`shell:git push*`,`shell:rm *`]},allowAlways:!1,expires:`7d`,maxActionsPerHour:60}),Ds=[`answer`,`deny`,`approve`,`stop`,`prompt`];function Os(e,t){let n=e??Es(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 ks=e=>e.split(`
|
|
14
|
+
`).map(e=>e.trim()).filter(Boolean),As=/^(\d+)(h|d)$/;function js(e){let t={},n=[...new Set(e.projects.map(e=>e.trim()).filter(Boolean))];n.length||(t.projects=`Pick at least one project`),Ds.filter(t=>e.allow.includes(t)).length||(t.allow=`Pick at least one action`);let r=e.expires.trim(),i=As.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=>Ds.includes(e)),projects:n,permissions:{allow:ks(e.permit),never:ks(e.never)},allowAlways:!1,expires:r,maxActionsPerHour:s}}}function Ms(e){let t=ks(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 Ns(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 Ps(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 Fs(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 Is(e,t){let n=$n(e,t);return n?`expires in ${n}`:`expired`}var Ls=[`machineID`,`directory`,`model`,`grant`,`connectors`,`timeZone`,`quietHours`,`quietAllowsUrgent`,`digests`];function Rs(e,t){let n={};for(let r of Ls)JSON.stringify(e[r])!==JSON.stringify(t[r])&&(n[r]=t[r]===void 0?null:t[r]);return{...n,expectedRevision:e.revision}}var zs=`__other__`,Bs=e=>(e??``).replace(/\/+$/,``);function Vs(e,t){if(!e)return{projects:[],roots:[]};let n=[...new Set(e.roots.map(Bs).filter(Boolean))],r=(t??[]).find(t=>t.id===e.id)?.processes.flatMap(e=>e.sessions.map(e=>Bs(e.project)||Bs(e.directory)))??[],i=[...new Set(r)].filter(e=>e.startsWith(`/`)&&(!n.length||n.some(t=>ws(e,t)))).sort();return{projects:i,roots:n.filter(e=>!i.includes(e))}}function Hs(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(Bs).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 Us=(e,t)=>e?t.includes(e)?e:zs:``;function Ws(e,t,n,r){if(e.machineID===t.id)return e;let{projects:i,roots:a}=Vs(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 Gs=(e,t)=>e.model!==void 0&&!t.includes(e.model)?{...e,model:void 0}:e,Ks=/^[A-Za-z0-9._-]{1,80}\/[!-~]{1,200}$/;function qs(e){let t=cs(e)&&Array.isArray(e.models)?e.models:[],n=new Map;for(let e of t){if(!cs(e)||!ls(e.providerID)||!ls(e.modelID)||e.enabled===!1)continue;let t=`${e.providerID}/${e.modelID}`;Ks.test(t)&&!n.has(t)&&n.set(t,{value:t,label:ls(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 Js(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 Ys=new Set([`yes`,`approve`,`go ahead`,`do it`]),Xs=new Set([`no`,`deny`,`don't`,`dont`,`hold`]),Zs=new Set([`um`,`umm`,`uh`,`uhm`,`uhh`,`er`,`erm`,`hm`,`hmm`,`ah`,`please`]),Qs=80;function $s(e){if(typeof e!=`string`||e.length>Qs||/[??]/.test(e))return;let t=e.normalize(`NFC`).toLowerCase().replace(/[\u2018\u2019\u02bc`´]/g,`'`).replace(/[.,!?;:…"“”«»()[\]{}\-–—]+/g,` `).split(/\s+/).filter(Boolean),n=0,r=t.length;for(;n<r&&Zs.has(t[n]);)n++;for(;r>n&&Zs.has(t[r-1]);)r--;let i=t.slice(n,r).join(` `);if(Ys.has(i))return`yes`;if(Xs.has(i))return`no`}function ec(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 tc(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 nc(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 rc(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 ic(e,t){if(!t||t.tier!==`confirm`||t.state!==`open`)return{kind:`speech`};let n=$s(e),r=n&&rc(t,n);return n&&r?{kind:`answer`,decisionID:t.id,option:r,intent:n}:{kind:`speech`}}var ac=60;function oc(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>ac?`${n.slice(0,59).join(``)}…`:n.join(``)}” by text: ${e.options.find(e=>e.id===t)?.label??t}`}var sc=e=>e&&e.state!==`disabled`?!0:`hidden`,cc={starting:`starting`,backoff:`restarting soon`,waiting_machine:`waiting for its machine`,stopping:`stopping`};function lc(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 (${cc[e.state]}${c})`,s?`attention`:`busy`];return{label:l,title:`${l} — ${n?`close`:`open`} it`,indicator:u,...i>0?{count:s}:{}}}var uc=e=>e?`Ask what needs you, or start Voice and talk.`:`Ask what needs you.`,dc=e=>`${e?`Say or type`:`Type`} “yes” or “no” (or tap). Anything else goes to the Concierge.`,fc=`The Concierge is off. Turn it on in Settings → Concierge.`;function pc(e,t){if(!e||e.state===`disabled`)return fc;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 mc(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=ic(a,t.armed());return o.kind===`speech`?e(r,i):(await t.answer(o.decisionID,o.option),Response.json({inboxID:`decision:${o.decisionID}`}))}}var hc=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function gc(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 _c(e,t,n){return n===void 0||!e||e.sessionID===t.sessionID?n:null}function vc(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=rt(n,e))}return n}function yc(e,t){if(e&&e.expiresAt!==void 0)return Math.max(0,e.expiresAt-t)}function bc(e,t){return e&&e.expiresAt!==void 0&&e.expiresAt<=t?null:e}var xc=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 Sc(e,t,n){return nc(e,t,{tiers:`all`}).filter(e=>e.id!==n?.id)}var Cc=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 wc(e){let t=e.find(e=>e.focused);return t?.visible?t:void 0}function Tc(e,t=ct){let n=[],r=wc(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 Ec(e,t,n){let r=t.length?Tc(t):n?[n]:[],[i]=r;return i?r.length>1?{lite:e,session:i,sessions:r}:{lite:e,session:i}:{lite:e}}function Dc(e,t,n=ct){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 Oc(e){return wc(e)?.sessionID}function kc(e,t){return wc(e)?.paneID===t}var Ac=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}},[jc,Mc]=x(0),Nc=new Cc(()=>Mc(e=>e+1));function Pc(){return jc(),Nc.views()}var Fc=()=>Oc(Pc()),Ic=(e,t)=>Ec(e,Pc(),t);function Lc(e,t=()=>!0){let n=Nc.register(e,t);return{paneID:n,focus:()=>void Nc.focus(n),takesInput:()=>kc(Pc(),n),streamed:()=>Uc(e),release:()=>Nc.release(n)}}var Rc=new Ac,[zc,Bc]=x(0);function Vc(e){Rc.opened(e),Bc(e=>e+1)}function Hc(e){Rc.message(e)&&Bc(e=>e+1)}function Uc(e){return zc(),Rc.covers(e)}var[Y,Wc]=pi(Do()),Gc=new Fo,[Kc,qc]=x(0),Jc=Kc,[X,Yc]=x(),[Xc,Zc]=x(),[Qc,$c]=x(),[el,tl]=x([]),[nl,rl]=x([]),[il,al]=x(new Map),ol=il,sl=200;function cl(e){e.length&&al(t=>{let n=new Map(t);for(let t of e)n.delete(t.id),n.set(t.id,t);for(;n.size>sl;)n.delete(n.keys().next().value);return n})}var[ll,ul]=x(),[dl,fl]=x(!1),[pl,ml]=x(!1),hl=()=>hs(dl(),pl(),Y.machines!==void 0),[gl,_l]=x();_(()=>C(()=>{let e=gl(),t=yc(e,Date.now());if(t===void 0)return;let n=setTimeout(()=>_l(t=>t===e?bc(t,Date.now()):t),t+50);j(()=>clearTimeout(n))}));var vl=_(()=>T(()=>{let e=X();if(!e)return[];try{return bs(localStorage.getItem(vs(e.user?.id)))}catch{return[]}}));_(()=>C(()=>{let e=ll(),t=X();if(dl()&&t)try{localStorage.setItem(vs(t.user?.id),JSON.stringify((e?.hiddenSessionIDs??[]).slice(-20)))}catch{}}));var yl=_(()=>T(()=>ps(ll(),Y.machines,dl()?[]:vl()),void 0,{equals:(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e))}));l(()=>yl());var[bl,xl]=x([]),[Sl,Cl]=x(new Map),wl=new Set;async function Tl(){try{Cl(new Map(Xn(await B(`/api/agent/grants`)).map(e=>[e.id,e])))}catch{}}var El=e=>Sl().get(e),Dl=new Set;function Ol(e){return Dl.add(e),()=>Dl.delete(e)}var kl=_(()=>T(e=>Pa(e,Na(Y.machines,Y.prefs,Y.reads,yl())))),Al=e=>jo(Y.machines,e),jl=e=>yl().has(e)?`the Concierge`:Al(e)?.session.title||void 0,[Ml,Nl]=x(new Map);async function Pl(){try{let e=await B(`/api/agent/who`),t=Array.isArray(e?.sessions)?e.sessions:[];Nl(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 Fl(e){if(yl().has(e))return An(e,void 0,!0);let t=Al(e)?.session,n=Ml().get(e);if(!n)for(let t of ol().values())t.from.kind===`session`&&t.from.sessionID===e&&t.from.name&&(n=t.from.name);return An(e,{name:n,title:t?.title,directory:typeof t?.project==`string`&&t.project||t?.directory})}var Il=new Ui;Ne(()=>{He().name!==`pair`&&(iu(),Yc(void 0),Ll())});function Ll(){let e=location.pathname+location.search;a(`/pair${e===`/`||e.startsWith(`/pair`)?``:`?next=${V(e)}`}`,{replace:!0})}async function Rl(){if(X())return!0;let e=await fetch(`/api/me`,{credentials:`same-origin`});if(e.status===401)return Ll(),!1;if(!e.ok)throw Error(`HTTP ${e.status}`);return Yc(await e.json()),!0}async function zl(){if(Xc()!==void 0)return Xc()??null;try{let e=await fetch(`/api/auth`,{credentials:`same-origin`}),t=e.ok?await e.json():null;return Zc(t),t}catch{return null}}var Bl,Vl,Hl=1e3,Ul=()=>!1,Wl={lite:!1},[Gl,Kl]=x(``),ql,Jl=!1,Yl=new Lo({setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e),open:(e,t)=>nu(e,t),close:()=>tu(),keepOpen:()=>Ul()});function Xl(e){Ul=e}function Zl(e){Wl=e,Yl.setScope(e)}var Ql=!1;function $l(){Ql||(Ql=!0,document.addEventListener(`visibilitychange`,()=>document.visibilityState===`hidden`?Yl.hidden():Yl.visible()),window.addEventListener(`pageshow`,e=>{e.persisted&&Yl.state!==`stopped`&&Yl.reopen()}),window.addEventListener(`online`,()=>Yl.state===`open`&&Y.connection===`down`&&Yl.reopen()))}function eu(e={lite:!1}){Yl.state===`stopped`&&($l(),Wl=e,Yl.start(e),dl()||(du(),setTimeout(()=>!dl()&&ml(!0),ms)),document.visibilityState===`hidden`&&Yl.hidden())}function tu(){clearTimeout(Vl),Bl?.close(),Bl=void 0,Yl.state===`paused`&&Wc(`connection`,`paused`)}function nu(e,t){clearTimeout(Vl),Bl?.close();let n=Ro(Y.connection,t);Jl=n.reconnecting,n.reconnecting&&ru(`reconnecting`),Wc(`connection`,n.connection),Vc(Wl);let r=new EventSource(e,{withCredentials:!0});Bl=r,r.onopen=()=>{Hl=1e3,Wc(`connection`,`live`),Jl&&ru(`updated`,2e3),Jl=!1,Eu(),ou(),xu(),gu(),Pl(),Tl(),du()},r.onerror=async()=>{Bl===r&&(Wc(`connection`,`down`),(await fetch(`/api/me`,{credentials:`same-origin`}).catch(()=>void 0))?.status===401?(iu(),Yc(void 0),Ll()):r.readyState===EventSource.CLOSED&&Bl===r&&(Bl=void 0,Vl=setTimeout(()=>Yl.state===`open`&&Yl.reopen(),Hl),Hl=Math.min(3e4,Hl*2)))},r.addEventListener(`ping`,()=>Yl.received()),r.onmessage=e=>{Yl.received(e.lastEventId||void 0);let t;try{t=JSON.parse(e.data)}catch{return}au(t)}}function ru(e,t){clearTimeout(ql),Kl(e),t&&(ql=setTimeout(()=>Kl(``),t))}function iu(){Yl.stop(),Bl?.close(),Bl=void 0,clearTimeout(Vl)}function au(e){Ee(()=>{if(Hc(e),e.type===`prefs`?(Wc(bi(t=>Ao(t,e))),Y.prefsStale&&!Y.prefsPending&&Du()):e.type===`catalog`?Wc(bi(t=>{Ao(t,e),Il.apply(t.machines,Date.now())})):Wc(bi(t=>Ao(t,e))),e.type===`status`){let t=Al(e.sessionID);!Gc.has(e.sessionID)&&t&&Gc.feed(e.sessionID)}if(Gc.apply(e)!==void 0&&qc(e=>e+1),e.type===`enrollment`&&xu(),e.type===`decision`){let t=qt(e.decision);t&&(hu.event(t),rl(e=>Xt(e,t)),cl([t]))}if(e.type===`concierge`){let t=ds(e.status);t&&(_l(e=>_c(ll(),t,e)),ul(t),fl(!0),cu++);let n=ec(e.armed);n!==void 0&&(pu.event(),_l(n))}if(e.type===`agent`){let t=sr(e.entry);t&&xl(e=>Rr(e,t)),t?.grant&&!Sl().has(t.grant)&&!wl.has(t.grant)&&(wl.add(t.grant),Tl())}if(e.type===`resync`&&(ou(),Du(),xu(),gu(),Pl(),Tl(),du()),e.type===`handoff`&&(He().name!==`session`||He().id!==e.sessionID)){let t=Al(e.sessionID);q(`Handed off: ${t?.session.title||e.sessionID}`,``,{label:`Open`,run:()=>a(`/s/${V(e.sessionID)}`)})}});for(let t of Dl)t(e)}async function ou(){try{let{reads:e}=await B(`/api/reads`);Wc(`reads`,e??{})}catch{}}async function su(e){try{let{reads:t}=await(await G(`${P(e)}/read`,{method:`POST`,json:{}})).json();t&&typeof t==`object`&&Wc(`reads`,t)}catch{}}var cu=0,lu,uu;function du(){return lu?(uu??=lu.then(()=>(uu=void 0,du())),uu):(lu=fu().finally(()=>lu=void 0),lu)}async function fu(){let t=cu;try{let e=fs(await B(`/api/agent/concierge`));e&&t===cu&&ul(e.status)}catch(n){n instanceof e&&n.status===404&&t===cu&&ul(void 0);return}finally{fl(!0)}await mu()}var pu=new xc;async function mu(){let t=pu.begin();try{let e=ec((await B(`/api/agent/concierge/arm`)).armed);pu.fresh(t)&&e!==void 0&&_l(bc(e,Date.now()))}catch(n){pu.fresh(t)&&n instanceof e&&(n.status===404||n.status===403)&&_l(void 0)}}var hu=new an;async function gu(){let t=hu.begin();try{let{decisions:e}=await B(`/api/decisions?state=open`),n=hu.settle(t,(e??[]).map(qt).filter(e=>!!e));if(!n)return;rl(n),cl(n)}catch(n){hu.fail(t),n instanceof e&&n.status===404&&rl([])}}var _u=new as({fetch:e=>B(`/api/decisions/${V(e)}`),parse:e=>qt(e?.decision)??void 0,status:t=>t instanceof e?t.status:void 0});function vu(e){let t=il().get(e);return t?Promise.resolve(t):_u.recall(e).then(t=>(t&&!il().has(e)&&cl([t]),t))}function yu(e){hu.event(e),rl(t=>Xt(t,e)),cl([e])}function bu(e){let t=nl().find(t=>t.id===e);t&&hu.event({...t,state:`closed`}),rl(t=>t.filter(t=>t.id!==e)),gu()}async function xu(){if(!ht(X()))tl([]);else try{tl((await B(`/api/enrollments`)).enrollments??[])}catch{tl([])}}async function Su(){try{$c((await B(`/api/settings/speech`)).ready??null)}catch{$c(null)}}var Cu=`voice.viewPrefs`,wu=!1,Tu=()=>Y.prefsSource===`hub`||Y.prefsSource===`local`;async function Eu(){if(!(Tu()||wu)){wu=!0;try{Wc({prefs:Bi(await B(`/api/prefs/view`)),prefsSource:`hub`})}catch(t){if(t instanceof e&&t.status===404){let e;try{e=JSON.parse(localStorage.getItem(Cu)??`null`)}catch{}Wc({prefs:Bi(e),prefsSource:`local`})}else Wc(`prefsSource`,`error`)}finally{wu=!1}Tu()&&await Ou()}}async function Du(){Wc({prefsStale:!1,prefsSource:`unknown`}),await Eu()}async function Ou(){let{clear:e,patch:t}=qi(localStorage.getItem(`voice.pins`),localStorage.getItem(`voice.pinnedWorkspaces`),Y.prefs);e&&(t&&(Wc(`prefs`,e=>({...e,...t})),!(await ku(t)).ok)||(localStorage.removeItem(`voice.pins`),localStorage.removeItem(`voice.pinnedWorkspaces`)))}async function ku(e){if(Y.prefsSource===`local`)return localStorage.setItem(Cu,JSON.stringify(Y.prefs)),{ok:!0};Wc(`prefsPending`,e=>e+1);try{let t=await(await G(`/api/prefs/view`,{method:`PUT`,json:e})).json().catch(()=>void 0);return Y.prefsPending===1&&t&&!Y.prefsStale&&Wc(`prefs`,Bi(t)),{ok:!0}}catch(e){return{ok:!1,error:e}}finally{Wc(`prefsPending`,e=>e-1),!Y.prefsPending&&Y.prefsStale&&Du()}}function Au(e,t,n,r={}){ju(e,[t],n,r)}function ju(e,t,n,{message:r,undo:i=!1}={}){if(!Tu()){q(`Your view settings are still loading. Try again in a moment.`,`err`),Eu();return}let a=new Set(Y.prefs[e]),o=t.filter(e=>a.has(e)!==n),{prefs:s,patch:c}=Gi(Y.prefs,e,o,n);c&&(Wc(`prefs`,s),r&&q(r,``,i?{label:`Undo`,run:()=>ju(e,o,!n)}:void 0),ku(c).then(({ok:t,error:r})=>{t||(Wc(`prefs`,Gi(Y.prefs,e,o,!n).prefs),q(`Could not save that change: ${W(r)}`,`err`))}))}async function Mu(e,t){try{return await G(`${P(e)}/expose`,{method:`POST`,json:{on:t}}),q(t?`Voice enabled`:`Voice disabled`),!0}catch(e){return q(`Could not ${t?`enable`:`disable`} Voice: ${W(e)}`,`err`),!1}}async function Nu(e,t){let n=Vi(t);if(`error`in n)return q(n.error,`err`),!1;let{title:r}=n,i=Al(e)?.session.title;if(i===r)return!1;Il.set(e,r,Date.now()),Wc(bi(t=>void Hi(t.machines,e,r)));try{let t=await(await G(`${P(e)}/rename`,{method:`POST`,json:{title:r}})).json().catch(()=>void 0),n=typeof t?.title==`string`&&t.title?t.title:r;return n!==r&&Al(e)?.session.title===r&&(Il.drop(e,r),Il.set(e,n,Date.now()),Wc(bi(t=>void Hi(t.machines,e,n)))),!0}catch(t){return Il.drop(e,r),i!==void 0&&Al(e)?.session.title===r&&Wc(bi(t=>void Hi(t.machines,e,i))),q(`Could not rename: ${W(t)}`,`err`),!1}}var[Pu,Fu]=x(new Set),Iu=e=>Pu().has(e),Lu=(e,t)=>Fu(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r}),Ru=6e4;async function zu(e){if(Iu(e))return;let t=Al(e)?.session.title;Lu(e,!0);let n=!1;try{let r=await(await G(`${P(e)}/rename`,{method:`POST`,json:{auto:!0}})).json().catch(()=>void 0);if(r?.pending){n=!0,q(`OpenCode is still naming it; the title changes when it's ready`);let r=Date.now()+Ru,i=()=>{let n=Al(e)?.session.title;n!==void 0&&n!==t?(Lu(e,!1),q(`Renamed to “${n}”`)):Date.now()>=r?Lu(e,!1):setTimeout(i,500)};setTimeout(i,500);return}let i=typeof r?.title==`string`?r.title:void 0;if(r?.unchanged||!i||i===t){q(`OpenCode kept the title`);return}Il.set(e,i,Date.now()),Wc(bi(t=>void Hi(t.machines,e,i))),q(`Renamed to “${i}”`)}catch(e){q(`Could not auto-name: ${W(e)}`,`err`)}finally{n||Lu(e,!1)}}async function Bu(e){try{let{stopped:t}=await(await G(`${P(e)}/stop`,{method:`POST`,json:{}})).json(),n=Array.isArray(t)?t.length:0;q(n?`Stopped ${n} session${n===1?``:`s`}`:`Nothing was running`)}catch(e){q(`Could not stop: ${W(e)}`,`err`)}}var Vu=J(`<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 Hu(e){let t=()=>e.size??18;return(()=>{var n=Vu();return D(r=>{var i=`hub-mark${e.class?` ${e.class}`:``}`,a=t(),o=t();return i!==r.e&&R(n,`class`,r.e=i),a!==r.t&&R(n,`width`,r.t=a),o!==r.a&&R(n,`height`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})()}var Uu=J(`<p class=error role=alert>`),Wu=J(`<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`),Gu=J(`<p class=muted>Sign in to see and control your own OpenCode sessions.`),Ku=J(`<a class="btn primary signin">Sign in with Google`),qu=J(`<details class=card><summary>Have a pairing code?`),Ju=J(`<main class=entry><h1 class="display brand-big"> Hub`),Yu=J(`<p class=muted>Loading…`),Xu=J(`<p class=muted>Pair this browser with your hub to see and control your OpenCode sessions.`),Zu=J(`<p>A terminal on <strong></strong> asks to act as you through the hub CLI.`),Qu=J(`<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.`),$u=J(`<fieldset class=stack><legend class=small>What it may do`),ed=J(`<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.`),td=J(`<div class=row><button type=button class="btn primary">Approve</button><button type=button class="btn danger">Deny`),nd=J(`<p role=status>`),rd=J(`<main class=entry><h1 class=display>CLI login for </h1><div class="card stack"><a class=btn href=/>Back to sessions`),id=J(`<label class=check><input type=checkbox><span><span class=mono></span> `),ad=J(`<main class=entry><p class=muted>Loading…`),od=J(`<strong>`),sd=J(`<p>`),cd=J(`<p class="small muted">Approve only if this code matches the one shown in OpenCode.`),ld=J(`<p class=small>`),ud=J(`<main class=entry><h1 class=display>Approve machine</h1><div class="card stack"><a class=btn href=/>Back to sessions`),dd=J(`<p>No code given.`),fd=J(`<strong class=mono>`);function pd(){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 md(t){let[r,i]=x(),[o,s]=x(!1),[c,l]=x(``),[d,f]=x(pd()),[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),zl()]);if(e?.ok)return Yc(await e.json()),a(t.next,{replace:!0});i(xt(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 G(`/api/pair`,{method:`POST`,json:{code:r,deviceName:d().trim()||pd()}}),Yc(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.`:W(t)),g(!1)}},v=()=>(()=>{var e=Wu(),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),L(e,n(u,{get when(){return p()},get children(){var e=Uu();return L(e,p),e}}),o),D(()=>o.disabled=h()),D(()=>r.value=c()),D(()=>a.value=d()),e})();return(()=>{var e=Ju(),i=e.firstChild,a=i.firstChild;return L(i,n(Hu,{class:`brand-mark`,size:30}),a),L(e,n(u,{get when(){return o()},get fallback(){return Yu()},get children(){return n(u,{get when(){return r()},get fallback(){return[Xu(),H(v)]},get children(){return[Gu(),(()=>{var e=Ku();return D(()=>R(e,`href`,r())),e})(),(()=>{var e=qu();return e.firstChild,L(e,v,null),D(()=>e.open=!!t.error),e})()]}})}}),null),e})()}function hd(t){let r=qn(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`?Jn(i()):{ok:!0,body:{}};if(!r.ok)return c(r.error);p(!0);try{await G(`/api/cli-logins/${V(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.`:W(t)),p(!1)}};return(()=>{var e=rd(),c=e.firstChild;c.firstChild;var d=c.nextSibling,p=d.firstChild;return L(c,()=>t.login.clientName,null),L(d,n(u,{get when(){return!l()},get fallback(){return(()=>{var e=nd();return L(e,l),e})()},get children(){return[(()=>{var e=Zu(),n=e.firstChild.nextSibling;return L(n,()=>t.login.clientName),e})(),(()=>{var e=Qu(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,L(e,m,n),L(e,()=>ze(t.login.created),r),e})(),(()=>{var e=$u();return e.firstChild,L(e,n(o,{each:r,children:e=>(()=>{var t=id(),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))),L(o,()=>e.scope),L(r,()=>e.label,null),L(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 ed()}}),(()=>{var e=td(),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=nd();return L(e,s),e}})]}}),p),e})()}function gd(e){let[t,r]=x(),[i,a]=x(!e.code);return ue(async()=>{if(e.code){try{r(Kn(await(await G(`/api/cli-logins/${V(e.code.toUpperCase())}`)).json()))}catch{}a(!0)}}),n(u,{get when(){return i()},get fallback(){return ad()},get children(){return n(u,{get when(){return t()},get fallback(){return n(_d,{get code(){return e.code}})},children:e=>n(hd,{get login(){return e()}})})}})}function _d(t){let r=()=>t.code.toUpperCase(),[i,a]=x(``),[o,s]=x(``),[c,l]=x(!1),[d,f]=x(!ht(X()));ue(async()=>{await xu(),f(!0)});let p=()=>el().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 G(`/api/enrollments/${V(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():W(t)),l(!1)}};return(()=>{var e=ud(),t=e.firstChild.nextSibling,a=t.firstChild;return L(t,n(u,{get when(){return!o()},get fallback(){return(()=>{var e=nd();return L(e,o),e})()},get children(){return n(u,{get when(){return r()},get fallback(){return dd()},get children(){return n(u,{get when(){return d()},get fallback(){return Yu()},get children(){return n(u,{get when(){return!ht(X())||p()},get fallback(){return(()=>{var e=sd();return L(e,m),e})()},get children(){return[(()=>{var e=sd();return L(e,n(u,{get when(){return p()},get fallback(){return[`A machine showing code `,(()=>{var e=fd();return L(e,r),e})(),` wants to connect to this hub.`]},get children(){return[(()=>{var e=od();return L(e,()=>p().machineName),e})(),` wants to connect to this hub.`]}})),e})(),(()=>{var e=cd(),t=e.firstChild;return L(e,(()=>{var e=H(()=>!!p());return()=>e()?`Code ${p().userCode} · requested ${ze(p().created)}. `:``})(),t),e})(),(()=>{var e=ld();return L(e,()=>St(X())),e})(),(()=>{var e=td(),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=nd();return L(e,i),e}})]}})}})}})}}),a),e})()}F([`input`,`click`]);var vd=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window&&window.isSecureContext;function yd(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 bd=(e,t)=>!e||e.byteLength!==t.byteLength?!1:new Uint8Array(e).every((e,n)=>e===t[n]),[xd,Sd]=x(0),[Cd,wd]=x(new Set),Td=()=>`Notification`in window?Notification.permission:`default`;async function Ed(){if(`serviceWorker`in navigator)return await navigator.serviceWorker.getRegistration(`/`).catch(()=>void 0)??void 0}async function Dd(){if(vd())return await(await Ed())?.pushManager.getSubscription()??void 0}async function Od(e){let t=await B(`/api/push/prefs${e?`?endpoint=${encodeURIComponent(e)}`:``}`);return wd(new Set(t.muted??[])),t}async function kd(){let e=vd(),t=e?await Ed():void 0,n=await t?.pushManager.getSubscription().catch(()=>null)??void 0,r=await Od(n?.endpoint).catch(()=>void 0);return{env:{supported:e,permission:Td(),worker:!!t,...n?{endpoint:n.endpoint}:{},hubSubscribed:!!r?.subscribed,hubSubscriptions:r?.subscriptions??0},view:r}}async function Ad(){let{publicKey:e}=await B(`/api/push/key`),t=yd(e);await Ed()||await navigator.serviceWorker.register(`/sw.js`,{scope:`/`});let n=await navigator.serviceWorker.ready,r=await n.pushManager.getSubscription();return r&&!bd(r.options?.applicationServerKey,t)&&(await r.unsubscribe(),r=null),r??=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),await G(`/api/push/subscribe`,{method:`POST`,json:{subscription:r.toJSON()}}),r}async function jd(){if(!vd())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 Ad()}async function Md(){let e=await Dd();e&&(await G(`/api/push/unsubscribe`,{method:`POST`,json:{endpoint:e.endpoint}}).catch(()=>{}),await e.unsubscribe().catch(()=>{}))}async function Nd(e){return(await G(`/api/push/test`,{method:`POST`,json:e?{kind:e}:{}})).json()}async function Pd(e,t){let n=Cd(),r=new Set(n);t?r.add(e):r.delete(e),wd(r);try{let n=await(await G(`/api/push/mute`,{method:`PUT`,json:{sessionID:e,muted:t}})).json();wd(new Set(n.muted)),q(t?`Notifications muted for this session`:`Notifications on for this session`)}catch(e){wd(n),q(e instanceof Error?e.message:String(e),`err`)}}async function Fd(){let{env:e}=await kd().catch(()=>({env:void 0}));e&&Ke(e)&&await Ad().then(()=>Sd(e=>e+1),e=>console.warn(`push re-subscribe:`,e?.message??e))}function Id(){`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 Ld)e(t)}))}var Ld=new Set;function Rd(e){return Ld.add(e),()=>Ld.delete(e)}var zd=()=>{try{return globalThis.localStorage}catch{return}},[Bd,Vd]=x(Je(zd())??at()),Hd=Bd;function Ud(e){let t=Bd(),n=e(t);return n===t||(Vd(n),lt(zd(),n))}var Wd=`Up to ${ct} panes side by side. Close one to open another.`;function Gd(e){if(We(e))return a(`/concierge`);let{layout:t,outcome:n}=st(Hd(),{sessionID:e},{beside:!0});if(n===`limit`)return q(Wd,`warn`);n!==`invalid`&&Ud(()=>t),a(k(e))}function Kd(e){if(e.sessionID!==void 0&&We(e.sessionID))return!1;let{layout:t,outcome:n}=st(Hd(),e,{beside:!0});if(n===`limit`)return q(Wd,`warn`),!1;if(n===`invalid`)return!1;Ud(()=>t);let r=He();return r.name!==`session`&&r.name!==`panes`&&a(`/panes`),!0}var qd=e=>Kd({artifactID:e}),Jd=(e,t)=>Kd({sessionID:e,sideChatID:t});function Yd(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 Xd=e=>e===`left`||e===`right`?`vertical`:`horizontal`;function Zd(e,t,n,r){let i=r?t+1:t;if(i<=1)return`single`;let a=Xd(n);return i===2?a:e===`grid`?`grid`:e===a?r&&i>=ct?`grid`:a:`grid`}function Qd(e,t,n,r){return r===`grid`&&n===`bottom`?Math.min(e,t+2):n===`left`||n===`top`?t:t+1}var $d=(e,t)=>Number.isInteger(t)&&t>=0&&t<e.panes.length;function ef(e,t,n){if(!$d(e,t))return{layout:e,outcome:`invalid`};let r=()=>({layout:Ze(e.split,e.panes,t),outcome:`focused`});if(`empty`in n)return r();let{index:i,zone:a}=n;if(!$d(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:Ze(e.split,n,i),outcome:`moved`}}let s=e.panes.filter((e,n)=>n!==t),c=Zd(e.split,e.panes.length,a,!1),l=Qd(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:Ze(c,u,l),outcome:d?`focused`:`moved`}}function tf(e,t,n){let r=nt(t);if(!r)return{layout:e,outcome:`invalid`};let i=e.panes.findIndex(e=>tt(e,r));if(i>=0)return ef(e,i,n);let a=e.panes.length;if(!a)return{layout:Ze(e.split,[r],0),outcome:`added`};let{index:o,zone:s}=`empty`in n?{index:a-1,zone:`right`}:n;if(!$d(e,o))return{layout:e,outcome:`invalid`};if(s===`center`)return{layout:Ze(e.split,e.panes.map((e,t)=>t===o?r:e),o),outcome:`replaced`};if(a>=ct)return{layout:e,outcome:`limit`};let c=Zd(e.split,a,s,!0),l=Qd(a,o,s,c);return{layout:Ze(c,[...e.panes.slice(0,l),r,...e.panes.slice(l)],l),outcome:`added`}}var nf={side:{min:180,max:480,default:235},rail:{min:220,max:640,default:260}},rf=`hub.panels`,af=(e,{min:t,max:n})=>Math.min(n,Math.max(t,e));function of(e,t,n){let{min:r,max:i}=nf[e];return{min:r,max:Math.max(r,Math.min(i,Math.floor(t-420-n)))}}var sf={min:320,max:440,share:.4};function cf(e,t,n){let r=e=>t-(n.concierge&&e?sf.min:0),i=af(e.side,of(`side`,r(n.side),n.rail?nf.rail.min:0)),a=af(e.rail,of(`rail`,r(n.rail),n.side?i:0));if(!n.concierge)return{side:i,rail:a};let o=Math.min(sf.max,Math.floor(t*sf.share)),s=t-420-(n.side?i:0)-(n.rail?a:0);return{side:i,rail:a,concierge:Math.max(sf.min,Math.min(o,s))}}function lf(e,t,n,r,i){let a=r?64:16,o=e===`side`?`ArrowRight`:`ArrowLeft`,s=e===`side`?`ArrowLeft`:`ArrowRight`;if(n===o)return af(t+a,i);if(n===s)return af(t-a,i);if(n===`Home`)return i.min;if(n===`End`)return i.max}function uf(e,t,n,r){let i=e===`side`?t+n:t-n;return e===`side`&&i<r.min-48?{collapse:!0}:{width:af(Math.round(i),r)}}var df=(e,t)=>{let{min:n,max:r,default:i}=nf[e];return typeof t==`number`&&Number.isFinite(t)?af(Math.round(t),{min:n,max:r}):i};function ff(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:df(`side`,n.side),rail:df(`rail`,n.rail)}}function pf(e,t,n){try{e.setItem(rf,JSON.stringify({...ff(e),[t]:df(t,n)}))}catch{}}var mf=window.matchMedia(`(max-width: 760px)`),[hf,gf]=x(mf.matches);mf.addEventListener(`change`,()=>{gf(mf.matches),wf(!mf.matches&&localStorage.getItem(vf)!==`0`)});var Z=hf,_f=`hub.sidebar.collapsed`,vf=`hub.rail.open`,[yf,bf]=x(localStorage.getItem(_f)===`1`),[xf,Sf]=x(!1),[Cf,wf]=x(!mf.matches&&localStorage.getItem(vf)!==`0`);function Tf(e){bf(e),localStorage.setItem(_f,e?`1`:`0`)}function Ef(e){wf(e),hf()||localStorage.setItem(vf,e?`1`:`0`)}function Df(){hf()?Sf(!xf()):Tf(!yf())}var[Of,kf]=x(window.innerWidth);window.addEventListener(`resize`,()=>kf(window.innerWidth));var[Af,jf]=x(ff(localStorage)),[Mf,Nf]=x(!1),[Pf,Ff]=x(),[If,Lf]=x(!1),Rf=()=>cf(Af(),Of(),{side:!yf()&&!hf(),rail:Mf(),concierge:If()&&!hf()});function zf(e){let t=Rf(),n=e===`side`?Mf()?t.rail:0:!yf()&&!hf()?t.side:0;return of(e,Of()-(t.concierge??0),n)}function Bf(e,t,n=!0){jf(n=>({...n,[e]:t})),n&&pf(localStorage,e,t)}var Vf=`application/x-hub-pane`,[Hf,Uf]=x(),Wf=``,Gf=0,Kf=Hf,qf=()=>typeof globalThis.crypto?.randomUUID==`function`?crypto.randomUUID():`${Date.now()}-${Math.random()}`;function Jf(e,t){let n=e.dataTransfer;return Z()||!n?!1:(n.clearData(),Wf=qf(),n.setData(Vf,Wf),n.effectAllowed=t.move?`move`:`copyMove`,cancelAnimationFrame(Gf),Gf=requestAnimationFrame(()=>Uf(t)),!0)}function Yf(){cancelAnimationFrame(Gf),Gf=0,Wf=``,Uf(void 0)}function Xf(e){return!!Hf()&&[...e.dataTransfer?.types??[]].includes(`application/x-hub-pane`)}function Zf(e){let t=Hf();return t?tf(Hd(),t.target,e).outcome:void 0}function Qf(e,t){let{layout:n,outcome:r}=tf(Hd(),e,t);if(r===`limit`&&q(Wd,`warn`),r===`limit`||r===`invalid`)return r;Ud(()=>n);let i=n.panes[n.focused],o=i&&!i.sideChatID?i.sessionID:void 0,s=He();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 $f(e,t){let n=Hf(),r=n&&e.dataTransfer?.getData(`application/x-hub-pane`)===Wf;return Yf(),r?Qf(n.target,t):`invalid`}function ep(e,t){let n=Hd();return Qf(e,n.panes.length?{index:n.focused,zone:t}:{empty:!0})}if(typeof document<`u`){let e=()=>Hf()&&Yf();document.addEventListener(`dragend`,e,!0),document.addEventListener(`drop`,()=>queueMicrotask(e)),document.addEventListener(`mousemove`,t=>t.buttons===0&&e(),{passive:!0})}var tp=e=>!!e&&typeof e==`object`&&!Array.isArray(e),np=e=>typeof e==`string`&&e.length>0,rp=e=>typeof e==`number`&&Number.isFinite(e),ip=new Set([`online`,`offline`,`archived`,`deleted`,`unknown`]),ap=new Set([`current`,`left`,`missing`]),op=new Set([`open`,`in_progress`,`blocked`,`done`,`cancelled`]),sp=new Set([`done`,`cancelled`]),cp=e=>rp(e)&&e>=0?e:0;function lp(e){if(!tp(e)||!np(e.memberID)||!np(e.sessionID)||!np(e.role))return;let t=tp(e.session)&&typeof e.session.state==`string`?e.session:void 0,n=tp(e.assignments)?e.assignments:{};return{memberID:e.memberID,sessionID:e.sessionID,role:e.role,master:e.master===!0,presence:ip.has(e.presence)?e.presence:`unknown`,generation:rp(e.generation)?e.generation:1,...t?{session:{state:t.state,online:t.online===!0,...np(t.machineID)?{machineID:t.machineID}:{},...np(t.name)?{name:t.name}:{},...rp(t.lastSeen)?{lastSeen:t.lastSeen}:{}}}:{},workload:{open:cp(n.open),in_progress:cp(n.in_progress),blocked:cp(n.blocked)},...tp(e.blockers)&&e.blockers.reported===!0&&rp(e.blockers.count)?{blockers:e.blockers.count}:{}}}function up(e){if(tp(e)&&np(e.memberID)&&np(e.supervisorMemberID)&&rp(e.order))return{memberID:e.memberID,supervisorMemberID:e.supervisorMemberID,order:e.order,member:ap.has(e.member)?e.member:`missing`,supervisor:ap.has(e.supervisor)?e.supervisor:`missing`}}function dp(e){if(tp(e)&&np(e.id)&&np(e.memberID)&&np(e.title)&&op.has(e.status))return{id:e.id,memberID:e.memberID,title:e.title,status:e.status,...np(e.ref)?{ref:e.ref}:{},assignee:ap.has(e.assignee)?e.assignee:`missing`,...Array.isArray(e.stale)?{stale:e.stale.filter(np)}:{}}}function fp(e){if(tp(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 pp=(e,t)=>Array.isArray(e)?e.map(t).filter(e=>e!==void 0):[];function mp(e){if(!tp(e)||!tp(e.workspace)||!tp(e.members)||!tp(e.supervision))return;let t=e.workspace;if(!np(t.id)||typeof t.title!=`string`||!np(t.state)||!rp(t.revision)||!rp(e.supervision.revision))return;let n=tp(e.assignments)?e.assignments:{},r=fp(e.decisions),i=fp(e.artifacts);return{workspace:{id:t.id,title:t.title,state:t.state,revision:t.revision,...np(t.masterMemberID)?{masterMemberID:t.masterMemberID}:{}},revision:e.supervision.revision,members:pp(e.members.items,lp),membersTruncated:e.members.truncated===!0,links:pp(e.supervision.links,up),linksTruncated:e.supervision.truncated===!0,assignments:pp(n.items,dp),assignmentsTruncated:n.truncated===!0,sections:{...r?{decisions:r}:{},...i?{artifacts:i}:{}}}}function hp(e){return tp(e)?{items:pp(e.items,e=>tp(e)&&np(e.id)&&typeof e.title==`string`&&np(e.state)&&rp(e.revision)?{id:e.id,title:e.title,...np(e.description)?{goal:e.description}:{},state:e.state,revision:e.revision}:void 0),...np(e.cursor)?{cursor:e.cursor}:{}}:{items:[]}}function gp(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 _p(e){let{links:t,stale:n}=gp(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)sp.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 vp(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}=gp(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 Qe(o,t.memberID,t.supervisorMemberID)}function yp(e,t){return e===void 0&&t===void 0?0:e===void 0?t-1:t===void 0?e+1:(e+t)/2}var bp=(e,t)=>e.flat.find(e=>e.member.memberID===t),xp=(e,t)=>t.supervisorMemberID===void 0?e.roots:bp(e,t.supervisorMemberID).children,Sp=(e,t)=>{let n=e.children.filter(e=>e.member.memberID!==t);return n.length?n[n.length-1].order+1:0};function Cp(e,t,n){if(!bp(e,t))return;if(`root`in n)return{memberID:t,supervisorMemberID:null};if(n.memberID===t)return;let r=bp(e,n.memberID);if(!r)return;if(n.position===`inside`)return{memberID:t,supervisorMemberID:r.member.memberID,order:Sp(r,t)};if(r.supervisorMemberID===void 0)return{memberID:t,supervisorMemberID:null};let i=xp(e,r).filter(e=>e.member.memberID!==t),a=i.indexOf(r),o=n.position===`before`?yp(i[a-1]?.order,r.order):yp(r.order,i[a+1]?.order);return{memberID:t,supervisorMemberID:r.supervisorMemberID,order:o}}function wp(e,t,n){let r=bp(e,t);if(!r)return;let i=xp(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:Sp(e)}:void 0}case`outdent`:{if(o===void 0)return;let n=bp(e,o);if(n.supervisorMemberID===void 0)return{memberID:t,supervisorMemberID:null};let r=xp(e,n);return{memberID:t,supervisorMemberID:n.supervisorMemberID,order:yp(n.order,r[r.indexOf(n)+1]?.order)}}case`up`:return o===void 0||a===0?void 0:{memberID:t,supervisorMemberID:o,order:yp(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:yp(i[a+1].order,i[a+2]?.order)};case`detach`:return o===void 0?void 0:{memberID:t,supervisorMemberID:null}}}function Tp(e,t){return{memberID:e.memberID,supervisorMemberID:e.supervisorMemberID,...e.order!==void 0&&e.supervisorMemberID!==null?{order:e.order}:{},expectedRevision:t}}var Ep={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 ${$e.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.`},Dp=e=>Ep[e];function Op(e,t){let n=vp(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. ${Ep[n]}`}:{kind:`reapply`,body:Tp(e,t.revision)}}function kp(e){let t=e.details?.violation;if(e.status===400&&(t===`cycle`||t===`depth`))return Ep[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 Ap(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 jp(e,t){let n=Ap(e,t);if(!n)return{found:!1};let{machine:r,process:i,session:a}=n,o=a.parentID,s=o?Ap(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 Mp(e,t,n){let r=jp(n,e.member.sessionID),i=e.supervisorMemberID?t.members.find(t=>t.memberID===e.supervisorMemberID):void 0,a=i?jp(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 Np={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 Pp(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:Np[e.presence]}),n}var Fp=e=>e.length>1?e.replace(/\/+$/,``):e,Ip=(e,t)=>{let n=Fp(e),r=Fp(t);return n===r||n.startsWith(`${r}/`)};function Lp(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=>Ip(n,e))}}))}var Rp=e=>typeof e==`object`&&!!e&&!Array.isArray(e),zp=e=>typeof e==`string`&&e.length>0,Bp=e=>typeof e==`number`&&Number.isFinite(e),Vp=[`launching`,`ready`,`failed`,`unknown`];function Hp(e){if(Rp(e)&&zp(e.id)&&typeof e.text==`string`)return{id:e.id,role:zp(e.role)?e.role:`message`,text:e.text,...Bp(e.at)?{at:e.at}:{},...e.clipped===!0?{clipped:!0}:{},...e.changed===!0?{changed:!0}:{},...e.stale?{stale:!0}:{}}}function Up(e){if(!Rp(e)||!zp(e.id)||!zp(e.workspaceID)||!zp(e.sourceSessionID)||!Bp(e.revision))return;let t=e.snapshot;if(!Rp(t)||!Bp(t.generation)||!Bp(t.takenAt))return;let n=Rp(e.launch)&&zp(e.launch.state)?e.launch:void 0;return{id:e.id,workspaceID:e.workspaceID,sourceSessionID:e.sourceSessionID,...zp(e.sessionID)?{sessionID:e.sessionID}:{},...zp(e.machineID)?{machineID:e.machineID}:{},revision:e.revision,status:Vp.includes(e.status)?e.status:`unknown`,...n?{launch:{state:n.state,...zp(n.outcome)?{outcome:n.outcome}:{},...zp(n.reason)?{reason:n.reason}:{}}}:{},snapshot:{generation:t.generation,takenAt:t.takenAt,omitted:Bp(t.omitted)?t.omitted:0,items:Array.isArray(t.items)?t.items.map(Hp).filter(e=>e!==void 0):[]},...typeof e.stale==`boolean`?{stale:e.stale}:{}}}function Wp(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 Gp(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 Kp(e,t){let n=e.snapshot,r=[`${ut(n.items.length,`message`)} from the main session`,`copied ${Gp(n.takenAt,t)}`];return n.generation>1&&r.push(`refreshed ${ut(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 qp(e){let t=Rp(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${zp(t.message)?`: ${t.message}`:`.`}`:`Context refreshed.`}var Jp=9900;function Yp(e){if(!e.trim())return`Write what to send to the main session.`;if(e.length>9900)return`At most ${Jp} characters.`}var Xp=encodeURIComponent,Zp=e=>`/api/agent/workspaces/${Xp(e.workspaceID)}/side-chats/${Xp(e.id)}`,Qp={one:e=>`/api/agent/side-chats/${Xp(e)}`,create:e=>`/api/agent/workspaces/${Xp(e)}/side-chats`,refresh:e=>`${Zp(e)}/refresh`,send:e=>`${Zp(e)}/send`},$p=e=>Math.min(3e4,2e3*2**Math.max(0,e)),em=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function tm(e,t){return t?{sourceSessionID:e,bindingID:t}:{sourceSessionID:e}}function nm(e){return(em(e)&&Array.isArray(e.bindings)?e.bindings:[]).flatMap(e=>em(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 rm(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 im=`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 am(e){return e.status===0?`The hub can't be reached. Check your connection and try again.`:e.status===422&&e.details?.feature===`sideChatHost`?im: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 om=J(`<label><span>Workspace</span><select aria-label=Workspace><option value>Choose a workspace…`),sm=J(`<p class=cmp-note role=status>`),cm=J(`<label><span>Host repository</span><select aria-label="Host repository"><option value>Choose a repository…`),lm=J(`<p class="cmp-note err"role=alert>`),um=J(`<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`),dm=J(`<p class=muted role=status>Loading workspaces…`),fm=J(`<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.`),pm=J(`<option>`),[mm,hm]=x(),gm=(e,t={})=>hm({sessionID:e,...t});function _m(){return n(u,{get when(){return mm()},keyed:!0,children:e=>n(bm,{request:e,onClose:()=>hm(void 0)})})}var vm=()=>`console-sidechat-${[...crypto.getRandomValues(new Uint8Array(12))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`,ym=t=>t instanceof e?{status:t.status,...t.code?{code:t.code}:{},message:t.message,...t.details?{details:t.details}:{}}:{status:t instanceof ye?0:-1,message:t instanceof Error?t.message:String(t)};function bm(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=Al(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(nm(await B(`/api/agent/workspaces/${V(e)}/bindings`)))}catch(e){f([]),v(am(ym(e)))}}ue(async()=>{try{i(hp(await B(`/api/agent/workspaces?state=active&limit=50`)).items)}catch(e){i([]),s(am(ym(e)))}c()&&S(c())});let C=T(()=>d()?rm(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=tm(t.request.sessionID,i.kind===`ready`?i.bindingID:void 0),o=JSON.stringify([r,a]);y?.body!==o&&(y={body:o,value:vm()}),g(!0),v(void 0);try{let n=Up((await(await G(`/api/agent/workspaces/${V(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(),Jd(t.request.sessionID,n.id)&&q(`Side chat started beside the main session.`)}catch(e){e instanceof ye||(y=void 0),v(am(ym(e)))}finally{g(!1)}}return n(Re,{open:!0,title:`Start a side chat`,get onClose(){return t.onClose},get children(){var e=um(),i=e.firstChild,s=i.firstChild.nextSibling,f=i.nextSibling,g=f.firstChild,y=g.nextSibling;return e.addEventListener(`submit`,w),L(s,b),L(e,n(u,{get when(){return r()},get fallback(){return dm()},get children(){return n(u,{get when(){return!a()},get fallback(){return(()=>{var e=lm();return L(e,a),e})()},get children(){return n(u,{get when(){return r().length},get fallback(){return fm()},get children(){var e=om(),t=e.firstChild.nextSibling;return t.firstChild,t.addEventListener(`change`,e=>{l(e.currentTarget.value),v(void 0),S(e.currentTarget.value)}),L(t,n(o,{get each(){return r()},children:e=>(()=>{var t=pm();return L(t,()=>e.title||e.id),D(()=>t.value=e.id),t})()}),null),D(()=>t.value=c()),e}})}})}}),f),L(e,n(u,{get when(){return C()?.kind===`none`},get children(){var e=sm();return L(e,im),e}}),f),L(e,n(u,{get when(){return H(()=>!!d())()&&d().length>1},get children(){var e=cm(),t=e.firstChild.nextSibling;return t.firstChild,t.addEventListener(`change`,e=>m(e.currentTarget.value)),L(t,n(o,{get each(){return d()},children:e=>(()=>{var t=pm();return L(t,(()=>{var t=H(()=>!!e.label);return()=>t()?`${e.label} (${e.repo})`:e.repo})()),D(()=>t.value=e.id),t})()}),null),D(()=>t.value=p()),e}}),f),L(e,n(u,{get when(){return _()},get children(){var e=lm();return L(e,_),e}}),f),L(g,()=>h()?`Starting…`:`Start side chat`),Oe(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&&R(g,`aria-busy`,e.t=n),e},{e:void 0,t:void 0}),e}})}F([`click`]);var[xm,Sm]=x(),Cm=(e,t)=>xm()?.id===e&&xm()?.place===t;function wm(e,t){if(!e.length)return;let n=t?`Archived`:`Unarchived`,r=e.length===1?`${n} “${e[0].title}”`:`${n} ${e.length} sessions`;ju(`hiddenSessions`,e.map(e=>e.id),t,{message:r,undo:!0})}function Tm(e,{open:t=!0,place:n}={}){return[...t?[{label:`Open`,run:()=>a(k(e.id))}]:[],...n===`topbar`?[]:[{label:`Open beside`,run:()=>Gd(e.id)}],{label:`Start side chat…`,run:()=>gm(e.id)},...n?[{label:`Rename…`,run:()=>Sm({id:e.id,place:n})}]:[],{label:Iu(e.id)?`Naming…`:`Auto-name`,run:()=>void zu(e.id),disabled:Iu(e.id)},{label:e.pinned?`Unpin`:`Pin`,run:()=>Au(`pinnedSessions`,e.id,!e.pinned)},{label:e.archived?`Unarchive`:`Archive`,run:()=>wm([e],!e.archived)},...e.running?[{label:`Stop`,run:()=>void Bu(e.id),danger:!0}]:[],`sep`,{label:e.exposed?`Disallow Voice`:`Allow Voice`,run:()=>void Mu(e.id,!e.exposed)},Cd().has(e.id)?{label:`Unmute notifications`,run:()=>void Pd(e.id,!1)}:{label:`Mute notifications`,run:()=>void Pd(e.id,!0)},...n!==`topbar`&&!Z()?[`sep`,...[`left`,`right`,`top`,`bottom`].map(t=>({label:`Open in pane → ${t}`,run:()=>void ep({sessionID:e.id},t)}))]:[]]}var Em=J(`<button type=button class="link-btn small clamp-toggle">`),Dm=J(`<span>`),Om=J(`<p>`),km=J(`<span class="muted small cut-note"data-cut>… cut at <!> characters (of <!>)`),Am=J(`<span class="muted small cut-note"data-more>+<!> more <!> not stored`),jm=J(`<dt>Requested by`),Mm=J(`<dd>`),Nm=J(`<dt>Proposes`),Pm=J(`<dt>Action`),Fm=J(`<dd class=mono data-action>`),Im=J(`<dt>`),Lm=J(`<span class="muted small cut-note"data-incomplete>The hub received this request already shortened`),Rm=J(`<dd data-resources>`),zm=J(`<dt>Always saves`),Bm=J(`<dd data-saves>`),Vm=J(`<dt>Shown from`),Hm=J(`<dd class=muted>`),Um=J(`<dt>Prompt`),Wm=J(`<dt>Form`),Gm=J(`<dt>Answer`),Km=J(`<dd data-answer>`),qm=J(`<dt>Outside its grant`),Jm=J(`<dl class="escalation-details decision-details small">`),Ym=J(`<dt>Session`),Xm=J(`<dd><a>`),Zm=J(`<span class=decision-answer-field><span class=muted>:</span> `),Qm=J(`<dt>Purpose`),$m=J(`<dd data-purpose> <span class=muted>(<!>)`),eh={label:Fl,blockers:e=>Ti(Al(e)?.session)};function th(e){let[t,r]=x(!1),i=re(),a=T(()=>e.reveal?Tn(e.text):e.text),o=T(()=>Cn(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=Em();return n.$$click=()=>r(!t()),R(n,`aria-controls`,`clamp-${i}`),L(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&&R(n,`aria-expanded`,r.e=i),a!==r.t&&R(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=Om();return R(n,`id`,`clamp-${i}`),L(n,s),D(r=>{var i=e.class,a=o().cut&&!t()?``:void 0;return i!==r.e&&K(n,r.e=i),a!==r.t&&R(n,`data-clamped`,r.t=a),r},{e:void 0,t:void 0}),n})(),H(c)]},get children(){return[(()=>{var n=Dm();return R(n,`id`,`clamp-${i}`),L(n,s),D(r=>{var i=e.class,a=o().cut&&!t()?``:void 0;return i!==r.e&&K(n,r.e=i),a!==r.t&&R(n,`data-clamped`,r.t=a),r},{e:void 0,t:void 0}),n})(),H(()=>c())]}})}var nh={live:`Live request`,request:`The hub's record of the request`,text:`From the request text`},rh=new Set([`bash`,`shell`]),ih=e=>e&&rh.has(e)?`the command`:`the request`,ah=e=>e.toLocaleString(`en-US`);function oh(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=km(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,L(t,()=>ah(ch),n),L(t,()=>ah(e().length),r),t})()})}function sh(e){return n(u,{get when(){return e.count},get children(){var t=Am(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,L(t,()=>ah(e.count),n),L(t,()=>e.count===1?`item`:`items`,r),t}})}var ch=2e3,lh={stop:`Stop the session`,deny:`Deny its permission request`,prompt:`Send a prompt as you`,answer:`Answer its form as you`},uh=e=>e.verb===`answer`&&e.cancel?`Dismiss its form`:lh[e.verb??``]??e.verb;function dh(e){let t=T(()=>yn(e.decision,e.context??eh));return n(u,{get when(){return t()},children:t=>(()=>{var r=Jm();return L(r,n(u,{get when(){return t().requester},get children(){return[jm(),(()=>{var n=Mm();return L(n,()=>t().requester),D(()=>R(n,`title`,Pn(e.decision))),n})()]}}),null),L(r,n(u,{get when(){return t().verb},get children(){return[Nm(),(()=>{var e=Mm();return L(e,()=>uh(t())),D(()=>R(e,`data-verb`,t().verb)),e})()]}}),null),L(r,n(u,{get when(){return t().target},children:e=>[Ym(),(()=>{var t=Xm(),n=t.firstChild;return L(n,()=>e().label),D(t=>{var r=k(e().id),i=e().id;return r!==t.e&&R(n,`href`,t.e=r),i!==t.t&&R(n,`title`,t.t=i),t},{e:void 0,t:void 0}),t})()]}),null),L(r,n(u,{get when(){return t().action},get children(){return[Pm(),(()=>{var e=Fm();return L(e,()=>t().action,null),L(e,()=>t().always?` (always)`:``,null),e})()]}}),null),L(r,n(u,{get when(){return t().resources.length},get children(){return[(()=>{var e=Im();return L(e,()=>t().resources.length===1?`Resource`:`Resources`),e})(),(()=>{var e=Rm();return L(e,n(o,{get each(){return t().resources},children:(e,r)=>[n(th,{tag:`span`,class:`escalation-resource mono`,text:e,chars:240,lines:4,get what(){return ih(t().action)},reveal:!0}),n(oh,{get detail(){return t()},field:`resources`,get index(){return r()}})]}),null),L(e,n(sh,{get count(){return t().resourcesMore}}),null),L(e,n(u,{get when(){return t().incomplete},get children(){return Lm()}}),null),e})()]}}),null),L(r,n(u,{get when(){return t().saves?.length},get children(){return[zm(),(()=>{var e=Bm();return L(e,n(o,{get each(){return t().saves},children:(e,r)=>[n(th,{tag:`span`,class:`escalation-resource mono`,text:e,chars:240,lines:4,what:`the saved pattern`,reveal:!0}),n(oh,{get detail(){return t()},field:`save`,get index(){return r()}})]}),null),L(e,n(sh,{get count(){return t().savesMore}}),null),e})()]}}),null),L(r,n(u,{get when(){return H(()=>!!t().source)()&&(t().action||t().resources.length||t().form)},get children(){return[Vm(),(()=>{var e=Hm();return L(e,()=>nh[t().source]),D(()=>R(e,`data-source`,t().source)),e})()]}}),null),L(r,n(u,{get when(){return t().text},get children(){return[Um(),(()=>{var e=Mm();return L(e,n(th,{class:`decision-prompt mono`,get text(){return t().text},chars:400,lines:6,what:`the prompt`,reveal:!0})),e})()]}}),null),L(r,n(u,{get when(){return t().formID},get children(){return[Wm(),(()=>{var e=Mm();return L(e,()=>t().form??t().formID),e})()]}}),null),L(r,n(u,{get when(){return t().answer?.length},get children(){return[Gm(),(()=>{var e=Km();return L(e,n(o,{get each(){return t().answer},children:e=>(()=>{var t=Zm(),r=t.firstChild,i=r.firstChild;return r.nextSibling,L(r,()=>e.key,i),L(t,n(th,{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),L(r,n(u,{get when(){return t().outsideGrant},get children(){return[qm(),(()=>{var e=Mm();return L(e,()=>t().outsideGrant),e})()]}}),null),L(r,n(u,{get when(){return t().purpose},children:e=>[Qm(),(()=>{var t=$m(),n=t.firstChild,r=n.nextSibling,i=r.firstChild.nextSibling;return i.nextSibling,L(t,()=>e().text,n),L(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&&R(r,`data-decision-detail`,e.e=n),i!==e.t&&R(r,`data-escalation`,e.t=i),a!==e.a&&R(r,`data-live`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),r})()})}var fh=(e,t=eh)=>yn(e,t)?.purpose?.text;F([`click`]);var ph=J(`<span class="badge-pill agent-request"title="An agent asked to act outside its grant">Agent request`),mh=J(`<span>`),hh=J(`<p role=timer>`),gh=J(`<div role=radiogroup aria-label=Options class=choice-group>`),_h=J(`<p class="muted small decision-why">Why: `),vh=J(`<input type=text class=decision-note aria-label="Note (optional)"placeholder="Note (optional)">`),yh=J(`<p class="muted small decision-tier">`),bh=J(`<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`),xh=J(`<a>`),Sh=J(`<label class=text-field><span class=field-title>Your answer</span><textarea rows=2 aria-label="Your answer">`),Ch=J(`<span class="badge-pill safe"title="A timeout may pick this option">safe`),wh=J(`<span class="badge-pill recommended">Recommended`),Th=J(`<label><input type=radio><span>`),Eh={low:`Low urgency`,normal:``,high:`Urgent`};function Dh(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?Al(r().sessionID):void 0,v=async t=>{t.preventDefault();let n=rn(r(),i(),s());if(!n.ok)q(n.problem,`err`);else{d(!0);try{let{decision:e}=await(await G(`/api/decisions/${V(r().id)}/answer`,{method:`POST`,json:n.body})).json();q(`Answer sent`),e?yu(e):bu(r().id)}catch(t){if(t instanceof e&&t.status===409&&t.code===`gone`){q(`Already answered or expired`),bu(r().id);return}q(W(t),`err`),d(!1)}}},y=e=>r().recommendation?.option===e;return(()=>{var e=bh(),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`?he(C,e):g=e,L(p,()=>Nn(r(),Fl,yl()),null),L(d,n(u,{get when(){return qr(r())},get children(){return ph()}}),null),L(d,n(u,{get when(){return Eh[r().urgency]},get children(){var e=mh();return L(e,()=>Eh[r().urgency]),D(()=>K(e,`badge-pill urgency ${r().urgency}`)),e}}),null),L(d,n(u,{get when(){return H(()=>!!t.showSession)()&&_()},children:e=>[` · `,(()=>{var t=xh();return L(t,()=>e().session.title||e().session.id),D(()=>R(t,`href`,k(e().session.id))),t})()]}),null),L(m,()=>Fn(r(),Fl,yl())),L(e,n(dh,{get decision(){return r()}}),b),L(e,n(u,{get when(){return nn(r(),f())},get children(){var e=hh();return L(e,()=>nn(r(),f())),D(()=>K(e,`decision-deadline small${r().escalatedAt!==void 0||r().deadline<=f()?` overdue`:``}`)),e}}),b),b.addEventListener(`submit`,e=>void v(e)),L(x,n(u,{get when(){return r().options.length},get fallback(){return(()=>{var e=Sh(),t=e.firstChild.nextSibling;return t.$$input=e=>c(e.currentTarget.value),D(()=>t.value=s()),e})()},get children(){return[(()=>{var e=gh();return L(e,n(o,{get each(){return r().options},children:e=>(()=>{var t=Th(),o=t.firstChild,s=o.nextSibling;return o.addEventListener(`change`,()=>a(e.id)),L(s,()=>e.label),L(t,n(u,{get when(){return e.safe},get children(){return Ch()}}),null),L(t,n(u,{get when(){return y(e.id)},get children(){return wh()}}),null),D(n=>{var i=`choice${y(e.id)?` recommended`:``}`,a=`d-${r().id}`;return i!==n.e&&K(t,n.e=i),a!==n.t&&R(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 H(()=>!!r().recommendation?.why)()&&r().recommendation.why!==fh(r())},get children(){var e=_h();return e.firstChild,L(e,()=>r().recommendation.why,null),e}}),(()=>{var e=vh();return e.$$input=e=>c(e.currentTarget.value),D(()=>e.value=s()),e})()]}}),S),L(x,n(u,{get when(){return en(r())},get children(){var e=yh();return L(e,()=>en(r())),e}}),S),D(t=>{var n=`card decision urgency-${r().urgency}${h()?` targeted`:``}`,i=`Decision: ${r().question}`,a=r().id,o=Pn(r()),s=r().question,c=l();return n!==t.e&&K(e,t.e=n),i!==t.t&&R(e,`aria-label`,t.t=i),a!==t.a&&R(e,`data-decision`,t.a=a),o!==t.o&&R(p,`title`,t.o=o),s!==t.i&&R(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 Oh(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(Dh,{get decision(){return t()},get showSession(){return e.showSession}})})})}F([`input`]);var kh=J(`<span class="naming muted small"role=status><span class="spinner small"aria-hidden=true></span>Naming…`),Ah=J(`<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">✨`),jh,Mh=0;function Nh(e){return n(u,{get when(){return Cm(e.id,e.place)},get fallback(){return e.children},get children(){return n(Fh,{get id(){return e.id},get title(){return e.title},get place(){return e.place},get class(){return e.class}})}})}function Ph(e){return n(u,{get when(){return Iu(e.id)},get children(){return kh()}})}function Fh(e){let t,n=!1,r=jh&&jh.id===e.id&&jh.place===e.place?jh.value:void 0,i=()=>{n||(n=!0,jh=void 0,Sm(void 0),zu(e.id))},a=r=>{if(n)return;n=!0;let i=t.value;jh=void 0,Sm(void 0),r&&i.trim()&&i.trim()!==e.title&&Nu(e.id,i)};return ue(()=>{Mh++,t.focus(),r===void 0&&t.select()}),j(()=>{if(Mh--,setTimeout(()=>{Mh>0||(jh=void 0,xm()?.id===e.id&&xm()?.place===e.place&&Sm(void 0))},0),n)return;n=!0;let r=xm();r?.id===e.id&&r.place===e.place&&(jh={id:e.id,place:e.place,value:t.value})}),(()=>{var n=Ah(),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`?he(c,o):t=o,R(o,`maxlength`,200),s.$$click=e=>{e.preventDefault(),e.stopPropagation(),i()},s.$$mousedown=e=>{e.preventDefault(),e.stopPropagation()},D(()=>K(o,`rename-field${e.class?` ${e.class}`:``}`)),D(()=>o.value=r??e.title),n})()}F([`click`,`mousedown`,`keydown`]);var Ih=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()}},Lh={phase:`off`,voice:`off`,level:0,held:``,paused:!1},Rh=class{deps;state=Lh;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({...Lh,phase:`starting`,sessionID:e,voice:`starting`});let i=await this.deps.expose(e);if(t!==this.run)return;if(!i)return this.set({...Lh,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({...Lh,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(Lh))}});this.conversation=a;let o=await a.start();if(t===this.run){if(!o)return this.run++,this.conversation=void 0,this.set({...Lh,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(Lh),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()}},zh=3e3,Bh=`Voice mode on`,Vh=`Voice mode paused · unlock to talk`,Hh={starting:`starting`,listening:`listening`,hearing:`listening`,transcribing:`thinking`,sent:`thinking`,speaking:`speaking`,paused:`muted`,suspended:`paused`,off:`off`},Uh=(e,t,n)=>({sessionID:e,title:n===`suspended`?Vh:Bh,body:`${t} · ${Hh[n]??n}`}),Wh=class{controller;surface;options;shown;shownAt=0;timer;mediaFor;now;setTimer;clearTimer;unsubscribe;constructor(e,t,n){this.controller=e,this.surface=t,this.options=n,this.now=n.now??Date.now,this.setTimer=n.setTimer??((e,t)=>setTimeout(e,t)),this.clearTimer=n.clearTimer??(e=>clearTimeout(e)),this.unsubscribe=e.subscribe(()=>this.refresh())}needsPermission(){return this.controller.state.phase===`on`&&!this.surface.allowed()}async endFromNotification(e){this.controller.state.phase!==`off`&&this.controller.state.sessionID===e&&await this.controller.end()}refresh(){let e=this.controller.state;if(e.phase!==`on`||!e.sessionID)return this.clear();let t=e.sessionID,n=this.options.title(t);if(this.mediaFor!==t&&(this.mediaFor=t,this.surface.media({title:Bh,artist:n},()=>void this.controller.end())),!this.surface.allowed())return;let r=Uh(t,n,e.voice);if(this.shown&&this.shown.sessionID===r.sessionID&&this.shown.body===r.body)return this.cancel();let i=r.title!==this.shown?.title,a=this.shown?.sessionID===t&&!i?this.shownAt+zh-this.now():0;if(a<=0)return this.show(r);this.timer===void 0&&(this.timer=this.setTimer(()=>{this.timer=void 0,this.refresh()},a))}dispose(){this.unsubscribe(),this.cancel(),this.surface.close(),this.mediaFor&&this.surface.media(null),this.shown=this.mediaFor=void 0}show(e){this.cancel(),this.surface.show(e),this.shown=e,this.shownAt=this.now()}clear(){this.cancel(),this.shown&&this.surface.close(),this.mediaFor&&this.surface.media(null),this.shown=this.mediaFor=void 0}cancel(){this.timer!==void 0&&(this.clearTimer(this.timer),this.timer=void 0)}},Gh=[`image/png`,`image/jpeg`,`image/webp`,`image/gif`],Kh={maxImages:4,maxSide:1600,perImageBase64:18e4,totalBase64:7e5},qh=[.85,.72,.6,.48,.36],Jh=[1,.75,.55,.4,.28,.2],Yh=class extends Error{constructor(e=`This image is too large to attach, even after shrinking it`){super(e),this.name=`ImageTooLargeError`}},Xh=e=>4*Math.ceil(e/3),Zh=e=>Gh.includes(e);function Qh(e,t,n=Kh){if(e>=n.maxImages)return`Attach at most ${n.maxImages} images to a message`;if(!Zh(t))return`Only PNG, JPEG, WebP or GIF images can be attached`}function $h(e,t=Kh){return Math.max(0,Math.min(t.perImageBase64,t.totalBase64-e))}function eg(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 tg(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 ng(e,t,n,r=Kh){if(t<=0)throw new Yh(`No room for another image in this message`);let i=eg(e.width,e.height,r.maxSide);for(let r of Jh){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}]:[],...qh.map(e=>({type:`image/jpeg`,quality:e,width:a,height:o}))];for(let e of s){let r=await n(e);if(Xh(r.size)<=t)return{blob:r,request:e}}}throw new Yh}var rg=()=>({draft:``,images:[],pending:[],stopping:!1});function ig(e,t){switch(t.type){case`input`:return{...e,draft:t.text,error:void 0};case`attach`:return e.images.length>=Kh.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,Kh.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 ag(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 og(e,t){return e===202?t.mode===`turn`?`accepted`:`steered`:`result`}function sg(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 cg(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 lg=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)}},ug=-19.5,dg=-50,fg=20,pg=9,mg=2,hg=60,gg=.4,_g=.1,vg=-70,yg=-10,bg=e=>e>0?20*Math.log10(e):-1/0,xg=e=>e>0?-.691+10*Math.log10(e):-1/0;function Sg(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 Cg(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 wg(e,t){if(!e.length)return-1/0;let[n,r]=Sg(t),i=Cg(Cg(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(gg*t),s=Math.round(_g*t);if(i.length<o){let e=xg(a[i.length]/i.length);return e>vg?e:-1/0}let c=[];for(let e=0;e+o<=i.length;e+=s){let t=(a[e+o]-a[e])/o;xg(t)>vg&&c.push(t)}if(!c.length)return-1/0;let l=e=>e.reduce((e,t)=>e+t,0)/e.length,u=xg(l(c))+yg,d=c.filter(e=>xg(e)>u);return xg(l(d.length?d:c))}function Tg(e){let t=0;for(let n=0;n<e.length;n++)t=Math.max(t,Math.abs(e[n]));return bg(t)}function Eg(e,t){let n=10**(dg/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 Dg(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,mg/1e3*t)),n=Math.exp(-1/Math.max(1,hg/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 Og(e,t,n){let r=Eg(e,t),i=wg(r,t);if(!Number.isFinite(i))return{samples:r,gainDb:0,loudness:i};let a=10**(-1/20),o=Math.min(fg,-1-Tg(r)+pg),s=Math.min(n-i,o),c=Dg(r,t,10**(s/20),a);for(let e=0;e<3;e++){let e=n-wg(c,t);if(e<.1||s>=o)break;s=Math.min(s+e,o),c=Dg(r,t,10**(s/20),a)}return{samples:c,gainDb:s,loudness:i}}function kg(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 Ag=`voice.replyLoudness`,jg=8;function Mg(e){try{let t=JSON.parse(e.getItem(Ag)??`{}`);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}function Ng(e,t){let n=Mg(e)[t];return Array.isArray(n)?n.filter(e=>typeof e==`number`&&Number.isFinite(e)):[]}function Pg(e,t,n){if(!(!Number.isFinite(n)||n<-50||n>0))try{let r=Mg(e),i=[...Ng(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-jg)))delete r[e];e.setItem(Ag,JSON.stringify(r))}catch{}}var Fg=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 Ig(e,t){let n=[];try{t!==void 0&&(n=Ng(e,t))}catch{n=[]}return n.length?Math.min(-14,Math.max(-26,Fg(n))):ug}var Lg={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}]},Rg=`hub-cues-v2`,zg=[`hub-cues-v1`],Bg=`x-hub-cue-target`,Vg=1,Hg=`https://hub-cues.invalid`,Ug=e=>`${Hg}/${encodeURIComponent(e)}/`,Wg=(e,t)=>`${Ug(e)}${encodeURIComponent(t)}`;async function Gg(){try{let e=globalThis.caches;return e?await e.open(Rg):void 0}catch{return}}function Kg(e,t){e.defaultPlaybackRate=t,e.playbackRate=t,e.preservesPitch=!0,e.webkitPreservesPitch=!0}var qg=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))}},Jg=class{api;speed;onSpeaking;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,audio:r,normalize:i,target:a,memory:o=qg}){this.api=e,this.speed=t,this.onSpeaking=n,this.normalize=i,this.target=a,this.memory=o,this.audio=r??new Audio}unlock(){let e=globalThis,t=e.AudioContext||e.webkitAudioContext;t&&((!this.ctx||this.ctx.state===`closed`)&&(this.ctx=new t),this.ctx.resume?.().catch(()=>{}))}play(e){for(let t of e??[])t.type===`earcon`?this.earcon(t.name):t.type===`speak`&&this.say(t.text)}earcon(e){let t=this.ctx,n=Lg[e];if(!t||!n||t.state===`closed`)return;let r=t.currentTime+.01;for(let e of n){if(e.gap){r+=e.gap/1e3;continue}let n=t.createOscillator(),i=t.createGain(),a=r+(e.ms??0)/1e3;n.type=`sine`,n.frequency.value=e.freq??440,i.gain.setValueAtTime(1e-4,r),i.gain.exponentialRampToValueAtTime(.12,r+.012),i.gain.exponentialRampToValueAtTime(1e-4,a),n.connect(i).connect(t.destination),n.start(r),n.stop(a+.02),r=a}}async prefetch(e,t){this.key=Promise.resolve(t).catch(()=>void 0);let n=[...e],{signal:r}=this.loading;await Promise.all([this.prune(),...Array.from({length:Math.min(2,n.length)},async()=>{for(let e=n.shift();e!==void 0&&!r.aborted;e=n.shift())await this.phrase(e).catch(()=>void 0)})])}ready(e){return this.urls.has(e)}phrase(e){let t=this.phrases.get(e);return t||(t=this.load(e),this.phrases.set(e,t),t.catch(()=>this.phrases.delete(e))),t}async load(e){let{signal:t}=this.loading,n=await this.key,r=n?await Gg():void 0,i=n?Wg(n,e):``,a=this.target?.(n)??-19.5,o=e=>!this.normalize||Math.abs((e??NaN)-a)<=Vg,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(Bg);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[Bg]=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 Gg():void 0;if(!t||!e)return;let n=globalThis.caches;for(let e of zg)await n?.delete(e).catch(()=>!1);try{for(let n of await t.keys())n.url.startsWith(Ug(e))||await t.delete(n)}catch{}}say(e){let t=this.urls.get(e);return t?this.playURL(t):(this.earcon(`pending`),this.phrase(e).catch(()=>{}),Promise.resolve())}async playURL(e){let t=this.audio;this.setSpeaking(!0),t.src=e,t.volume=1,Kg(t,this.speed?.()??1);let n=new Promise(e=>{t.onended=t.onpause=t.onerror=()=>e()});await t.play().then(()=>!0,()=>!1)&&await n,t.onended=t.onpause=t.onerror=null,this.setSpeaking(!1)}stop(){this.audio.paused||this.audio.pause(),this.setSpeaking(!1)}setSpeaking(e){e!==this.speaking&&(this.speaking=e,this.onSpeaking?.(e))}close(){this.stop(),this.loading.abort(),this.loading=new AbortController,this.ctx?.close?.().catch(()=>{}),this.ctx=void 0}},Yg=new Set([`um`,`umm`,`uh`,`uhh`,`uhm`,`erm`,`er`,`eh`,`ah`,`hmm`,`hm`,`mm`,`mmm`,`mhm`,`mm-hmm`,`uh-huh`]),Xg=new Set([...Yg,`and`,`but`,`so`,`or`,`because`,`cause`,`then`,`with`,`to`,`the`,`a`,`an`,`of`,`for`,`if`,`that`,`like`,`maybe`]),Zg=new Map([[`stop`,`interrupt`],[`cancel`,`interrupt`],[`never mind`,`interrupt`],[`nevermind`,`interrupt`],[`stop that`,`interrupt`],[`hold on`,`interrupt`],[`pause listening`,`pause`]]);function Qg(e){return String(e??``).toLowerCase().replace(/[^\p{L}\p{N}'\s-]+/gu,` `).split(/\s+/).map(e=>e.replace(/^[-']+|[-']+$/g,``)).filter(Boolean)}function $g(e){return Zg.get(Qg(e).join(` `))}function e_(e){return Qg(e).every(e=>Yg.has(e))}function t_(e){let t=String(e??``).trim(),n=Qg(t);return!n.length||Xg.has(n[n.length-1])||/(\.\.\.|…|[,;:\-–—])["'”’)\]]*$/.test(t)?!1:/[.?!]["'”’)\]]*$/.test(t)?!0:n.length>=3}var n_=new Set([`e.g.`,`i.e.`,`mr.`,`mrs.`,`ms.`,`dr.`,`st.`,`vs.`,`cf.`,`prof.`,`jr.`,`sr.`,`approx.`,`no.`,`fig.`]),r_=/[.?!…]+["'”’)\]]*(?=\s|$)/g;function i_(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(a_),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=>o_(e,n))}function a_(e){let t=[],n=0;for(let r of e.matchAll(r_)){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(n_.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 o_(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 s_=16e3;function c_(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 l_(e,t){return kg(c_(e,t,s_),s_)}function u_(e){return{audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,...e?{deviceId:{exact:e}}:{}}}}var d_=Object.freeze({minSpeechMs:300,endSilenceMs:350,trailingKeepMs:200,preRollMs:300,holdMs:1600,finishedHoldMs:1e3}),f_=d_.trailingKeepMs,p_=120,m_=4,h_=e=>e.reduce((e,t)=>e+t.ms,0);function g_(e,t){for(;e.length>1&&h_(e)-e[0].ms>=t;)e.shift()}var __=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=d_.minSpeechMs,endSilenceMs:n=d_.endSilenceMs,preRollMs:r=d_.preRollMs,maxSegmentMs:i=6e4,onsetGapMs:a=p_,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=h_(this.frames),this.preroll=[],this.onsetMs=this.voicedMs=n.ms,this.gapMs=0):(this.preroll.push(n),g_(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,g_(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-f_;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}}},v_=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-m_: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}}},y_=class{sendFn;holdMs;finishedHoldMs;maxUtteranceMs;onHeld;setTimer;clearTimer;now;nextID=1;pending=[];text=``;ms=0;speaking=!1;endedAt=0;timer;constructor({send:e,holdMs:t=d_.holdMs,finishedHoldMs:n=d_.finishedHoldMs,maxUtteranceMs:r=6e4,onHeld:i,setTimer:a=(e,t)=>setTimeout(e,t),clearTimer:o=e=>clearTimeout(e),now:s=()=>Date.now()}){this.sendFn=e,this.holdMs=t,this.finishedHoldMs=n,this.maxUtteranceMs=r,this.onHeld=i,this.setTimer=a,this.clearTimer=o,this.now=s,this.reset()}get held(){return this.text}reset(){this.cancelHold(),this.pending=[],this.text=``,this.ms=0,this.speaking=!1,this.onHeld?.(``)}speechStarted(){this.speaking=!0,this.cancelHold()}segmentEnded(e){this.speaking=!1,this.endedAt=this.now();let t=this.nextID++;return this.pending.push({id:t,ms:e}),t}transcribed(e,t){let n=this.pending.find(t=>t.id===e);if(n){for(n.text=String(t??``).replace(/\s+/g,` `).trim();this.pending[0]?.text!==void 0;)this.apply(this.pending.shift());this.evaluate()}}apply({text:e,ms:t}){$g(e)?(this.cancelHold(),this.text=``,this.ms=0,this.sendFn(e)):e_(e)||(this.text=this.text?`${this.text} ${e}`:e,this.ms+=t,this.ms>=this.maxUtteranceMs&&this.flush())}evaluate(){if(this.onHeld?.(this.text),!this.text||this.speaking||this.pending.length)return;this.cancelHold();let e=(t_(this.text)?this.finishedHoldMs:this.holdMs)-(this.now()-this.endedAt);if(e<=0)return this.flush();this.timer=this.setTimer(()=>{this.timer=void 0,this.flush()},e)}flush(){this.cancelHold();let e=this.text;this.text=``,this.ms=0,e&&this.sendFn(e),this.onHeld?.(``)}cancelHold(){this.timer!==void 0&&this.clearTimer(this.timer),this.timer=void 0}},b_=2,x_=class{synth;play;stop;onState;onError;items=[];generation=0;controller=new AbortController;speaking=!1;playing=!1;constructor({synth:e,play:t,stop:n,onState:r,onError:i}){this.synth=e,this.play=t,this.stop=n,this.onState=r,this.onError=i}enqueue(e){for(let t of e)String(t??``).trim()&&this.items.push({text:String(t).trim()});this.items.length&&(this.speaking?this.prefetch():this.run(this.generation))}prefetch(){for(let e of this.items.slice(0,this.playing?b_:3))this.fetch(e)}clear(){this.generation++,this.controller.abort(),this.controller=new AbortController,this.items=[],this.playing=!1,this.stop(),this.setSpeaking(!1)}fetch(e){e&&!e.audio&&(e.audio=this.synth(e.text,this.controller.signal),e.audio.catch(()=>{}))}async run(e){for(this.setSpeaking(!0);e===this.generation&&this.items.length;){let t=this.items[0];this.prefetch();let n;try{n=await t.audio}catch(n){if(e!==this.generation)return;this.items.shift(),this.onError?.(n,t.text);continue}if(e!==this.generation)return;this.items.shift(),this.playing=!0,this.prefetch();try{await this.play(n)}catch(n){e===this.generation&&this.onError?.(n,t.text)}finally{e===this.generation&&(this.playing=!1)}}e===this.generation&&this.setSpeaking(!1)}setSpeaking(e){e!==this.speaking&&(this.speaking=e,this.onState?.(e))}},S_=class{parts=new Map;limit;constructor({limit:e=50}={}){this.limit=e}get size(){return this.parts.size}accept(e){let t=String(e.text??``);if(typeof e.seq!=`number`)return{sentences:i_(t),text:t};let n=`${e.messageID??``} ${e.ordinal??0}`,r=this.parts.get(n);if(r||(r={next:0,held:new Map,texts:[],muted:!1},this.parts.set(n,r),this.parts.size>this.limit&&this.parts.delete(this.parts.keys().next().value)),e.seq<r.next||r.held.has(e.seq))return;r.held.set(e.seq,t);let i=[];for(;r.held.has(r.next);)i.push(r.held.get(r.next)),r.held.delete(r.next++);if(i.length)return r.texts.push(...i),{sentences:r.muted?[]:i.flatMap(e=>i_(e)),text:r.texts.join(` `)}}mute(){for(let e of this.parts.values())e.muted=!0}},C_=class{pending={};turn;last;mark(e,t){switch(e){case`speechEnd`:return this.pending={speechEnd:t},!0;case`transcript`:return this.pending.speechEnd!==void 0&&(this.pending.transcript=t,!0);case`accepted`:return this.turn={...this.pending,accepted:t},this.pending={},!0;case`firstSay`:return!this.turn||this.turn.firstSay!==void 0?!1:(this.turn.firstSay=t,!0);case`firstByte`:return this.turn?.firstSay===void 0||this.turn.firstByte!==void 0?!1:(this.turn.firstByte=t,!0);case`firstAudio`:return this.turn?.firstSay!==void 0&&(this.last={...this.turn,firstAudio:t},this.turn=void 0,!0)}}},w_=e=>`${(e/1e3).toFixed(1)} s`;function T_(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} ${w_(n-i)}`),i=n)}return{summary:`last turn: ${w_(e.firstAudio-t)} to first audio`,detail:r.join(` · `)}}var E_=12,D_=e=>String(e??``).replace(/\s+/g,` `).trim();function O_(e,t){let n=D_(e),r=D_(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>=E_;e--)if(n.endsWith(r.slice(0,e)))return{mode:`update`,text:n+r.slice(e)};return{mode:`new`,text:t}}function k_(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 A_=16e3,j_=512/A_*1e3,M_=Object.freeze({startProb:.6,endProb:.35,speakingStartProb:.85,minSpeechMs:250,endSilenceMs:d_.endSilenceMs,maxSegmentMs:6e4,gateDb:3,energyMarginDb:10,energyMinSpeechMs:d_.minSpeechMs}),N_=Object.freeze([`low`,`normal`,`high`]);function P_(e){return N_.includes(e)?e:`normal`}var F_=Object.freeze({low:Object.freeze({...M_,startProb:.75,endProb:.45,speakingStartProb:.92,minSpeechMs:350,gateDb:6,energyMarginDb:13,energyMinSpeechMs:400}),normal:M_,high:Object.freeze({...M_,startProb:.45,endProb:.25,speakingStartProb:.75,minSpeechMs:180,gateDb:0,energyMarginDb:7,energyMinSpeechMs:250})});function I_(e){return F_[P_(e)]}var L_=.75,R_=class{speaking=!1;segmenter;current;constructor(e,t=A_){this.current=e,this.segmenter=new __({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=L_;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)}},z_=class{from;ratio;input=new Float32Array;pos=0;out=new Float32Array(512);filled=0;constructor(e){this.from=e,this.ratio=e/A_}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}},B_=64,V_=class{sampleRate=A_;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=M_,onEvents:n,onLevel:r,warn:i=e=>console.warn(e),now:a=()=>performance.now()}){this.resampler=new z_(e),this.meter=new v_({marginDb:t.energyMarginDb}),this.vad=new R_(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/j_)),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,j_,n);this.onLevel?.(a);let s={chunk:e,energyVoiced:o,guarded:t};this.queue.push(s),this.model&&this.inFlight>=B_&&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 H_(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 U_(e){return e.audioState===`suspended`||e.error===`NotAllowedError`&&!e.activated&&e.micPermission!==`denied`}var W_=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(`.`)),G_=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`]),K_=[/^(?:subtitles?|captions?|subtitled|captioned|transcribed|transcription|translated|translation)\b.*\bby\b/,/\bamara\s*\.?\s*org\b/,/^sous-titr/,/^untertitel\b/],q_=/^(?:\[[^\]]*\]|\([^)]*\)|\*[^*]*\*|♪[^♪]*♪|\s)+$/u;function J_(e){return e.toLowerCase().replace(/[^\p{L}\p{N}'\s]+/gu,` `).replace(/\s+/g,` `).trim()}function Y_(e,{speechMs:t}={}){let n=String(e??``).trim();if(!n)return`empty`;if(!/[\p{L}\p{N}]/u.test(n))return`no words`;if(q_.test(n))return`sound`;let r=J_(n);if(r.replace(/\s/g,``).length<2)return`too short`;if(G_.has(r)||G_.has(r.replace(/ /g,``))||K_.some(e=>e.test(r)||e.test(n.toLowerCase())))return`noise`;let i=r.split(` `),a=i.some(e=>W_.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 X_=3e4,Z_;function Q_(){return Z_??=$_().catch(e=>{throw Z_=void 0,e}),Z_}function $_(){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(),Z_=void 0,a||t(e)},s=setTimeout(()=>o(Error(`the speech model took too long to load`)),X_);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 ev=()=>Object.assign(Error(`The download was aborted`),{name:`AbortError`}),tv=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 ev();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 nv(e,t){let n=new tv;if(!e)return n.end(),n;let r=e.getReader(),i=()=>{n.fail(ev()),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?ev():e)}finally{t?.removeEventListener(`abort`,i)}})(),n}async function rv(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 iv(e){try{return e.MediaSource?.isTypeSupported?.(`audio/mpeg`)===!0}catch{return!1}}var av=24e3,ov=1,sv=2;async function cv(e){let t=globalThis,n=t.OfflineAudioContext||t.webkitOfflineAudioContext;if(!n)throw Error(`No OfflineAudioContext here`);let r=new n(1,1,av),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 lv(e,t){let{samples:n,rate:r}=await cv(await e.arrayBuffer()),i=Og(n,r,t);return new Blob([kg(i.samples,r)],{type:`audio/wav`})}function uv(e){try{return Ig(localStorage,e)}catch{return Ig({getItem:()=>null,setItem:()=>{}},e)}}var dv=0,fv=e=>{let t=globalThis;t.requestIdleCallback?t.requestIdleCallback(e,{timeout:5e3}):setTimeout(e,500)};function pv(e,t){!t||!e.length||dv>=sv||(dv++,fv(()=>{(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 cv(n.buffer);if(i.length<a*ov)return;Pg(localStorage,t,wg(i,a))}catch{}finally{dv--}})()}))}var mv=500,hv=8e3,gv=e=>Math.min(hv,mv*2**Math.max(0,e)),_v=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)}},vv=2500,yv=3e3,bv=!1,xv=2,Sv=`Tap to start Voice mode`,Cv=`GestureRequired`,wv=500,Tv=500,Ev=3e3,Dv=()=>navigator.userActivation?.hasBeenActive??!0;async function Ov(){try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return`unknown`}}var kv={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`},Av=class{sessionID;api;player;ui;opts;active=!1;paused=!1;agent;inflight=0;sent=new Map;typed=new Set;typing=0;heardAt=0;lastStatus;cuePicker=new fo({ready:e=>this.cuePlayer?.ready(e)??!1});scheduler=new po({pick:e=>this.cuePicker.pick(e)});cuePlayer;voiceKey;onVisibility;liveness=new _v({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=iv(window);says=new S_;turns=new C_;cueClock;speechEndedAt;silence;silenceURL;wakeLock;warnedAutoplay=!1;state;ignoredTimer;sensitivity=`normal`;cueSpeaking=!1;attempt=0;constructor({sessionID:e,api:t,player:n,ui:r,options:i={}}){this.sessionID=e,this.api=t,this.player=n,this.ui=r,this.opts={cues:!0,background:!1,speed:()=>1,title:()=>`OpenCode session`,sensitivity:()=>`normal`,...i},this.lastStatus=i.status,this.scheduler.enabled=this.opts.cues!==!1,this.scheduler.working(_o(i.status),Date.now()),this.cuePlayer=new Jg({api:this.api,speed:this.opts.speed,normalize:lv,target:uv,onSpeaking:e=>{this.cueSpeaking=e,this.guardEcho(),this.scheduler.cueSpeaking(e,Date.now()),this.cueClock.poke()}}),this.cueClock=new mo({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(u_(this.opts.deviceId))}catch(e){if(t())return!1;let n=e;return U_({error:n.name,micPermission:await Ov(),activated:Dv()})?this.ui.note(Sv,`gesture`):this.ui.note(n.name===`NotAllowedError`?`Microphone permission was denied. Allow it in the browser's site settings.`:`Microphone: ${n.message}`,`err`),this.ui.state(`off`),this.stopSilence(),!1}if(t())return r.getTracks().forEach(e=>e.stop()),!1;this.stream=r;try{let{agent:e}=await(await this.api(`${this.path}/conversation`,{method:`POST`,json:{on:!0}})).json();this.agent=e}catch(e){return this.release(),this.stopSilence(),t()||(this.ui.note(`Could not start Voice mode: ${e.message}`,`err`),this.ui.state(`off`)),!1}if(t())return this.release(),await this.api(`${this.path}/conversation`,{method:`POST`,json:{on:!1}}).catch(()=>{}),!1;this.active=!0,this.prefetchCues();try{await this.listen()}catch(e){return t()||(e.name===Cv?this.ui.note(Sv,`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(),Tv),this.cueClock.poke(),this.refresh(),!0)}prefetchCues(){this.opts.cues!==!1&&this.scheduler.enabled&&this.cuePlayer.prefetch(uo(),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,wv))]),U_({audioState:n.state,activated:Dv()}))throw Object.assign(Error(Sv),{name:Cv});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 V_({sampleRate:n.sampleRate,params:I_(this.sensitivity),onEvents:e=>this.vadEvents(e),onLevel:e=>this.ui.level(e)});this.ui.detector?.({mode:`energy`}),Q_().then(e=>{this.vad===r&&(e.reset(),r.classifier=t=>e.classify(t),this.ui.detector?.({mode:`silero`}))},e=>{bv||console.warn(`Voice: on-device speech detection unavailable (${e?.message??e}); using the energy detector`),bv=!0}),this.endpointer=new y_({send:e=>void this.deliver(e),onHeld:e=>this.ui.held?.(e)}),this.queue=new x_({synth:(e,t)=>this.synth(e,t),play:e=>this.play(e),stop:()=>{this.player.paused||this.player.pause()},onState:e=>{this.guardEcho(),this.scheduler.agentSpeaking(e,Date.now()),e&&this.cuePlayer.stop(),this.cueClock.poke(),this.refresh()},onError:e=>{e?.name!==`AbortError`&&this.ui.note(`Could not read the reply aloud: ${e?.message}`,`err`)}})}guardEcho(){this.vad&&(this.vad.speaking=!!this.queue?.speaking||this.cueSpeaking)}frame(e){if(!this.active||(this.liveness.frame(Date.now()),!this.vad||this.paused||!this.liveness.live))return;let t=this.opts.sensitivity();t!==this.sensitivity&&(this.sensitivity=t,this.vad.params=I_(t)),this.vad.push(e)}vadEvents(e){let t=this.vad;if(this.active&&t&&!this.paused&&this.liveness.live)for(let n of e){if(n.type===`start`)this.endpointer.speechStarted(),this.scheduler.userTalking(!0,Date.now()),this.cuePlayer.stop(),this.queue.speaking?this.hushReplies():this.says.mute();else{this.speechEndedAt=Date.now(),this.markTurn(`speechEnd`),this.cuePlayer.play(this.scheduler.speechEnded(this.speechEndedAt));let e=this.endpointer.segmentEnded(n.durationMs);this.transcribe(e,l_(n.samples,t.sampleRate),n.speechMs),this.ui.detector?.({mode:t.mode,...t.mode===`silero`?{avgMs:t.stats.avgMs}:{}})}this.cueClock.poke(),this.refresh()}}async transcribe(e,t,n){this.inflight++,this.refresh();let r=``;try{r=(await(await this.api(`/api/transcribe`,{method:`POST`,body:t,headers:{"content-type":`audio/wav`}})).json()).text??``}catch(e){this.active&&this.ui.note(`Transcription failed: ${e.message}`,`err`)}finally{this.inflight--}this.active&&(Y_(r,{speechMs:n})&&(r.trim()&&this.showIgnored(r.trim()),r=``),r.trim()&&this.markTurn(`transcript`),this.endpointer?.transcribed(e,r),this.refresh())}showIgnored(e){clearTimeout(this.ignoredTimer),this.ui.ignored?.(e),this.ignoredTimer=setTimeout(()=>this.ui.ignored?.(``),yv)}async deliver(e,t=!1){let n=$g(e);if(n===`pause`)return this.ui.note(`Paused listening.`),this.stop();if(n===`interrupt`){this.hushReplies(),this.ui.note(`“${e}” — interrupting.`);try{await this.api(`${this.path}/interrupt`,{method:`POST`,json:{}})}catch(e){this.ui.note(`Could not interrupt: ${e.message}`,`err`)}return}let r=this.ui.user(e);t&&this.typing++,this.scheduler.awaitReply(t?Date.now():this.speechEndedAt??Date.now()),this.cueClock.poke();try{let{inboxID:n}=await(await this.api(`${this.path}/utterance`,{method:`POST`,json:{text:e}})).json();this.markTurn(`accepted`),this.sent.get(n)===`heard`?this.ui.tick(r,`heard`):(this.ui.tick(r,`sent`),t&&this.typed.add(n)),this.sent.set(n,r)}catch(e){let t=e;this.ui.tick(r,`failed`),this.ui.note(t.status===409?t.message:`Could not send: ${t.message}`,`err`)}finally{t&&this.typing--}}sendTyped(e){return this.hushReplies(),this.deliver(e,!0)}hushReplies(){this.queue?.clear(),this.says.mute()}onEvent(e){if(e.sessionID===this.sessionID){if(e.type===`heard`){let t=this.sent.get(e.inboxID);t!==void 0&&t!==`heard`?this.ui.tick(t,`heard`):this.sent.set(e.inboxID,`heard`),this.heardAt=Date.now();let n=this.typed.delete(e.inboxID)||t===void 0&&this.typing>0;this.active&&!this.paused&&this.cuePlayer.play(this.scheduler.heard(this.heardAt,{tone:n})),this.cueClock.poke(),this.refresh(),setTimeout(()=>this.refresh(),2550)}else if(e.type===`say`){if(!this.active)return;let t=this.says.accept(e);if(!t)return;this.scheduler.agentSaid(Date.now()),this.cuePlayer.stop(),this.cueClock.poke(),this.ui.agent({messageID:e.messageID,text:t.text}),t.sentences.length&&this.markTurn(`firstSay`),this.queue?.enqueue(t.sentences)}else e.type===`conversation`&&!e.on&&this.active&&(this.ui.note(`Voice mode was turned off.`),this.stop({post:!1}))}}onStatus(e){let t=Date.now(),{started:n,finished:r}=go(this.lastStatus,e,this.sessionID);if(this.lastStatus=e,this.scheduler.working(_o(e),t),this.active){for(let e=0;e<n.length;e++)this.scheduler.subagentStarted(t);r.length&&!this.paused&&this.cuePlayer.play(this.scheduler.subagentFinished(t)),this.cueClock.poke()}}setCues(e){this.scheduler.enabled=e,e?this.active&&this.prefetchCues():this.cuePlayer.stop(),this.cueClock.poke()}setBackground(e){this.opts.background=e,this.active&&(e?(this.wakeLock?.release().catch(()=>{}),this.wakeLock=void 0,this.startSilence(),this.mediaSession()):(this.stopSilence(),this.clearMediaSession(),this.lockScreen()))}pause(){this.active&&!this.paused&&(this.paused=!0,this.cueClock.stop(),this.hushReplies(),this.cuePlayer.stop(),this.endpointer?.reset(),this.vad?.reset(),this.stream?.getAudioTracks().forEach(e=>e.enabled=!1),this.silence?.pause(),navigator.mediaSession&&(navigator.mediaSession.playbackState=`paused`),this.ui.level(0),this.refresh())}resume(){this.active&&this.paused&&(this.paused=!1,this.stream?.getAudioTracks().forEach(e=>e.enabled=!0),this.ctx?.resume().catch(()=>{}),this.opts.background&&(this.silence?.play().catch(()=>{}),navigator.mediaSession&&(navigator.mediaSession.playbackState=`playing`)),this.cueClock.poke(),this.refresh())}mediaSession(){navigator.mediaSession&&(navigator.mediaSession.playbackState=this.paused||!this.liveness.live?`paused`:`playing`)}watchTrack(e){this.unwatchTrack();let t=e.getAudioTracks?.()[0];t?.addEventListener&&(this.track=t,t.addEventListener(`mute`,this.onTrackMute),t.addEventListener(`unmute`,this.onTrackUnmute),t.addEventListener(`ended`,this.onTrackEnded),t.muted&&this.liveness.muted(!0,Date.now()),t.readyState===`ended`&&this.liveness.ended(Date.now()))}unwatchTrack(){let e=this.track;this.track=void 0,e?.removeEventListener&&(e.removeEventListener(`mute`,this.onTrackMute),e.removeEventListener(`unmute`,this.onTrackUnmute),e.removeEventListener(`ended`,this.onTrackEnded))}checkMic(){if(!this.active)return;let e=Date.now();this.liveness.tick(e),!(this.liveness.live||document.visibilityState===`visible`||e-this.lastResumeTry<Ev)&&(this.lastResumeTry=e,this.ctx&&this.ctx.state!==`running`&&this.ctx.resume().catch(()=>{}),this.opts.background&&!this.paused&&this.silence?.play().catch(()=>{}))}livenessChanged(e,t){this.active&&(e?(clearTimeout(this.recoverTimer),this.recoverTimer=void 0,this.recoverAttempt=0,this.cuePlayer.earcon(`resumed`),this.cueClock.poke()):(this.vad?.reset(),this.ui.level(0),this.cuePlayer.earcon(`paused`),this.lastResumeTry=Date.now(),this.liveness.wantsRecovery&&this.scheduleRecover()),this.opts.background&&this.mediaSession(),this.refresh())}scheduleRecover(){this.recoverTimer===void 0&&this.active&&(this.recoverTimer=setTimeout(()=>{this.recoverTimer=void 0,this.recover()},gv(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,wv))])}async reacquire(){let e;try{e=await navigator.mediaDevices.getUserMedia(u_(this.opts.deviceId))}catch(e){if(!this.active)return;U_({error:e.name,micPermission:await Ov(),activated:Dv()})&&this.ui.note(Sv,`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([l_(new Float32Array(16e3*xv),16e3)],{type:`audio/wav`})),t=new Audio(e);t.loop=!0,t.setAttribute(`aria-hidden`,`true`),this.silence=t,this.silenceURL=e}this.silence.play().catch(()=>{})}stopSilence(){this.silence&&=(this.silence.pause(),this.silence.removeAttribute(`src`),this.silence.load(),this.silenceURL&&URL.revokeObjectURL(this.silenceURL),this.silenceURL=void 0)}hush(){if(this.paused)return this.resume();this.hushReplies(),this.cuePlayer.stop()}async synth(e,t){let n=nv((await this.api(`/api/speak`,{method:`POST`,json:{text:e},signal:t})).body,t);return n.firstByte.then(()=>this.markTurn(`firstByte`),()=>{}),n.whole().then(async e=>pv(e,await(this.voiceKey??=this.cueKey()))).catch(()=>{}),n}async play(e){let t=this.player,n=new AbortController,r;try{if(this.streaming){if(await e.firstByte,e.done&&!e.chunks.length)return;let i=new MediaSource;r=URL.createObjectURL(i),t.src=r,this.feedSource(i,e,n.signal)}else{let n=await e.whole();if(!n.length)return;r=URL.createObjectURL(new Blob(n,{type:`audio/mpeg`})),t.src=r}let i=new Promise(e=>{t.onended=t.onpause=t.onerror=()=>e()});if(!await t.play().then(()=>!0,()=>!1)){this.warnedAutoplay||this.ui.note(`The browser blocked audio playback. Tap the mic to allow it.`),this.warnedAutoplay=!0;return}this.markTurn(`firstAudio`),await i}finally{n.abort(),t.onended=t.onpause=t.onerror=null,r&&URL.revokeObjectURL(r)}}async feedSource(e,t,n){try{if(e.readyState!==`open`&&await new Promise(t=>e.addEventListener(`sourceopen`,t,{once:!0})),n.aborted)return;let r=e.addSourceBuffer(`audio/mpeg`);!await rv(t,{append:e=>new Promise((t,n)=>{r.addEventListener(`updateend`,()=>t(),{once:!0}),r.addEventListener(`error`,()=>n(Error(`Could not decode the reply audio`)),{once:!0}),r.appendBuffer(e)}),end:()=>{e.readyState===`open`&&!r.updating&&e.endOfStream()}},n)&&!n.aborted&&e.readyState===`open`&&!r.updating&&e.endOfStream()}catch{}}markTurn(e){if(!this.turns.mark(e,Date.now()))return;try{performance.mark(kv[e])}catch{}let t=e===`firstAudio`?T_(this.turns.last):void 0;t&&this.ui.timing?.(t)}refresh(){if(!this.active)return;let e=this.paused?`paused`:this.liveness.live?this.queue?.speaking?`speaking`:this.vad?.active?`hearing`:this.inflight>0||this.endpointer?.held?`transcribing`:Date.now()-this.heardAt<vv?`sent`:`listening`:`suspended`;e!==this.state&&(this.state=e,this.ui.state(e))}async lockScreen(){if(`wakeLock`in navigator&&document.visibilityState===`visible`&&(!this.wakeLock||this.wakeLock.released))try{this.wakeLock=await navigator.wakeLock.request(`screen`)}catch{}}release(){this.unwatchTrack(),this.stream?.getTracks().forEach(e=>e.stop()),this.stream=void 0}async stop({post:e=!0,keepalive:t=!1}={}){this.attempt++;let n=this.active;this.active=!1,this.paused=!1,this.state=void 0,document.removeEventListener(`visibilitychange`,this.onVisibility),window.removeEventListener?.(`pageshow`,this.onWake),window.removeEventListener?.(`focus`,this.onWake),clearInterval(this.micTimer),clearTimeout(this.recoverTimer),this.micTimer=this.recoverTimer=void 0,this.recoverAttempt=0,this.ctx&&(this.ctx.onstatechange=null),this.cueClock.stop(),this.cuePlayer.close(),this.stopSilence(),this.opts.background&&this.clearMediaSession(),this.queue?.clear(),this.endpointer?.reset(),this.vad?.reset();try{this.source?.disconnect(),this.tap?.disconnect(),this.tap&&`port`in this.tap&&(this.tap.port.onmessage=null),this.sink?.disconnect()}catch{}this.ctx?.close().catch(()=>{}),this.ctx=this.source=this.tap=this.sink=this.vad=void 0,this.release(),this.wakeLock?.release().catch(()=>{}),this.wakeLock=void 0,this.ui.level(0),this.ui.held?.(``),clearTimeout(this.ignoredTimer),this.ui.ignored?.(``),this.ui.state(`off`),this.ui.ended(),e&&n&&await this.api(`${this.path}/conversation`,{method:`POST`,json:{on:!1},keepalive:t}).catch(()=>{})}},jv=`voice.speed`,Mv=`voice.cues`,Nv=`voice.background`,Pv=`voice.micDevice`,Fv=`voice.sensitivity`,Iv=P_(localStorage.getItem(Fv)),Lv={get speed(){return no(localStorage.getItem(jv))},set speed(e){localStorage.setItem(jv,String(no(e))),Kg(Rv,no(e))},get cues(){return localStorage.getItem(Mv)!==`0`},set cues(e){localStorage.setItem(Mv,e?`1`:`0`)},get background(){return localStorage.getItem(Nv)===`1`},set background(e){localStorage.setItem(Nv,e?`1`:`0`)},get sensitivity(){return Iv},set sensitivity(e){Iv=P_(e),localStorage.setItem(Fv,Iv)}},Rv=new Audio;Rv.preload=`none`,Rv.volume=1,Kg(Rv,Lv.speed);function zv(){Rv.paused&&(Rv.muted=!0,Rv.play().catch(()=>{}).finally(()=>{Rv.pause(),Rv.muted=!1}))}var[Bv,Vv]=x(localStorage.getItem(Pv)??``);function Hv(e){Vv(e),localStorage.setItem(Pv,e)}async function Uv(){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 Wv(e,t){let n=await navigator.mediaDevices.getUserMedia(u_(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 Gv=6e4;function Kv(){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 qv(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(u_(Bv()||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=Kv(),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 G(`/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((Gv-(Date.now()-a))/1e3))),1e3),l=setTimeout(()=>r.state===`recording`&&r.stop(),Gv);return{finish(){return r.state===`recording`&&r.stop(),s},cancel(){o=!0,r.state===`recording`&&r.stop()}}}var[Jv,Yv]=x(Date.now());setInterval(()=>gl()&&Yv(Date.now()),1e3);var[Xv,Zv]=x(!1),Qv=e=>Zv(e),$v=()=>tc(nl(),gl(),Math.max(Jv(),Date.now())),ey=(e,t)=>nl().find(t=>t.id===e)?.options.find(e=>e.id===t)?.label??t;async function ty(t,n,r){let i=ey(t,n);try{let{decision:e}=await(await G(`/api/decisions/${V(t)}/answer`,{method:`POST`,json:{option:n,...r?{via:r}:{}}})).json().catch(()=>({}));e?yu(e):bu(t),q(`Answered “${i}”${r?` by ${r}`:``}`)}catch(n){throw n instanceof e&&n.status===409&&n.code===`gone`?(bu(t),new e(409,`Already answered or expired`)):n}}function ny(t){return mc(G,{sessionID:t,current:()=>ll()?.sessionID,armed:()=>$v(),present:()=>Xv()&&document.visibilityState===`visible`,answer:async(t,n)=>{try{await ty(t,n,`voice`)}catch(t){let n=t instanceof e&&t.status===403;throw Object.assign(Error(n?`Not answered by voice: ${t.message}. Tap an option on the card.`:`Not answered: ${t instanceof Error?t.message:String(t)}`),{status:409})}}})}var ry=new Rh({async expose(e){let t=()=>Al(e)?.session.exposed!==!1;if(t())return!0;if(!await Mu(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 Av({sessionID:e,api:ny(e),player:Rv,ui:t,options:{cues:Lv.cues,background:Lv.background,speed:()=>Lv.speed,sensitivity:()=>Lv.sensitivity,title:()=>Al(e)?.session.title||`OpenCode session`,status:Al(e)?.session.status,deviceId:Bv()||void 0}}),stopPlayback:()=>{Rv.paused||Rv.pause()},notify:(e,t)=>q(e,t===`err`?`err`:``)}),[iy,ay]=x(0);ry.subscribe(()=>ay(e=>e+1));var oy=`voice-mode`,sy=Promise.resolve(),cy=e=>{sy=sy.then(async()=>{let t=`serviceWorker`in navigator?await navigator.serviceWorker.getRegistration(`/`):void 0;t&&await e(t)}).catch(()=>{})},ly={allowed:()=>`Notification`in window&&Notification.permission===`granted`&&`serviceWorker`in navigator,show:e=>cy(t=>t.showNotification(e.title,{body:e.body,tag:oy,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:()=>cy(async e=>(await e.getNotifications({tag:oy})).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{}}},uy=new Wh(ry,ly,{title:e=>Al(e)?.session.title||`OpenCode session`});Rd(e=>{e?.type===`voice-end`&&typeof e.sessionID==`string`&&uy.endFromNotification(e.sessionID)});function dy(){return iy(),uy.needsPermission()}async function fy(){try{await jd()}catch(e){q(e instanceof Error?e.message:String(e),`err`)}uy.refresh(),ay(e=>e+1)}function py(){return iy(),ry.state}var my=()=>{let e=py().sessionID;return e?Al(e)?.session.title||`Session`:``};Ol(e=>{e.type===`say`||e.type===`heard`||e.type===`conversation`?ry.onEvent(e):e.type===`status`&&typeof e.sessionID==`string`&&Array.isArray(e.sessions)&&ry.onStatus(e.sessionID,e.sessions)}),window.addEventListener(`pagehide`,()=>{ry.stop({keepalive:!0}),ly.close()});var hy=new lg,gy=new Ih({record:e=>qv(e),deliver:(e,t)=>void hy.append(e,t),notify:(e,t)=>q(e,t),hold:()=>ry.hold()}),[_y,vy]=x(0);gy.subscribe(()=>vy(e=>e+1));function yy(e){return _y(),gy.forSession(e)}var by=J(`<div class=banner><span></span><a class="btn small"href=/settings/machines>Review`),xy=J(`<div class=banner><span><strong>Set up speech</strong> · </span><a class="btn small"href=/settings/voice#speech>Set up`),Sy=J(`<section class=decisions aria-label=Decisions><h2 class=section-title>`),Cy=J(`<select aria-label=Server><option value>All servers`),wy=J(`<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`),Ty=J(`<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.`),Ey=J(`<ul class=home-list>`),Dy=J(`<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>`),Oy=J(`<option>`),ky=J(`<button type=button class=chip>`),Ay=J(`<p class="muted small offline-line"><strong></strong> · offline · seen `),jy=J(`<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">`),My=J(`<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>`),Ny=J(`<th><button type=button class=th-btn><span class=sort-mark aria-hidden=true>`),Py=J(`<tr><td colspan=9 class="muted empty-cell">No sessions match.`),Fy=J(`<span class=jobs-badge>`),Iy=J(`<a>`),Ly=J(`<span class=unread-dot role=img aria-label=Unread>`),Ry=J(`<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>`),zy=J(`<a class=home-item-link><span class=home-item-text><span class=home-item-title></span><span>`),By=J(`<li>`),Vy=J(`<span class=home-item-link>`),Hy=`hub.table`;function Uy(e){Jc();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=Gc.has(e.id)?Gc.feed(e.id):void 0,r=n?.pulse(),i=e.jobs?` · ${ja(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: ${ja(e.jobs)}`:`Working`}var Wy=[[`status`,`Status`],[`title`,`Title`],[`project`,`Project`],[`server`,`Server`],[`source`,`Open in`],[`activity`,`Last activity`]],Gy=[[`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 Ky(){let[e,t]=x(Ka(localStorage.getItem(Hy))),[r,i]=x(``),a=e=>{t(e),localStorage.setItem(Hy,qa(e))},s=T(()=>Wa(kl(),{...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=()=>{wm(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,Fa.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=()=>Eo(Qc()??void 0,X()?.publicURL);return(()=>{var t=Dy(),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 L(x,n(U,{name:`plus`}),C),L(t,n(u,{get when(){return el().length},get children(){var e=by(),t=e.firstChild;return L(t,(()=>{var e=H(()=>el().length===1);return()=>e()?`${el()[0].machineName} wants to connect.`:`${el().length} machines want to connect.`})()),e}}),w),L(t,n(u,{get when(){return S()},get children(){var e=xy(),t=e.firstChild;return t.firstChild.nextSibling,L(t,()=>S().reason,null),e}}),w),L(t,n(u,{get when(){return nl().length},get children(){var e=Sy(),t=e.firstChild;return L(t,(()=>{var e=H(()=>nl().length===1);return()=>e()?`A decision waits for you`:`${nl().length} decisions wait for you`})()),L(e,n(Oh,{get decisions(){return nl()},showSession:!0}),null),e}}),w),L(T,n(U,{name:`search`}),E),E.$$input=e=>i(e.currentTarget.value),ee.$$click=()=>g(!0),L(w,n(u,{get when(){return _().length>1},get children(){var t=Cy();return t.firstChild,t.addEventListener(`change`,t=>a({...e(),filters:{...e().filters,machine:t.currentTarget.value}})),L(t,n(o,{get each(){return _()},children:e=>(()=>{var t=Oy();return L(t,()=>e.name),D(()=>t.value=e.id),t})()}),null),D(()=>t.value=e().filters.machine),t}}),null),L(te,n(o,{each:Gy,children:([e,t,n])=>(()=>{var r=ky();return r.$$click=()=>y(n),R(r,`data-chip`,e),L(r,t),D(()=>R(r,`aria-pressed`,v(n))),r})()})),L(t,n(u,{get when(){return d().length},get children(){var t=wy(),n=t.firstChild,r=n.firstChild,i=n.nextSibling,a=i.nextSibling;return L(n,()=>d().length,r),i.$$click=m,L(i,()=>e().filters.archived?`Unarchive`:`Archive`),a.$$click=()=>p(!1),t}}),O),L(O,(()=>{var t=H(()=>Y.machines===void 0);return()=>t()?`Loading…`:$a(s().length,kl().filter(e=>!e.hidden).length,nl().length,e().filters.status===`needs`)})()),L(t,n(u,{get when(){return H(()=>!!Y.machines)()&&Y.machines.length===0},get children(){return Ty()}}),null),L(t,n(u,{get when(){return Z()},get fallback(){return n(Yy,{get rows(){return s()},get table(){return e()},sortBy:b,get picked(){return c()},pick:f,pickAll:p})},get children(){var e=Ey();return L(e,n(o,{get each(){return s()},children:e=>n(Xy,{row:e})})),e}}),null),L(t,n(o,{get each(){return _().filter(e=>!e.online)},children:e=>(()=>{var t=Ay(),n=t.firstChild;return n.nextSibling,L(n,()=>e.name),L(t,()=>ze(e.lastSeen,I()),null),t})()}),null),L(t,n(Jy,{get open(){return h()},get rows(){return kl()},onClose:()=>g(!1)}),null),D(()=>E.value=r()),t})()}var qy=30;function Jy(e){let[t,r]=x(String(qy)),i=T(()=>e.open?Za(e.rows,Number(t()),I()):[]),a=()=>i().length,o=()=>{wm(i(),!0),e.onClose()};return n(Re,{get open(){return e.open},title:`Archive inactive sessions`,get onClose(){return e.onClose},get children(){var n=jy(),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),L(c,(()=>{var e=H(()=>a()===1);return()=>e()?`1 session`:`${a()} sessions`})(),l),L(c,(()=>{var e=H(()=>Number(t())===1);return()=>e()?`1 day`:`${t()||`?`} days`})(),u),Oe(d,`click`,e.onClose,!0),L(f,(()=>{var e=H(()=>a()===1);return()=>e()?`Archive 1 session`:`Archive ${a()} sessions`})()),D(()=>f.disabled=!a()),D(()=>s.value=t()),n}})}function Yy(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=My(),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)),L(c,n(o,{each:Wy,children:([t,n])=>(()=>{var i=Ny(),a=i.firstChild,o=a.firstChild;return K(i,`col-${t}`),a.$$click=()=>e.sortBy(t),L(a,n,o),L(o,(()=>{var n=H(()=>e.table.sort.key===t);return()=>n()?e.table.sort.dir===`asc`?`↑`:`↓`:``})()),D(()=>R(i,`aria-sort`,r(t))),i})()}),f),L(p,n(o,{get each(){return e.rows},get fallback(){return Py()},children:t=>(()=>{var r=Ry(),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)),L(s,n(ge,{get state(){return t.state}}),c),L(c,()=>Ie[t.state]),L(s,n(u,{get when(){return t.error},children:e=>n(je,{get text(){return e()}})}),null),L(s,n(u,{get when(){return t.jobs},get children(){var e=Fy();return L(e,()=>t.jobs),D(n=>{var r=ja(t.jobs),i=ja(t.jobs);return r!==n.e&&R(e,`title`,n.e=r),i!==n.t&&R(e,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),e}}),null),L(l,n(u,{get when(){return Qa(t,py())},get children(){return n(De,{})}}),null),L(l,n(Nh,{get id(){return t.id},get title(){return t.title},place:`table`,get children(){var e=Iy();return L(e,()=>t.title),D(()=>R(e,`href`,k(t.id))),e}}),null),L(l,n(Ph,{get id(){return t.id}}),null),L(l,n(u,{get when(){return t.unread},get children(){return Ly()}}),null),L(d,()=>t.where),L(p,()=>t.machineName),L(m,()=>Me[t.source]),L(h,()=>ze(t.updated,I())),L(g,()=>Uy(t)),L(_,n(pe,{get label(){return`More actions for ${t.title}`},class:`icon-btn small`,items:()=>Tm(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&&K(r,e.e=n),i!==e.t&&R(o,`aria-label`,e.t=i),a!==e.a&&R(d,`title`,e.a=a),s!==e.o&&K(p,e.o=s),c!==e.i&&K(g,e.i=c),l!==e.n&&R(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 Xy(e){let t=()=>e.row;return(()=>{var e=By();return L(e,n(u,{get when(){return!Cm(t().id,`phone`)},get fallback(){return(()=>{var e=Vy();return L(e,n(ge,{get state(){return t().state}}),null),L(e,n(Nh,{get id(){return t().id},get title(){return t().title},place:`phone`,children:null}),null),e})()},get children(){var e=zy(),r=e.firstChild,i=r.firstChild,a=i.nextSibling;return L(e,n(ge,{get state(){return t().state}}),r),L(e,n(u,{get when(){return t().error},children:e=>n(je,{get text(){return e()}})}),r),L(i,n(u,{get when(){return Qa(t(),py())},get children(){return n(De,{})}}),null),L(i,()=>t().title,null),L(i,n(Ph,{get id(){return t().id}}),null),L(i,n(u,{get when(){return t().unread},get children(){return Ly()}}),null),L(a,()=>Uy(t())||`${t().where} · ${t().machineName} · ${ze(t().updated,I())}`),D(n=>{var r=k(t().id),i=`home-item-meta ${t().error?`error`:`muted`}`;return r!==n.e&&R(e,`href`,n.e=r),i!==n.t&&K(a,n.t=i),n},{e:void 0,t:void 0}),e}}),null),L(e,n(pe,{get label(){return`More actions for ${t().title}`},class:`icon-btn small`,items:()=>Tm(t(),{place:`phone`})}),null),D(()=>K(e,`home-item${t().unread?` unread`:``}`)),e})()}F([`input`,`click`]);var Zy=J(`<div role=separator aria-orientation=vertical tabindex=0>`);function Qy(e){let t=0,n=0,r=0,i,a=()=>Rf()[e.panel],o=()=>zf(e.panel),s=()=>{r=0,i!==void 0&&Bf(e.panel,i,!1)},c=()=>{r&&cancelAnimationFrame(r),r=0,i=void 0,Ff(void 0),document.documentElement.classList.remove(`resizing`)},l=(t,n,r)=>{t.hasPointerCapture(n)&&t.releasePointerCapture(n),c(),Bf(e.panel,r)};return ue(()=>e.panel===`rail`&&Nf(!0)),j(()=>{e.panel===`rail`&&Nf(!1),Pf()===e.panel&&c()}),(()=>{var c=Zy();return c.$$keydown=t=>{let n=lf(e.panel,a(),t.key,t.shiftKey,o());n!==void 0&&(t.preventDefault(),Bf(e.panel,n))},c.$$dblclick=()=>Bf(e.panel,nf[e.panel].default),c.addEventListener(`pointercancel`,t=>Pf()===e.panel&&l(t.currentTarget,t.pointerId,i??a())),c.$$pointerup=t=>Pf()===e.panel&&l(t.currentTarget,t.pointerId,i??a()),c.$$pointermove=a=>{if(Pf()!==e.panel)return;let c=uf(e.panel,t,a.clientX-n,o());`collapse`in c?(l(a.currentTarget,a.pointerId,t),Tf(!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,Ff(e.panel),document.documentElement.classList.add(`resizing`))},D(t=>{var n=`panel-handle${Pf()===e.panel?` dragging`:``}`,r=e.panel,i=e.label,s=a(),l=o().min,u=o().max;return n!==t.e&&K(c,t.e=n),r!==t.t&&R(c,`data-panel`,t.t=r),i!==t.a&&R(c,`aria-label`,t.a=i),s!==t.o&&R(c,`aria-valuenow`,t.o=s),l!==t.i&&R(c,`aria-valuemin`,t.i=l),u!==t.n&&R(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})()}F([`pointerdown`,`pointermove`,`pointerup`,`dblclick`,`keydown`]);var $y={service:`background service`,standalone:`standalone`};function eb(e){return(e??[]).map(e=>{let t=!!e.online,n=e.processes.find(e=>e.kind===`service`)??e.processes[0],r=t?n?[$y[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 tb(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 nb(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 rb(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:nb(e,i?.machine===t?{key:i.key,dir:i.dir}:{},a?.machine===t?a:void 0)??o}function ib(e,t){let n=Oi(t).split(/\s+/).filter(Boolean);return n.length?e.filter(e=>{let t=[e.label,...e.directories].map(Oi);return n.every(e=>t.some(t=>t.includes(e)))}):[...e]}var ab=`hub.newSession`;function ob(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 sb(e,t){try{e.setItem(ab,JSON.stringify({machine:t.machine,key:t.key,dir:t.dir}))}catch{}}var cb=`hub.railCollapsed`;function lb(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 ub(e,t){let n=lb(e);n.has(t)?n.delete(t):n.add(t);try{e.setItem(cb,JSON.stringify([...n]))}catch{}return n}var db=0,fb=e=>e.reduce((e,t)=>e+t.data.length,0);async function pb(e,t){let n=Qh(t.length,e.type);if(n)throw Error(n);let r=await mb(e);try{let n=e.type!==`image/jpeg`&&gb(r),{blob:i,request:a}=await ng({width:r.width,height:r.height,keepPng:n},$h(fb(t)),e=>_b(r,e)),o=await vb(i);return{id:`img${++db}`,mime:a.type,data:o.slice(o.indexOf(`,`)+1),name:tg(e.name||`image`,a.type),preview:URL.createObjectURL(i)}}finally{`close`in r&&r.close()}}async function mb(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 hb(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 gb(e){let t=Math.max(1,Math.min(64,e.width)),n=Math.max(1,Math.min(64,e.height)),[,r]=hb(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 _b(e,t){let[n,r]=hb(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 vb(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 yb(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 bb=new Map;function xb(e,t){bb.set(e,t)}function Sb(e){let t=bb.get(e);return bb.delete(e),t}var Cb=J(`<li class="attachment busy"aria-label="Preparing image"><span class="spinner small">`),wb=J(`<ul class=attachments aria-label="Attached images">`),Tb=J(`<span class="spinner small">`),Eb=J(`<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">`),Db=J(`<span class="meta-chip readonly"title="Branch of this folder"><span class="chip-text mono">`),Ob=J(`<label class="meta-chip toggle-chip"><input type=checkbox><span class=chip-text>Open in Herdr tab`),kb=J(`<div class=env-meta role=group aria-label="Where the session runs">`),Ab=J(`<p data-new-dir>`),jb=J(`<p class="small new-need-project"role=alert data-need-project>Choose a project first: the session starts in one of <!>'s folders.`),Mb=J('<p class="small warn"> has no background service connected; start `opencode serve --service` there to create sessions.'),Nb=J(`<p class=error role=alert>`),Pb=J(`<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?`),Fb=J(`<p class=muted>No machine is connected to this hub yet.`),Ib=J(`<li class=attachment><img><button type=button class=attachment-remove>`),Lb=J(`<span aria-hidden=true>`),Rb=J(`<span class=chip-text>`),zb=J(`<button type=button aria-haspopup=dialog aria-label="Choose project folder"><span class=chip-text>`),Bb=J(`<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>`),Vb=J(`<p class="muted small pad">No folder matches.`),Hb=J(`<div class=menu-section> · Herdr`),Ub=J(`<button type=button role=option class=menu-item><span class=menu-check></span><span class=menu-label></span><span class="menu-hint mono">`);function Wb(t){let r=ob(localStorage),i=()=>Y.machines??[],s=T(()=>eb(i())),[c,l]=x(),d=()=>{let e=c();return e&&s().some(t=>t.id===e&&t.online)?e:tb(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=da(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:ve(t.dir),directories:[t.dir]}),n}),[g,_]=x(),[v,y]=x(!1),b=()=>rb(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 B(`${P(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 pb(t,ae());A(t=>[...t,e])}catch(e){ce(W(e))}}finally{j(!1)}})},N=()=>!le()&&!oe()&&!!p()?.canCreate&&!!w()&&(!!re().trim()||ae().length>0),[me,ge]=x(!1),_e,F=async()=>{let t=p(),n=S(),r=w();if(!r&&t&&!le()&&(re().trim()||ae().length>0))ge(!0),_e?.focus();else if(N()&&t&&n){M(!0),ce(``);try{let e=fa({target:n,directory:r,openInHerdr:ne()}),i=await(await G(`/api/machines/${V(t.id)}/sessions`,{method:`POST`,json:e})).json();sb(localStorage,{machine:t.id,key:n.key,dir:r}),xb(i.sessionID,{text:re().trim(),images:ae()}),a(k(i.sessionID),{replace:!0}),i.warning?q(`Session created, but Herdr didn't open it: ${i.warning}`,`warn`):i.openedIn===`herdr`&&q(`Opened in Herdr · ${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: ${W(n)}`),M(!1)}}},ye=()=>[{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))}}))],I,be;ue(()=>I?.focus());let xe=()=>{I.style.height=`auto`,I.style.height=`${Math.min(I.scrollHeight,320)}px`};return(()=>{var e=Pb(),t=e.firstChild,r=t.firstChild,i=t.nextSibling;return i.firstChild,L(t,n(u,{get when(){return Z()},get children(){return n(z,{icon:`menu`,label:`Open sidebar`,onClick:Df})}}),r),L(i,n(u,{get when(){return s().length},get fallback(){return Fb()},get children(){return[(()=>{var e=Eb(),t=e.firstChild,r=t.firstChild,i=r.nextSibling,a=i.nextSibling.firstChild,s=a.nextSibling.nextSibling;e.addEventListener(`drop`,e=>{let t=yb(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(),F()}),L(t,n(u,{get when(){return ae().length||oe()},get children(){var e=wb();return L(e,n(o,{get each(){return ae()},children:e=>(()=>{var t=Ib(),r=t.firstChild,i=r.nextSibling;return i.$$click=()=>A(t=>t.filter(t=>t.id!==e.id)),L(i,n(U,{name:`close`})),D(t=>{var n=e.preview,a=e.name,o=e.name,s=`Remove ${e.name}`;return n!==t.e&&R(r,`src`,t.e=n),a!==t.t&&R(r,`alt`,t.t=a),o!==t.a&&R(r,`title`,t.a=o),s!==t.o&&R(i,`aria-label`,t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),null),L(e,n(u,{get when(){return oe()},get children(){return Cb()}}),null),e}}),r),r.$$keydown=e=>{e.key===`Enter`&&!e.shiftKey&&!e.isComposing&&!(matchMedia(`(max-width: 760px)`).matches&&`ontouchstart`in window)&&(e.preventDefault(),F())},r.addEventListener(`paste`,e=>{let t=yb(e.clipboardData);t.length&&(e.preventDefault(),fe(t))}),r.$$input=e=>{ie(e.currentTarget.value),xe()};var c=I;typeof c==`function`?he(c,r):I=r,i.addEventListener(`change`,e=>{let t=[...e.currentTarget.files??[]];e.currentTarget.value=``,t.length&&fe(t)});var l=be;return typeof l==`function`?he(l,i):be=i,a.$$click=()=>be.click(),L(a,n(U,{name:`plus`})),L(s,n(u,{get when(){return le()},get fallback(){return n(U,{name:`send`})},get children(){return Tb()}})),D(e=>{var t=Gh.join(`,`),n=ae().length>=Kh.maxImages||oe(),r=N()||w()?`Start session`:`Choose a project first`,o=!N(),c=!N();return t!==e.e&&R(i,`accept`,e.e=t),n!==e.t&&(a.disabled=e.t=n),r!==e.a&&R(s,`title`,e.a=r),o!==e.o&&(s.disabled=e.o=o),c!==e.i&&R(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=kb();return L(e,n(pe,{label:`Choose environment`,class:`meta-chip env-chip`,align:`left`,items:ye,get text(){return[n(U,{name:`cloud`}),(()=>{var e=Lb();return D(()=>K(e,`online-dot${p()?.online?` on`:``}`)),e})(),(()=>{var e=Rb();return L(e,()=>p()?.name??`No environment`),e})(),n(U,{name:`down`,class:`chip-caret`})]}}),null),L(e,n(Gb,{get targets(){return h()},get current(){return b()},get dir(){return w()},get disabled(){return!p()},get asked(){return H(()=>!!me())()&&!w()},buttonRef:e=>_e=e,foldersOf:C,onPick:(e,t)=>_({machine:d(),key:e,dir:t})}),null),L(e,n(u,{get when(){return H(()=>!!w())()&&ee()},get children(){var e=Db(),t=e.firstChild;return L(e,n(U,{name:`branch`}),t),L(t,ee),e}}),null),L(e,n(u,{get when(){return H(()=>!!p()?.herdr)()&&S()?.kind===`herdr`},get children(){var e=Ob(),t=e.firstChild;return t.addEventListener(`change`,e=>O(e.currentTarget.checked)),D(()=>R(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=Ab();return L(e,(()=>{var e=H(()=>!!w());return()=>e()?w():H(()=>!!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&&K(e,t.e=n),r!==t.t&&R(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e})(),n(u,{get when(){return H(()=>!(!me()||w()))()&&p()},get children(){var e=jb(),t=e.firstChild.nextSibling;return t.nextSibling,L(e,()=>p().name,t),e}}),n(u,{get when(){return H(()=>!!p())()&&!p().canCreate},get children(){var e=Mb(),t=e.firstChild;return L(e,()=>p().name,t),e}}),n(u,{get when(){return se()},get children(){var e=Nb();return L(e,se),e}})]}}),null),e})()}function Gb(e){let[t,r]=x(!1),[i,a]=x(``),[s,c]=x({top:0,left:0}),l,d,f,p=()=>ib(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} · ${ve(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`&&!be(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=zb(),i=r.firstChild;return r.$$click=g,he(t=>{l=t,e.buttonRef?.(t)},r),L(r,n(U,{name:`folder`}),i),L(i,h),L(r,n(U,{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&&K(r,n.e=i),a!==n.t&&R(r,`aria-expanded`,n.t=a),o!==n.a&&R(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(_e,{get children(){var t=Bb(),r=t.firstChild,c=r.nextSibling,l=d;typeof l==`function`?he(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`?he(m,r):f=r,L(c,n(u,{get when(){return p().length},get fallback(){return Vb()},get children(){return n(o,{get each(){return p()},children:t=>n(u,{get when(){return H(()=>t.kind===`herdr`)()&&e.foldersOf(t).length>1},get fallback(){return(()=>{var n=Ub(),r=n.firstChild,i=r.nextSibling,a=i.nextSibling;return n.$$click=()=>y(t.key,e.foldersOf(t)[0]??``),L(r,()=>e.current?.key===t.key?`✓`:``),L(i,()=>t.label),L(a,(()=>{var n=H(()=>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&&R(n,`aria-selected`,r.e=i),a!==r.t&&R(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()},get children(){return[(()=>{var e=Hb(),n=e.firstChild;return L(e,()=>t.label,n),e})(),n(o,{get each(){return e.foldersOf(t)},children:n=>(()=>{var r=Ub(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling;return r.$$click=()=>y(t.key,n),R(r,`title`,n),L(i,()=>e.current?.key===t.key&&e.dir===n?`✓`:``),L(a,()=>ve(n)),L(o,n),D(()=>R(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&&xe(t,`top`,e.e=n),r!==e.t&&xe(t,`left`,e.t=r),e},{e:void 0,t:void 0}),D(()=>r.value=i()),t}})}})]}F([`input`,`keydown`,`click`]);var Kb={name:`home`},qb=_(()=>T(()=>{let e=He();return e.name===`concierge`?Z()?e:Kb:Kb=e})),Jb=e=>String(e??``).normalize(`NFD`).replace(/[\u0300-\u036f]/g,``).toLowerCase();function Yb(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 Xb(e){let t=e?.note;return!Array.isArray(e)&&typeof t==`string`&&t.trim()?t.trim():void 0}var Zb=e=>e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;function Qb(e,t,{current:n=``,limit:r=200,grouped:i=!1}={}){let a=String(t??``).trim(),o=Jb(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=Jb(e.id),r=`${n} ${Jb(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(Zb(t.option.id))||e.set(Zb(t.option.id),e.size);u.sort((t,n)=>e.get(Zb(t.option.id))-e.get(Zb(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 $b(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 ex=J(`<input type=search class=picker-search autofocus>`),tx=J(`<button type=button class="btn small">Retry`),nx=J(`<p class="muted small"role=status>`),rx=J(`<p class="muted small picker-note">`),ix=J(`<li><button type=button><span class=po-name>Use “<!>”</span><span class="po-id muted">as a custom `),ax=J(`<ul class=picker-list role=listbox>`),ox=J(`<div class="picker-group muted small">`),sx=J(`<span class="po-id muted">`),cx=J(`<span class=po-mark>✓ Current`),lx=J(`<li><button type=button><span class=po-name>`);function ux(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(W(e))))};C(h(()=>e.request,e=>{e&&(r(``),p(0),m())}));let g=T(()=>Qb(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(Re,{get open(){return!!e.request},get title(){return e.request?.title??``},get onClose(){return e.onClose},class:`picker`,get children(){return[(()=>{var e=ex();return e.$$keydown=e=>{let t={ArrowDown:1,ArrowUp:-1};if(e.key in t)e.preventDefault(),p($b(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&&R(e,`placeholder`,t.e=n),r!==t.t&&R(e,`aria-label`,t.t=r),t},{e:void 0,t:void 0}),D(()=>e.value=t()),e})(),(()=>{var e=nx();return L(e,(()=>{var e=H(()=>!!s());return()=>e()?`Couldn't load the ${y()} list: ${s()}. Type any ${y()}.`:H(()=>i()===void 0)()?`Loading ${y()}s…`:H(()=>!i().length)()?`No suggestions. Type any ${y()}.`:`${g().total} ${g().total===1?y():`${y()}s`}`})(),null),L(e,n(u,{get when(){return s()},get children(){return[` `,(()=>{var e=tx();return e.$$click=m,e})()]}}),null),e})(),n(u,{get when(){return l()},get children(){var e=rx();return L(e,l),e}}),(()=>{var t=ax();return L(t,n(o,{get each(){return g().items},children:(t,r)=>(()=>{var i=lx(),a=i.firstChild,o=a.firstChild;return L(i,n(u,{get when(){return H(()=>!!e.request?.grouped)()&&(r()===0||Zb(g().items[r()-1].id)!==Zb(t.id))},get children(){var e=ox();return L(e,()=>Zb(t.id)||`Other`),e}}),a),a.$$click=()=>v(t.id),L(o,()=>t.id),L(a,n(u,{get when(){return t.name},get children(){var e=sx();return L(e,()=>t.name),e}}),null),L(a,n(u,{get when(){return t.current},get children(){return cx()}}),null),D(e=>{var n=`picker-opt${f()===r()?` active`:``}`,i=!!t.current;return n!==e.e&&K(a,e.e=n),i!==e.t&&R(a,`aria-selected`,e.t=i),e},{e:void 0,t:void 0}),i})()}),null),L(t,n(u,{get when(){return g().custom},get children(){var e=ix(),t=e.firstChild,n=t.firstChild,r=n.firstChild.nextSibling;r.nextSibling;var i=n.nextSibling;return i.firstChild,t.$$click=()=>v(g().custom),L(n,()=>g().custom,r),L(i,y,null),D(()=>K(t,`picker-opt${f()===g().items.length?` active`:``}`)),e}}),null),t})()]}})}F([`input`,`keydown`,`click`]);var dx=J(`<div class=chips role=group aria-label="Which speech settings"><button type=button class=chip>Yours</button><button type=button class=chip>Server default`),fx=J(`<div class="speech-panel stack">`),px=J(`<p class=error>`),mx=J(`<p class=muted>Loading…`),hx=J(`<p class="small inherit">`),gx=J(`<p class="small muted">`),_x=J(`<p class=field-error>`),vx=J(`<div class=field><label>`),yx=J(`<input type=text autocomplete=off autocapitalize=off>`),bx=J(`<div class=row><button type=button class="btn small">Browse…`),xx=J(`<input type=password autocomplete=new-password placeholder="Paste the new key"aria-label="New API key">`),Sx=J(`<div class=row><button type=button class="btn small">Cancel`),Cx=J(`<div class="field key-field"><span class=field-label>API key`),wx=J(`<p>`),Tx=J(`<button type=button class="btn small">Undo`),Ex=J(`<button type=button class="btn small danger">Clear`),Dx=J(`<div class=row><button type=button class="btn small">`),Ox=J(`<fieldset class="card speech-card"><legend>`),kx=J(`<div class="row reset-row"><span class="small muted grow"></span><button type=button class="btn small">Reset to server default`),Ax=J(`<option>`),jx=J(`<select>`),Mx=J(`<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.`),Nx=J(`<button type=button class=btn>Preview voice`),Px=J(`<form class=stack novalidate><div class=row><button type=submit class="btn primary">Save</button></div><p role=status>`),Fx=J(`<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.`),Ix=[[`openrouter`,`OpenRouter`],[`openai-compatible`,`OpenAI-compatible`]],Lx={settings:`from settings`,config:`from hub.json`,env:`from env`,user:`yours`},Rx={user:`/api/settings/speech`,default:`/api/settings/speech/default`},zx={stt:`Speech-to-text`,tts:`Text-to-speech`};function Bx(){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 B(Rx[n]);n===`user`&&a(yt(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: ${W(t)}`)}};ue(()=>void d(`user`));let f=e=>{e!==t()&&(r(e),d(e))};return(()=>{var e=fx();return L(e,n(u,{get when(){return i()},get children(){var e=dx(),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&&R(n,`aria-pressed`,e.e=i),a!==e.t&&R(r,`aria-pressed`,e.t=a),e},{e:void 0,t:void 0}),e}}),null),L(e,n(u,{get when(){return!c()},get fallback(){return(()=>{var e=px();return L(e,c),e})()},get children(){return n(u,{get when(){return o()},get fallback(){return mx()},keyed:!0,children:e=>n(Vx,{settings:e,get scope(){return t()},onSaved:e=>s(e)})})}}),null),e})()}function Vx(e){let[t,r]=pi(xo(e.settings)),[i,a]=x({}),[s,c]=x({text:``,kind:``}),[l,d]=x(!1),[f,p]=x(),m=()=>e.scope===`user`?wt(e.settings):void 0,h=()=>e.scope===`user`?Eo(e.settings.ready,X()?.publicURL):void 0,g=()=>Object.keys(So(e.settings,ti(t))).length>0,_={},v=e=>(_[e]??=B(`/api/settings/speech/models?kind=${e}`).then(e=>({options:Yb(e),note:Xb(e)})),_[e].catch(()=>delete _[e]),_[e]),y=(e,t,r,a,o)=>{let s=()=>m()?.[e]?.[t];return(()=>{var c=vx(),l=c.firstChild;return R(l,`for`,`sp-${e}-${t}`),L(l,r),L(c,a,null),L(c,n(u,{get when(){return s()?.inherited},get children(){var e=hx();return L(e,()=>s().note),e}}),null),L(c,n(u,{when:o,get children(){var e=gx();return L(e,o),e}}),null),L(c,n(u,{get when(){return i()[`${e}.${t}`]},get children(){var n=_x();return L(n,()=>i()[`${e}.${t}`]),n}}),null),c})()},b=(e,n,a={})=>(()=>{var o=yx();return R(o,`id`,`sp-${e}-${n}`),R(o,`spellcheck`,!1),N(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=bx(),c=s.firstChild;return L(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=Cx();return e.firstChild,L(e,n(u,{get when(){return c().action===`set`},get fallback(){return[(()=>{var e=wx();return L(e,(()=>{var e=H(()=>c().action===`clear`);return()=>e()?`Key will be removed when you save.`:H(()=>!!s()?.inherited)()?s().note:H(()=>!!o.set)()?`Key set${o.last4?` ••••${o.last4}`:``} (${Lx[o.source]??o.source})`:`No key set`})()),D(()=>K(e,`key-summary${s()?.inherited&&c().action!==`clear`?` inherit`:``}`)),e})(),(()=>{var e=Dx(),t=e.firstChild;return t.$$click=()=>r(a,`apiKey`,{action:`set`,value:``}),L(t,(()=>{var e=H(()=>!!s()?.inherited);return()=>e()?`Use your own key`:o.set?`Replace`:`Add key`})()),L(e,n(u,{get when(){return c().action===`clear`},get children(){var e=Tx();return e.$$click=()=>r(a,`apiKey`,{action:`keep`,value:``}),e}}),null),L(e,n(u,{get when(){return H(()=>c().action!==`clear`)()&&l()},get children(){var e=Ex();return e.$$click=()=>r(a,`apiKey`,{action:`clear`,value:``}),e}}),null),e})()]},get children(){return[(()=>{var e=xx();return e.$$input=e=>r(a,`apiKey`,`value`,e.currentTarget.value),R(e,`id`,`sp-${a}-apiKey`),D(()=>e.value=c().value),e})(),(()=>{var e=Sx(),t=e.firstChild;return t.$$click=()=>r(a,`apiKey`,{action:`keep`,value:``}),e})()]}}),null),L(e,n(u,{get when(){return i()[`${a}.apiKey`]},get children(){var e=_x();return L(e,()=>i()[`${a}.apiKey`]),e}}),null),e})()},w=async t=>{if(await Se(`Reset ${zx[t].toLowerCase()} to the server default? Your own ${zx[t].toLowerCase()} settings are removed.`,`Reset`,{danger:!0}))try{let n=await(await G(Rx.user,{method:`PUT`,json:Tt(t)})).json().catch(()=>({})),r=n?.stt&&n?.tts?n:await B(Rx.user);$c(r.ready??null),e.onSaved(r),q(`${zx[t]} reset to the server default`)}catch(e){q(`Could not reset: ${W(e)}`,`err`)}},T=i=>(()=>{var a=Ox(),s=a.firstChild;return L(s,()=>zx[i]),L(a,n(u,{get when(){return m()},children:e=>(()=>{var t=kx(),n=t.firstChild,r=n.nextSibling;return L(n,(()=>{var t=H(()=>!!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),L(a,()=>y(i,`provider`,`Provider`,(()=>{var e=jx();return e.addEventListener(`change`,e=>r(i,`provider`,e.currentTarget.value)),R(e,`id`,`sp-${i}-provider`),L(e,n(o,{each:Ix,children:([e,t])=>(()=>{var n=Ax();return n.value=e,L(n,t),n})()}),null),L(e,n(u,{get when(){return!Ix.some(([e])=>e===t[i].provider)},get children(){var e=Ax();return L(e,()=>t[i].provider||`—`),D(()=>e.value=t[i].provider),e}}),null),D(()=>e.value=t[i].provider),e})()),null),L(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),L(a,()=>y(i,`model`,`Model`,S(i,`model`,i===`stt`?`Speech-to-text model`:`Text-to-speech model`,`model`,()=>v(i))),null),L(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[H(()=>y(i,`voice`,`Voice`,S(i,`voice`,`Voice`,`voice`,async()=>Yb(wo(e.settings.voiceHints,t.tts.model))))),H(()=>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),L(a,()=>C(i),null),a})(),E=async n=>{n.preventDefault();let i=ti(t),o=Co(i);if(a(o),Object.keys(o).length)return c({text:`Fix the highlighted fields.`,kind:`error`});let s=So(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 G(Rx[e.scope],{method:`PUT`,json:s})).json().catch(()=>({})),n=t?.stt&&t?.tts?t:await B(Rx[e.scope]);e.scope===`user`?$c(n.ready??null):Su(),r(_i(xo(n))),e.onSaved(n),q(e.scope==="default"?`Server default saved`:`Speech settings saved`)}catch(e){let t=e.field;t&&a({[t]:W(e)}),c({text:`Could not save: ${W(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 G(`/api/settings/speech/test`,{method:`POST`,json:{kind:`tts`,text:`Hi! This is how replies will sound.`}})).blob();if(e=URL.createObjectURL(t),Rv.src=e,Kg(Rv,Lv.speed),!await Rv.play().then(()=>!0,()=>!1))throw Error(`the browser blocked playback`);c({text:`Playing preview.`,kind:`muted`}),await new Promise(e=>Rv.onended=Rv.onpause=Rv.onerror=()=>e()),c({text:``,kind:``})}catch(e){c({text:`Preview failed: ${W(e)}`,kind:`error`})}finally{Rv.onended=Rv.onpause=Rv.onerror=null,e&&URL.revokeObjectURL(e)}};return(()=>{var t=Px(),r=t.firstChild,i=r.firstChild,a=r.nextSibling;return t.$$input=()=>c({text:g()?`Unsaved changes.`:``,kind:`muted`}),t.addEventListener(`submit`,E),L(t,n(u,{get when(){return e.scope==="default"},get children(){return Mx()}}),r),L(t,n(u,{get when(){return h()},children:e=>(()=>{var t=Fx(),r=t.firstChild,i=r.firstChild.nextSibling;return i.nextSibling,L(i,()=>e().reason),L(r,n(u,{get when(){return e().storage},get children(){var t=gx();return L(t,()=>e().storage),t}}),null),t})()}),r),L(t,()=>T(`stt`),r),L(t,()=>T(`tts`),r),L(r,n(u,{get when(){return e.scope===`user`},get children(){var e=Nx();return e.$$click=()=>void ee(),e}}),null),L(a,()=>s().text),L(t,n(ux,{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&&K(a,e.t=n),e},{e:void 0,t:void 0}),t})()}F([`click`,`input`]);var Hx=[`queued`,`placing`,`provisioning`,`running`],Ux=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Wx=e=>typeof e==`string`,Gx=e=>typeof e==`number`&&Number.isFinite(e);function Kx(e){if(!Ux(e)||!Wx(e.id)||!Wx(e.state)||!Ux(e.spec)||!Ux(e.spec.workspace)||!Wx(e.spec.workspace.repo))return;let t=e.spec.workspace,n=e.waiting;return{id:e.id,state:e.state,reason:Wx(e.reason)?e.reason:``,repo:t.repo,...Wx(t.branch)?{branch:t.branch}:{},...Wx(e.by)?{by:e.by}:{},...Wx(e.byLabel)?{byLabel:e.byLabel}:{},launcherRevoked:e.launcherRevoked===!0,...Ux(n)&&Wx(n.wait)&&Wx(n.reason)&&Gx(n.since)?{waiting:{wait:n.wait,reason:n.reason,since:n.since}}:{},...Wx(e.name)?{name:e.name}:{},...Wx(e.sessionID)?{sessionID:e.sessionID}:{},...Wx(e.machineID)?{machineID:e.machineID}:{},concierge:e.by===`app:concierge`&&Ux(e.spec.labels)&&e.spec.labels[`hub/system`]===`concierge`,created:Gx(e.created)?e.created:0}}function qx(e){return!Ux(e)||!Array.isArray(e.launches)?[]:e.launches.map(Kx).filter(e=>e!==void 0)}function Jx(e,t){if(!Ux(t)||t.type!==`launch`)return e;let n=Kx(t.launch);return n?Hx.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 Yx(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 Xx={queued:`Queued`,placing:`Placing`,provisioning:`Starting`,running:`Running`,ended:`Ended`},Zx=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 Qx(e,t){let n=e.name?`@${e.name.replace(/^@+/,``)}`:`${e.repo}${e.branch?` (${e.branch})`:``}`;return{title:n,status:`${Xx[e.state]??e.state} · by ${Yx(e)}`,detail:e.state===`queued`&&e.waiting?`${e.waiting.reason} · ${Zx(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 $x(e,t){if(e.state!==`ready`&&e.state!==`refreshing`)return;let n=e.latest();return n?Jx(n,t):void 0}var eS=J(`<div id=agent-activity>`),tS=J(`<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`),nS=J(`<ul class=list>`),rS=J(`<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`),iS=J(`<p class="small muted">`),aS=J(`<p class="small muted">No app tokens yet.`),oS=J(`<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`),sS=J(`<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`),cS=J(`<p class="small muted">No live launches.`),lS=J(`<div class="small warn"data-launcher-revoked>`),uS=J(`<div class="small muted"data-launch-managed>`),dS=J(`<button type=button class="btn small danger">Stop`),fS=J(`<li class=row><div class=grow><div class=name></div><div class="small muted"></div><div class=small data-launch-reason>`),pS=J(`<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`),mS=J(`<p class=error role=alert>`),hS=J(`<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`),gS=J(`<label class=check><input type=checkbox><span>`),_S=J(`<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>`),vS=J(`<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>`),yS=J(`<p class="small warn"role=status data-acting-note>`),bS=J(`<ul class="list grants">`),xS=J(`<div class=stack><div class=row><p class="small muted grow">Each grant lets one holder (a session, a reserved role like @@orchestrator, or an app) act in some projects, for a while.</p><button type=button class="btn small primary">New grant`),SS=J(`<p class="small muted">No grants. Agents can still ask you (Decisions).`),CS=J(`<dt>Permissions`),wS=J(`<dd class=mono>`),TS=J(`<dt>Never`),ES=J(`<button type=button class="btn small">Edit`),DS=J(`<button type=button class="btn small danger">Revoke`),OS=J(`<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>`),kS=J(`<p class="field-error small"role=alert>`),AS=J(`<span class="field-desc muted small">`),jS=J(`<label class="text-field grow"><span class=field-title></span><input type=text>`),MS=J(`<label class=text-field><span class=field-title></span><span class="field-desc muted small"></span><textarea rows=2>`),NS=J(`<p class=error role=alert data-error=form>`),PS=J(`<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`),FS=J(`<ol class="list audit agent-audit">`),IS=J(`<p class="small muted">Loading…`),LS=J(`<button type=button class="btn small">Load older`),RS=J(`<div class=stack>`),zS=J(`<p class="small err">Could not load: `),BS=J(`<p class="small muted">No agent actions yet.`),VS=J(`<span>`),HS=J(`<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">`),US=50,WS=`/api/agent/grants`,GS=`/api/agent/app-tokens`,KS=`/api/agent/launches`,[qS,JS]=x(0);function YS(){let[e,t]=x(`grants`);return C(()=>{let e=ie().hash;e===`#agent-activity`?t(`activity`):e===`#grants`&&t(`grants`)}),(()=>{var r=tS(),i=r.firstChild.nextSibling,a=i.firstChild,o=a.nextSibling;return L(r,n($S,{}),i),L(r,n(XS,{}),i),L(r,n(ZS,{}),i),a.$$click=()=>t(`grants`),o.$$click=()=>t(`activity`),L(r,n(u,{get when(){return e()===`grants`},get children(){return n(eC,{})}}),null),L(r,n(u,{get when(){return e()===`activity`},get children(){var e=eS();return L(e,n(nC,{})),e}}),null),D(t=>{var n=e()===`grants`,r=e()===`activity`;return n!==t.e&&R(a,`aria-pressed`,t.e=n),r!==t.t&&R(o,`aria-pressed`,t.t=r),t},{e:void 0,t:void 0}),r})()}function XS(){let[e,{mutate:t,refetch:r}]=f(()=>B(GS).then(Hn)),[i,a]=x(!1),s=async e=>{if(await Se(`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 G(`${GS}/${V(e.id)}`,{method:`DELETE`}),t(t=>(t??[]).filter(t=>t.id!==e.id)),JS(e=>e+1),q(`App token revoked`)}catch(e){q(W(e),`err`),r()}};return(()=>{var r=rS(),c=r.firstChild.firstChild.nextSibling;return c.$$click=()=>a(!0),L(r,n(u,{get when(){return i()},get children(){return n(QS,{onClose:()=>a(!1),onCreated:e=>t(t=>[e,...(t??[]).filter(t=>t.id!==e.id)])})}}),null),L(r,n(u,{get when(){return e()},get fallback(){return(()=>{var t=iS();return L(t,(()=>{var t=H(()=>!!e.error);return()=>t()?`Could not load: ${W(e.error)}`:`Loading…`})()),t})()},get children(){return n(u,{get when(){return e().length},get fallback(){return aS()},get children(){var t=nS();return L(t,n(o,{get each(){return e()},children:e=>(()=>{var t=oS(),n=t.firstChild,r=n.firstChild,i=r.nextSibling;i.firstChild;var a=i.nextSibling,o=n.nextSibling;return L(r,()=>e.label||`Unnamed app`),L(i,()=>e.id,null),L(a,()=>e.scopes.join(`, `)||`No scopes`,null),L(a,(()=>{var t=H(()=>!!e.created);return()=>t()?` · created ${ze(e.created,I())}`:``})(),null),o.$$click=()=>void s(e),D(()=>R(t,`data-app-token`,e.id)),t})()})),t}})}}),null),r})()}function ZS(){let[e,{refetch:t,mutate:r}]=f(qS,()=>B(`${KS}?state=${Hx.join(`,`)}`).then(e=>qx(e)));j(Ol(t=>{let n=$x({state:e.state,latest:()=>e.latest},t);n&&r(n)}));let[i,a]=x(),s=async e=>{if(await Se(`Stop ${Qx(e,I()).title}? Its session is stopped and its workspace cleaned up by its policy.`,`Stop`,{danger:!0})){a(e.id);try{await G(`${KS}/${V(e.id)}`,{method:`DELETE`}),q(`Launch stopped`)}catch(e){q(W(e),`err`)}finally{a(void 0),t()}}};return(()=>{var r=sS(),a=r.firstChild.firstChild.nextSibling;return a.$$click=()=>void t(),L(r,n(u,{get when(){return e()},get fallback(){return(()=>{var t=iS();return L(t,(()=>{var t=H(()=>!!e.error);return()=>t()?`Could not load: ${W(e.error)}`:`Loading…`})()),t})()},get children(){return n(u,{get when(){return e().length},get fallback(){return cS()},get children(){var t=nS();return L(t,n(o,{get each(){return e()},children:e=>{let t=()=>Qx(e,I());return(()=>{var r=fS(),a=r.firstChild,o=a.firstChild,c=o.nextSibling,l=c.nextSibling;return L(o,()=>t().title),L(c,()=>t().status),L(l,()=>t().detail),L(a,n(u,{get when(){return t().flag},get children(){var e=lS();return L(e,()=>t().flag),e}}),null),L(a,n(u,{get when(){return t().managed},get children(){var e=uS();return L(e,()=>t().managed),e}}),null),L(r,n(u,{get when(){return t().stopLabel},get children(){var n=dS();return n.$$click=()=>void s(e),D(r=>{var a=t().stopLabel,o=i()===e.id;return a!==r.e&&R(n,`aria-label`,r.e=a),o!==r.t&&(n.disabled=r.t=o),r},{e:void 0,t:void 0}),n}}),null),D(()=>R(r,`data-launch`,e.id)),r})()}})),t}})}}),null),r})()}function QS(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=Un(t(),i());if(!r.ok)return p(r.error);h(!0),p(``);try{let t=await(await G(GS,{method:`POST`,json:r.body})).json(),n=Vn(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(W(e))}finally{h(!1)}},_=async(e,t)=>{try{await navigator.clipboard.writeText(e),q(`${t} copied`)}catch{q(`Could not copy ${t.toLowerCase()}`,`err`)}};return n(Re,{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=hS(),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),L(d,n(o,{each:Bn,children:e=>(()=>{var t=gS(),n=t.firstChild,r=n.nextSibling;return n.addEventListener(`change`,t=>a(t.currentTarget.checked?[...i(),e]:i().filter(t=>t!==e))),L(r,e),D(()=>n.checked=i().includes(e)),t})()}),null),L(s,n(u,{get when(){return f()},get children(){var e=mS();return L(e,f),e}}),p),Oe(_,`click`,e.onClose,!0),D(()=>h.disabled=m()),D(()=>l.value=t()),s})()},get children(){var t=pS(),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`),Oe(u,`click`,e.onClose,!0),D(()=>r.value=s()),D(()=>o.value=l()),t}})}})}function $S(){let[e,{mutate:t}]=f(()=>B(`/api/agent/acting`).then(Wr)),[r,i]=f(()=>ht(X())||void 0,()=>B(`/api/admin/agents/acting`).then(e=>e?.enabled!==!1)),[a,o]=x(!1),s=async e=>{let n=e.checked;o(!0);try{t(Wr(await(await G(`/api/agent/acting`,{method:`PUT`,json:{enabled:n}})).json())),q(n?`Agent actions are on for you`:`Agent actions are off for you`)}catch(t){e.checked=!n,q(W(t),`err`)}finally{o(!1)}},c=async e=>{let n=e.checked;if(!n&&!await Se(`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 G(`/api/admin/agents/acting`,{method:`PUT`,json:{enabled:n}})).json();i.mutate(e?.enabled!==!1),q(n?`Agent actions are on for this hub`:`Agent actions are off for this hub`);let r=await B(`/api/agent/acting`).catch(()=>void 0);r&&t(Wr(r))}catch(t){e.checked=!n,q(W(t),`err`)}finally{o(!1)}}};return n(u,{get when(){return e()},get fallback(){return(()=>{var t=iS();return L(t,(()=>{var t=H(()=>!!e.error);return()=>t()?`Could not load: ${W(e.error)}`:`Loading…`})()),t})()},children:e=>[(()=>{var t=vS(),i=t.firstChild.firstChild.firstChild.nextSibling;return i.addEventListener(`change`,e=>void s(e.currentTarget)),L(t,n(u,{get when(){return H(()=>!!ht(X()))()&&r()!==void 0},get children(){var e=_S(),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=yS();return L(t,()=>e().note),t}})]})}function eC(){let[e,{refetch:t,mutate:r}]=f(()=>B(WS).then(Xn)),[i,a]=x(),[s,c]=x(Date.now()),l=setInterval(()=>c(Date.now()),1e3);j(()=>clearInterval(l));let d=async e=>{if(await Se(`Revoke the grant of ${e.holder}? It stops at once.`,`Revoke`,{danger:!0}))try{let n=Yn((await(await G(`${WS}/${V(e.id)}`,{method:`DELETE`})).json())?.grant);n?r(e=>(e??[]).map(e=>e.id===n.id?n:e)):t(),q(`Grant of ${e.holder} revoked`)}catch(e){q(W(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=xS(),r=t.firstChild.firstChild.nextSibling;return r.$$click=()=>a(`new`),L(t,n(u,{get when(){return i()},keyed:!0,children:e=>n(tC,{grant:e===`new`?void 0:e,onSaved:p,onClose:()=>a(void 0)})}),null),L(t,n(u,{get when(){return e()},get fallback(){return(()=>{var t=iS();return L(t,(()=>{var t=H(()=>!!e.error);return()=>t()?`Could not load: ${W(e.error)}`:`Loading…`})()),t})()},get children(){return n(u,{get when(){return e().length},get fallback(){return SS()},get children(){var t=bS();return L(t,n(o,{get each(){return e()},children:e=>{let t=()=>er(e,s());return(()=>{var r=OS(),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 L(i,()=>t().holder,o),L(o,()=>t().stateLabel),L(c,()=>t().projects),L(l,()=>t().verbs),L(s,n(u,{get when(){return t().permit},get children(){return[CS(),(()=>{var e=wS();return L(e,()=>t().permit),e})()]}}),f),L(s,n(u,{get when(){return t().never},get children(){return[TS(),(()=>{var e=wS();return L(e,()=>t().never),e})()]}}),f),L(p,()=>t().limits),L(m,()=>t().expiry),L(r,n(u,{get when(){return t().editable},get children(){return[(()=>{var t=ES();return t.$$click=()=>a(e),D(()=>R(t,`aria-label`,`Edit grant of ${e.holder}`)),t})(),(()=>{var t=DS();return t.$$click=()=>void d(e),D(()=>R(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&&K(r,n.e=i),a!==n.t&&R(r,`data-grant`,n.t=a),s!==n.a&&K(o,n.a=s),n},{e:void 0,t:void 0,a:void 0}),r})()}})),t}})}}),null),t})()}function tC(t){let[r,i]=x(tr(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=ar(r());if(!i.ok)s(i.errors);else{s({}),f(!0);try{let e=t.grant?`${WS}/${V(t.grant.id)}`:WS,n=Yn((await(await G(e,{method:t.grant?`PUT`:`POST`,json:i.body})).json())?.grant);q(t.grant?`Grant updated`:`Grant created`),n?t.onSaved(n):t.onClose()}catch(t){let n=W(t),r=t instanceof e&&(t.status===400||t.status===404)?or(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=kS();return L(t,()=>a()[e.field]),D(()=>R(t,`data-error`,e.field)),t}}),g=e=>(()=>{var t=jS(),i=t.firstChild,a=i.nextSibling;return L(i,()=>e.label),L(t,n(u,{get when(){return e.hint},get children(){var t=AS();return L(t,()=>e.hint),t}}),a),a.$$input=t=>p(e.field,t.currentTarget.value),L(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&&R(a,`aria-label`,t.e=n),r!==t.t&&R(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=MS(),i=t.firstChild,a=i.nextSibling,o=a.nextSibling;return L(i,()=>e.label),L(a,()=>e.hint),o.$$input=t=>p(e.field,t.currentTarget.value),L(t,n(h,{get field(){return e.field}}),null),D(t=>{var n=e.label,r=e.placeholder??``;return n!==t.e&&R(o,`aria-label`,t.e=n),r!==t.t&&R(o,`placeholder`,t.t=r),t},{e:void 0,t:void 0}),D(()=>o.value=r()[e.field]),t})();return n(Re,{open:!0,get title(){return H(()=>!!t.grant)()?`Edit grant of ${t.grant.holder}`:`New grant`},get onClose(){return t.onClose},wide:!0,class:`grant-dialog`,get children(){var e=PS(),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)),L(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),L(e,n(_,{field:`projects`,label:`Projects`,hint:`Absolute project directories, one per line (subdirectories and worktrees included).`,placeholder:`/home/you/projects/api`}),i),L(i,n(o,{each:In,children:e=>(()=>{var t=gS(),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))),R(n,`aria-label`,e),L(i,e),D(()=>n.checked=r().allow.includes(e)),t})()}),null),L(e,n(h,{field:`allow`}),a),L(e,n(_,{field:`permit`,label:`Permissions it may approve`,hint:`Patterns action[:glob], one per line (e.g. shell:bun test *).`}),a),L(e,n(_,{field:`never`,label:`Never`,hint:`Patterns it may never approve, one per line; never wins.`,placeholder:`shell:rm *`}),a),L(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),L(a,n(g,{field:`maxActionsPerHour`,label:`Actions per hour`,hint:`1–1000`}),null),l.addEventListener(`change`,e=>p(`allowAlways`,e.currentTarget.checked)),L(e,n(h,{field:`allowAlways`}),f),L(e,n(u,{get when(){return c()},get children(){var e=NS();return L(e,c),e}}),f),L(v,()=>t.grant?`Save`:`Create grant`),Oe(y,`click`,t.onClose,!0),D(()=>v.disabled=d()),D(()=>l.checked=r().allowAlways),e}})}function nC(){let[e,t]=x([]),[r,i]=x(),[a,s]=x(`loading`),[c,l]=x(``),d=async e=>{s(`loading`);try{let n=cr(await B(`/api/agent/audit?limit=${US}${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(W(e)),s(`failed`)}};d();let[p]=f(async()=>{try{let{decisions:e}=await B(`/api/decisions`);return(e??[]).map(qt).filter(e=>!!e)}catch{return[]}}),m=()=>{let e=new Map((p()??[]).map(e=>[e.id,e]));for(let t of ol().values())e.set(t.id,t);return[...e.values()]},h=()=>{let t=e()[0]?.seq??0;return[...bl().filter(e=>e.seq>t),...e()]};return(()=>{var e=RS();return L(e,n(u,{get when(){return a()!==`failed`},get fallback(){return(()=>{var e=zS();return e.firstChild,L(e,c,null),e})()},get children(){return[n(u,{get when(){return h().length||a()!==`ready`},get fallback(){return BS()},get children(){var e=FS();return L(e,n(o,{get each(){return h()},children:e=>{let t=()=>Ar(e,br(e,m()),Fl);return(()=>{var r=HS(),i=r.firstChild,a=i.firstChild,o=a.firstChild,s=o.nextSibling.nextSibling,c=a.nextSibling,l=c.firstChild,d=i.nextSibling;return L(o,()=>t().who),L(s,()=>t().what),L(l,()=>t().result),L(c,n(u,{get when(){return t().grant},get children(){return[` · `,(()=>{var e=VS();return L(e,()=>t().grant),D(()=>R(e,`title`,t().grantTitle)),e})()]}}),null),L(c,(()=>{var e=H(()=>!!t().reason);return()=>e()?` · ${t().reason}`:``})(),null),L(d,()=>ze(e.at,I())),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&&R(r,`data-seq`,n.e=i),a!==n.t&&R(o,`title`,n.t=a),c!==n.a&&R(s,`title`,n.a=c),u!==n.o&&K(l,n.o=u),f!==n.i&&R(d,`datetime`,n.i=f),p!==n.n&&R(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 IS()}}),n(u,{get when(){return H(()=>a()===`ready`)()&&r()!==void 0},get children(){var e=LS();return e.$$click=()=>void d(r()),e}})]}})),e})()}F([`click`,`input`]);var rC=J(`<fieldset class=stack id=concierge-watchlist><legend class=field-title>Watchlist`),iC=J(`<p class="small muted">`),aC=J(`<span class="field-desc muted small"data-watchlist-count>Watching <!> session<!> now.`),oC=J(`<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)`),sC=J(`<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)">`),cC=J(`<label class=check><input type=checkbox><span>Pinned sessions and workspaces<span class=muted> (<!> now)`),lC=J(`<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`),uC=J(`<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`),dC=J(`<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">`),fC=J(`<datalist id=concierge-sessions>`),pC=J(`<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">`),mC=J(`<li class="small muted">No sessions added.`),hC=J(`<li class=row><span class="small grow"></span><button type=button class="btn small">Remove`),gC=J(`<li class="small muted">Nothing muted.`),_C=J(`<li class=row><span class="small grow"></span><button type=button class="btn small">Unmute`),vC=J(`<option>`),yC=`/api/agent/concierge/watchlist`,bC=e=>Fl(e),xC=(e,t)=>e.filter(e=>e.reasons.includes(t)).length,SC=e=>[...new Set(e.split(`
|
|
17
|
+
`).map(e=>e.trim()).filter(Boolean))];function CC(){let[t,{refetch:r,mutate:i}]=f(()=>B(yC)),[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}),q(a),!0}catch(t){return q(t instanceof e&&t.status===409?`The watchlist changed elsewhere: reloaded`:`Could not save the watchlist: ${W(t)}`,`err`),!1}finally{s(!1),r()}},h=e=>m(()=>G(yC,{method:`PUT`,json:{...e,expectedRevision:t().config.revision}}),`Watchlist saved`),g=(e,t)=>m(()=>G(`${yC}/${e}`,{method:`POST`,json:{session:t}}),e===`watch`?`Watching ${bC(t)}`:e===`mute`?`Muted ${bC(t)} for the Concierge`:`Watchlist saved`);return(()=>{var e=rC();return e.firstChild,L(e,n(u,{get when(){return t()},get fallback(){return(()=>{var e=iC();return L(e,(()=>{var e=H(()=>!!t.error);return()=>e()?`Could not load the watchlist: ${W(t.error)}`:`Loading…`})()),e})()},children:e=>{let t=()=>e().config;return[(()=>{var t=aC(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,L(t,()=>e().entries.length,n),L(t,()=>e().truncated?`+`:``,n),L(t,()=>e().entries.length===1?``:`s`,r),t})(),(()=>{var n=oC(),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})),L(i,()=>t().activeWithinHours,o),L(s,()=>xC(e().entries,`active`),c),D(()=>r.disabled=a()),D(()=>r.checked=t().autoActive),n})(),(()=>{var e=sC(),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=cC(),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})),L(i,()=>xC(e().entries,`pinned`)+xC(e().entries,`pinned_project`),o),D(()=>r.disabled=a()),D(()=>r.checked=t().usePins),n})(),(()=>{var e=lC(),r=e.firstChild.nextSibling,i=r.nextSibling,s=i.firstChild,u=s.nextSibling;return L(r,n(o,{get each(){return t().sessions},get fallback(){return mC()},children:e=>(()=>{var t=hC(),n=t.firstChild,r=n.nextSibling;return R(t,`data-watch-session`,e),R(n,`title`,e),R(n,`data-session-id`,e),L(n,()=>bC(e)),r.$$click=()=>void g(`unwatch`,e),D(t=>{var n=a(),i=`Stop watching ${bC(e)}`;return n!==t.e&&(r.disabled=t.e=n),i!==t.t&&R(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=uC(),r=e.firstChild.nextSibling,i=r.nextSibling,s=i.firstChild,c=s.nextSibling;return L(r,n(o,{get each(){return t().muted},get fallback(){return gC()},children:e=>(()=>{var t=_C(),n=t.firstChild,r=n.nextSibling;return R(t,`data-muted-session`,e),R(n,`title`,e),R(n,`data-session-id`,e),L(n,()=>bC(e)),r.$$click=()=>void g(`unmute`,e),D(t=>{var n=a(),i=`Unmute ${bC(e)}`;return n!==t.e&&(r.disabled=t.e=n),i!==t.t&&R(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=dC(),n=e.firstChild.nextSibling;return n.addEventListener(`change`,e=>void h({projects:SC(e.currentTarget.value)})),D(()=>n.disabled=a()),D(()=>n.value=t().projects.join(`
|
|
18
|
+
`)),e})(),(()=>{var e=fC();return L(e,n(o,{get each(){return kl().filter(e=>!e.hidden).slice(0,200)},children:e=>(()=>{var t=vC();return D(()=>R(t,`label`,e.title)),D(()=>t.value=e.id),t})()})),e})(),(()=>{var e=pC(),n=e.firstChild.nextSibling;return n.addEventListener(`change`,e=>void h({mutedProjects:SC(e.currentTarget.value)})),D(()=>n.disabled=a()),D(()=>n.value=t().mutedProjects.join(`
|
|
19
|
+
`)),e})()]}}),null),e})()}F([`input`,`click`]);var wC=J(`<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.`),TC=J(`<button type=button class="btn small">Retry`),EC=J(`<p class="small muted"data-concierge-load>`),DC=J(`<button type=button class="btn small">Restart`),OC=J(`<button type=button class="btn small danger">Turn off`),kC=J(`<button type=button class="btn small primary">Turn on`),AC=J(`<p class="small muted"data-concierge-problem>`),jC=J(`<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).`),MC=J(`<div class="row concierge-notice err"role=alert data-concierge-suspended><span class=grow>Stopped: </span><button type=button class="btn small">Restart`),NC=J(`<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`),PC=J(`<li class="small muted">No machines yet.`),FC=J(`<li class=row><label class="check grow"><input type=radio name=concierge-machine><span><span class="small muted"> · `),IC=J(`<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…`),LC=J(`<button type=button class="btn small">Renew`),RC=J(`<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`),zC=J(`<optgroup label=Projects>`),BC=J(`<optgroup label="Workspace roots">`),VC=J(`<input class=mono aria-describedby=concierge-directory-hint>`),HC=J(`<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>`),UC=J(`<option>`),WC=J(`<input class=mono aria-label="Other model (provider/model)"aria-describedby=concierge-model-hint placeholder=provider/model>`),GC=J(`<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>`),KC=J(`<optgroup>`),qC=J(`<p class="field-error small"role=alert>`),JC=J(`<label class=text-field><span class=field-title></span><span class="field-desc muted small"></span><textarea rows=2>`),YC=J(`<p class="small warn"role=note data-shell-warning>`),XC=J(`<p class=error role=alert data-error=form>`),ZC=J(`<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`),QC=J(`<label class=check><input type=checkbox><span class="mono small">`),$C=J(`<label class=check><input type=checkbox><span>`),ew=J(`<button type=button class="btn small">Turn off quiet hours`),tw=J(`<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`),nw=J(`<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`),rw=J(`<li class="small muted">No digests.`),iw=J(`<li class=row><input type=time><span class=digest-days></span><button type=button class="btn small danger">Remove`),aw=J(`<label class="check small"><input type=checkbox><span>`),ow=`/api/agent/concierge`;async function sw(){let e=fs(await B(ow));if(!e)throw Error(`The hub answered an unexpected Concierge view`);return e}async function cw(e){if(!e)return;let{grants:t}=await B(`/api/agent/grants`);return t?.find(t=>t.id===e)}function lw(){let[e,{refetch:t,mutate:r}]=f(sw),i=()=>e.error?void 0:e(),[a,{refetch:s}]=f(()=>i()?.settings.grantID,cw),[c,l]=x(!1),[d,p]=x(!1),[m,_]=x({}),[v,y]=x(),b=()=>ll()??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(()=>ll()?.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}),q(e)}catch(e){q(W(e),`err`)}finally{l(!1),t(),s()}},E=(e,t=`Saved`,n={})=>{let r=i().settings;return T(t,()=>G(`${ow}/settings`,{method:`PUT`,json:{...Rs(r,e),...n}}))},ee=()=>T(`Concierge on`,()=>G(`${ow}/enable`,{method:`POST`,json:{expectedRevision:i().settings.revision,timeZone:g()}})),te=async()=>{if(await Se(`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`,()=>G(`${ow}/disable`,{method:`POST`,json:{expectedRevision:i().settings.revision}}))},O=()=>T(`Restarting the Concierge`,()=>G(`${ow}/restart`,{method:`POST`,json:{}}));return(()=>{var l=wC();return l.firstChild,L(l,n(u,{get when(){return i()},get fallback(){return(()=>{var r=EC();return L(r,(()=>{var t=H(()=>!!e.error);return()=>t()?`Could not load: ${W(e.error)} `:`Loading…`})(),null),L(r,n(u,{get when(){return e.error},get children(){var e=TC();return e.$$click=()=>(S=0,void t()),e}}),null),r})()},children:e=>{let l=()=>e().settings,f=()=>Cs(e().machines),h=()=>Ts(l(),e().machines),x=()=>e().machines.find(e=>e.id===l().machineID);return(()=>{var S=NC(),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,L(w,()=>Ss(b(),e().machines,I())),L(C,n(u,{get when(){return l().enabled},get children(){return[(()=>{var e=DC();return e.$$click=()=>void O(),D(()=>e.disabled=c()),e})(),(()=>{var e=OC();return e.$$click=()=>void te(),D(()=>e.disabled=c()),e})()]}}),null),L(C,n(u,{get when(){return!l().enabled},get children(){var e=kC();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&&R(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e}}),null),L(S,n(u,{get when(){return H(()=>!l().enabled)()&&h()},get children(){var e=AC();return L(e,h),e}}),T),L(S,n(u,{get when(){return!l().enabled},get children(){return jC()}}),T),L(S,n(u,{get when(){return H(()=>!!(l().enabled&&b()?.state===`failed`))()&&b()?.reason},get children(){var e=MC(),t=e.firstChild;t.firstChild;var n=t.nextSibling;return L(t,()=>b().reason,null),n.$$click=()=>void O(),D(()=>n.disabled=c()),e}}),T),L(ne,n(o,{get each(){return f()},get fallback(){return PC()},children:e=>(()=>{var t=FC(),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(Ws(l(),e,Y.machines,t))}),L(r,()=>e.name,i),L(i,()=>e.note,null),D(r=>{var i=e.id,a=e.eligible?`yes`:`no`,o=!e.selectable||c();return i!==r.e&&R(t,`data-concierge-machine`,r.e=i),a!==r.t&&R(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})()})),L(S,n(uw,{get settings(){return l()},get machine(){return x()},get busy(){return c()},save:E}),re),L(S,n(dw,{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=Gs(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}}:{}})}),L(S,n(pw,{get settings(){return l()},get busy(){return c()},save:E}),k),L(S,n(mw,{get settings(){return l()},get busy(){return c()},save:E}),k),L(S,n(CC,{}),k),L(k,n(u,{get when(){return l().grant},get fallback(){return(()=>{var e=IC(),t=e.firstChild.nextSibling,n=t.nextSibling;return t.$$click=()=>void E({...l(),grant:Es([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=RC(),r=t.firstChild,i=r.firstChild,o=i.nextSibling,s=o.nextSibling,f=s.firstChild,m=r.nextSibling,h=m.nextSibling;return L(i,()=>Fs(e()).head),L(o,()=>Fs(e()).permissions),L(s,()=>e().maxActionsPerHour,f),L(s,(()=>{var e=H(()=>!!a());return()=>e()?` · ${a().state===`active`?Is(a().expiresAt,I()):a().state}`:l().enabled?``:` · created when you turn it on`})(),null),m.$$click=()=>p(!0),L(t,n(u,{get when(){return l().enabled},get children(){var t=LC();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),L(k,n(u,{get when(){return d()},get children(){return n(fw,{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),q(`Grant saved`),t(),s()}})}}),null),D(()=>R(S,`data-concierge-state`,b()?.state??`disabled`)),D(()=>ae.value=l().timeZone),S})()}}),null),l})()}function uw(e){let t=()=>Vs(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()?zs:Us(e.settings.directory,r()),c=t=>{t!==e.settings.directory&&e.save({...e.settings,directory:t})},l=()=>t().roots,d=()=>Hs(e.machine,t());return(()=>{var r=HC(),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)}),L(f,n(u,{get when(){return t().projects.length},get children(){var e=zC();return L(e,n(o,{get each(){return t().projects},children:e=>(()=>{var t=UC();return t.value=e,L(t,e),t})()})),e}}),p),L(f,n(u,{get when(){return l().length},get children(){var e=BC();return L(e,n(o,{get each(){return l()},children:e=>(()=>{var t=UC();return t.value=e,L(t,e),t})()})),e}}),p),p.value=zs,L(m,d),L(r,n(u,{get when(){return s()===zs},get children(){var t=VC();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&&R(t,`aria-label`,n.e=r),i!==n.t&&R(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 dw(e){let t=()=>Js(e.machine),[r,{refetch:i}]=f(()=>e.machine&&!t()?e.machine.id:void 0,async e=>({id:e,options:qs(await B(`${ow}/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()?zs:p()??Us(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: ${W(r.error)}`:!a()||s().length?``:`Its OpenCode reports no models: type one, or keep the machine default.`;return(()=>{var t=GC(),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)}),L(l,n(u,{get when(){return p()},children:e=>(()=>{var t=UC();return L(t,e),D(()=>t.value=e()),t})()}),f),L(l,n(o,{get each(){return c()},children:e=>(()=>{var t=KC();return R(t,`label`,e),L(t,n(o,{get each(){return s().filter(t=>t.provider===e)},children:e=>(()=>{var t=UC();return L(t,()=>e.label),D(()=>t.value=e.value),t})()})),t})()}),f),f.value=zs,L(h,_,null),L(h,n(u,{get when(){return r.error},get children(){return[` `,(()=>{var e=TC();return e.$$click=()=>void i(),e})()]}}),null),L(t,n(u,{get when(){return m()===zs},get children(){var t=WC();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&&R(l,`aria-busy`,t.t=i),t},{e:void 0,t:void 0}),D(()=>l.value=m()),t})()}function fw(t){let[r,i]=x(Os(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),_=()=>Ps(g(),t.directory,r().projects),v=async n=>{n.preventDefault(),l(``);let i=js(r());if(!i.ok)return s(i.errors);s({}),f(!0);try{let e=await(await G(`${ow}/settings`,{method:`PUT`,json:{grant:i.body,expectedRevision:t.revision}})).json();t.onSaved(e.settings)}catch(t){let n=W(t),r=t instanceof e&&t.status===400?Ns(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=qC();return L(t,()=>a()[e.field]),D(()=>R(t,`data-error`,e.field)),t}}),b=e=>(()=>{var t=JC(),i=t.firstChild,a=i.nextSibling,o=a.nextSibling;return L(i,()=>e.label),L(a,()=>e.hint),o.$$input=t=>h(e.field,t.currentTarget.value),L(t,n(y,{get field(){return e.field}}),null),D(t=>{var n=e.label,r=e.placeholder??``;return n!==t.e&&R(o,`aria-label`,t.e=n),r!==t.t&&R(o,`placeholder`,t.t=r),t},{e:void 0,t:void 0}),D(()=>o.value=r()[e.field]),t})();return(()=>{var e=ZC(),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)),L(i,n(o,{get each(){return _()},children:e=>(()=>{var t=QC(),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))),R(n,`aria-label`,e),L(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(``)),L(i,n(y,{field:`projects`}),null),L(f,n(o,{each:Ds,children:e=>(()=>{var t=$C(),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))),R(n,`aria-label`,e),L(i,e),D(()=>n.checked=r().allow.includes(e)),t})()}),null),L(e,n(y,{field:`allow`}),g),L(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),L(e,n(u,{get when(){return Ms(r().permit)},get children(){var e=YC();return L(e,()=>Ms(r().permit)),e}}),g),L(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),L(x,n(y,{field:`expires`}),null),w.$$input=e=>h(`maxActionsPerHour`,e.currentTarget.value),L(C,n(y,{field:`maxActionsPerHour`}),null),L(e,n(u,{get when(){return c()},get children(){var e=XC();return L(e,c),e}}),T),Oe(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 pw(e){let[t,r]=x(e.settings.quietHours?.start??``),[i,a]=x(e.settings.quietHours?.end??``);return(()=>{var o=tw(),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 L(s,(()=>{var t=H(()=>!!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`),L(h,()=>e.settings.quietHours?`Save quiet hours`:`Turn on quiet hours`),L(l,n(u,{get when(){return e.settings.quietHours},get children(){var t=ew();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 mw(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=nw(),s=a.firstChild.nextSibling,c=s.firstChild.nextSibling;c.nextSibling;var l=s.nextSibling,u=l.nextSibling.firstChild;return L(s,()=>e.settings.timeZone,c),L(l,n(o,{get each(){return t()},get fallback(){return rw()},children:(a,s)=>(()=>{var c=iw(),l=c.firstChild,u=l.nextSibling,d=u.nextSibling;return l.addEventListener(`change`,e=>e.currentTarget.value&&i(s(),{at:e.currentTarget.value})),L(u,n(o,{each:hc,children:(t,n)=>(()=>{var r=aw(),o=r.firstChild,c=o.nextSibling;return o.addEventListener(`change`,e=>{let t=gc(a.days,n(),e.currentTarget.checked);JSON.stringify(t)===JSON.stringify(a.days)?e.currentTarget.checked=!0:i(s(),{days:t})}),L(c,t),D(n=>{var r=`Digest ${s()+1} on ${t}`,i=e.busy;return r!==n.e&&R(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&&R(c,`data-digest`,t.e=n),r!==t.t&&R(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&&R(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})()}F([`click`,`input`]);function hw(e,t){let n=Math.max(0,Math.ceil((e-t)/1e3));return`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}`}function gw(e,t){return t.find(t=>!e.has(t.id))}function _w(e,t,n){let r=t?Date.parse(t):NaN;return Number.isFinite(r)?n+Math.max(0,e-r-1e3):e}var vw={L:0,M:1,Q:2,H:3},yw={L:1,M:0,Q:3,H:2},bw=[[-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]],xw=[[-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]],Sw=(e,t)=>!!(e>>>t&1);function Cw(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 ww(e,t){let n=vw[t];return Math.floor(Cw(e)/8)-bw[n][e]*xw[n][e]}function Tw(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 Ew(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]=Tw(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=Tw(n,2)}return t}function Dw(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]^=Tw(t,e))}return n}function Ow(e,t,n){let r=vw[n],i=xw[r][t],a=bw[r][t],o=Math.floor(Cw(t)/8),s=i-o%i,c=Math.floor(o/i),l=Ew(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=Dw(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 kw(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=ww(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 Aw=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=yw[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,Sw(r,e));this.set(8,7,Sw(r,6)),this.set(8,8,Sw(r,7)),this.set(7,8,Sw(r,8));for(let e=9;e<15;e++)this.set(14-e,8,Sw(r,e));for(let e=0;e<8;e++)this.set(i-1-e,8,Sw(r,e));for(let e=8;e<15;e++)this.set(8,i-15+e,Sw(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,Sw(t,e)),this.set(r,n,Sw(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]=Sw(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 jw(e,t={}){let n=t.ecc??`M`,r=new TextEncoder().encode(e),i=1;for(;4+(i<=9?8:16)+r.length*8>ww(i,n)*8;)if(++i>40)throw Error(`Text too long for a QR code`);let a=new Aw(i,n);a.codewords(Ow(kw(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 Mw(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 Nw=.8,Pw=1.8,Fw=.05,Iw=`hub.fontScale`,Lw=e=>Math.min(Pw,Math.max(Nw,e)),Rw=(e,t)=>Number((Math.round(e/t)*t).toFixed(2));function zw(e){return Number.isFinite(e)?Rw(Lw(e),Fw):1}function Bw(e){return e?zw(Number(e)):1}function Vw(e,t,n){return zw(!(t>0)||!(n>0)?e:n/t*e)}function Hw(e,t){let n=Lw((Number.isFinite(e)?e:1)*Math.exp(-t*.01));return Number(n.toFixed(3))}var Uw=e=>`${Math.round(e*100)}%`;function Ww(e){try{return Bw(e.getItem(Iw))}catch{return 1}}function Gw(e,t){let n=zw(t);try{n===1?e.removeItem(Iw):e.setItem(Iw,String(n))}catch{}return n}var Kw=()=>typeof localStorage>`u`?void 0:localStorage,[qw,Jw]=x(Kw()?Ww(Kw()):1),Yw=qw;function Xw(e){document.documentElement.style.setProperty(`--font-scale`,String(e))}var Zw;function Qw(e,t={}){let n=t.settle===!1?e:zw(e);Jw(n),Xw(n),clearTimeout(Zw);let r=()=>{let e=Kw();if(!e)return;let t=Gw(e,n);t!==qw()&&(Jw(t),Xw(t))};t.settle===!1?Zw=setTimeout(r,250):r()}var $w=`.scroller, .home-scroll`,eT=e=>e instanceof Element&&e.closest($w)!==null;function tT(e=document){Xw(qw());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`&&eT(e.target)&&(t.set(e.pointerId,{x:e.clientX,y:e.clientY}),t.size===2&&(n={scale:qw(),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=Vw(n.scale,n.distance,r());e!==qw()&&Qw(e,{settle:!1})}},o=e=>{t.delete(e.pointerId)&&t.size<2&&n&&(n=void 0,Qw(qw()))},s=e=>{e.touches.length>=2&&eT(e.target)&&e.preventDefault()},c=e=>{e.ctrlKey&&eT(e.target)&&(e.preventDefault(),Qw(Hw(qw(),e.deltaMode===1?e.deltaY*16:e.deltaY),{settle:!1}))},l,u=e=>{eT(e.target)&&(e.preventDefault(),e.type===`gesturestart`?l=qw():e.type===`gesturechange`&&l!==void 0&&e.scale?Qw(Vw(l,1,e.scale),{settle:!1}):e.type===`gestureend`&&(l=void 0,Qw(qw())))},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 nT=[`light`,`system`,`dark`],rT=`hub.theme`;function iT(e){return e===`light`||e===`dark`||e===`system`?e:`system`}function aT(e){return e===`system`?void 0:e}function oT(){try{return iT(localStorage.getItem(rT))}catch{return`system`}}var[sT,cT]=x(oT());function lT(e){let t=aT(e);t?document.documentElement.dataset.theme=t:delete document.documentElement.dataset.theme;try{e===`system`?localStorage.removeItem(rT):localStorage.setItem(rT,e)}catch{}cT(e)}var uT=J(`<h3 class=section-title>`),dT=J(`<section class=settings-section>`),fT=J(`<div class=settings-search role=search><input type=search placeholder="Search settings"aria-label="Search settings">`),pT=J(`<nav class=settings-nav aria-label="Settings sections">`),mT=J(`<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`),hT=J(`<a>`),gT=J(`<ul class=settings-results aria-label="Search results">`),_T=J(`<p class="muted settings-empty">No settings match.`),vT=J(`<li><a><span class=name></span><span class="small muted"> · `),yT=J(`<ul class=settings-list aria-label="Settings sections">`),bT=J(`<li><a><span class=grow><span class=name></span><span class="small muted">`),xT=J(`<div class=settings-page><p class=muted>No such settings section.</p><a class="btn small"href=/settings>All settings`),ST=J(`<div class=settings-page><h2 class=settings-page-title>`),CT=J(`<span class=badge-pill>`),wT=J(`<div class="small muted">`),TT=J(`<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`),ET=J(`<h3>Notify me when`),DT=J(`<p class="small notify-summary"data-notify-summary>`),OT=J(`<p class="small warn">These apply once this device is subscribed.`),kT=J(`<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.`),AT=J(`<h4>When`),jT=J(`<ul class=switches><li id=quiet-hours><label class=switch><span>Quiet hours</span><input type=checkbox>`),MT=J(`<p class="small muted"> muted (⋯ menu of a session → Unmute notifications).`),NT=J(`<p class="small muted">Checking this device…`),PT=J(`<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>`),FT=J(`<button type=button class="btn small primary">Enable notifications on this device`),IT=J(`<button type=button class="btn small">Turn off on this device`),LT=J(`<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`),RT=J(`<div class=row-actions>`),zT=J(`<option>`),BT=J(`<p data-test-result>`),VT=J(`<details class=notify-group><summary><h4></h4><span class="small muted notify-group-summary"data-group-summary></span></summary><ul class=switches>`),HT=J(`<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.`),UT=J(`<li><label class=switch><span class=notify-kind><span></span><span class="small muted"></span></span><input type=checkbox>`),WT=J(`<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.`),GT=J(`<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`),KT=J(`<p class="small muted">On this device. Pinch the conversation or the session list to change it too (a trackpad pinch works on desktop).`),qT=J(`<button type=button role=radio class=theme-choice><span>`),JT=J(`<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.`),YT=J(`<button type=button class=chip role=radio>`),XT=J(`<h3>Waiting for approval`),ZT=J(`<ul class=list>`),QT=J(`<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`),$T=J(`<p class="small muted">None. In OpenCode run /hub → Connect to a hub….`),eE=J(`<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`),tE=J(`<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`),nE=J(`<p class="small muted">`),rE=J(`<span class=muted> · this device`),iE=J(`<li><div class=grow><div class=name></div><div class="small muted">last seen </div></div><button type=button class="btn small danger">`),aE=J(`<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>`),oE=J(`<p class="small muted">Expires in <span class=add-app-countdown></span> · single use`),sE=J(`<div class=row><code class="add-app-link grow"></code><button type=button class="btn small">Copy</button><a class="btn small">Open`),cE=J(`<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.`),lE=J(`<div class=add-app-expired><p class="small warn">This code expired.</p><button type=button class="btn small primary">New code`),uE=J(`<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`),dE=J(`<p class="small muted">How your <a href=/teams>teams</a> work with the rest of your sessions.`),fE=J(`<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>`),pE=J(`<div class=chips role=group aria-label="Admin sections">`),mE=J(`<p class=error role=alert>`),hE=J(`<div id=admin-machines>`),gE=J(`<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=…).`),_E=J(`<div id=admin-audit>`),vE=J(`<span class=count>`),yE=J(`<button type=button class=chip>`),bE=J(`<p class=muted>No machines are waiting for approval.`),xE=J(`<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">`),SE=J(`<p class=muted>`),CE=J(`<li class=muted>No users match.`),wE=J(`<span class=badge-pill>Admin`),TE=J(`<span class="badge-pill off">Disabled`),EE=J(`<span class=badge-pill>You`),DE=J(`<li><div class=grow><div class=name></div><div class="small muted"> · <!> · seen `),OE=J(`<button type=button>`),kE=J(`<p class=muted>No machines are connected to this hub yet.`),AE=J(`<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`),jE=J(`<ol class="list audit">`),ME=J(`<p class=muted>Nothing recorded yet.`),NE=J(`<li><div class=grow><div class=name></div><div class="small muted"></div></div><time class="small muted">`);function PE(e){return(()=>{var t=dT();return N(t,ce({get id(){return e.id}},()=>e.title?{"aria-labelledby":`h-${e.id}`}:{"aria-label":e.label??e.id}),!1,!0),L(t,n(u,{get when(){return e.title},get children(){var t=uT();return L(t,()=>e.title),D(()=>R(t,`id`,`h-${e.id}`)),t}}),null),L(t,()=>e.children,null),t})()}var FE=2400,IE=3e3;function LE(e){if(!e)return;let t=Date.now()+IE,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`),FE)}};requestAnimationFrame(n)}var RE=e=>Ce(!0).find(t=>t.id===e)?.label,zE=!1;function BE(){let e=()=>ht(X()),r=()=>{let e=qb();return e.name===`settings`?e.section:void 0},i=()=>E(r(),{admin:e(),phone:Z()}),[s,c]=x(``),l=()=>Te(s(),t(e()));C(h(ie,e=>LE(decodeURIComponent(e.hash.slice(1)))));let d=()=>{zE?(zE=!1,history.back()):a(`/settings`)},f=()=>(()=>{var e=fT(),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=mT(),r=t.firstChild,a=r.firstChild,p=r.nextSibling,m=p.firstChild,h=m.firstChild,g=h.firstChild.nextSibling;return g.nextSibling,L(r,n(u,{get when(){return Z()},get children(){return n(u,{get when(){return i()!==`list`},get fallback(){return n(z,{icon:`menu`,label:`Open sidebar`,onClick:Df})},get children(){return n(z,{icon:`back`,label:`All settings`,onClick:d})}})}}),a),L(a,(()=>{var e=H(()=>!!(Z()&&i()!==`list`));return()=>e()?RE(i())??`Settings`:`Settings`})()),L(p,n(u,{get when(){return!Z()},get children(){var t=pT();return L(t,f,null),L(t,n(o,{get each(){return Ce(e())},children:e=>(()=>{var t=hT();return t.$$click=()=>c(``),L(t,()=>e.label),D(n=>{var r=`/settings/${e.id}`,a=i()===e.id&&!s()?`page`:void 0;return r!==n.e&&R(t,`href`,n.e=r),a!==n.t&&R(t,`aria-current`,n.t=a),n},{e:void 0,t:void 0}),t})()}),null),t}}),m),L(m,n(u,{get when(){return H(()=>!!Z())()&&i()===`list`},get children(){return f()}}),h),L(m,n(u,{get when(){return!s()},get fallback(){return n(VE,{get results(){return l()},onPick:()=>c(``)})},get children(){return n(ee,{get fallback(){return n(UE,{})},get children(){return[n(A,{get when(){return i()===`list`},get children(){return n(HE,{onPick:()=>zE=!0})}}),n(A,{get when(){return H(()=>i()!==`list`)()&&i()},keyed:!0,children:e=>n(WE,{id:e})})]}})}}),h),L(h,()=>X()?.publicURL??location.origin,g),L(h,()=>X()?.version??`?`,null),t})()}function VE(e){return n(u,{get when(){return e.results.length},get fallback(){return _T()},get children(){var t=gT();return L(t,n(o,{get each(){return e.results},children:t=>(()=>{var n=vT(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild;return Oe(r,`click`,e.onPick,!0),L(i,()=>t.label),L(a,()=>RE(t.section),o),L(a,()=>t.description,null),D(()=>R(r,`href`,`/settings/${t.section}#${t.id}`)),n})()})),t}})}function HE(e){return(()=>{var t=yT();return L(t,n(o,{get each(){return Ce(ht(X()))},children:t=>(()=>{var r=bT(),i=r.firstChild,a=i.firstChild.firstChild,o=a.nextSibling;return Oe(i,`click`,e.onPick,!0),L(a,()=>t.label),L(o,()=>t.description),L(i,n(U,{name:`chevron`}),null),D(()=>R(i,`href`,`/settings/${t.id}`)),r})()})),t})()}function UE(){return xT()}function WE(e){return(()=>{var t=ST(),r=t.firstChild;return L(r,()=>RE(e.id)),L(t,n(ee,{get children(){return[n(A,{get when(){return e.id===`general`},get children(){return[n(KE,{}),n(JE,{}),n(rD,{})]}}),n(A,{get when(){return e.id===`notifications`},get children(){return n(qE,{})}}),n(A,{get when(){return e.id===`voice`},get children(){return[n(XE,{}),n(PE,{id:`speech`,title:`Speech`,get children(){return n(Bx,{})}})]}}),n(A,{get when(){return e.id===`machines`},get children(){return[n($E,{}),n(eD,{})]}}),n(A,{get when(){return e.id===`agents`},get children(){return n(YS,{})}}),n(A,{get when(){return e.id===`concierge`},get children(){return n(lw,{})}}),n(A,{get when(){return e.id===`teams`},get children(){return n(aD,{})}}),n(A,{get when(){return H(()=>e.id===`admin`)()&&ht(X())},get children(){return n(cD,{})}})]}}),null),D(()=>R(t,`data-settings-section`,e.id)),t})()}async function GE(){if(gt(X()).mode!==`pairing`||await Se(`Sign out this device? You will need a new pairing code.`,`Sign out`,{danger:!0})){await(await Dd().catch(()=>void 0))?.unsubscribe().catch(()=>{}),await G(`/api/logout`,{method:`POST`,json:{}}).catch(()=>{});try{ys(localStorage)}catch{}iu(),location.href=`/`}}function KE(){let e=()=>gt(X());return n(PE,{id:`account`,title:`Account`,get children(){var t=TT(),r=t.firstChild,i=r.nextSibling,a=i.firstChild,o=a.firstChild,s=a.nextSibling;s.firstChild;var c=i.nextSibling;return L(r,()=>e().initial),L(o,()=>e().title),L(a,n(u,{get when(){return e().badge},get children(){var t=CT();return L(t,()=>e().badge),t}}),null),L(i,n(u,{get when(){return e().subtitle},get children(){var t=wT();return L(t,()=>e().subtitle),t}}),s),L(s,()=>X()?.device?.name??`paired`,null),c.$$click=()=>void GE(),D(()=>K(r,`avatar large${e().badge?` admin`:``}`)),t}})}function qE(){let[e,{refetch:t}]=f(xd,()=>kd()),[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&&q(n)}catch(e){q(W(e),`err`)}finally{i(!1),h(void 0),t()}},ae=async e=>{try{let t=await(await G(`/api/push/prefs`,{method:`PUT`,json:e})).json();h(t.prefs),v(t.quietHours??null),t.activityMinutes!==void 0&&C(t.activityMinutes)}catch(e){q(W(e),`err`)}},k=async()=>{c(void 0);try{c(d(await Nd(l()||void 0)))}catch(e){c({ok:!1,text:W(e)})}};return n(PE,{id:`notifications`,label:`Notifications`,get children(){return[n(u,{get when(){return E()},get fallback(){return NT()},children:t=>[(()=>{var n=PT(),r=n.firstChild,i=r.nextSibling.firstChild.nextSibling.firstChild.nextSibling,a=i.nextSibling.nextSibling,o=a.nextSibling.nextSibling;return L(r,()=>t().message),L(i,(()=>{var t=H(()=>!!e().env.supported);return()=>t()?e().env.permission:`unsupported`})()),L(a,()=>e().env.worker?`registered`:`not registered`),L(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&&K(r,e.e=n),i!==e.t&&R(r,`data-state`,e.t=i),e},{e:void 0,t:void 0}),n})(),(()=>{var i=RT();return L(i,n(u,{get when(){return t().action===`enable`},get children(){var e=FT();return e.$$click=()=>void ie(jd,`Notifications are on for this device`),D(()=>e.disabled=r()),e}}),null),L(i,n(u,{get when(){return t().action===`disable`},get children(){var e=IT();return e.$$click=()=>void ie(Md,`Notifications are off for this device`),D(()=>e.disabled=r()),e}}),null),L(i,n(u,{get when(){return e().env.hubSubscriptions>0},get children(){var e=LT(),t=e.firstChild;t.firstChild;var r=t.nextSibling;return t.addEventListener(`change`,e=>p(e.currentTarget.value)),L(t,n(o,{each:te,children:e=>(()=>{var t=zT();return L(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=BT();return L(t,()=>e().text),D(()=>K(t,e().ok?`small ok`:`small err`)),t})()})]}),n(u,{get when(){return O()},get children(){return[ET(),(()=>{var e=DT();return L(e,()=>ne(O())),e})(),n(u,{get when(){return H(()=>!!E())()&&E().state!==`on`},get children(){return OT()}}),n(u,{get when(){return H(()=>`activity`in O()&&!O().activity)()&&!O().done},get children(){return kT()}}),n(o,{get each(){return w.filter(e=>e.kinds.some(e=>e.key in O()))},children:e=>(()=>{var t=VT(),r=t.firstChild,i=r.firstChild,a=i.nextSibling,c=r.nextSibling;return L(i,()=>e.title),L(a,()=>s(e.kinds,O())),L(c,n(o,{get each(){return e.kinds.filter(e=>e.key in O())},children:e=>(()=>{var t=UT(),r=t.firstChild.firstChild,i=r.firstChild,a=i.nextSibling,s=r.nextSibling;return L(i,()=>e.label),L(a,()=>e.description),s.addEventListener(`change`,t=>void ae({[e.key]:t.currentTarget.checked})),L(t,n(u,{get when(){return H(()=>e.key===`activity`)()&&O().activity},get children(){var e=HT(),t=e.firstChild.firstChild.nextSibling;return t.addEventListener(`change`,e=>void ae({activityMinutes:Number(e.currentTarget.value)})),L(t,n(o,{each:S,children:e=>(()=>{var t=zT();return L(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&&R(t,`id`,n.e=r),i!==n.t&&R(s,`data-pref`,n.t=i),n},{e:void 0,t:void 0}),D(()=>s.checked=!!O()[e.key]),t})()})),D(()=>R(t,`data-notify-group`,e.title)),t})()}),AT(),(()=>{var e=jT(),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})),L(t,n(u,{get when(){return re()},children:e=>(()=>{var t=WT(),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()}})),L(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 Cd().size},get children(){var e=MT(),t=e.firstChild;return L(e,()=>ut(Cd().size,`session`),t),e}})]}})]}})}function JE(){return n(PE,{id:`appearance`,title:`Appearance`,get children(){return[(()=>{var e=GT(),t=e.firstChild,r=t.firstChild.nextSibling,i=t.nextSibling.firstChild.nextSibling,a=i.nextSibling,s=a.nextSibling;return L(r,n(o,{each:nT,children:e=>(()=>{var t=qT(),n=t.firstChild;return t.$$click=()=>lT(e),L(t,e===`light`?`☀`:e===`dark`?`☾`:`▣`,n),L(n,()=>e[0].toUpperCase()+e.slice(1)),D(()=>R(t,`aria-checked`,sT()===e)),t})()})),i.$$input=e=>Qw(Number(e.currentTarget.value)),R(i,`min`,Nw),R(i,`max`,Pw),R(i,`step`,Fw),L(a,()=>Uw(Yw())),s.$$click=()=>Qw(1),D(e=>{var t=Uw(Yw()),n=Yw()===1;return t!==e.e&&R(i,`aria-valuetext`,e.e=t),n!==e.t&&(s.disabled=e.t=n),e},{e:void 0,t:void 0}),D(()=>i.value=Yw()),e})(),KT()]}})}var YE={low:`Low`,normal:`Normal`,high:`High`};function XE(){let[e,t]=x(Lv.speed),[r,i]=x(Lv.sensitivity);return n(PE,{id:`voice`,title:`Voice`,get children(){var a=JT(),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=>{Lv.speed=Number(e.currentTarget.value),t(Lv.speed)},R(c,`min`,eo),R(c,`max`,2),R(c,`step`,to),L(l,()=>ro(e())),L(d,n(o,{each:N_,children:e=>(()=>{var t=YT();return t.$$click=()=>{Lv.sensitivity=e,i(e)},L(t,()=>YE[e]),D(n=>{var i=r()===e,a=r()===e;return i!==n.e&&R(t,`aria-checked`,n.e=i),a!==n.t&&R(t,`aria-pressed`,n.t=a),n},{e:void 0,t:void 0}),t})()})),p.addEventListener(`change`,e=>Lv.cues=e.currentTarget.checked),m.addEventListener(`change`,e=>Lv.background=e.currentTarget.checked),D(()=>R(c,`aria-valuetext`,ro(e()))),D(()=>c.value=e()),D(()=>p.checked=Lv.cues),D(()=>m.checked=Lv.background),a}})}async function ZE(e,t){try{await G(`/api/enrollments/${V(e.userCode)}/${t}`,{method:`POST`,json:{}}),q(t===`approve`?`${e.machineName} approved; it belongs to you`:`Request denied`)}catch(e){q(W(e),`err`)}xu()}function QE(){return n(u,{get when(){return el().length},get children(){return[XT(),(()=>{var e=ZT();return L(e,n(o,{get each(){return el()},children:e=>(()=>{var t=QT(),n=t.firstChild,r=n.firstChild,i=r.nextSibling,a=i.firstChild.nextSibling;a.nextSibling;var o=n.nextSibling,s=o.nextSibling;return L(r,()=>e.machineName),L(i,()=>e.userCode,a),L(i,()=>ze(e.created,I()),null),o.$$click=()=>void ZE(e,`approve`),s.$$click=()=>void ZE(e,`deny`),t})()})),e})()]}})}function $E(){let e=async e=>{if(await Se(`Revoke ${e.name}? Its OpenCode processes disconnect and it must be connected again.`,`Revoke`,{danger:!0}))try{await G(`/api/machines/${V(e.id)}`,{method:`DELETE`}),q(`${e.name} revoked`)}catch(e){q(W(e),`err`)}};return n(PE,{id:`machines`,title:`Machines`,get children(){return[n(QE,{}),n(u,{get when(){return(Y.machines??[]).length},get fallback(){return $T()},get children(){var t=ZT();return L(t,n(o,{get each(){return Y.machines},children:t=>(()=>{var n=eE(),r=n.firstChild,i=r.firstChild,a=i.firstChild;a.nextSibling;var o=i.nextSibling,s=r.nextSibling;return L(i,()=>t.name,null),L(o,(()=>{var e=H(()=>!!t.online);return()=>e()?`online · ${ut(t.processes.length,`OpenCode process`)}`:`offline · seen ${ze(t.lastSeen,I())}`})()),s.$$click=()=>void e(t),D(e=>{var n=`online-dot${t.online?` on`:``}`,r=`Revoke machine ${t.name}`;return n!==e.e&&K(a,e.e=n),r!==e.t&&R(s,`aria-label`,e.t=r),e},{e:void 0,t:void 0}),n})()})),t}})]}})}function eD(){let[e,{refetch:t,mutate:r}]=f(()=>B(`/api/devices`).then(e=>e.devices)),[i,a]=x(!1),s=async e=>{if(e.current)return void GE();if(await Se(`Revoke ${e.name}?`,`Revoke`,{danger:!0})){try{await G(`/api/devices/${V(e.id)}`,{method:`DELETE`}),q(`${e.name} revoked`)}catch(e){q(W(e),`err`)}t()}};return n(PE,{id:`devices`,title:`Devices`,get children(){return[(()=>{var e=tE(),t=e.firstChild.nextSibling;return t.$$click=()=>a(!0),e})(),n(u,{get when(){return i()},get children(){return n(nD,{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=nE();return L(t,(()=>{var t=H(()=>!!e.error);return()=>t()?W(e.error):`Loading…`})()),t})()},get children(){var t=ZT();return L(t,n(o,{get each(){return e()},children:e=>(()=>{var t=iE(),r=t.firstChild,i=r.firstChild,a=i.nextSibling;a.firstChild;var o=r.nextSibling;return L(i,()=>e.name,null),L(i,n(u,{get when(){return e.current},get children(){return rE()}}),null),L(a,()=>ze(e.lastSeen,I()),null),o.$$click=()=>void s(e),L(o,()=>e.current?`Sign out`:`Revoke`),t})()})),t}})]}})}var tD=2e3;function nD(e){let[t,r]=x(),[i,a]=x(``),[o,s]=x(Date.now()),c=async()=>{a(``);try{let e=await G(`/api/devices/link`,{method:`POST`,json:{}}),t=await e.json(),n=Date.now();s(n),r({...t,expiresAt:_w(t.expiresAt,e.headers.get(`date`),n)})}catch(e){a(W(e))}},l=()=>(t()?.expiresAt??0)<=o(),d=()=>{let e=t();return e?jw(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 B(`/api/devices`)).devices,n=gw(e.known,t);n&&(e.onLinked(t),q(`${n.name} linked`),e.onClose())}catch{}finally{p=!1}}},tD);return j(()=>{clearInterval(f),clearInterval(m)}),c(),n(Re,{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=nE();return L(e,()=>i()||`Creating a link code…`),e})()},children:e=>(()=>{var t=cE(),r=t.firstChild,i=r.firstChild.nextSibling.nextSibling.nextSibling,a=r.nextSibling;return L(i,()=>e().hub),L(t,n(u,{get when(){return!l()},get fallback(){return(()=>{var e=lE(),t=e.firstChild.nextSibling;return t.$$click=()=>void c(),e})()},get children(){return[(()=>{var e=aE(),t=e.firstChild.nextSibling;return D(n=>{var r=`0 0 ${d().size+8} ${d().size+8}`,i=Mw(d(),4);return r!==n.e&&R(e,`viewBox`,n.e=r),i!==n.t&&R(t,`d`,n.t=i),n},{e:void 0,t:void 0}),e})(),(()=>{var t=oE(),n=t.firstChild.nextSibling;return L(n,()=>hw(e().expiresAt,o())),t})(),(()=>{var t=sE(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling;return L(n,()=>e().url),r.$$click=()=>void navigator.clipboard?.writeText(e().url).then(()=>q(`Link copied`),()=>q(`Copy failed`,`err`)),D(()=>R(i,`href`,e().url)),t})()]}}),a),t})()})}})}function rD(){let[e,t]=x(),r=async()=>{try{t(new Set((await B(`/api/devices`)).devices.map(e=>e.id)))}catch(e){q(W(e),`err`)}};return n(PE,{id:`add-app`,title:`Add the Hub app`,get children(){return[(()=>{var e=uE(),t=e.firstChild.nextSibling;return t.$$click=()=>void r(),e})(),n(u,{get when(){return e()},children:e=>n(nD,{get known(){return e()},onLinked:()=>{},onClose:()=>t(void 0)})})]}})}var iD=`/api/agent/team-settings`;function aD(){let[t,{mutate:r,refetch:i}]=f(()=>B(iD).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 G(iD,{method:`PUT`,json:{teamIsolation:s,expectedRevision:a.revision}})).json();r(e.settings),q(s?`Team isolation is on`:`Team isolation is off`)}catch(t){n.checked=!s,t instanceof e&&t.status===409?(q(`Team settings changed elsewhere. Showing the current setting; try again.`,`err`),i()):q(W(t),`err`)}finally{o(!1)}};return n(PE,{id:`teams`,label:`Teams`,get children(){return[dE(),n(u,{get when(){return t()},get fallback(){return(()=>{var e=nE();return L(e,(()=>{var e=H(()=>!!t.error);return()=>e()?`Could not load: ${W(t.error)}`:`Loading…`})()),e})()},children:e=>(()=>{var t=fE(),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 oD=(e,t)=>Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[],sD=e=>e.id===`local`?`Hub owner (pairing)`:e.name||e.email||e.id;function cD(){let e=()=>vt(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(``),q(t),!0}catch(e){return a(jt(e)),q(i(),`err`),!1}};return n(PE,{id:`admin`,label:`Admin`,get children(){return[(()=>{var i=pE();return L(i,n(o,{get each(){return e()},children:([e,i])=>(()=>{var o=yE();return o.$$click=()=>(r(e),a(``)),L(o,i,null),L(o,n(u,{get when(){return e===`approvals`&&el().length},get children(){var e=vE();return L(e,()=>el().length),e}}),null),D(()=>R(o,`aria-pressed`,t()===e)),o})()})),i})(),n(u,{get when(){return i()},get children(){var e=mE();return L(e,i),e}}),n(u,{get when(){return t()===`users`},get children(){return n(lD,{change:s})}}),n(u,{get when(){return t()===`machines`},get children(){var e=hE();return L(e,n(uD,{change:s})),e}}),n(u,{get when(){return t()===`approvals`},get children(){return[gE(),n(u,{get when(){return el().length},get fallback(){return bE()},get children(){return n(QE,{})}})]}}),n(u,{get when(){return t()===`audit`},get children(){var e=_E();return L(e,n(dD,{})),e}})]}})}function lD(e){let[t,{refetch:r}]=f(()=>B(`/api/admin/users`).then(e=>oD(e,`users`))),[i,a]=x(``),[s,c]=x(`all`),[l,d]=x(`role`),p=async(t,n)=>{await Se(n.confirm,n.label,{danger:!!n.danger})&&(await e.change(()=>G(`/api/admin/users/${V(t.id)}`,{method:`PUT`,json:n.change}),`${sD(t)}: ${n.label.toLowerCase()} done`)&&t.id===X()?.user?.id&&(Yc(void 0),await Rl().catch(()=>!1)),r())};return(()=>{var e=xE(),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)),L(f,n(o,{each:pt,children:([e,t])=>(()=>{var n=zT();return n.value=e,L(n,t),n})()})),m.addEventListener(`change`,e=>d(e.currentTarget.value)),L(m,n(o,{each:ft,children:([e,t])=>(()=>{var n=zT();return n.value=e,L(n,t),n})()})),L(e,n(u,{get when(){return t()},get fallback(){return(()=>{var e=SE();return L(e,(()=>{var e=H(()=>!!t.error);return()=>e()?`Could not load: ${jt(t.error)}`:`Loading…`})()),e})()},get children(){var e=ZT();return L(e,n(o,{get each(){return kt(t(),{query:i(),filter:s(),sort:l()})},get fallback(){return CE()},children:e=>(()=>{var r=DE(),i=r.firstChild,a=i.firstChild,s=a.nextSibling,c=s.firstChild,l=c.nextSibling;return l.nextSibling,L(a,()=>sD(e),null),L(a,n(u,{get when(){return e.role===`admin`},get children(){return wE()}}),null),L(a,n(u,{get when(){return e.disabled},get children(){return TE()}}),null),L(a,n(u,{get when(){return e.id===X()?.user?.id},get children(){return EE()}}),null),L(i,n(u,{get when(){return H(()=>!!e.name)()&&e.email},get children(){var t=wT();return L(t,()=>e.email),t}}),s),L(s,()=>ut(e.machines??0,`machine`),c),L(s,()=>ut(e.devices??0,`device`),l),L(s,()=>ze(e.lastSeen,I())||`never`,null),L(r,n(o,{get each(){return At(e,t(),X()?.user?.id)},children:t=>(()=>{var n=OE();return n.$$click=()=>void p(e,t),L(n,()=>t.label),D(()=>K(n,`btn small${t.danger?` danger`:``}`)),n})()}),null),D(()=>K(r,e.disabled?`disabled`:``)),r})()})),e}}),null),D(()=>r.value=i()),D(()=>f.value=s()),D(()=>m.value=l()),e})()}function uD(e){let[t,{refetch:r}]=f(()=>B(`/api/admin/machines`).then(e=>oD(e,`machines`)));return n(u,{get when(){return t()},get fallback(){return(()=>{var e=SE();return L(e,(()=>{var e=H(()=>!!t.error);return()=>e()?`Could not load: ${jt(t.error)}`:`Loading…`})()),e})()},get children(){return n(u,{get when(){return t().length},get fallback(){return kE()},get children(){var i=ZT();return L(i,n(o,{get each(){return t()},children:t=>{let n=t.ownerEmail??(t.ownerID===`local`?`hub owner`:t.ownerID)??`unknown`;return(()=>{var i=AE(),a=i.firstChild,o=a.firstChild,s=o.firstChild;s.nextSibling;var c=o.nextSibling,l=c.firstChild,u=a.nextSibling;return L(o,()=>t.name,null),L(c,n,l),L(c,()=>t.ownerID===X()?.user?.id?` (you)`:``,l),L(c,(()=>{var e=H(()=>!!t.online);return()=>e()?`online`:`offline · seen ${ze(t.lastSeen,I())}`})(),null),u.$$click=async()=>{await Se(`Revoke ${t.name} (${n})? Its OpenCode processes disconnect and it must be connected again.`,`Revoke`,{danger:!0})&&(await e.change(()=>G(`/api/admin/machines/${V(t.id)}`,{method:`DELETE`}),`${t.name} revoked`),r())},D(()=>K(s,`online-dot${t.online?` on`:``}`)),i})()}})),i}})}})}function dD(){let[e]=f(async()=>{let[e,t,n]=await Promise.all([B(`/api/admin/audit`),B(`/api/admin/users`).then(e=>oD(e,`users`),()=>[]),B(`/api/admin/machines`).then(e=>oD(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 Dt(oD(e,`audit`).length?oD(e,`audit`):oD(e,`entries`),r)});return n(u,{get when(){return e()},get fallback(){return(()=>{var t=SE();return L(t,(()=>{var t=H(()=>!!e.error);return()=>t()?`Could not load: ${jt(e.error)}`:`Loading…`})()),t})()},get children(){return n(u,{get when(){return e().length},get fallback(){return ME()},get children(){var t=jE();return L(t,n(o,{get each(){return e()},children:e=>(()=>{var t=NE(),n=t.firstChild,r=n.firstChild,i=r.nextSibling,a=n.nextSibling;return L(r,()=>e.action),L(i,()=>e.actor,null),L(i,(()=>{var t=H(()=>!!e.target);return()=>t()?` → ${e.target}`:``})(),null),L(i,(()=>{var t=H(()=>!!e.detail);return()=>t()?` · ${e.detail}`:``})(),null),L(a,()=>ze(e.at,I())),D(t=>{var n=new Date(e.at).toISOString(),r=new Date(e.at).toLocaleString();return n!==t.e&&R(a,`datetime`,t.e=n),r!==t.t&&R(a,`title`,t.t=r),t},{e:void 0,t:void 0}),t})()})),t}})}})}F([`input`,`keydown`,`click`]);var fD=J(`<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 pD(){let e=()=>py().sessionID??``;return(()=>{var t=fD(),r=t.firstChild,i=r.firstChild.nextSibling,a=r.nextSibling;return L(t,n(U,{name:`wave`}),r),L(i,my),a.$$click=()=>void ry.end(),D(n=>{var i=`voice-pill ${py().voice}`,a=`Voice mode is on in ${my()}`,o=k(e());return i!==n.e&&K(t,n.e=i),a!==n.t&&R(t,`aria-label`,n.t=a),o!==n.a&&R(r,`href`,n.a=o),n},{e:void 0,t:void 0,a:void 0}),t})()}F([`click`]);var mD=`/api/agent/workspaces`,hD=50,gD=4e3,_D=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 ye||t instanceof Error?t.message:String(t)},vD=e=>kp(_D(e));function yD(){let[t,n]=x(`loading`),[r,i]=x(),[a,o]=x([]),[s,c]=pi({}),[l,u]=x(),[d,f]=x(new Set),p=new Map,m=new Map,h=!1;async function g(){try{let e=hp(await B(`${mD}?state=active&limit=${hD}`));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(vD(t)),n(`error`))}}async function _(e){p.set(e,Date.now()),c(e,e=>({...e??{},loading:!0}));try{let t=mp(await B(`${mD}/${V(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:vD(t)}));return}}async function v(){try{u(Xn(await B(`/api/agent/grants`)))}catch{u(`error`)}}function y(e){if(m.has(e))return;let t=Math.max(0,(p.get(e)??0)+gD-Date.now());m.set(e,setTimeout(()=>{m.delete(e),d().has(e)&&document.visibilityState!==`hidden`&&_(e)},t))}function b(){h||(h=!0,g(),Ol(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 G(`${mD}/${V(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=vp(r,t);if(i)i!==`unchanged`&&C(e,{text:Dp(i),kind:`warn`});else{c(e,e=>({...e,saving:!0,notice:{text:`Saving: ${n}…`,kind:``}}));try{await E(e,t,Tp(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:vD(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=Op(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:vD(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 bD=_(yD),xD=`hub.sidebar.sections.collapsed`;function SD(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 CD(e,t){let n=SD(e);n.has(t)?n.delete(t):n.add(t);try{e.setItem(xD,JSON.stringify([...n]))}catch{}return n}var wD=e=>e!==`results`;function TD(e,t,n){if(t&&wD(e)){if(e===`needs`)return{text:String(t),label:`${ut(t,`session`)} ${t===1?`needs`:`need`} you`};if(n)return{text:String(t),label:ut(t,e===`workspaces`?`workspace`:`session`)}}}var ED=J(`<button type=button class=side-section-toggle><span class=side-section-title>`),DD=J(`<div class=side-section-head>`),OD=J(`<span class=side-section-title>`),kD=J(`<span aria-hidden=true data-section-count>`),[AD,jD]=x(SD(localStorage)),MD=(e,t)=>wD(t)&&AD().has(e),ND=e=>`side-sec-${e.replace(/[^A-Za-z0-9_-]/g,`-`)}`;function PD(e){let t=()=>MD(e.id,e.kind),r=()=>TD(e.kind,e.count,t());return(()=>{var i=DD();return L(i,n(u,{get when(){return wD(e.kind)},get fallback(){return(()=>{var t=OD();return L(t,()=>e.title),t})()},get children(){var i=ED(),a=i.firstChild;return i.$$click=()=>jD(CD(localStorage,e.id)),L(i,n(U,{get name(){return t()?`chevron`:`down`},class:`side-section-caret`}),a),L(a,()=>e.title),L(i,n(u,{get when(){return r()},children:t=>(()=>{var n=kD();return L(n,()=>t().text),D(()=>K(n,`side-count${e.kind===`needs`?` needs`:``}`)),n})()}),null),D(n=>{var a=!t(),o=ND(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&&R(i,`aria-expanded`,n.e=a),o!==n.t&&R(i,`aria-controls`,n.t=o),s!==n.a&&R(i,`data-section-toggle`,n.a=s),c!==n.o&&R(i,`aria-label`,n.o=c),l!==n.i&&R(i,`title`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),i}}),null),L(i,()=>e.children,null),i})()}F([`click`]);var FD=J(`<p class=side-empty>Workspaces are not available to this device.`),ID=J(`<p class=side-empty role=alert>Could not load workspaces: <!> <button type=button class=link-btn>Retry`),LD=J(`<ul class=ws-list>`),RD=J(`<section aria-label=Workspaces data-section=workspaces>`),zD=J(`<p class=ws-goal><span class=sr-only>Goal: `),BD=J(`<div class=ws-panel>`),VD=J(`<li><button type=button class=ws-head><span class=ws-title>`),HD=J(`<p class=ws-notice role=status aria-live=polite>`),UD=J(`<p class=side-empty role=alert>Could not load the board: <!> <button type=button class=link-btn>Retry`),WD=J(`<button type=button class=link-btn>Retry`),GD=J(`<p class=side-empty>Loading…`),KD=J(`<p class=side-empty>No members yet.`),qD=J(`<ul role=tree>`),JD=J(`<div>Drop here: no supervisor`),YD=J(`<p class=ws-keys>Drag to change supervision, or Alt+arrows. Supervision grants nothing.`),XD=J(`<p class=ws-keys>`),ZD=J(`<span class="ws-rel ws-spawned"title="Native parent session (unchanged by supervision)">spawned by <a tabindex=-1>`),QD=J(`<span class="ws-rel ws-supervised"title="Workspace supervision link">supervised by `),$D=J(`<ul class=ws-assignments>`),eO=J(`<li role=treeitem><div class=ws-row><a class=ws-member tabindex=-1></a></div><p class=ws-meta>`),tO=J(`<span>`),nO=J(`<span class=ws-assignment-stale> · stale`),rO=J(`<li><span class=ws-assignment-title></span> <span class=ws-assignment-status>`),iO=J(`<ul>`),aO=J(`<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.`),oO=J(`<p>Could not load your grants.`),sO=J(`<p>Loading…`),cO=J(`<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.`),lO=J(`<li> · <!> · <!> <span class=muted>(grant <!>)`),uO=new Set([`idle`,`working`,`blocked`,`error`]),dO={open:`open`,in_progress:`in progress`,blocked:`blocked`},fO={ArrowRight:`indent`,ArrowLeft:`outdent`,ArrowUp:`up`,ArrowDown:`down`};function pO(e){let t=bD;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=RD();return L(r,n(PD,{id:`workspaces`,kind:`workspaces`,title:`Workspaces`,get count(){return t.workspaces().length}}),null),L(r,n(u,{get when(){return t.availability()===`forbidden`},get children(){return FD()}}),null),L(r,n(u,{get when(){return t.availability()===`error`},get children(){var e=ID(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling;return L(e,()=>t.listError(),n),r.$$click=()=>void t.loadList(),e}}),null),L(r,n(u,{get when(){return!MD(`workspaces`,`workspaces`)},get children(){var r=LD();return L(r,n(o,{get each(){return t.workspaces()},children:t=>n(mO,{ws:t,get onPick(){return e.onPick}})})),D(()=>R(r,`id`,ND(`workspaces`))),r}}),null),D(()=>K(r,`side-section ws-section${MD(`workspaces`,`workspaces`)?` collapsed`:``}`)),r}})}function mO(e){let t=bD,r=()=>t.expanded().has(e.ws.id),i=`ws-panel-${e.ws.id}`;return(()=>{var a=VD(),o=a.firstChild,s=o.firstChild;return o.$$click=()=>t.toggle(e.ws.id),R(o,`aria-controls`,i),L(o,n(U,{get name(){return r()?`down`:`chevron`}}),s),L(s,()=>e.ws.title),L(a,n(u,{get when(){return e.ws.goal},get children(){var t=zD();return t.firstChild,L(t,()=>e.ws.goal,null),D(()=>R(t,`title`,e.ws.goal)),t}}),null),L(a,n(u,{get when(){return r()},get children(){var t=BD();return R(t,`id`,i),L(t,n(_O,{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&&K(a,t.e=n),i!==t.t&&R(a,`data-workspace`,t.t=i),s!==t.a&&R(o,`aria-expanded`,t.a=s),t},{e:void 0,t:void 0,a:void 0}),a})()}var hO=(e,t)=>{let n=e.members.find(e=>e.memberID===t);if(!n)return`a member`;let r=jp(Y.machines,n.sessionID);return r.found?r.title:n.session?.name??n.sessionID};function gO(e,t,n){let r=hO(e,t.memberID);return t.supervisorMemberID===null?`${r} has no supervisor`:n===`reorder`?`${r} reordered`:`${r} supervised by ${hO(e,t.supervisorMemberID)}`}function _O(e){let t=bD,r=()=>e.ws.id,i=()=>t.boards[r()],s=()=>i()?.board,c=T(()=>s()?_p(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,gO(a,e,n)))},S=(n,i,o)=>{let s=o.flat.indexOf(i);if(n.altKey&&fO[n.key]){n.preventDefault();let e=fO[n.key],a=wp(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=wp(t,r,e);s&&!vp(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&&!vp(n,Cp(t,r,{memberID:e.member.memberID,position:`inside`})));if(a.length){i.push({section:`Supervised by`});for(let e of a)i.push({label:hO(n,e.member.memberID),run:()=>b(Cp(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=HD();return L(e,()=>i()?.notice?.text??``,null),L(e,n(u,{get when(){return i()?.notice?.pending},children:e=>(()=>{var t=WD();return t.$$click=()=>b(e(),`supervise`),t})()}),null),e})(),n(u,{get when(){return i()?.error},get children(){var e=UD(),n=e.firstChild.nextSibling,a=n.nextSibling.nextSibling;return L(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 GD()}})},children:a=>[n(u,{get when(){return!a().flat.length},get children(){return KD()}}),(()=>{var c=qD(),l=g;return typeof l==`function`?he(l,c):g=c,L(c,n(o,{get each(){return a().flat},children:i=>{let c=()=>jp(Y.machines,i.member.sessionID),l=()=>hO(s(),i.member.memberID),g=()=>i.supervisorMemberID?a().flat.find(e=>e.member.memberID===i.supervisorMemberID)?.children??[]:a().roots,_=()=>Mp(i,s(),Y.machines),y=()=>uO.has(i.member.session?.state??``)?i.member.session.state:`idle`,x=()=>s().workspace.state===`active`&&!t.boards[r()]?.saving;return(()=>{var t=eO(),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(Cp(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`,()=>{Yf(),p(void 0),h(void 0)}),t.addEventListener(`dragstart`,e=>{Jf(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)),L(r,n(ge,{get state(){return y()}}),s),s.$$click=()=>e.onPick?.(),R(s,`draggable`,!1),L(s,l),L(r,n(pe,{get label(){return`Move ${l()}`},class:`icon-btn small row-more`,items:()=>E(i,a())}),null),L(C,n(o,{get each(){return Pp(i.member,c())},children:e=>(()=>{var t=tO();return L(t,()=>e.label),D(n=>{var r=`ws-badge ${e.kind}`,i=e.title;return r!==n.e&&K(t,n.e=r),i!==n.t&&R(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),null),L(C,n(u,{get when(){return _().spawnedBy},get children(){var e=ZD(),t=e.firstChild.nextSibling;return L(t,()=>_().spawnedBy.title),D(()=>R(t,`href`,k(_().spawnedBy.sessionID))),e}}),null),L(C,n(u,{get when(){return _().supervisedBy},get children(){var e=QD();return e.firstChild,L(e,()=>_().supervisedBy.title,null),e}}),null),L(t,n(u,{get when(){return i.assignments.length},get children(){var e=$D();return L(e,n(o,{get each(){return i.assignments},children:e=>(()=>{var t=rO(),r=t.firstChild,i=r.nextSibling.nextSibling;return L(r,()=>e.title),L(i,()=>dO[e.status]??e.status),L(t,n(u,{get when(){return e.stale?.length},get children(){var t=nO();return D(()=>R(t,`title`,e.stale.join(`, `))),t}}),null),D(()=>K(t,`ws-assignment ${e.status}`)),t})()})),D(()=>R(e,`aria-label`,`Assignments of ${l()}`)),e}}),null),L(t,n(u,{get when(){return _().supervisedBy},children:e=>n(vO,{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&&R(t,`aria-level`,e.e=n),r!==e.t&&R(t,`aria-setsize`,e.t=r),a!==e.a&&R(t,`aria-posinset`,e.a=a),o!==e.o&&R(t,`aria-selected`,e.o=o),c!==e.i&&R(t,`aria-label`,e.i=c),u!==e.n&&R(t,`tabindex`,e.n=u),d!==e.s&&R(t,`data-member`,e.s=d),p!==e.h&&K(t,e.h=p),h!==e.r&&xe(t,`--ws-depth`,e.r=h),y!==e.d&&R(t,`draggable`,e.d=y),b!==e.l&&R(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&&K(c,t.e=n),a!==t.t&&R(c,`aria-label`,t.t=a),o!==t.a&&R(c,`aria-describedby`,t.a=o),s!==t.o&&R(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=JD();return e.addEventListener(`drop`,e=>{e.preventDefault();let t=f();p(void 0),h(void 0),t&&b(Cp(a(),t,{root:!0}),`supervise`)}),e.addEventListener(`dragleave`,()=>h(void 0)),e.addEventListener(`dragover`,e=>{e.preventDefault(),h(`root`)}),D(()=>K(e,`ws-root-drop${m()===`root`?` over`:``}`)),e}}),(()=>{var e=YD();return D(()=>R(e,`id`,`ws-keys-${r()}`)),e})(),n(u,{get when(){return a().staleLinks||s().membersTruncated||s().linksTruncated},get children(){var e=XD();return L(e,n(u,{get when(){return a().staleLinks},get children(){return[H(()=>a().staleLinks),` link(s) to departed members not shown. `]}}),null),L(e,n(u,{get when(){return s().membersTruncated||s().linksTruncated},children:`Some members are not shown (limit).`}),null),e}})]})]}function vO(e){let t=bD,r=()=>{let n=t.grants();return Array.isArray(n)?Lp(n,e.supervisorSessionID,e.memberDirectory,Date.now()):n};return(()=>{var t=aO(),i=t.firstChild.nextSibling;return L(t,n(u,{get when(){return r()!==`error`},get fallback(){return oO()},get children(){return n(u,{get when(){return Array.isArray(r())},get fallback(){return sO()},get children(){return n(u,{get when(){return r().length},get fallback(){return(()=>{var t=cO(),n=t.firstChild;return L(t,()=>e.supervisorTitle,n),t})()},get children(){var e=iO();return L(e,n(o,{get each(){return r()},children:e=>(()=>{var t=lO(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling.nextSibling,a=i.nextSibling.nextSibling,o=a.firstChild.nextSibling;return o.nextSibling,L(t,()=>e.verbs.join(`, `),n),L(t,(()=>{var t=H(()=>e.covers===void 0);return()=>t()?`folder unknown`:e.covers?`covers this session's folder`:`not this session's folder`})(),r),L(t,()=>Is(e.expiresAt,Date.now()),i),L(a,()=>e.grantID,o),t})()})),e}})}})}}),i),t})()}F([`click`,`keydown`]);var yO=J(`<nav aria-label=Primary><ul>`),bO=J(`<a>`),xO=J(`<li>`),SO=J(`<a class="side-link nav-link disabled"aria-disabled=true>`),CO=J(`<div class=nav-rail>`),wO=()=>({signedIn:!!X(),concierge:ll()?.state});function TO(e){let t=()=>se(ie().pathname);return(()=>{var r=yO(),i=r.firstChild;return L(i,n(o,{get each(){return m(wO())},children:r=>(()=>{var i=xO();return L(i,n(u,{get when(){return r.enabled},get fallback(){return(()=>{var t=SO();return L(t,n(U,{get name(){return r.dest.icon}}),null),L(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&&R(t,`title`,n.e=i),a!==n.t&&R(t,`aria-label`,n.t=a),n},{e:void 0,t:void 0}),t})()},get children(){var i=bO();return i.$$click=()=>e.onPick?.(),L(i,n(U,{get name(){return r.dest.icon}}),null),L(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&&K(i,n.e=a),o!==n.t&&R(i,`href`,n.t=o),s!==n.a&&R(i,`aria-current`,n.a=s),c!==n.o&&R(i,`aria-label`,n.o=c),l!==n.i&&R(i,`title`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),i}})),i})()})),D(()=>K(r,e.compact?`nav-rail-links`:`feature-nav`)),r})()}function EO(e){return(()=>{var t=CO();return L(t,n(z,{icon:`sidebar`,label:`Show sidebar (⌘B)`,get onClick(){return e.onExpand}}),null),L(t,n(TO,{compact:!0}),null),t})()}F([`click`]);var DO=J(`<span class=concierge-btn-text>Concierge`),OO=J(`<span aria-hidden=true>`),kO=J(`<button type=button>`),AO=J(`<a href=/settings/concierge data-concierge-button=disabled data-indicator=off>`),jO;function MO(){let e=jO;return jO=void 0,e}function NO(e){let t=()=>He().name===`concierge`,r=()=>e.labelled?DO():null,i=e=>n(u,{get when(){return e.indicator!==`running`},get children(){var t=OO();return L(t,(()=>{var t=H(()=>e.indicator===`attention`);return()=>t()?e.count??`!`:``})()),D(()=>K(t,`concierge-ind ind-${e.indicator}`)),t}});return n(u,{get when(){return ll()},children:o=>{let s=()=>lc(o(),gl(),t(),Date.now(),nc(nl(),o(),{tiers:`all`}).length,new Set(nl().filter(e=>e.state===`open`).map(e=>e.id)));return n(u,{get when(){return sc(o())===!0},get fallback(){return(()=>{var t=AO();return t.$$click=()=>e.onPick?.(),L(t,n(U,{name:`spark`}),null),L(t,r,null),L(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&&K(t,n.e=r),i!==n.t&&R(t,`aria-label`,n.t=i),a!==n.a&&R(t,`title`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()},get children(){var c=kO();return c.$$click=n=>{if(e.onPick?.(),t())return me(`/`);jO=n.currentTarget,a(`/concierge`)},L(c,n(U,{name:`spark`}),null),L(c,r,null),L(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&&K(c,n.e=r),i!==n.t&&R(c,`aria-label`,n.t=i),a!==n.a&&R(c,`aria-expanded`,n.a=a),l!==n.o&&R(c,`title`,n.o=l),u!==n.i&&R(c,`data-concierge-button`,n.i=u),d!==n.n&&R(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}})}})}F([`click`]);var PO=J(`<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>`),FO=J(`<span class=badge title="Machines waiting for approval">`),IO=J(`<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>`),LO=J(`<p class=side-empty>`),RO=J(`<a class="icon-btn small">`),zO=J(`<ul class=side-list>`),BO=J(`<section>`),VO=J(`<span class=jobs-badge>`),HO=J(`<span class=unread-dot role=img aria-label=Unread>`),UO=J(`<a class=side-row-link><span class=side-title>`),WO=J(`<li>`),GO=J(`<span class=side-row-link>`),KO=`hub.sidebar.groupBy`,qO=`hub.sidebar.sort`;function JO(e){let[t,r]=x(``),[i,a]=x(localStorage.getItem(KO)===`machine`?`machine`:`project`),[s,c]=x(localStorage.getItem(qO)===`title`?`title`:`recent`),l=T(()=>Ya(kl(),{query:t(),groupBy:i(),sortBy:s()})),d=()=>{let e=qb();return e.name===`session`?e.id:void 0},f=()=>gt(X()),p=(e,t)=>{e&&(a(e),localStorage.setItem(KO,e)),t&&(c(t),localStorage.setItem(qO,t))};return(()=>{var a=IO(),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(),L(m,n(Hu,{class:`brand-mark`}),h),L(g,n(NO,{labelled:!0,onPick:()=>e.phone&&e.onClose()}),null),L(g,n(u,{get when(){return e.phone},get fallback(){return n(z,{icon:`sidebar`,label:`Collapse sidebar (⌘B)`,get onClick(){return e.onCollapse}})},get children(){return n(z,{icon:`close`,label:`Close sidebar`,get onClick(){return e.onClose}})}}),null),L(_,n(U,{name:`search`}),v),v.$$keydown=e=>e.key===`Escape`&&r(``),v.$$input=e=>r(e.currentTarget.value),y.$$click=()=>e.phone&&e.onClose(),L(y,n(U,{name:`plus`}),b),L(a,n(TO,{onPick:()=>e.phone&&e.onClose()}),x),L(S,n(pe,{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),L(C,n(u,{get when(){return nl().length},get children(){var t=PO(),n=t.firstChild.firstChild.firstChild,r=n.firstChild.nextSibling;return n.$$click=()=>e.phone&&e.onClose(),L(r,(()=>{var e=H(()=>nl().length===1);return()=>e()?`A Decision waits for you`:`${nl().length} Decisions wait for you`})()),D(()=>R(n,`href`,nc(nl(),ll(),{tiers:`all`}).length===nl().length?`/concierge`:`/`)),t}}),null),L(C,n(u,{get when(){return l().length},get fallback(){return(()=>{var e=LO();return L(e,()=>t()?`No sessions match.`:`No sessions yet.`),e})()},get children(){return n(o,{get each(){return l()},children:t=>(()=>{var r=BO();return L(r,n(PD,{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 H(()=>t.kind===`group`)()&&t.machineID},get children(){var e=RO();return L(e,n(U,{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&&R(e,`aria-label`,n.e=r),i!==n.t&&R(e,`title`,n.t=i),a!==n.a&&R(e,`href`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),e}})}}),null),L(r,n(u,{get when(){return!MD(t.id,t.kind)},get children(){var r=zO();return L(r,n(o,{get each(){return t.rows},children:t=>n(YO,{row:t,get active(){return d()===t.id},onPick:()=>e.phone&&e.onClose()})})),D(()=>R(r,`id`,ND(t.id))),r}}),null),D(e=>{var n=`side-section ${t.kind}${MD(t.id,t.kind)?` collapsed`:``}`,i=t.title,a=t.id;return n!==e.e&&K(r,e.e=n),i!==e.t&&R(r,`aria-label`,e.t=i),a!==e.a&&R(r,`data-section`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),r})()})}}),null),L(C,n(pO,{onPick:()=>e.phone&&e.onClose()}),null),w.$$click=()=>e.phone&&e.onClose(),L(T,()=>f().initial),L(E,()=>f().title),L(w,n(u,{get when(){return el().length},get children(){var e=FO();return L(e,()=>el().length),e}}),null),L(w,n(U,{name:`settings`}),null),D(e=>{var t=`Settings (${f().title})`,n=`avatar${f().badge?` admin`:``}`;return t!==e.e&&R(w,`aria-label`,e.e=t),n!==e.t&&K(T,e.t=n),e},{e:void 0,t:void 0}),D(()=>v.value=t()),a})()}function YO(e){let t=()=>e.row,r=()=>py().phase!==`off`&&py().sessionID===t().id;return(()=>{var i=WO();return L(i,n(u,{get when(){return!Cm(t().id,`sidebar`)},get fallback(){return(()=>{var e=GO();return L(e,n(ge,{get state(){return t().state}}),null),L(e,n(Nh,{get id(){return t().id},get title(){return t().title},place:`sidebar`,class:`side-title`,children:null}),null),e})()},get children(){var r=UO(),i=r.firstChild;return Oe(r,`dragend`,Yf),r.addEventListener(`dragstart`,e=>Jf(e,{target:{sessionID:t().id},label:t().title})),Oe(r,`click`,e.onPick,!0),L(r,n(ge,{get state(){return t().state}}),i),L(r,n(u,{get when(){return Qa(t(),py())},get children(){return n(De,{})}}),i),L(i,()=>t().title),L(r,n(Ph,{get id(){return t().id}}),null),L(r,n(u,{get when(){return t().error},children:e=>n(je,{get text(){return e()}})}),null),L(r,n(u,{get when(){return t().jobs},get children(){var e=VO();return L(e,()=>t().jobs),D(n=>{var r=ja(t().jobs),i=ja(t().jobs);return r!==n.e&&R(e,`title`,n.e=r),i!==n.t&&R(e,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),e}}),null),L(r,n(u,{get when(){return t().unread},get children(){return HO()}}),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&&R(r,`href`,n.e=i),a!==n.t&&R(r,`aria-current`,n.t=a),o!==n.a&&R(r,`title`,n.a=o),s!==n.o&&R(r,`draggable`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),r}}),null),L(i,n(pe,{get label(){return`More actions for ${t().title}`},class:`icon-btn small row-more`,items:()=>Tm(t(),{open:!1,place:`sidebar`})}),null),D(()=>K(i,`side-row${e.active?` active`:``}${t().unread?` unread`:``}${r()?` voice-here`:``}`)),i})()}F([`click`,`input`,`keydown`]);var XO={cycle:`F6`,close:`Control+Alt+W`,moveEarlier:`Control+Alt+Shift+ArrowLeft`,moveLater:`Control+Alt+Shift+ArrowRight`,focus:e=>`Control+Alt+${e}`},ZO=new Set([`ArrowLeft`,`ArrowUp`]),QO=new Set([`ArrowRight`,`ArrowDown`]);function $O(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 ZO.has(e.key)?{type:`move`,step:-1}:QO.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<=ct?{type:`focus`,index:n-1}:void 0}var ek=`hub.paneSizes.v1`,tk={cols:280,rows:160},nk=[`vertical`,`horizontal`,`grid`];function rk(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 ik(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 ak(e){return e>0?Array.from({length:e},()=>1/e):[]}function ok(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 sk(e,t,n,r,i,a,o){let s=r?64:16,[c,l]=o===`cols`?[`ArrowRight`,`ArrowLeft`]:[`ArrowDown`,`ArrowUp`];if(n===c)return ok(e,t,s,i,a);if(n===l)return ok(e,t,-s,i,a);if(n===`Home`)return ok(e,t,-2*i,i,a);if(n===`End`)return ok(e,t,2*i,i,a)}var ck=(e,t,n)=>`${e}:${t}:${n}`;function lk(e){let[t,n,r,...i]=e.split(`:`),a=Number(n);if(i.length||!nk.includes(t)||!Number.isInteger(a)||a<2||a>ct||r!==`cols`&&r!==`rows`)return;let o=rk(t,a)[r];return o>1?o:void 0}function uk(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 dk(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=lk(e),i=n===void 0?void 0:uk(t,n);i&&(r[e]=i)}return r}function fk(e,t,n,r,i,a){let o=ck(n,r,i),s=lk(o),c=s===void 0?void 0:uk(a,s);if(!c)return t;let l={...t,[o]:c};try{e?.setItem(ek,JSON.stringify({v:1,sizes:l}))}catch{}return l}function pk(e,t,n){let r=rk(t,n),i=i=>{let a=e[ck(t,n,i)];return a&&a.length===r[i]?a:ak(r[i])};return{cols:i(`cols`),rows:i(`rows`)}}function mk(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 hk=200,gk=10,_k=e=>e instanceof Error?e.message:String(e),vk=e=>e&&typeof e==`object`&&typeof e.status==`number`?e.status:void 0,yk=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=_k(t),this.invalid=vk(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=_k(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<gk;e++){let e=await this.fetch({limit:hk,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()}},bk=[`native`,`hooks`,`rpc`,`screen`],xk={opencode:`OpenCode`,"claude-code":`Claude Code`,codex:`Codex`},Sk=e=>xk[e]??e;function Ck(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=bk.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:Sk(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 wk={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 Tk(e){if(e.native)return;let t=wk[e.evidence];return{level:e.evidence,label:t.label,detail:t.detail(e.harnessName)}}function Ek(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 Dk(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 Ok={queued:`queued`,retained:`held`,pending:`pending`,dropped:`not delivered`};function kk(e){return typeof e==`string`?Ok[e]:void 0}function Ak(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 jk=/data:([\w.+-]+\/[\w.+-]+)?((?:;[\w.+-]+=[^;,\s"'<>]*)*);base64,([A-Za-z0-9+/_-]+={0,2})/gi,Mk=/^[A-Za-z0-9+/_-]+={0,2}$/,Nk=[`mime`,`mimeType`,`media_type`,`mediaType`];function Pk(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 Fk(e,t){return`[${e||`data`}, ${Pk(t)} — not shown]`}function Ik(e){return e.includes(`base64,`)?e.replace(jk,(e,t,n,r)=>Fk(t?.toLowerCase(),r)):e}function Lk(e){if(typeof e.data!=`string`||!Mk.test(e.data))return;let t=Nk.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 Rk(e){return zk(e)}function zk(e){if(typeof e==`string`)return Ik(e);if(Array.isArray(e))return e.map(zk);if(!e||typeof e!=`object`)return e;let t=e,n=Lk(t),r={};for(let[e,i]of Object.entries(t))r[e]=e===`data`&&n?Fk(n,i):zk(i);return r}var Bk=(e,t,n)=>`/api/sessions/${encodeURIComponent(e)}/timeline/messages/${encodeURIComponent(t)}/files/${n}`;function Vk(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=Zh(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:Bk(e.sessionID,e.messageID,n.index)}:{}})}return t}function Hk(e,t={}){let n=[];for(let r of e)if(!((r.depth??0)>0))switch(r.kind){case`user`:{let e=Vk(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(Kk(r));break;case`error`:n.push(r.declined===!0?{type:`error`,key:r.key,label:`${t.denied?.(r)??`Denied`}: the turn stopped`,denied:!0}:Wk(r));break;case`retry`:n.push({type:`retry`,key:r.key,...Uk(`attempt`,r.attempt),...Uk(`next`,r.next),...typeof r.errorType==`string`?{errorType:r.errorType}:{},...Uk(`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 Uk=(e,t)=>typeof t==`number`&&Number.isFinite(t)?{[e]:t}:{};function Wk(e){let t=typeof e.text==`string`&&e.text.trim()?e.text.trim():void 0,n=pa(e.errorType),r=ha(e.errorStatus);return{type:`error`,key:e.key,label:n??t??`Error`,...n&&t?{message:t}:{},...r?{status:r}:{}}}function Gk(e,t){return{text:xa(e,t),waiting:ga(e.next,t)!==void 0}}function Kk(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=kk(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 qk=`The model didn't share its reasoning text (only an encrypted summary).`;function Jk(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…`:qk,muted:!0}}function Yk(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 Xk(e,t){return JSON.stringify(Rk(e??{summary:t.summary||void 0,error:t.error}),null,2)}var Zk=J(`<p class=composer-error role=alert>`),Qk=J(`<p class="composer-hint muted small">`),$k=J(`<li class="attachment busy"aria-label="Preparing image"><span class="spinner small">`),eA=J(`<ul class=attachments aria-label="Attached images">`),tA=J(`<div><button type=button class=split-main>`),nA=J(`<button type=button class="btn stop"aria-label="Stop the session and its subagents"> Stop`),rA=J(`<span class=sr-only>`),iA=J(`<button type=button class=model-chip title="Voice model (the orchestrator you talk to)">Voice: `),aA=J(`<button type=button class=model-chip title="Worker model (subagents that do the work)">Worker: `),oA=J(`<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>`),sA=J(`<li class=attachment><img><button type=button class=attachment-remove title=Remove>`),cA=J(`<span class="spinner small">`),lA=J(`<button type=button class=split-chev aria-label="Choose microphone"aria-haspopup=dialog>`),uA=J(`<p class="error small pad">`),dA=J(`<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>`),fA=J(`<button type=button class=menu-item role=menuitemradio><span class=menu-check></span><span class=menu-label>`),pA=J(`<span class=muted> · “<!>…”`),mA=J(`<span class=voice-ignored title="Heard as background noise, not sent"> · ignored: “<!>”`),hA=J(`<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`),gA=J(`<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`),_A=J(`<span>`);function vA(e){let t,r,[i,a]=x(!1),s=()=>e.images.length>=Kh.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=oA(),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=yb(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()}),L(c,n(u,{get when(){return e.error},get children(){var t=Zk();return L(t,()=>e.error),t}}),d),L(c,n(u,{get when(){return e.view.hint},get children(){var t=Qk();return L(t,()=>e.view.hint),t}}),d),L(d,n(u,{get when(){return e.images.length||e.attaching},get children(){var t=eA();return L(t,n(o,{get each(){return e.images},children:t=>(()=>{var r=sA(),i=r.firstChild,a=i.nextSibling;return a.$$click=()=>e.onDetach(t.id),L(a,n(U,{name:`close`})),D(e=>{var n=t.preview,r=t.name,o=t.name,s=`Remove ${t.name}`;return n!==e.e&&R(i,`src`,e.e=n),r!==e.t&&R(i,`alt`,e.t=r),o!==e.a&&R(i,`title`,e.a=o),s!==e.o&&R(a,`aria-label`,e.o=s),e},{e:void 0,t:void 0,a:void 0,o:void 0}),r})()}),null),L(t,n(u,{get when(){return e.attaching},get children(){return $k()}}),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=yb(t.clipboardData);n.length&&(t.preventDefault(),e.onAttach(n))}),f.$$input=t=>e.onInput(t.currentTarget.value);var b=t;typeof b==`function`?he(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`?he(x,p):r=p,h.$$click=()=>r.click(),L(h,n(U,{name:`plus`})),Oe(g,`click`,e.onDictate,!0),L(g,n(u,{get when(){return!e.transcribing},get fallback(){return cA()},get children(){return n(U,{get name(){return e.dictating===!1?`mic`:`stop`}})}})),L(m,n(u,{get when(){return e.showVoice!==!1},get children(){var t=tA(),r=t.firstChild;return Oe(r,`click`,e.onVoice,!0),L(r,n(U,{name:`wave`})),L(t,n(yA,{}),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&&K(t,n.e=i),a!==n.t&&R(r,`aria-pressed`,n.t=a),o!==n.a&&R(r,`aria-label`,n.a=o),s!==n.o&&R(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}}),_),L(m,n(u,{get when(){return e.view.showStop},get children(){var t=nA(),r=t.firstChild;return Oe(t,`click`,e.onStop,!0),L(t,n(U,{name:`stop`}),r),D(()=>t.disabled=!e.view.canStop),t}}),_),L(_,n(u,{get when(){return e.view.primary===`send`},get fallback(){return l()},get children(){return[n(U,{name:`send`}),(()=>{var e=rA();return L(e,l),e})()]}})),L(y,()=>e.metaLeft),L(v,n(u,{get when(){return e.showModels!==!1},get children(){return[(()=>{var t=iA();return t.firstChild,t.$$click=()=>e.onModel(`voice`),L(t,()=>e.voiceModel,null),t})(),(()=>{var t=aA();return t.firstChild,t.$$click=()=>e.onModel(`worker`),L(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=Gh.join(`,`),o=s()?`At most ${Kh.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&&K(c,t.e=n),r!==t.t&&R(f,`placeholder`,t.t=r),a!==t.a&&R(p,`accept`,t.a=a),o!==t.o&&R(h,`title`,t.o=o),l!==t.i&&(h.disabled=t.i=l),u!==t.n&&K(g,t.n=u),d!==t.s&&R(g,`aria-label`,t.s=d),m!==t.h&&R(g,`title`,t.h=m),v!==t.r&&(g.disabled=t.r=v),y!==t.d&&K(_,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 yA(){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 Wv(Bv(),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 Uv().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`&&!be(f)&&v();return document.addEventListener(`mousedown`,y),document.addEventListener(`keydown`,b),j(()=>{document.removeEventListener(`mousedown`,y),document.removeEventListener(`keydown`,b),v()}),[(()=>{var t=lA();t.$$click=()=>e()?v():void _();var r=d;return typeof r==`function`?he(r,t):d=t,L(t,n(U,{name:`down`})),D(()=>R(t,`aria-expanded`,e())),t})(),n(u,{get when(){return e()},get children(){return n(_e,{get children(){var e=dA(),t=e.firstChild.nextSibling,i=t.firstChild,s=f;return typeof s==`function`?he(s,e):f=e,L(e,n(o,{get each(){return[{deviceId:``,label:`System default`},...r().filter(e=>e.deviceId&&e.deviceId!=="default")]},children:(e,t)=>(()=>{var n=fA(),r=n.firstChild,i=r.nextSibling;return n.$$click=()=>{Hv(e.deviceId),g()},L(r,()=>Bv()===e.deviceId?`✓`:``),L(i,()=>e.label||`Microphone ${t()}`),D(()=>R(n,`aria-checked`,Bv()===e.deviceId)),n})()}),t),L(e,n(u,{get when(){return c()},get children(){var e=uA();return L(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&&xe(e,`right`,n.e=r),o!==n.t&&xe(e,`bottom`,n.t=o),s!==n.a&&R(t,`aria-valuenow`,n.a=s),c!==n.o&&xe(i,`width`,n.o=c),n},{e:void 0,t:void 0,a:void 0,o:void 0}),e}})}})]}var bA={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 xA(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 SA(e){let t=()=>e.state===`listening`&&e.working?`Thinking`:bA[e.state],r=[.5,.8,1,.7,.45];return(()=>{var i=gA(),a=i.firstChild,s=a.nextSibling,c=s.nextSibling.nextSibling,l=c.nextSibling,d=l.nextSibling;return L(a,n(o,{each:r,children:t=>(()=>{var n=_A();return D(r=>xe(n,`transform`,`scaleY(${Math.max(.15,Math.min(1,(e.state===`speaking`?.6:e.level)*t*1.6))})`)),n})()})),L(s,t,null),L(s,n(u,{get when(){return e.held},get children(){var t=pA(),n=t.firstChild.nextSibling;return n.nextSibling,L(t,()=>e.held,n),t}}),null),L(s,n(u,{get when(){return e.ignored},get children(){var t=mA(),n=t.firstChild.nextSibling;return n.nextSibling,L(t,()=>e.ignored,n),t}}),null),Oe(c,`click`,e.onModel,!0),L(c,()=>e.model),Oe(l,`click`,e.onMute,!0),L(l,n(U,{get name(){return e.state===`paused`?`muted`:`mic`}})),Oe(d,`click`,e.onEnd,!0),L(i,n(u,{get when(){return e.notifyHint},get children(){var t=hA(),n=t.firstChild.nextSibling;return n.$$click=()=>e.onAllowNotifications?.(),t}}),null),D(t=>{var n=`voice-bar ${e.state}`,r=e.detector?.mode,a=xA(e.timing,e.detector),o=`icon-btn${e.state===`paused`?` on`:``}`,c=e.state===`paused`,u=e.state===`paused`?`Unmute`:`Mute`,d=e.state===`paused`?`Unmute`:`Mute`;return n!==t.e&&K(i,t.e=n),r!==t.t&&R(i,`data-vad`,t.t=r),a!==t.a&&R(s,`title`,t.a=a),o!==t.o&&K(l,t.o=o),c!==t.i&&R(l,`aria-pressed`,t.i=c),u!==t.n&&R(l,`aria-label`,t.n=u),d!==t.s&&R(l,`title`,t.s=d),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),i})()}F([`input`,`keydown`,`click`]);var CA=()=>({query:``,active:0}),wA=e=>[void 0,...(e.variants??[]).filter(e=>e!=="default")];function TA(e,t,n=100){if(t.chosen)return{mode:`variants`,model:t.chosen,rows:wA(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 EA=(e,t)=>({...e,query:t,active:0}),DA=(e,t)=>({providerID:e.providerID,modelID:e.modelID,...t?{variant:t}:{}});function OA(e,t,n){let r=TA(e,t);if(r.mode===`variants`)return n<0||n>=r.rows.length?{state:t}:{state:t,pick:DA(r.model,r.rows[n])};let i=r.rows[n];return i?wA(i).length>1?{state:{...t,chosen:i,active:0}}:{state:t,pick:DA(i)}:{state:t}}function kA(e,t,n,{inSearch:r}){let i=TA(e,t).rows.length;if(n===`ArrowDown`||n===`ArrowUp`)return{state:{...t,active:Math.max(0,$b(t.active,n===`ArrowDown`?1:-1,i))},handled:!0};if(n===`Enter`)return{...OA(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}:{...OA(e,t,r),handled:!0}}return{state:t,handled:!1}}var AA=(e,t)=>({[e]:t}),jA=J(`<div>`),MA=J(`<p class="error small"role=alert>Couldn't load models: `),NA=J(`<p class="muted small">Loading models…`),PA=J(`<input type=search class=picker-search placeholder="Search models"aria-label="Search models"autofocus>`),FA=J(`<p class="muted small"role=status>`),IA=J(`<ul class=picker-list role=listbox aria-label=Models>`),LA=J(`<li class="muted small">No models match.`),RA=J(`<div class="picker-group muted small">`),zA=J(`<span class="po-id muted">variants ›`),BA=J(`<span class=po-mark>✓`),VA=J(`<kbd>`),HA=J(`<li><button type=button role=option><span class=po-name></span><span class="po-id muted">`),UA=J(`<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>`),WA=J(`<li><button type=button role=option><span class=po-name></span><kbd>`);function GA(e,t){let n=e?.prefs[t]??e?.defaults[t];return n?`${n.modelID}${n.variant?` · ${n.variant}`:``}`:`default`}function KA(e){let[t,n]=x(),[r,i]=x(``),[a,o]=x();return{prefs:t,error:r,load:async()=>{try{n(await B(`${P(e())}/model-prefs`)),i(``)}catch(e){i(W(e))}},loadCatalog:async()=>{if(a())return a();let{models:t}=await B(`${P(e())}/models`),n=new Pt(t);return o(n),n},save:async(t,r)=>{try{n(await(await G(`${P(e())}/model-prefs`,{method:`PUT`,json:AA(t,r)})).json()),q(`${t===`voice`?`Voice`:`Worker`} model applies to the next ${t===`voice`?`turn`:`task`}.`)}catch(e){q(`Couldn't set the ${t===`voice`?`Voice`:`Worker`} model: ${W(e)}`,`err`)}}}}function qA(e){let[t,r]=x(CA()),[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(CA()),c(``),e.models.loadCatalog().then(a,e=>c(W(e)))},m=T(()=>i()?TA(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(OA(i(),t(),e)),v=e=>{if(!i()||e.altKey||e.ctrlKey||e.metaKey)return;let n=kA(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(Re,{get open(){return l()},get title(){return`${e.kind===`voice`?`Voice`:`Worker`} model`},get onClose(){return e.onClose},class:`picker`,get children(){var e=jA();return e.$$keydown=v,L(e,n(u,{get when(){return!s()},get fallback(){return(()=>{var e=MA();return e.firstChild,L(e,s,null),e})()},get children(){return n(u,{get when(){return m()},get fallback(){return NA()},children:e=>n(u,{get when(){return H(()=>e().mode===`models`)()&&e()},get fallback(){return n(JA,{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=PA();return e.$$input=e=>r(t=>EA(t,e.currentTarget.value)),D(()=>e.value=t().query),e})(),(()=>{var t=FA();return L(t,(()=>{var t=H(()=>e().total===1);return()=>t()?`1 model`:`${e().total} models`})(),null),L(t,(()=>{var t=H(()=>!!e().more);return()=>t()?` · showing ${e().rows.length}, search to narrow`:``})(),null),t})(),(()=>{var r=IA();return L(r,n(o,{get each(){return e().rows},get fallback(){return LA()},children:(r,i)=>(()=>{var a=HA(),o=a.firstChild,s=o.firstChild,c=s.nextSibling;return L(a,n(u,{get when(){return i()===0||e().rows[i()-1].group!==r.group},get children(){var e=RA();return L(e,()=>r.group),e}}),o),o.$$click=()=>_(i()),L(s,()=>r.name||r.modelID),L(c,()=>r.modelID),L(o,n(u,{get when(){return(r.variants??[]).some(e=>e!=="default")},get children(){return zA()}}),null),L(o,n(u,{get when(){return f(r)},get children(){return BA()}}),null),L(o,n(u,{get when(){return i()<9},get children(){var e=VA();return L(e,()=>i()+1),e}}),null),D(e=>{var n=`picker-opt${t().active===i()?` active`:``}`,a=f(r);return n!==e.e&&K(o,e.e=n),a!==e.t&&R(o,`aria-selected`,e.t=a),e},{e:void 0,t:void 0}),a})()})),r})()]})})}})),e}})}function JA(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=UA(),a=i.firstChild,s=a.firstChild,c=s.nextSibling;c.firstChild;var l=a.nextSibling;return Oe(s,`click`,e.onBack,!0),L(c,()=>e.view.model.name||e.view.model.modelID,null),L(l,n(o,{get each(){return e.view.rows},children:(i,a)=>(()=>{var o=WA(),s=o.firstChild,c=s.firstChild,l=c.nextSibling;return s.$$click=()=>e.onPick(a()),he(e=>a()===0&&(t=e),s),L(c,i??`Default`),L(s,n(u,{get when(){return H(()=>!!r())()&&e.current?.variant===i},get children(){return BA()}}),l),L(l,()=>a()+1),D(t=>{var n=`picker-opt${e.active===a()?` active`:``}`,o=r()&&e.current?.variant===i;return n!==t.e&&K(s,t.e=n),o!==t.t&&R(s,`aria-selected`,t.t=o),t},{e:void 0,t:void 0}),o})()})),i})()}F([`keydown`,`input`,`click`]);var YA=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;function XA(e){let t=[],n=0,r=0,i=!1;for(let a of String(e??``).replace(/\r\n?/g,`
|
|
21
|
+
`).split(`
|
|
22
|
+
`)){let e=YA.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 ZA=new Set([`user`,`launch`,`self`,`prompt`,`title`]),QA=e=>`/api/agent/sessions/${encodeURIComponent(e)}/intent`,$A=e=>e.replace(/\s+/g,` `).trim();function ej(e){let t=Array.from($A(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 tj=(e,t)=>({text:e===null?null:$A(e),expectedRevision:t});function nj(e){if(e?.source===`user`)return{text:null,expectedRevision:e.revision};if(e?.source===`prompt`)return{source:`prompt`,text:null,expectedRevision:e.revision}}function rj(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 ij(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`||!ZA.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 aj(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 oj(e,t,n){return e.type===`intent`&&e.sessionID===t&&e.revision!==n}var sj=J(`<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`),cj=J(`<div class=intent-field>`),lj=J(`<button type=button class="btn small">Retry`),uj=J(`<button type=button class="btn small">Clear`),dj=J(`<div class=row><button type=button class="btn small">Edit`),fj=J(`<p class="muted small intent-error">Could not load the intent.`),pj=J(`<p class="muted small">Loading…`),mj=J(`<p class="muted small">No intent yet.`),hj=J(`<p class="small intent-text">`),gj=J(`<p class="muted small">`),_j=J(`<p class=field-error>`);function vj(t){let[r,{refetch:i,mutate:a}]=f(()=>t.sessionID,async e=>ij(await B(QA(e)))),[o,s]=x(!1),[c,l]=x(``),[d,p]=x(!1),[m,h]=x(``),g=()=>ej(c()),_=()=>r.error?void 0:r.loading?r.latest:r();j(Ol(e=>{!o()&&oj(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?nj(_()):tj(n,_()?.revision??0);if(o){p(!0),h(``);try{let e=ij(await(await G(QA(t.sessionID),{method:`PUT`,json:o})).json());r.error?i():a(e),s(!1)}catch(t){let n=aj(t instanceof e?{status:t.status,...t.code?{code:t.code}:{},message:t.message}:{message:W(t)},{loaded:!r.error});h(n.text),n.reload&&(s(!1),i())}finally{p(!1)}}};return(()=>{var e=cj();return L(e,n(u,{get when(){return o()},get fallback(){return[n(u,{get when(){return!r.error},get fallback(){return fj()},get children(){return n(u,{get when(){return!r.loading||_()},get fallback(){return pj()},get children(){return n(u,{get when(){return _()},get fallback(){return mj()},children:e=>[(()=>{var t=hj();return L(t,()=>e().text),t})(),(()=>{var t=gj();return L(t,()=>rj(e())),t})()]})}})}}),(()=>{var e=dj(),t=e.firstChild;return t.$$click=v,L(e,n(u,{get when(){return r.error},get children(){var e=lj();return e.$$click=()=>void i(),e}}),null),L(e,n(u,{get when(){return nj(_())},get children(){var e=uj();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&&R(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=sj(),r=e.firstChild,i=r.nextSibling,a=i.nextSibling,o=a.firstChild,f=o.nextSibling;return he(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),R(i,`maxlength`,560),L(e,n(u,{get when(){return H(()=>!!c())()&&g()},children:e=>(()=>{var t=_j();return L(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&&R(r,`for`,e.e=n),a!==e.t&&R(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),L(e,n(u,{get when(){return m()},children:e=>(()=>{var t=_j();return L(t,e),t})()}),null),e})()}F([`input`,`keydown`,`click`]);var yj=J(`<section><h3><button type=button class=card-toggle><span>`),bj=J(`<ul class=job-list>`),xj=J(`<ul class=mcp-list>`),Sj=J(`<aside class=rail aria-label="Session details"><div class=rail-head><span class=rail-title>Details`),Cj=J(`<p class="rail-error small"><strong>`),wj=J(`<p class="muted small">`),Tj=J(`<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>`),Ej=J(`<span class=muted>`),Dj=J(`<p class="small retry-note">`),Oj=J(`<li><span aria-hidden=true></span><span class="job-command mono"></span><span class="muted small">`),kj=J(`<div class=meter role=meter aria-valuemin=0 aria-valuemax=100 aria-label="Context used"><span>`),Aj=J(`<p class=small><strong></strong><span class=muted> `),jj=J(`<li><span aria-hidden=true></span><span class=mcp-name></span><span class="muted small">`),Mj=J(`<span class=diffstat><span class=add>+</span> <span class=del>−`),Nj=J(`<ul class=file-list>`),Pj=J(`<p class="muted small">No changes.`),Fj=J(`<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>−`),Ij=J(`<p class="muted small more-files">+<!> more <!> (only the most-changed files are listed)`),Lj=J(`<table class=diff><tbody>`),Rj=J(`<p class="muted small pad">The diff is too large to show completely (512 KB).`),zj=J(`<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>`),Bj=J(`<option>`),Vj=J(`<p class="muted small pad">Loading diff…`),Hj=J(`<p class="muted small pad">`),Uj=J(`<p class="muted small pad">No textual changes (binary file, or a rename).`),Wj=J(`<tr><td class=ln></td><td class=ln></td><td class=code-line><span class=sign>`),Gj=e=>e.truncated&&e.totalFiles?Math.max(0,e.totalFiles-e.files.length):0,[Kj,qj]=x(lb(localStorage));function Jj(e){let t=()=>!Kj().has(e.id);return(()=>{var r=yj(),i=r.firstChild,a=i.firstChild,o=a.firstChild;return a.$$click=()=>qj(ub(localStorage,e.id)),L(a,n(U,{name:`chevron`,class:`card-chevron`}),o),L(o,()=>e.title),L(i,()=>e.extra,null),L(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&&K(r,n.e=i),o!==n.t&&R(r,`aria-label`,n.t=o),s!==n.a&&R(r,`id`,n.a=s),c!==n.o&&R(r,`data-card`,n.o=c),l!==n.i&&R(a,`aria-expanded`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),r})()}var Yj=e=>e>=1e3?`${(e/1e3).toFixed(e>=1e5?0:1)}k`:String(e);function Xj(e){let t=()=>e.found?.session,r=()=>t()?.open?t()?.terminal?.source===`herdr`?`herdr`:`tui`:`background`,i=()=>Oa(t()?.status,I()),a=()=>i().filter(e=>e.status===`running`).length,s=()=>t()?.state===`working`||t()?.status?.some(e=>e.state===`working`)?Ma(t()?.status,t()?.id,Pe()):void 0,c=()=>Ca(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=Sj(),f=d.firstChild;return f.firstChild,L(f,n(z,{icon:`close`,label:`Close details`,get onClick(){return e.onClose}}),null),L(d,n(u,{get when(){return c()},children:e=>(()=>{var n=Cj(),r=n.firstChild;return L(r,()=>e().label),L(n,(()=>{var t=H(()=>!!e().status);return()=>t()?` · ${e().status}`:``})(),null),L(n,(()=>{var n=H(()=>!!(e().title&&e().sessionID!==t()?.id));return()=>n()?` · ${e().title}`:``})(),null),D(()=>R(n,`title`,e().text)),n})()}),null),L(d,n(Jj,{id:`environment`,title:`Environment`,get children(){return n(u,{get when(){return e.found},get fallback(){return(()=>{var e=wj();return L(e,()=>Y.machines?`Not reported by any connected machine.`:`Loading…`),e})()},children:i=>(()=>{var a=Tj(),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 L(o,()=>i().machine.name,c),L(l,(()=>{var e=H(()=>Y.connection!==`live`);return()=>e()?`Connecting`:i().machine.online?`online`:`offline`})(),null),L(u,()=>ve(e.summary?.directory??i().session.directory)),L(p,()=>e.summary?.directory??i().session.directory),L(d,n(z,{icon:`copy`,label:`Copy the directory`,onClick:()=>{let t=e.summary?.directory??i().session.directory;navigator.clipboard.writeText(t).then(()=>q(`Directory copied`),()=>q(`Could not copy the directory`,`err`))}}),null),L(m,()=>e.summary?.branch??(()=>{var t=Ej();return L(t,()=>e.loading?`…`:`—`),t})()),L(h,()=>Me[r()],null),L(h,(()=>{var e=H(()=>!!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&&K(s,t.e=n),r!==t.t&&R(u,`title`,t.t=r),a!==t.a&&R(f,`title`,t.a=a),t},{e:void 0,t:void 0,a:void 0}),a})()})}}),null),L(d,n(u,{get when(){return t()?.id},children:e=>n(Jj,{id:`intent`,title:`Intent`,label:`Session intent`,get children(){return n(vj,{get sessionID(){return e()}})}})}),null),L(d,n(u,{get when(){return i().length||s()},get children(){return n(Jj,{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=Dj();return L(t,e),t})()}),(()=>{var e=bj();return L(e,n(o,{get each(){return i()},children:e=>(()=>{var n=Oj(),r=n.firstChild,i=r.nextSibling,a=i.nextSibling;return L(i,()=>e.command??e.id),L(a,()=>Aa(e,I()),null),L(a,(()=>{var n=H(()=>!!(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&&K(n,t.e=i),a!==t.t&&R(n,`title`,t.t=a),o!==t.a&&K(r,t.a=o),t},{e:void 0,t:void 0,a:void 0}),n})()})),e})()]}})}}),null),L(d,n(Jj,{id:`context`,title:`Context`,get children(){return n(u,{get when(){return e.summary?.context},get fallback(){return(()=>{var t=wj();return L(t,()=>e.loading?`Loading…`:`No usage reported yet.`),t})()},children:e=>[(()=>{var t=kj(),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&&R(t,`aria-valuenow`,r.e=i),a!==r.t&&xe(n,`width`,r.t=a),o!==r.a&&K(n,r.a=o),r},{e:void 0,t:void 0,a:void 0}),t})(),(()=>{var t=Aj(),n=t.firstChild,r=n.nextSibling;return r.firstChild,L(n,(()=>{var t=H(()=>e().percent!==void 0);return()=>t()?`${e().percent}%`:Yj(e().used)})()),L(r,(()=>{var t=H(()=>!!e().limit);return()=>t()?`${Yj(e().used)} / ${Yj(e().limit)} tokens`:`tokens`})(),null),L(r,(()=>{var t=H(()=>!!e().model);return()=>t()?` · ${e().model}`:``})(),null),t})()]})}}),null),L(d,n(Jj,{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=wj();return L(t,()=>e.loading?`Loading…`:`No MCP servers.`),t})()},get children(){var t=xj();return L(t,n(o,{get each(){return e.summary.mcp},children:e=>(()=>{var t=jj(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling;return L(r,()=>e.name),L(i,()=>e.status.replace(`_`,` `)),D(r=>{var i=e.error??e.status,a=`mcp-dot ${e.status}`;return i!==r.e&&R(t,`title`,r.e=i),a!==r.t&&K(n,r.t=a),r},{e:void 0,t:void 0}),t})()})),t}})}}),null),L(d,n(Jj,{id:`changes`,title:`Changes`,domID:`rail-changes`,get extra(){return n(u,{get when(){return e.summary?.changes},children:e=>(()=>{var t=Mj(),n=t.firstChild;n.firstChild;var r=n.nextSibling.nextSibling;return r.firstChild,L(n,()=>e().additions,null),L(r,()=>e().deletions,null),t})()})},get children(){return n(u,{get when(){return e.summary?.changes},get fallback(){return(()=>{var t=wj();return L(t,(()=>{var t=H(()=>!!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 Pj()},get children(){return[(()=>{var r=Nj();return L(r,n(o,{get each(){return t().files},children:t=>(()=>{var n=Fj(),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),L(i,()=>t.status[0].toUpperCase()),L(o,()=>t.file),L(s,()=>t.additions,null),L(c,()=>t.deletions,null),D(e=>{var n=t.file,a=`file-status ${t.status}`;return n!==e.e&&R(r,`title`,e.e=n),a!==e.t&&K(i,e.t=a),e},{e:void 0,t:void 0}),n})()})),r})(),n(u,{get when(){return Gj(t())},children:e=>(()=>{var t=Ij(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,L(t,e,n),L(t,()=>e()===1?`file`:`files`,r),t})()})]}})})}}),null),d})()}function Zj(e){let[t]=f(()=>e.file,async t=>B(`${P(e.sessionID)}/diff?file=${V(t)}`)),[r,i]=x(!1);return(()=>{var a=zj(),s=a.firstChild,c=s.firstChild,l=c.nextSibling,d=l.firstChild,f=s.nextSibling;return L(s,n(U,{name:`diff`}),c),c.addEventListener(`change`,t=>e.onFile(t.currentTarget.value)),L(c,n(o,{get each(){return e.files},children:e=>(()=>{var t=Bj();return t.value=e,L(t,e),t})()})),L(s,n(u,{get when(){return t()},children:e=>(()=>{var t=Mj(),n=t.firstChild;n.firstChild;var r=n.nextSibling.nextSibling;return r.firstChild,L(n,()=>e().additions,null),L(r,()=>e().deletions,null),t})()}),l),d.addEventListener(`change`,e=>i(e.currentTarget.checked)),L(s,n(z,{icon:`close`,label:`Close diff`,get onClick(){return e.onClose}}),null),L(f,n(u,{get when(){return!t.loading},get fallback(){return Vj()},get children(){return n(u,{get when(){return!t.error},get fallback(){return(()=>{var e=Hj();return L(e,(()=>{var e=H(()=>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 Uj()},get children(){return[(()=>{var e=Lj(),r=e.firstChild;return L(r,n(o,{get each(){return XA(t().patch).filter(e=>e.type!==`meta`)},children:e=>(()=>{var t=Wj(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling,a=i.firstChild;return L(n,()=>e.oldNo??``),L(r,()=>e.newNo??``),L(a,(()=>{var t=H(()=>e.type===`add`);return()=>t()?`+`:e.type===`del`?`−`:` `})()),L(i,()=>e.text,null),D(()=>K(t,e.type)),t})()})),e})(),n(u,{get when(){return t().truncated},get children(){return Rj()}})]}})}})}})),D(t=>{var n=`Changes in ${e.file}`,i=`diff-body${r()?` wrap`:``}`;return n!==t.e&&R(a,`aria-label`,t.e=n),i!==t.t&&K(f,t.t=i),t},{e:void 0,t:void 0}),D(()=>c.value=e.file),D(()=>d.checked=r()),a})()}F([`click`]);function Qj(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 $j(e,t){return e&&(e.type===`number`||e.type===`integer`)&&typeof t==`string`&&t.trim()?Number(t):typeof t==`string`?t.trim():t}function eM(e,t){let n=new Map(e.map(e=>[e.key,e]));return e.filter(e=>(e.when??[]).every(e=>{let r=$j(n.get(e.key),t[e.key])===e.value;return e.op===`eq`?r:!r}))}var tM=e=>typeof e==`string`?e.trim():``;function nM(e,t){let n={};for(let r of eM(e,t)){let e=rM(r,t[r.key]);e&&(n[r.key]=e)}return n}function rM(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=tM(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=tM(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 iM(e,t){let n={};for(let r of eM(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=tM(e);if(!t)continue;n[r.key]=r.type===`number`||r.type===`integer`?Number(t):t}}}return n}var aM=J(`<p class="muted small"data-answer-unavailable> can't take this answer from the hub; answer it in the terminal.`),oM=J(`<p class="blocker-recommendation small"data-recommendation>`),sM=J(`<p class=blocker-text>`),cM=J(`<div role=group><p class=blocker-head><strong>`),lM=J(`<p class="muted small">This question has nothing to fill in here; answer it in the terminal.`),uM=J(`<p class="answered-by small muted"data-answered-by>`),dM=J(`<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`),fM=J(`<form class=form-card novalidate><fieldset><div class=row><button type=submit class="btn small primary"></button><button type=button class="btn small">Dismiss`),pM=J(`<p class="field-error small"role=alert>`),mM=J(`<div>`),hM=J(`<span class=field-title>`),gM=J(`<span class="field-desc muted small">`),_M=J(`<a class="btn small"target=_blank rel="noopener noreferrer">Open link`),vM=J(`<label class=check><input type=checkbox>`),yM=J(`<input type=text placeholder="Other (comma separated)">`),bM=J(`<div role=group class=choice-group>`),xM=J(`<input type=text placeholder="Type your own answer">`),SM=J(`<div role=radiogroup class=choice-group>`),CM=J(`<label class=text-field>`),wM=J(`<input type=text>`),TM=J(`<span class="muted small"> — `),EM=J(`<label class=choice><input type=checkbox><span>`),DM=J(`<label class=choice><input type=radio><span>`);function OM(t,n){return!(t instanceof e)||t.status!==409||t.code!==`gone`?!1:(q(`Already answered or expired`),n(),!0)}function kM(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=cM(),s=t.firstChild,c=s.firstChild;return L(c,(()=>{var e=H(()=>i().kind===`permission`);return()=>e()?`Permission`:i().question?`Question`:`Form`})()),L(s,a,null),L(t,n(ee,{get fallback(){return lM()},get children(){return[n(A,{get when(){return e.canAnswer===!1},get children(){return[n(th,{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=aM(),n=t.firstChild;return L(t,()=>e.harnessName??`This harness`,n),t})()]}}),n(A,{get when(){return i().kind===`permission`},get children(){return[n(th,{class:`blocker-text mono`,get text(){return i().summary},what:`the request`,reveal:!0}),n(u,{get when(){return Jr(i().recommendation,Fl)},get children(){var e=oM();return L(e,()=>Jr(i().recommendation,Fl)),e}}),n(AM,{get sessionID(){return e.sessionID},get blocker(){return i()},onGone:()=>r(!0)})]}}),n(A,{get when(){return H(()=>i().kind===`form`)()&&i().fields?.length},get children(){return[n(u,{get when(){return!i().question||i().summary!==`Questions`},get children(){var e=sM();return L(e,()=>i().summary),e}}),n(jM,{get sessionID(){return e.sessionID},get blocker(){return i()},get fields(){return i().fields},onGone:()=>r(!0)})]}})]}}),null),L(t,n(u,{get when(){return zr(bl(),i().id,Fl,El)},children:e=>(()=>{var t=uM();return L(t,()=>e().text),D(()=>R(t,`title`,e().title)),t})()}),null),D(e=>{var n=`card blocker ${i().kind}`,r=`${o()}: ${i().summary}`;return n!==e.e&&K(t,e.e=n),r!==e.t&&R(t,`aria-label`,e.t=r),e},{e:void 0,t:void 0}),t}})}function AM(e){let[t,n]=x(!1),r=async t=>{n(!0);try{await G(`${P(e.sessionID)}/permission`,{method:`POST`,json:{requestID:e.blocker.id,decision:t}}),q(t===`reject`?`Denied`:`Allowed`)}catch(t){OM(t,e.onGone)||q(Ak(t)??W(t),`err`),n(!1)}};return(()=>{var e=dM(),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 jM(e){let[t,r]=x(Qj(e.fields)),[i,a]=x({}),[s,c]=x(!1),[l,d]=x(!1),f=T((n=[])=>{let r=eM(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 G(`${P(e.sessionID)}/form`,{method:`POST`,json:{formID:e.blocker.id,...t}}),d(!0),q(n)}catch(t){OM(t,e.onGone)||q(Ak(t)??W(t),`err`),c(!1)}},g=n=>{n.preventDefault();let r=nM(e.fields,t());if(a(r),Object.keys(r).length)return;let i=iM(e.fields,t());e.blocker.question&&!Object.values(i).some(e=>Array.isArray(e)?e.length>0:e!==``&&e!==!1)?q(`Pick or type an answer first (Dismiss skips the questions)`,`err`):h({answer:i},`Answer sent`)},_=()=>s()||l();return(()=>{var r=fM(),a=r.firstChild,s=a.firstChild,c=s.firstChild,d=c.nextSibling;return r.addEventListener(`submit`,g),L(a,n(o,{get each(){return f()},children:r=>n(u,{get when(){return p(r)},children:a=>(()=>{var o=mM();return R(o,`data-key`,r),L(o,n(MM,{get field(){return a()},get value(){return t()[r]},onChange:e=>m(r,e),get formID(){return e.blocker.id}}),null),L(o,n(u,{get when(){return i()[r]},get children(){var e=pM();return L(e,()=>i()[r]),e}}),null),D(()=>K(o,`form-field ${a().type}`)),o})()})}),s),L(c,()=>l()?`Sent`:`Submit`),d.$$click=()=>void h({cancel:!0},`Dismissed`),D(()=>a.disabled=_()),r})()}function MM(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=hM();return L(e,i,null),L(e,()=>t().required?` *`:``,null),e})(),n(u,{get when(){return t().description},get children(){var e=gM();return L(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=_M();return D(()=>R(e,`href`,t().url)),e})()]}}),n(A,{get when(){return t().type===`boolean`},get children(){var t=vM(),r=t.firstChild;return r.addEventListener(`change`,t=>e.onChange(t.currentTarget.checked)),L(t,n(l,{}),null),D(()=>r.checked=e.value===!0),t}}),n(A,{get when(){return t().type===`multiselect`},get children(){var r=bM();return L(r,n(l,{}),null),L(r,n(o,{get each(){return t().options??[]},children:t=>(()=>{var r=EM(),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))),L(a,()=>t.label),L(r,n(u,{get when(){return t.description},get children(){var e=TM();return e.firstChild,L(e,()=>t.description,null),e}}),null),D(()=>i.checked=s().includes(t.value)),r})()}),null),L(r,n(u,{get when(){return t().custom},get children(){var t=yM();return t.addEventListener(`change`,t=>e.onChange([...s().filter(e=>c().has(e)),...t.currentTarget.value.split(`,`).map(e=>e.trim()).filter(Boolean)])),D(()=>R(t,`aria-label`,`${i()}: other`)),D(()=>t.value=s().filter(e=>!c().has(e)).join(`, `)),t}}),null),D(()=>R(r,`aria-label`,i())),r}}),n(A,{get when(){return H(()=>t().type===`string`)()&&t().options?.length},get children(){var s=SM();return L(s,n(l,{}),null),L(s,n(o,{get each(){return t().options??[]},children:t=>(()=>{var i=DM(),o=i.firstChild,s=o.nextSibling;return o.addEventListener(`change`,()=>e.onChange(t.value)),L(s,()=>t.label),L(i,n(u,{get when(){return t.description},get children(){var e=TM();return e.firstChild,L(e,()=>t.description,null),e}}),null),D(()=>R(o,`name`,r())),D(()=>o.checked=a()===t.value),i})()}),null),L(s,n(u,{get when(){return t().custom},get children(){var t=xM();return t.$$input=t=>e.onChange(t.currentTarget.value),D(()=>R(t,`aria-label`,`${i()}: your own answer`)),D(()=>t.value=c().has(a())?``:a()),t}}),null),D(()=>R(s,`aria-label`,i())),s}}),n(A,{when:!0,get children(){return[(()=>{var e=CM();return L(e,n(l,{})),D(()=>R(e,`for`,r())),e})(),(()=>{var n=wM();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&&R(n,`id`,e.e=i),a!==e.t&&R(n,`inputmode`,e.t=a),o!==e.a&&R(n,`placeholder`,e.a=o),e},{e:void 0,t:void 0,a:void 0}),D(()=>n.value=a()),n})()]}})]}})}F([`click`,`input`]);var NM=/^(\s{0,3})(`{3,}|~{3,})\s*([^\s`]*)/,PM=/^\s{0,3}(#{1,6})(?:\s+(.*))?$/,FM=/^\s{0,3}(={2,}|-{3,})\s*$/,IM=/^\s{0,3}([-*_])(\s*\1){2,}\s*$/,LM=/^\s{0,3}>\s?(.*)$/,RM=/^(\s*)([-*+]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/,zM=/^\[([ xX])\](?:\s+(.*))?$/,BM=/^:?-+:?$/,VM=e=>e.length-e.trimStart().length,HM=(e,t)=>e.slice(Math.min(t,VM(e))),UM=e=>NM.test(e),WM=e=>UM(e)||PM.test(e)||IM.test(e)||LM.test(e)||RM.test(e);function GM(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=KM(n,{streaming:r},!0).blocks;return $M(i,r?QM(i):void 0)}function KM(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=NM.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(HM(e[o],t.length))}r.push({type:`code`,lang:u[3]??``,text:i.join(`
|
|
26
|
+
`)});continue}if(i.length){let e=FM.exec(s);if(e){r.push({type:`heading`,level:e[1][0]===`=`?1:2,text:i.join(`
|
|
27
|
+
`)}),i=[];continue}}let d=PM.exec(s);if(d){l(),c(),r.push({type:`heading`,level:d[1].length,text:(d[2]??``).replace(/(^|\s+)#+\s*$/,``).trim()});continue}if(IM.test(s)){l(),c(),r.push({type:`rule`});continue}let f=ZM(e,o,t.streaming&&n);if(f){l(),c(),r.push(f.block),o=f.end-1;continue}if(LM.test(s)){l(),c();let i=[],a=o;for(;a<e.length;a++){let t=LM.exec(e[a]);if(t)i.push(t[1]);else if(e[a].trim()&&i.at(-1)?.trim()&&!WM(e[a]))i.push(e[a]);else break}r.push({type:`quote`,blocks:KM(i,t,n&&a===e.length).blocks}),o=a-1;continue}let p=RM.exec(s);if(p&&(!i.length||qM(p[2]))){l(),c();let i=JM(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 qM=e=>!/\d/.test(e)||/^0*1[.)]$/.test(e);function JM(e,t,n,r){let i=RM.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=RM.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=NM.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=VM(t),r;if(r=m?!0:_?n>=Math.min(f,i+2):n>=f?!0:RM.test(t)?n>=i+2:n>i||!WM(t)&&!UM(p.at(-1)),!r)break;for(;_;_--)p.push(``);let a=HM(t,f);p.push(a),h(a)}l=_>0;let v=zM.exec(p[0]),y=KM(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 YM(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 XM=e=>{let t=e.trim(),n=t.startsWith(`:`),r=t.length>1&&t.endsWith(`:`);return n&&r?`center`:r?`right`:n?`left`:null};function ZM(e,t,n){let r=e[t];if(!r.includes(`|`))return;let i=YM(r),a=e[t+1],o;if(a!==void 0){let r=YM(a),s=t+1===e.length-1;r.length===i.length&&r.every(e=>BM.test(e))?o=r.map(XM):s&&/^[\s|:-]*$/.test(a)&&(a.includes(`-`)||n)&&a.includes(`|`)&&r.length<=i.length&&(o=i.map((e,t)=>r[t]&&BM.test(r[t])?XM(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(`|`)||UM(t)||LM.test(t)||PM.test(t))break;s.push(YM(t).slice(0,i.length))}return{block:{type:`table`,align:o,head:i,rows:s},end:Math.min(c,e.length)}}function QM(e){let t=e.at(-1);if(t){if(t.type===`paragraph`||t.type===`heading`)return{node:t};if(t.type===`quote`)return QM(t.blocks);if(t.type===`list`)return QM(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 $M(e,t){let n=e=>t?.node===e;return e.map(e=>{switch(e.type){case`paragraph`:return{type:`paragraph`,children:pN(e.text,{streaming:n(e)})};case`heading`:return{type:`heading`,level:e.level,children:pN(e.text,{streaming:n(e)})};case`quote`:return{type:`quote`,blocks:$M(e.blocks,t)};case`list`:return{...e,items:e.items.map(e=>({...e.checked===void 0?{}:{checked:e.checked},blocks:$M(e.blocks,t)}))};case`table`:{let r=(r,i,a)=>pN(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 eN(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 tN=/[!-/:-@[-`{-~]/,nN=/\s/,rN=/[\p{L}\p{N}_]/u,iN={"**":`strong`,__:`strong`,"~~":`del`,"==":`mark`},aN=(e,t,n)=>{let r=0;for(;e[t+r]===n;)r++;return r};function oN(e,t,n){for(let r=t;r<e.length;r++){if(e[r]!=="`")continue;let t=aN(e,r,"`");if(t===n)return r;r+=t-1}return-1}function sN(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=aN(e,i,"`"),n=oN(e,i+t,t);i=(n>=0?n:i)+t-1}else if(e.startsWith(n,i)&&r(i))return i}return-1}function cN(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=aN(e,r,"`"),n=oN(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 lN(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 uN(e){let t=e.trim();return t.startsWith(`<`)?t.slice(1,t.indexOf(`>`)>0?t.indexOf(`>`):void 0):t.split(/\s+/)[0]??``}var dN=e=>e.map(e=>e.type===`text`||e.type===`code`?e.text:e.type===`image`?e.alt:e.type===`br`?` `:dN(e.children)).join(``);function fN(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 pN(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&&tN.test(i)){a+=i,s+=2;continue}}if(e===`
|
|
30
|
+
`){a=a.replace(/ +$/,``),o({type:`br`}),s++;continue}if(e==="`"){let e=aN(n,s,"`"),t=oN(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=iN[c];if(l&&i!==void 0&&n[s+2]!==void 0&&!nN.test(n[s+2])&&n[s+2]!==e&&(e!==`_`||s===0||!rN.test(n[s-1]))){let i=sN(n,s+3,c,t=>!nN.test(n[t-1])&&(e!==`_`||!rN.test(n[t+2]??``)));if(i>0||r){o({type:l,children:pN(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&&!nN.test(i)&&(e===`*`||s===0||!rN.test(n[s-1]))){let i=sN(n,s+1,e,t=>n[t+1]===e||n[t-1]===e?!1:!nN.test(n[t-1])&&(e!==`_`||!rN.test(n[t+1]??``)));if(i>s+1||r){o({type:`em`,children:pN(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=cN(n,e);if(i>0&&n[i+1]===`(`){let a=lN(n,i+2),c=pN(n.slice(e+1,i),{inLink:!0});if(a>0){let e=eN(uN(n.slice(i+2,a)));u?o({type:`image`,alt:dN(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:dN(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=eN(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=fN(n,s),t=e&&eN(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 mN=`modulepreload`,hN=function(e){return`/`+e},gN={},_N=function(e){return e.pathname.endsWith(`.css`)},vN=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},yN=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=hN(t,n);let r=s(t),i=_N(r);return vN(gN,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`:mN,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)})},bN=J(`<br>`),xN=J(`<code class=inline-code>`),SN=J(`<a rel="noopener noreferrer">`),CN=J(`<a class=md-image target=_blank rel="noopener noreferrer"title="Image (opens in a new tab)">`),wN=J(`<span class=md-image>`),TN=J(`<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>`),EN=J(`<span>`),DN=J(`<hr>`),ON=J(`<p>`),kN=J(`<input type=checkbox disabled>`),AN=J(`<li>`),jN=J(`<blockquote>`),MN=J(`<div class=table-wrap><table><thead><tr></tr></thead><tbody>`),NN=J(`<th>`),PN=J(`<tr>`),FN=J(`<td>`),IN=J(`<div class=md>`),[LN,RN]=x(),zN=!1;function BN(){zN||(zN=!0,yN(()=>import(`./highlight-y4rJE6Tt.js`).then(e=>RN({run:e.highlight,languageOf:e.languageOf}),()=>zN=!1),[]))}var VN=65536;function HN(e,t){BN();let n=LN();return!n||!e||t.length>VN||!n.languageOf(e)?[{text:t}]:n.run(t,e)}function UN(e){return n(Ue,{get each(){return e.nodes},children:e=>n(ee,{get children(){return[n(A,{get when(){return H(()=>e().type===`text`)()&&e()},children:e=>H(()=>e().text)}),n(A,{get when(){return e().type===`br`},get children(){return bN()}}),n(A,{get when(){return H(()=>e().type===`code`)()&&e()},children:e=>(()=>{var t=xN();return L(t,()=>e().text),t})()}),n(A,{get when(){return H(()=>e().type===`link`)()&&e()},children:e=>(()=>{var t=SN();return L(t,n(UN,{get nodes(){return e().children}})),D(n=>{var r=e().href,i=e().href.startsWith(`/`)?void 0:`_blank`;return r!==n.e&&R(t,`href`,n.e=r),i!==n.t&&R(t,`target`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(A,{get when(){return H(()=>e().type===`image`)()&&e()},children:e=>n(u,{get when(){return e().href},get fallback(){return(()=>{var t=wN();return L(t,()=>e().alt||`image`),t})()},get children(){var t=CN();return L(t,()=>e().alt||`image`),D(()=>R(t,`href`,e().href)),t}})}),n(A,{get when(){return H(()=>`children`in e())()&&e()},children:e=>n(Le,{get component(){return{strong:`strong`,em:`em`,del:`del`,mark:`mark`}[e().type]??`span`},get children(){return n(UN,{get nodes(){return e().children}})}})})]}})})}async function WN(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 GN(e){let[t,r]=x(!1),[i,a]=x(!1),o;j(()=>clearTimeout(o)),BN();let s=T(()=>{let t=LN();return!t||!e.lang||e.text.length>VN||!t.languageOf(e.lang)?[{text:e.text}]:t.run(e.text,e.lang)}),c=()=>e.lang||`text`;return(()=>{var l=TN(),d=l.firstChild,f=d.firstChild,p=f.nextSibling,m=p.nextSibling,h=d.nextSibling,g=h.firstChild;return L(f,c),p.$$click=()=>a(!i()),L(p,()=>i()?`No wrap`:`Wrap`),m.$$click=async()=>{await WN(e.text)&&(r(!0),clearTimeout(o),o=setTimeout(()=>r(!1),1500))},L(m,()=>t()?`Copied`:`Copy`),L(g,n(Ue,{get each(){return s()},children:e=>n(u,{get when(){return e().kind},get fallback(){return e().text},get children(){var t=EN();return L(t,()=>e().text),D(()=>K(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&&K(l,n.e=r),a!==n.t&&R(p,`aria-pressed`,n.t=a),o!==n.a&&R(p,`title`,n.a=o),s!==n.o&&R(m,`aria-label`,n.o=s),u!==n.i&&R(h,`data-lang`,n.i=u),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),l})()}var KN={left:`left`,center:`center`,right:`right`};function qN(e){return n(Ue,{get each(){return e.blocks},children:e=>n(ee,{get children(){return[n(A,{get when(){return H(()=>e().type===`paragraph`)()&&e()},children:e=>(()=>{var t=ON();return L(t,n(UN,{get nodes(){return e().children}})),t})()}),n(A,{get when(){return H(()=>e().type===`heading`)()&&e()},children:e=>n(Le,{get component(){return`h${Math.min(6,e().level+2)}`},get children(){return n(UN,{get nodes(){return e().children}})}})}),n(A,{get when(){return H(()=>e().type===`list`)()&&e()},children:e=>n(Le,{get component(){return e().ordered?`ol`:`ul`},get start(){return H(()=>!!(e().ordered&&e().start!==1))()?e().start:void 0},get class(){return e().loose?`loose`:void 0},get children(){return n(Ue,{get each(){return e().items},children:e=>(()=>{var t=AN();return L(t,n(u,{get when(){return e().checked!==void 0},get children(){var t=kN();return D(()=>R(t,`aria-label`,e().checked?`Done`:`Not done`)),D(()=>t.checked=e().checked),t}}),null),L(t,n(qN,{get blocks(){return e().blocks}}),null),D(()=>K(t,e().checked===void 0?void 0:`task`)),t})()})}})}),n(A,{get when(){return H(()=>e().type===`code`)()&&e()},children:e=>n(GN,{get lang(){return e().lang},get text(){return e().text}})}),n(A,{get when(){return H(()=>e().type===`quote`)()&&e()},children:e=>(()=>{var t=jN();return L(t,n(qN,{get blocks(){return e().blocks}})),t})()}),n(A,{get when(){return H(()=>e().type===`table`)()&&e()},children:e=>(()=>{var t=MN(),r=t.firstChild.firstChild,i=r.firstChild,a=r.nextSibling;return L(i,n(Ue,{get each(){return e().head},children:(t,r)=>(()=>{var i=NN();return L(i,n(UN,{get nodes(){return t()}})),D(t=>Ve(i,e().align[r]?{"text-align":KN[e().align[r]]}:void 0,t)),i})()})),L(a,n(Ue,{get each(){return e().rows},children:t=>(()=>{var r=PN();return L(r,n(Ue,{get each(){return t()},children:(t,r)=>(()=>{var i=FN();return L(i,n(UN,{get nodes(){return t()}})),D(t=>Ve(i,e().align[r]?{"text-align":KN[e().align[r]]}:void 0,t)),i})()})),r})()})),t})()}),n(A,{get when(){return e().type===`rule`},get children(){return DN()}})]}})})}function JN(e){let t=T(()=>GM(e.text,{streaming:e.streaming}));return(()=>{var e=IN();return L(e,n(qN,{get blocks(){return t()}})),e})()}F([`click`]);var YN=J(`<a class=msg-image target=_blank rel=noopener><img loading=lazy>`,!0,!1,!1),XN=J(`<span class=file-chip> `),ZN=J(`<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>`),QN=J(`<div class=msg-images>`),$N=J(`<div class=pill>`),eP=J(`<p class="msg-note muted small"data-answered-note>`),tP=J(`<div><div class=user-body>`),nP=J(`<div class=msg-tools role=toolbar aria-label="Copy, fork, revert">`),rP=J(`<span>`),iP=J(`<div class=transcript aria-label=Conversation>`),aP=J(`<div>`),oP=J(`<p class="note sys turn-denied">`),sP=J(`<span class=turn-error-status>`),cP=J(`<div class=turn-error-message>`),lP=J(`<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>`),uP=J(`<p><span class=turn-retry-mark aria-hidden=true>↻</span><span>`),dP=J(`<a><span class=sub-mark aria-hidden=true></span><span class=sub-label>Subagent · <strong></strong></span><span class="sub-state muted">`),fP=J(`<span class=spinner>`),pP=J(`<span class=hub-msg-kind>`),mP=J(`<span class="hub-msg-state muted">`),hP=J(`<span class="hub-msg-delivery muted"title="Not delivered into a turn yet: the recipient's harness takes it at its next step">`),gP=J(`<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>`),_P=J(`<div class="fold-body hub-msg-text">`),vP=J(`<div><button type=button class=fold-head><span class=hub-msg-mark aria-hidden=true>⇄</span><span>`),yP=J(`<a>`),bP=J(`<span class="spinner small">`),xP=J(`<div class="fold thought"><button type=button class=fold-head><span>`),SP=J(`<ul class="fold-body tool-list">`),CP=J(`<div><button type=button class=fold-head><span>`),wP=J(`<pre class=code>`),TP=J(`<div class=tool-detail>`),EP=J(`<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">`),DP=J(`<span class="muted small">Loading full details…`),OP=J(`<span class="error small">`),kP=J(`<span class="muted small">No details for this call yet.`),AP={pending:[`…`,`Sending`],sent:[`✓`,`Sent`],queued:[`◷`,`Queued: the harness takes it at its next step`],heard:[`✓✓`,`Heard by the agent`],failed:[`!`,`Not sent`]};function jP(e){let[t,r]=x(!1);return n(u,{get when(){return H(()=>!!e.image.src)()&&!t()},get fallback(){return(()=>{var t=XN(),r=t.firstChild;return L(t,n(U,{name:`file`}),r),L(t,()=>e.image.name,null),D(()=>R(t,`title`,e.image.mime)),t})()},get children(){var t=YN(),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&&R(t,`href`,r.e=i),a!==r.t&&R(t,`title`,r.t=a),o!==r.a&&R(n,`src`,r.a=o),s!==r.o&&R(n,`alt`,r.o=s),r},{e:void 0,t:void 0,a:void 0,o:void 0}),t}})}var MP=500;function NP(e){let[t,r]=x(!1),i,a=()=>clearTimeout(i),s=t=>{t.pointerType===`touch`&&e.actions&&(a(),i=setTimeout(()=>r(!0),MP))},c=(e,t)=>()=>{r(!1),e.enabled&&t()};return(()=>{var i=tP(),l=i.firstChild;return N(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),L(i,n(u,{get when(){return e.actions},get children(){var i=ZN();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())},L(i,n(U,{name:`more`})),D(n=>{var r=t(),a=`msg-tools-${e.block.key}`;return r!==n.e&&R(i,`aria-expanded`,n.e=r),a!==n.t&&R(i,`aria-controls`,n.t=a),n},{e:void 0,t:void 0}),i}}),l),L(l,n(u,{get when(){return e.block.images?.length},get children(){var t=QN();return L(t,n(o,{get each(){return e.block.images},children:e=>n(jP,{image:e})})),t}}),null),L(l,n(u,{get when(){return e.block.text},get children(){var t=$N();return L(t,()=>e.block.text),t}}),null),L(l,n(u,{get when(){return e.block.note},get children(){var t=eP();return L(t,()=>e.block.note),t}}),null),L(l,n(u,{get when(){return e.actions},children:t=>(()=>{var i=nP();return L(i,n(z,{icon:`copy`,label:`Copy`,"data-action":`copy`,onClick:()=>(r(!1),t().onCopy(e.block.text))}),null),L(i,n(u,{get when(){return e.block.messageID},children:r=>[n(z,{icon:`fork`,get label(){return H(()=>!!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(z,{icon:`split`,get label(){return H(()=>!!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(z,{icon:`undo`,get label(){return H(()=>!!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(()=>R(i,`id`,`msg-tools-${e.block.key}`)),i})()}),null),L(i,n(u,{get when(){return e.tick},children:e=>(()=>{var t=rP();return L(t,()=>AP[e()][0]),D(n=>{var r=`tick ${e()}`,i=AP[e()][1],a=AP[e()][1];return r!==n.e&&K(t,n.e=r),i!==n.t&&R(t,`aria-label`,n.t=i),a!==n.a&&R(t,`title`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),i})()}function PP(e){return(()=>{var t=iP();return L(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(NP,{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=aP();return L(t,n(JN,{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&&K(t,n.e=r),i!==n.t&&R(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(IP,{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(LP,{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(FP,{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=oP();return L(t,()=>e().label),D(()=>R(t,`data-key`,e().key)),t})()}),n(A,{get when(){return t.type===`error`&&t},children:e=>(()=>{var t=lP(),r=t.firstChild.nextSibling,i=r.firstChild,a=i.firstChild;return L(a,()=>e().label),L(i,n(u,{get when(){return e().status},get children(){var t=sP();return L(t,()=>e().status),t}}),null),L(r,n(u,{get when(){return e().message},get children(){var t=cP();return L(t,()=>e().message),t}}),null),D(n=>{var r=e().key,i=`Error: ${e().label}`;return r!==n.e&&R(t,`data-key`,n.e=r),i!==n.t&&R(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=()=>Gk(e(),Pe());return(()=>{var n=uP(),r=n.firstChild.nextSibling;return L(r,()=>t().text),D(r=>{var i=`msg turn-retry${t().waiting?` waiting`:``}`,a=e().key;return i!==r.e&&K(n,r.e=i),a!==r.t&&R(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=dP(),r=t.firstChild,i=r.nextSibling,a=i.firstChild.nextSibling,o=i.nextSibling;return L(r,(()=>{var t=H(()=>e().state===`working`);return()=>t()?fP():`◆`})()),L(a,()=>e().label),L(o,()=>e().state),L(t,n(U,{name:`chevron`,class:`chev`}),null),D(n=>{var r=`subagent ${e().state}`,i=k(e().sessionID),a=e().key;return r!==n.e&&K(t,n.e=r),i!==n.t&&R(t,`href`,n.t=i),a!==n.a&&R(t,`data-key`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})]}})})),t})()}function FP(e){let t=()=>!!e.expanded[e.block.key];return n(u,{get when(){return H(()=>!e.block.primer)()&&!e.block.summary},get fallback(){return(()=>{var r=vP(),i=r.firstChild,a=i.firstChild.nextSibling;return N(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()),L(a,()=>e.block.summary??e.block.label),L(i,n(U,{name:`chevron`,class:`chev`}),null),L(r,n(u,{get when(){return t()},get children(){var t=_P();return L(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&&R(i,`aria-expanded`,n.e=r),a!==n.t&&R(i,`title`,n.t=a),n},{e:void 0,t:void 0}),r})()},get children(){var t=gP(),r=t.firstChild,i=r.firstChild,a=i.nextSibling,s=r.nextSibling;return L(i,()=>e.block.direction===`out`?`↗`:`↘`),L(r,n(u,{get when(){return e.block.kind!==`msg`},get children(){var t=pP();return L(t,()=>e.block.kind),t}}),a),L(a,()=>jn(e.block.label,Fl)),L(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=mP();return L(t,()=>e.block.state),t}}),null),L(r,n(u,{get when(){return e.block.delivery},get children(){var t=hP();return L(t,()=>e.block.delivery),D(()=>R(t,`data-delivery`,e.block.delivery)),t}}),null),L(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=yP();return L(t,()=>e.text),D(()=>R(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} ${jn(e.block.label,Fl)}`,s=e.block.label;return r!==n.e&&K(t,n.e=r),i!==n.t&&R(t,`data-key`,n.t=i),o!==n.a&&R(t,`aria-label`,n.a=o),s!==n.o&&R(a,`title`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t}})}function IP(e){let t=()=>!!e.expanded[e.block.key],r=t=>e.onToggle(e.block.key,t),i=()=>Jk(e.block);return(()=>{var a=xP(),o=a.firstChild,s=o.firstChild;return o.$$click=()=>r(!t()),L(o,n(u,{get when(){return e.block.running},get children(){return bP()}}),s),L(s,()=>i().label),L(o,n(U,{name:`chevron`,class:`chev`}),null),L(a,n(u,{get when(){return t()},get children(){var e=aP();return L(e,()=>i().body),D(()=>K(e,`fold-body reasoning${i().muted?` hidden-reasoning`:``}`)),e}}),null),D(n=>{var r=e.block.key,i=t();return r!==n.e&&R(a,`data-key`,n.e=r),i!==n.t&&R(o,`aria-expanded`,n.t=i),n},{e:void 0,t:void 0}),a})()}function LP(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=CP(),s=i.firstChild,c=s.firstChild;return s.$$click=()=>r(!t()),L(s,n(u,{get when(){return e.block.running},get children(){return bP()}}),c),L(c,a),L(s,n(U,{name:`chevron`,class:`chev`}),null),L(i,n(u,{get when(){return t()},get children(){var t=SP();return L(t,n(o,{get each(){return e.block.items},children:t=>n(RP,{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&&K(i,n.e=r),a!==n.t&&R(i,`data-key`,n.t=a),o!==n.a&&R(s,`aria-expanded`,n.a=o),n},{e:void 0,t:void 0,a:void 0}),i})()}function RP(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?so(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 B(`${P(e.sessionID)}/timeline/messages/${V(c().messageID)}/parts/${V(String(c().partID))}`);e.onDetail(c().key,t.detail)}catch(e){s(W(e))}finally{a(!1)}}},f=()=>typeof c().summary==`string`?c().summary:``;return(()=>{var e=EP(),r=e.firstChild,a=r.firstChild,s=a.nextSibling,p=s.nextSibling,m=p.nextSibling;return r.$$click=d,L(a,(()=>{var e=H(()=>c().state===`running`);return()=>e()?bP():c().state===`failed`?`✕`:`✓`})()),L(s,()=>c().name??`tool`),L(p,f),L(m,l),L(e,n(u,{get when(){return t()},get children(){var e=TP();return L(e,n(u,{get when(){return!i()},get fallback(){return DP()},get children(){return n(u,{get when(){return!o()},get fallback(){return(()=>{var e=OP();return L(e,o),e})()},get children(){return n(u,{get when(){return c().detail!==void 0||f()||c().error},get fallback(){return kP()},get children(){var e=wP();return L(e,()=>Xk(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&&K(e,n.e=i),o!==n.t&&R(r,`aria-expanded`,n.t=o),s!==n.a&&R(a,`aria-label`,n.a=s),n},{e:void 0,t:void 0,a:void 0}),e})()}F([`click`]);var zP={profilesPerUser:200,versionsPerProfile:100,skillsPerProfile:32,commandsPerProfile:64,instructionsChars:32e3,skillChars:32e3,commandChars:8e3,versionBytes:524288,projectsPerProfile:16},BP=[`pending`,`applied`,`partial`,`rejected`,`unsupported`,`restart_required`];function VP(e){if(!O(e))return`content must be an object`;if(e.instructions!==void 0&&!v(e.instructions,zP.instructionsChars))return`instructions must be at most ${zP.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,zP.skillsPerProfile,zP.skillChars,`body`,`skills`],[e.commands,zP.commandsPerProfile,zP.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)||!Fe(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>zP.versionBytes)return`profile version is too large`}function HP(e){if(e===void 0)return;let t=zP.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 UP(e){return O(e)?Fe(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)??HP(e.projects)??VP(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 WP(e){return Array.isArray(e)?`[${e.map(WP).join(`,`)}]`:O(e)?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${WP(e[t])}`).join(`,`)}}`:JSON.stringify(e)}var GP=/^[a-z][a-z0-9_]{0,39}$/,KP=/^[A-Z][A-Z0-9_]{0,63}$/,qP=`secret:`;function JP(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(qP)){if(!KP.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(!GP.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`,YP=e=>typeof e==`number`&&Number.isFinite(e),XP=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=1,ZP=e=>Array.isArray(e)?e.filter($):[];function QP(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 $P(e){if(Q(e)&&$(e.id)&&$(e.name)&&$(e.title)&&XP(e.latestVersion)&&YP(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:ZP(e.tags),metadata:Q(e.metadata)?Object.fromEntries(Object.entries(e.metadata).filter(e=>$(e[1]))):{},projects:ZP(e.projects),latestVersion:e.latestVersion,revision:e.revision,updatedAt:YP(e.updatedAt)?e.updatedAt:0}}var eF=e=>QP(e,$P),tF=[`sessions`,`online`,`olderVersion`,`teamRoles`,`staffedSeats`,`launches`,`liveLaunches`];function nF(e){if(!Q(e))return;let t={};for(let n of tF)YP(e[n])&&(t[n]=e[n]);return Array.isArray(e.teams)&&(t.teams=ZP(e.teams)),Array.isArray(e.harnesses)&&(t.harnesses=ZP(e.harnesses)),t}function rF(e){if(Q(e)&&XP(e.version)&&YP(e.skills)&&YP(e.commands))return{version:e.version,skills:e.skills,commands:e.commands,instructions:e.instructions===!0}}function iF(e){let t=eF(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?nF(n[e.id]):void 0,i=r?rF(r[e.id]):void 0;return{profile:e,...t?{usage:t}:{},...i?{summary:i}:{}}}),...t.cursor?{cursor:t.cursor}:{}}}var aF=e=>!!e&&((e.sessions??0)>0||(e.teamRoles??0)>0||(e.launches??0)>0);function oF(e){if(!e)return[];let t=[];e.sessions&&t.push(ut(e.sessions,`session`)),e.teamRoles&&t.push(ut(e.teamRoles,`team role`)),e.launches&&t.push(ut(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 sF=e=>[...new Set(e)].sort();function cF(e){return{tags:sF(e.flatMap(e=>e.profile.tags)),projects:sF(e.flatMap(e=>e.profile.projects)),teams:sF(e.flatMap(e=>e.usage?.teams??[])),harnesses:sF(e.flatMap(e=>e.usage?.harnesses??[]))}}function lF(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`===aF(e.usage)))}var uF=e=>(e?.sessions??0)+(e?.teamRoles??0)+(e?.launches??0),dF=(e,t)=>e.profile.name<t.profile.name?-1:+(e.profile.name>t.profile.name);function fF(e,t){let n=[...e];return t===`updated`?n.sort((e,t)=>t.profile.updatedAt-e.profile.updatedAt||dF(e,t)):t===`usage`?n.sort((e,t)=>uF(t.usage)-uF(e.usage)||dF(e,t)):n.sort(dF)}var pF=[`sessions`,`teams`,`launches`,`workspaces`];function mF(e){if(!Q(e)||!$(e.sessionID)||!XP(e.version)||!YP(e.revision))return;let t=Q(e.effective)&&XP(e.effective.version)?e.effective.version:void 0,n=Q(e.ack)&&BP.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,...YP(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 hF(e){if(!Q(e)||!$(e.profileID)||!XP(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:{...nF(e.counts),...Q(e.counts)&&YP(e.counts.workspaces)?{workspaces:e.counts.workspaces}:{}},sessions:(n&&Array.isArray(n.items)?n.items:[]).flatMap(e=>mF(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}:{},...XP(e.version)?{version:e.version}:{},...YP(e.staffed)?{staffed:e.staffed}:{}})),launches:t(e.launches).filter(e=>$(e.id)&&$(e.state)&&XP(e.version)).map(e=>({id:e.id,state:e.state,...$(e.outcome)?{outcome:e.outcome}:{},version:e.version,...$(e.sessionID)?{sessionID:e.sessionID}:{},created:YP(e.created)?e.created:0,updated:YP(e.updated)?e.updated:0})),workspaces:t(e.workspaces).filter(e=>$(e.workspaceID)).map(e=>({workspaceID:e.workspaceID,...$(e.title)?{title:e.title}:{},sessions:YP(e.sessions)?e.sessions:0})),projects:ZP(e.projects),hidden:ZP(e.hidden).filter(e=>pF.includes(e)),truncated:ZP(e.truncated)}}var gF=(e,t)=>t?`/teams/${encodeURIComponent(e)}`:`/watchtower?group=team&team=${encodeURIComponent(e)}`;function _F(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)??HP(r);return i?{ok:!1,error:i}:{ok:!0,patch:{metadata:Object.keys(n).length?n:null,projects:r.length?r:null}}}function vF(e){if(!Q(e)||!$(e.profileID)||!XP(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:YP(e.createdAt)?e.createdAt:0,bytes:YP(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:ZP(e.params)}]:[]}),secretRefs:ZP(e.secretRefs)}}function yF(e){if(Q(e)&&XP(e.version)&&$(e.digest))return{version:e.version,digest:e.digest,bytes:YP(e.bytes)?e.bytes:0,createdAt:YP(e.createdAt)?e.createdAt:0}}var bF=e=>QP(e,yF);function xF(e){let t=Q(e)?e.version:void 0;if(!Q(t)||!$(t.profileID)||!XP(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:YP(t.createdAt)?t.createdAt:0,content:r}}function SF(e){if(Q(e)&&BP.includes(e.status)&&$(e.digest))return{status:e.status,digest:e.digest,notes:ZP(e.notes),at:YP(e.at)?e.at:0,offline:e.offline===!0}}function CF(e){if(Q(e)&&$(e.profileID)&&XP(e.version)&&$(e.digest)&&(e.status===`applied`||e.status===`partial`))return{profileID:e.profileID,version:e.version,digest:e.digest,status:e.status,at:YP(e.at)?e.at:0}}function wF(e){if(!Q(e)||!$(e.sessionID)||!$(e.profileID)||!XP(e.version)||!YP(e.revision))return;let t=SF(e.ack),n=CF(e.effective);return{sessionID:e.sessionID,profileID:e.profileID,version:e.version,revision:e.revision,...t?{ack:t}:{},...n?{effective:n}:{}}}function TF(e){if(!Q(e)||!(`assignment`in e))return;if(e.assignment===null)return{assignment:null};let t=wF(e.assignment);if(!t)return;let n=$P(e.profile),r=vF(e.version);return{assignment:t,...n?{profile:n}:{},...r?{version:r}:{}}}var EF={pending:`Pending`,applied:`Applied`,partial:`Partly applied`,rejected:`Rejected`,unsupported:`Unsupported`,restart_required:`Restart required`},DF={applied:`ok`,partial:`warn`,restart_required:`warn`,pending:`pending`,unsupported:`err`,rejected:`err`};function OF(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:DF[r],detail:`${e.profile?.title??n} v${t.version}: ${EF[r]}${t.ack?.offline?` (machine offline)`:``}${s?` · v${s} available`:``}`,requested:t.version,...a===void 0?{}:{effective:a},...s?{upgrade:s}:{}}}function kF(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 AF=`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.`,jF={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.`},MF=e=>jF[e]??`This harness reports what took effect after you pin; presets can't apply profiles.`,NF=()=>({instructions:``,model:``,skills:[],commands:[]}),PF=e=>({instructions:e.instructions??``,model:e.model??``,skills:e.skills.map(e=>({...e})),commands:e.commands.map(e=>({...e}))});function FF(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=VP(r);if(i)return{ok:!1,error:i};for(let e of r.commands){let t=JP(e.template);if(typeof t==`string`)return{ok:!1,error:`commands.${e.name}: ${t}`}}return{ok:!0,content:r}}function IF(e,t){let n=FF(e);return!n.ok||WP(n.content)!==WP(t)}function LF(e,t){let n=FF(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=UP(a);return o?{ok:!1,error:o}:{ok:!0,body:a}}function RF(e){let t=JP(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 zF=4e3;function BF(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 ${zF} characters`};n[r]=e}return{ok:!0,body:{params:n}}}function VF(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 HF=`Control+Alt+P`,UF=e=>e.ctrlKey&&e.altKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyP`,WF=(e,t)=>e?e.endsWith(`
|
|
32
|
+
`)?e+t:`${e}\n${t}`:t,GF=(e,t,n)=>({profileID:e,version:t,expectedRevision:n.assignment?.revision??0});function KF(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 qF=e=>!!e.assignment&&(e.assignment.ack?.status??`pending`)===`pending`,JF=15e3,YF=16,XF=e=>e>=YF?void 0:Math.min(JF,1e3*2**e);function ZF(e){let t=e,n=t?.message??String(e);switch(t?.code){case`conflict`:return`Changed elsewhere meanwhile${YP(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 QF=encodeURIComponent,$F=`/api/agent`,eI={list:(e=`active`,t=!0)=>`${$F}/profiles?state=${e}&limit=200${t?`&include=usage,summary`:``}`,usage:(e,t)=>`${$F}/profiles/${QF(e)}/usage?limit=200${t?`&cursor=${QF(t)}`:``}`,create:()=>`${$F}/profiles`,one:e=>`${$F}/profiles/${QF(e)}`,versions:e=>`${$F}/profiles/${QF(e)}/versions`,version:(e,t)=>`${$F}/profiles/${QF(e)}/versions/${t}`,session:e=>`${$F}/sessions/${QF(e)}/profile`,unpin:(e,t)=>`${$F}/sessions/${QF(e)}/profile?expectedRevision=${t}`,render:(e,t)=>`${$F}/sessions/${QF(e)}/profile/commands/${QF(t)}/render`},tI=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,nI=async e=>e.json().catch(()=>({})),rI=async(e=`active`)=>eF(await B(eI.list(e,!1))),iI=async(e=`active`)=>iF(await B(eI.list(e)));async function aI(e,t){let n=hF(await B(eI.usage(e,t)));if(!n)throw Error(`The hub sent an unreadable usage answer`);return n}async function oI(e,t){let n=$P((await nI(await G(eI.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 sI(e){let t=await B(eI.one(e)),n=$P(t.profile);if(!n)throw Error(`The hub sent an unreadable profile`);return{profile:n,latest:vF(t.latest)}}var cI=async e=>bF(await B(`${eI.versions(e)}?limit=200`));async function lI(e,t){let n=xF(await B(eI.version(e,t)));if(!n)throw Error(`The hub sent an unreadable version`);return n}async function uI(e,t){let n=$P((await nI(await G(eI.create(),{method:`POST`,json:e,headers:{"idempotency-key":t}}))).profile);if(!n)throw Error(`The hub sent an unreadable profile`);return n}async function dI(e,t,n){let r=$P((await nI(await G(eI.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 fI(e,t){let n=$P((await nI(await G(eI.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 pI(e){let t=TF(await B(eI.session(e)));if(!t)throw Error(`The hub sent an unreadable profile pin`);return t}async function mI(e,t){await G(eI.session(e),{method:`PUT`,json:t})}async function hI(e,t){await G(eI.unpin(e,t),{method:`DELETE`})}async function gI(e,t,n){let r=await nI(await G(eI.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 _I=J(`<p class="error small"role=alert>`),vI=J(`<input type=search role=combobox aria-label="Search commands"aria-controls=prof-commands aria-expanded=true placeholder="Type a command…"autofocus>`),yI=J(`<ul class=prof-commands id=prof-commands role=listbox aria-label=Commands>`),bI=J(`<p class=prof-note>Inserted text goes into this session's composer; review it, then send.`),xI=J(`<p class="muted small">No profile is pinned to this session, so it has no commands. Pin one from the session's profile chip.`),SI=J(`<p class="muted small">Loading commands…`),CI=J(`<p class="muted small">`),wI=J(`<li role=option class=prof-command><strong>/</strong><span class=prof-sub>`),TI=J(`<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.`),EI=J(`<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`),DI=J(`<label><textarea>`);function OI(e){let t=e.view.assignment,[r]=f(async()=>{if(!t)return[];let n=e.view.version?.commands??[];try{return(await lI(t.profileID,t.version)).content.commands.map(e=>{let t=RF(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(()=>VF(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=BF(t.params,p());if(!n.ok)return g(n.error);v(!0),g(``);try{let{prompt:r}=await gI(e.sessionID,t.name,n.body);hy.set(e.sessionID,WF(hy.get(e.sessionID),r)),e.onInserted()}catch(e){g(ZF(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(Re,{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 xI()},get children(){return[(()=>{var e=vI();return e.$$keydown=C,e.$$input=e=>(a(e.currentTarget.value),c(0)),D(()=>R(e,`aria-activedescendant`,y().length?w(s()):void 0)),D(()=>e.value=i()),e})(),n(u,{get when(){return r()},get fallback(){return SI()},get children(){return n(u,{get when(){return y().length},get fallback(){return(()=>{var n=CI();return L(n,(()=>{var n=H(()=>!!r().length);return()=>n()?`No command matches.`:`${e.view.profile?.name??`This profile`} v${t.version} has no commands.`})()),n})()},get children(){var e=yI();return L(e,n(o,{get each(){return y()},children:(e,t)=>(()=>{var n=wI(),r=n.firstChild;r.firstChild;var i=r.nextSibling;return n.addEventListener(`pointerenter`,()=>c(t())),n.$$click=()=>b(e),L(r,()=>e.name,null),L(i,()=>e.description,null),L(i,(()=>{var t=H(()=>!!e.params.length);return()=>t()?` · asks for ${e.params.join(`, `)}`:``})(),null),L(i,(()=>{var t=H(()=>!!e.secrets.length);return()=>t()?` · uses secret ${e.secrets.join(`, `)}`:``})(),null),D(e=>{var r=w(t()),i=t()===s();return r!==e.e&&R(n,`id`,e.e=r),i!==e.t&&R(n,`aria-selected`,e.t=i),e},{e:void 0,t:void 0}),n})()})),e}})}}),bI()]}})},children:e=>(()=>{var t=EI(),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()))),L(i,()=>e().name,null),L(a,()=>e().description),L(t,n(o,{get each(){return e().params},children:e=>(()=>{var t=DI(),n=t.firstChild;return L(t,e,n),n.$$input=t=>m({...p(),[e]:t.currentTarget.value}),R(n,`data-param`,e),R(n,`rows`,e===`arguments`?3:1),D(()=>n.value=p()[e]??``),t})()}),s),L(t,n(u,{get when(){return e().secrets.length},get children(){var t=TI(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return L(t,()=>e().secrets.join(`, `),n),L(r,()=>`{{secret:${e().secrets[0]}}}`),t}}),s),L(t,n(u,{get when(){return h()},get children(){var e=_I();return L(e,h),e}}),s),l.$$click=()=>d(void 0),D(()=>c.disabled=_()),t})()}),n(u,{get when(){return H(()=>!l())()&&h()},get children(){var e=_I();return L(e,h),e}})]}})}F([`input`,`keydown`,`click`]);var kI=J(`<span class=prof-up aria-hidden=true>↑v`),AI=J(`<button type=button>`),jI=J(`<section aria-label="Pinned profile"><h3>Pinned`),MI=J(`<label>Profile<select aria-label=Profile>`),NI=J(`<label>Version<select aria-label=Version>`),PI=J(`<div class=row><button type=button class="btn small primary">`),FI=J(`<section aria-label="Pin a profile"><h3></h3><p class=prof-note>`),II=J(`<p class="error small"role=alert>`),LI=J(`<p class="muted small">No profile is pinned to this session.`),RI=J(`<div class=prof-status><span></span><strong class=small>`),zI=J(`<ul class=prof-guidance aria-label="What took effect">`),BI=J(`<p class=prof-note>`),VI=J(`<div class=row><button type=button class="btn small">Unpin</button><button type=button class="btn small">Commands… (Ctrl+Alt+P)`),HI=J(`<li>`),UI=J(`<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`),WI=J(`<p class="muted small">`),GI=J(`<p class="muted small">No active profiles. Create one under Agent profiles (/profiles).`),KI=J(`<option> (<!>)`),qI=J(`<option>v`),JI=e=>{let t=Al(e)?.session.title;return typeof t==`string`&&t?t:`this session`};function YI(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 pI(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||!qF(e))return void(m=0);let t=XF(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=>{UF(e)&&t.takesInput()&&a()&&r()&&(e.preventDefault(),d(!0))};document.addEventListener(`keydown`,e),j(()=>document.removeEventListener(`keydown`,e))});let y=()=>OF(r()??{assignment:null}),b=()=>f?.closest(`.session-layout`)?.querySelector(`textarea[aria-label="Message"]`)?.focus();return n(u,{get when(){return H(()=>!!a())()&&r()},get children(){return[(()=>{var e=AI();e.$$click=()=>{c(!0),g()};var t=f;return typeof t==`function`?he(t,e):f=e,R(e,`aria-keyshortcuts`,HF),L(e,(()=>{var e=H(()=>!!r().assignment);return()=>e()?y().label:`Profile`})(),null),L(e,n(u,{get when(){return y().upgrade},get children(){var e=kI();return e.firstChild,L(e,()=>y().upgrade,null),e}}),null),D(t=>{var n=`prof-chip ${y().tone}`,i=r().assignment?.ack?.status??`none`,a=`${y().detail}. Commands: ${HF}`,o=r().assignment?`Agent profile: ${y().label}, ${EF[r().assignment.ack?.status??`pending`]}${y().upgrade?`, v${y().upgrade} available`:``}`:`Agent profile: none`;return n!==t.e&&K(e,t.e=n),i!==t.t&&R(e,`data-profile-status`,t.t=i),a!==t.a&&R(e,`title`,t.a=a),o!==t.o&&R(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(XI,{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(OI,{get sessionID(){return t.sessionID},get title(){return JI(t.sessionID)},get view(){return r()},onClose:()=>d(!1),onInserted:()=>{d(!1),requestAnimationFrame(b)}})}})]}})}function XI(e){let[t]=f(()=>rI(`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=>cI(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=()=>OF(e.view),_=()=>kF(e.view),v=()=>KF(e.view,r(),a()),y=async(t,n,r)=>{p(!0),l(``);try{await mI(e.sessionID,GF(t,n,e.view)),q(r),e.onChanged()}catch(t){l(ZF(t)),e.onChanged()}finally{p(!1)}},b=async()=>{let t=e.view.assignment;if(t){p(!0),l(``);try{await hI(e.sessionID,t.revision),q(`Unpinned. What the session already applied stays until it restarts.`),e.onChanged()}catch(t){l(ZF(t)),e.onChanged()}finally{p(!1)}}};return n(Re,{open:!0,get title(){return`Agent profile · ${JI(e.sessionID)}`},get onClose(){return e.onClose},class:`prof-dialog`,get children(){return[(()=>{var t=jI();return t.firstChild,L(t,n(u,{get when(){return e.view.assignment},get fallback(){return LI()},children:t=>[(()=>{var e=RI(),n=e.firstChild,r=n.nextSibling;return L(n,()=>g().label),L(r,()=>EF[t().ack?.status??`pending`],null),L(r,()=>t().ack?.offline?` · machine offline`:``,null),D(e=>{var i=`prof-chip ${g().tone}`,a=t().ack?.status??`pending`;return i!==e.e&&K(n,e.e=i),a!==e.t&&R(r,`data-ack`,e.t=a),e},{e:void 0,t:void 0}),e})(),(()=>{var e=zI();return L(e,n(o,{get each(){return _()},children:e=>(()=>{var t=HI();return L(t,e),t})()})),e})(),n(u,{get when(){return g().upgrade},children:n=>(()=>{var r=UI(),i=r.firstChild,a=i.firstChild.nextSibling,o=a.nextSibling.nextSibling,s=o.nextSibling.nextSibling;s.nextSibling;var c=i.nextSibling;return c.firstChild,L(i,n,a),L(i,()=>e.view.profile?.name??`this profile`,o),L(i,()=>t().version,s),c.$$click=()=>void y(t().profileID,n(),`Upgrading to v${n()}…`),L(c,n,null),D(()=>c.disabled=d()),r})()}),(()=>{var e=BI();return L(e,AF),e})(),(()=>{var t=VI(),n=t.firstChild,r=n.nextSibling;return n.$$click=()=>void b(),Oe(r,`click`,e.onCommands,!0),R(r,`aria-keyshortcuts`,HF),D(()=>n.disabled=d()),t})()]}),null),t})(),(()=>{var c=FI(),l=c.firstChild,f=l.nextSibling;return L(l,()=>e.view.assignment?`Change the pin`:`Pin a profile`),L(f,()=>MF(e.harness)),L(c,n(u,{get when(){return H(()=>!t.error)()&&t()},get fallback(){return(()=>{var e=WI();return L(e,(()=>{var e=H(()=>!!t.error);return()=>e()?ZF(t.error):`Loading profiles…`})()),e})()},get children(){return n(u,{get when(){return t().length},get fallback(){return GI()},get children(){return[(()=>{var e=MI(),a=e.firstChild.nextSibling;return a.addEventListener(`change`,e=>i(e.currentTarget.value)),L(a,n(o,{get each(){return t()},children:e=>(()=>{var t=KI(),n=t.firstChild,r=n.nextSibling;return r.nextSibling,L(t,()=>e.title,n),L(t,()=>e.name,r),D(()=>t.value=e.id),t})()})),D(()=>a.value=r()),e})(),(()=>{var e=NI(),t=e.firstChild.nextSibling;return t.addEventListener(`change`,e=>s(Number(e.currentTarget.value))),L(t,n(o,{get each(){return H(()=>!!m.error)()?[]:m()??[]},children:(e,t)=>(()=>{var n=qI();return n.firstChild,L(n,()=>e.version,null),L(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=PI(),t=e.firstChild;return t.$$click=()=>void y(r(),a(),`${v().label}: sent to the session`),L(t,()=>v().label),D(()=>t.disabled=d()||!r()||!a()),e})()]}})}}),null),D(()=>R(f,`data-harness`,e.harness)),c})(),n(u,{get when(){return c()},get children(){var e=II();return L(e,c),e}})]}})}F([`click`]);var ZI=10;function QI(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 ${Sk(t)} sessions yet`};return{fork:r(`fork`,`Fork`),revert:r(`revert`,`Revert`)}}var $I=e=>Number.isSafeInteger(e)&&e>=0?e:0;function eL(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:$I(t.hidden),...typeof t.at==`number`&&Number.isFinite(t.at)?{at:t.at}:{},files:n,filesTotal:Math.max($I(t.filesTotal),n.length),...tL(t.stagedAt)?{stagedAt:t.stagedAt}:{}}}var tL=e=>typeof e==`number`&&Number.isFinite(e);function nL(e){let t=e?.revertCommitted;if(t&&typeof t==`object`&&typeof t.messageID==`string`&&t.messageID&&tL(t.until)&&tL(t.at))return{messageID:t.messageID,...tL(t.from)?{from:t.from}:{},until:t.until,at:t.at}}function rL(e){let t=nL(e);return`${eL(e)?.messageID??``}|${t?`${t.messageID}@${t.at}`:``}`}function iL(e){let t=Math.max(e.filesTotal,e.files.length);return{text:`${ut(e.hidden,`message`)} reverted`,...t?{files:`${ut(t,`file`)} restored`}:{}}}function aL(e){let t=Math.max(e.filesTotal,e.files.length);if(!t)return;let n=e.files.slice(0,ZI).map(e=>e.file),r=t-n.length;return[`Revert ${ut(e.hidden,`message`)}?`,``,`The session changed ${ut(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 oL(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 sL(e,t){return t===void 0?e:e.trim()===t.trim()?``:e}var cL=new Map;function lL(e,t){t.length&&cL.set(e,t)}function uL(e){let t=cL.get(e)??[];return cL.delete(e),t}var dL=J(`<button type=button class="btn small changes"aria-label="Show changes"><span class=add>+</span> <span class=del>−`),fL=J(`<div class="banner warn">No connected OpenCode process reports this session. It is read-only until its machine reconnects.`),pL=J(`<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.`),mL=J(`<div class=history-sentinel aria-hidden=true>`),hL=J(`<p class="history-edge loading muted small"role=status><span class="spinner small"></span> Loading earlier messages…`),gL=J(`<p class="history-edge muted small">Beginning of conversation`),_L=J(`<p class="history-edge error small"role=alert>Couldn't load earlier messages: <!> <button type=button class="btn small">Retry`),vL=J(`<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.`),yL=J(`<p class="working-line muted"role=status><span class="spinner small"></span> `),bL=J(`<p class="idle-line muted small"> · last activity `),xL=J(`<button type=button class="btn primary tap-to-start">Tap to start Voice mode`),SL=J(`<p class="note err voice-error"role=alert>Voice mode: `),CL=J(`<div class=sheet-backdrop>`),wL=J(`<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>`),TL=J(`<a class="crumb muted"> <span class=crumb-sep aria-hidden=true>/`),EL=J(`<h1 class=title>`),DL=J(`<h1 class=title><button type=button class=title-btn>`),OL=J(`<span class=chip-server><span aria-hidden=true></span><span class=place-sep aria-hidden=true>·</span><span class=place-where>`),kL=J(`<span> · `),AL=J(`<span class=place-branch>`),jL=J(`<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>`),ML=J(`<span class=session-error-status>`),NL=J(`<span class="session-error-where muted">in subagent `),PL=J(`<div class=session-error-message>`),FL=J(`<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>`),IL=J(`<p class="muted pad">Loading conversation…`),LL=J(`<p class="muted pad empty-session">No messages yet. Type below, or start Voice mode.`),RL=J(`<p>`),zL=J(`<p class="answered-by small muted">`),BL=J(`<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`),VL=J(`<span class=muted> · `),HL=J(`<button type=button class="btn stop"aria-label="Stop the session and its subagents"> Stop`),UL=J(`<div class=composer-unavailable data-no-prompt><p class="muted small">`),WL=J(`<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`),GL=3e4,KL=80,qL=100,JL=2e3,YL;function XL(t){let r=t.id,i=Lc(r,t.visible);j(()=>i.release()),C(()=>t.focused?.()&&i.focus());let s=()=>Cf()&&(t.rail?.()??!0),c,l=()=>{let e=c??s();c=void 0,Ef(!e)},d=()=>document.visibilityState===`visible`&&(t.visible?.()??!0),f=()=>Al(r),m=()=>kl().find(e=>e.id===r),g=()=>{let e=f();return e?sa(e.machine.name,e.session,dt()?.branch):void 0},_=()=>f()?.session.status,v=()=>Po(O()?_()?.filter(e=>ne().has(e.id)):_()),y=()=>!f(),b=T(()=>Ck(f()?.process)),S=()=>Tk(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();mk(window.history,location.pathname+location.search+location.hash,typeof t==`string`?t:void 0)});let ne=T(()=>No(_(),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||Al(e)?.session.title||`Parent session`}},[ae,oe]=x(),se=()=>{let e=ae();return e?e.value:eL(f()?.session)};C(()=>{let e=ae();e&&eL(f()?.session)?.messageID===e.value?.messageID&&oe(void 0)});let ce=T(()=>QI(f()?.process)),le,M=new Vt,[de,fe]=x(0),N=()=>fe(e=>e+1),[me,_e]=x(!1),[ve,F]=x(!1),[be,xe]=x([]),[Ce,we]=x({}),Te=0,De=(e,t=``,n)=>xe(r=>[...r.slice(-20),{key:`n${++Te}`,text:e,kind:t,...n?{denial:n}:{}}]),[Oe,ke]=x([]),Ae=!1,je=()=>{let e=bl(),t=Oe();return t.length?[...e,...t.filter(t=>!e.some(e=>e.seq===t.seq))]:e},V=e=>typeof e.sessionID==`string`?Hr(je(),e.sessionID,Yk(M.rows(),e),El):void 0,Me=T(()=>(de(),new Set(M.rows().flatMap(e=>e.kind===`error`&&e.declined===!0?[V(e)?.key??``]:[]).filter(Boolean)))),Ne=new Map,Pe=T(()=>{de(),M.status(_(),r);let e=new Map,t=se(),n=nL(f()?.session),i=Hk(t||n?M.rows().filter(e=>!oL(e,t,n)):M.rows(),{denied:e=>V(e)?.text}).map(t=>{let n=JSON.stringify(t),r=Ne.get(t.key),i=r&&r.json===n?r:{json:n,block:t};return e.set(t.key,i),i.block});return Ne=e,i}),[Fe,Le]=pi({}),Re,Be=!0,Ve=()=>requestAnimationFrame(()=>Re&&(Re.scrollTop=Re.scrollHeight));C(h(Pe,()=>Be&&Ve())),C(h(Pe,e=>{!Ae&&e.some(e=>e.type===`error`&&e.denied&&e.label===`Denied: the turn stopped`)&&(Ae=!0,B(`/api/agent/audit?limit=${qL}`).then(e=>ke(cr(e).entries)).catch(()=>{}))}));let[He,Ue]=x(0),We=e=>new URLSearchParams(Object.entries(e).flatMap(([e,t])=>t===void 0?[]:[[e,String(t)]])).toString(),Ge=new yk(M,e=>B(`${P(r)}/timeline?${We(e)}`),{limit:KL,onChange:()=>{Ke(()=>Ee(()=>{Ue(e=>e+1),N()})),Ge.state===`idle`&&Ye()}}),J=()=>(He(),{state:Ge.state,error:Ge.error});function Ke(e){let t=Re;if(!t||Be)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 qe,Je;function Ye(){Je&&Re&&typeof IntersectionObserver<`u`&&(qe??=new IntersectionObserver(e=>e.some(e=>e.isIntersecting)&&void Ge.older(),{root:Re,rootMargin:`${Math.round(window.innerHeight*1.5)}px 0px 0px 0px`}),qe.unobserve(Je),qe.observe(Je))}j(()=>qe?.disconnect());let Xe=e=>{Je=e,requestAnimationFrame(()=>requestAnimationFrame(Ye))},Ze=()=>`${se()?.messageID??``}|${rL({revertCommitted:nL(f()?.session)})}`,Qe=p(Ze),$e=!1;C(h(Ze,e=>{if(e===Qe)return;let t=e.split(`|`)[0]===Qe.split(`|`)[0];Qe=e,t&&$e?$e=!1:me()&&et()}));async function et(){M.clear(),N();try{await Ge.first(),await nt(),Be=!0,Ve()}catch(e){De(`Could not refresh the conversation: ${W(e)}`,`err`)}}async function tt(){if(w())return _e(!0);try{await Ge.first(),_e(!0),N(),Ve()}catch(t){t instanceof e&&t.status===404&&!f()?F(!0):w()||Ak(t)||De(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: ${W(t)}`,`err`),_e(!0)}}async function nt(){try{let{messages:e}=await B(`${P(r)}/messages?limit=200`);for(let t of e??[]){let e=Wt(r,t);e&&M.hubMessage(e)}N()}catch{}}async function rt(){try{let e=await B(P(r)),t=Gc.feed(te());t.load(e.activity??[]),e.status&&t.status(e.status)}catch{}}let it=p(()=>_()),at=Ol(e=>{if(e.type===`resync`){me()?Ge.resync().catch(e=>De(`Could not refresh the conversation: ${W(e)}`,`err`)).then(nt):tt().then(nt),rt(),bt();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),N();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}),N();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}),N();else if(e.type===`message`){let t=Wt(r,e.message);t&&(M.hubMessage(t),N())}else if(e.type===`turn`&&e.sessionID===r&&qt){let{sub:t,sentAt:n}=qt;qt=void 0,Xt(e,t,n)}else if(e.type===`status`&&e.sessionID===te()){for(let t of k_(it,e.sessions,r))De(t,`sys`);let t=Po(it);if(it=e.sessions,!Po(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&&me()&&Ge.resync().catch(()=>{}).then(nt)}N(),xt()}}),ot;C(h(()=>f()?.session.updated,()=>{clearTimeout(ot),ot=setTimeout(()=>d()&&void su(r),400)}));let st=(e,t=!1)=>G(`${P(r)}/presence`,{method:`POST`,json:{visible:e},keepalive:t}).catch(()=>{}),ct=()=>{st(d(),document.visibilityState!==`visible`),d()&&su(r)};C(h(()=>t.visible?.()??!0,()=>ct(),{defer:!0}));let lt=p(i.streamed);C(h(i.streamed,e=>{if(e===void 0)return;let t=lt===!1&&e;lt=e,t&&me()&&Ge.resync().catch(()=>{}).then(nt)}));let ut,[dt,ft]=x(),[pt,mt]=x(``),[ht,gt]=x(!0),_t=0,vt,yt=0;async function bt(){if(_t=Date.now(),f()&&!b().summary)return mt(`Details aren't available for ${b().harnessName} sessions.`),gt(!1);try{let e=await B(`${P(r)}/summary`);ft(e),mt(``),(!e.branch||!e.changes)&&yt<2&&(yt++,clearTimeout(vt),vt=setTimeout(bt,4e3))}catch(t){mt(t instanceof e&&t.status===409?`The machine is disconnected.`:`Could not load details: ${W(t)}`)}finally{gt(!1)}}function xt(){clearTimeout(vt),vt=setTimeout(bt,Math.max(0,JL-(Date.now()-_t)))}let[St,Ct]=x(),wt=KA(()=>r),[Tt,Et]=x(),[Dt,Ot]=x({...rg(),draft:hy.get(r)}),kt=e=>{Ot(t=>ig(t,e)),hy.set(r,Dt().draft)};j(hy.subscribe(e=>{e===r&&hy.get(r)!==Dt().draft&&Ot(e=>ig(e,{type:`input`,text:hy.get(r)}))}));let At=()=>Ek(b(),v()),jt=()=>{let e=ag(Dt(),{running:v(),offline:y()}),t=At();return{...e,canSubmit:e.canSubmit&&t.allowed,showStop:e.showStop&&b().stop,...!e.hint&&t.hint?{hint:t.hint}:{}}},Mt=0,[Nt,Pt]=x(!1),Ft=Promise.resolve();function It(e){Ft=Ft.then(async()=>{Pt(!0);try{for(let t of e)try{kt({type:`attach`,image:await pb(t,Dt().images)})}catch(e){kt({type:`attachError`,message:W(e)})}}finally{Pt(!1)}})}async function Lt(e,t,n){let r=[];for(let i of n)if(Zh(i.mime))try{let n=await(await G(Bk(e,t,i.index))).blob();r.push(await pb(new File([n],i.name||`image`,{type:i.mime}),r))}catch{}return r}async function Rt(e){try{await navigator.clipboard.writeText(e),q(`Copied`)}catch{q(`Could not copy: the browser refused`,`err`)}}async function zt(e,t=!1){try{let n=await(await G(`${P(r)}/fork`,{method:`POST`,json:{messageID:e}})).json();n.text&&hy.set(n.sessionID,n.text),lL(n.sessionID,await Lt(r,e,n.attachments??[])),q(t?`Forked into a new session beside this one`:`Forked into a new session`),t?Gd(n.sessionID):a(k(n.sessionID))}catch(e){q(Ak(e)??`Could not fork: ${W(e)}`,`err`)}}async function Bt(e){if(v())return q(`Wait for the session to finish (or stop it) before reverting`,`warn`);try{let t=aL(await B(`${P(r)}/revert/preview?messageID=${encodeURIComponent(e)}`));if(t&&!await Se(t,`Revert`,{danger:!0}))return;let n=await(await G(`${P(r)}/revert`,{method:`POST`,json:{messageID:e,files:!0}})).json();oe({value:eL({revert:n.revert})}),Ee(()=>{for(let e of Dt().images)kt({type:`detach`,id:e.id});kt({type:`input`,text:n.text??``})}),le=n.text??``;for(let t of await Lt(r,e,n.attachments??[]))kt({type:`attach`,image:t})}catch(e){q(Ak(e)??`Could not revert: ${W(e)}`,`err`)}}async function Ht(){try{await G(`${P(r)}/revert/restore`,{method:`POST`,json:{}}),oe({value:void 0}),kt({type:`input`,text:sL(Dt().draft,le)}),le=void 0}catch(e){q(`Could not restore: ${W(e)}`,`err`)}}async function Ut(){if(!se())return!0;try{return await G(`${P(r)}/revert/commit`,{method:`POST`,json:{}}),$e=!0,oe({value:void 0}),le=void 0,!0}catch(e){return q(`Could not send: the revert could not be completed (${W(e)})`,`err`),!1}}let Gt=()=>{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 Rt(e),onFork:e=>void zt(e),onForkBeside:e=>void zt(e,!0),onRevert:e=>void Bt(e)}};async function Kt(){let t=Dt().draft.trim(),n=Dt().images;if(!t&&!n.length||se()&&!await Ut())return;if(nn()&&!n.length){kt({type:`input`,text:``}),ry.sendTyped(r,t);return}let i=++Mt,a=`local:${i}`,o=v(),s=Date.now();Ee(()=>{kt({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}))}:{}}),we(e=>({...e,[a]:`pending`})),N()}),Be=!0,Ve();try{let e={text:t,...n.length?{images:n.map(({mime:e,data:t,name:n})=>({mime:e,data:t,name:n}))}:{}},o=await G(`${P(r)}/turn`,{method:`POST`,json:e,headers:{prefer:`respond-async`}}),c=await o.json().catch(()=>({})),l=og(o.status,c);kt({type:`accepted`,id:i});let u=Dk(b(),l);we(e=>({...e,[a]:u.tick})),u.toast&&q(u.toast),l===`accepted`?qt={sub:i,sentAt:s}:Xt(c,i,s)}catch(t){if(t instanceof ye&&!o&&await cg(v)){kt({type:`accepted`,id:i}),we(e=>({...e,[a]:`sent`})),De(`Lost the connection to the hub after sending; the session is working on your message and its reply will appear here.`,`sys`);return}let n=Ak(t);n&&q(n,`err`);let r=n??(t instanceof e&&t.status===504?`OpenCode did not answer in time. The session may still be working.`:W(t));Ee(()=>{kt({type:`rejected`,id:i,message:r}),M.upsert({key:a,kind:`user`,text:``,images:[]}),N()})}}let qt,[Jt,Yt]=x(new Set);function Xt(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=Vr(bl(),new Set([r,...ne()]),Date.now(),void 0,El),o=sg(e,{denied:a?.text});o&&De(o.text,o.kind,a&&o.text.startsWith(a.text)?a.key:void 0),a&&o?.text.startsWith(a.text)&&Yt(e=>new Set([...e,a.key])),N()}async function Qt(){kt({type:`stop`});try{let{stopped:e}=await(await G(`${P(r)}/stop`,{method:`POST`,json:{}})).json(),t=Array.isArray(e)?e.length:0;q(t?`Stopped ${t} session${t===1?``:`s`}`:`Nothing was running`)}catch(e){q(Ak(e)??`Could not stop: ${W(e)}`,`err`)}finally{kt({type:`stopped`})}}let $t=()=>yy(r),en=()=>i.takesInput()?gy.toggle(r):i.focus(),tn=py,nn=()=>tn().phase!==`off`&&tn().sessionID===r,rn=()=>tn().phase!==`off`&&tn().sessionID!==void 0&&tn().sessionID!==r,an=()=>tn().error?.sessionID===r&&!tn().error.gesture?tn().error.message:void 0,on=()=>tn().error?.sessionID===r&&tn().error.gesture===!0,sn=()=>Eo(Qc()??void 0,X()?.publicURL)?.micBlocked?`Set up speech in Settings to use the microphone`:void 0;j(ry.attach(r,{user:e=>{let t=`voice:${++Te}`;return M.upsert({key:t,kind:`user`,text:e,at:Date.now()}),we(e=>({...e,[t]:`pending`})),N(),t},tick:(e,t)=>we(n=>({...n,[e]:t})),agent:e=>{let t=e.messageID?M.liveTextKey(e.messageID):`say:${++Te}`,{mode:n,text:r}=O_(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()}),N())},note:(e,t)=>De(e,t??`sys`)}));async function cn(){if(!nn()&&!i.takesInput())return i.focus();nn()||(zv(),gy.cancel()),await ry.toggle(r),ry.isOn(r)&&ry.state.phase===`on`&&De(`Voice mode on${ry.state.agent?` (${ry.state.agent} agent)`:``}. Speak naturally; say “stop” to interrupt, “pause listening” to end.`,`sys`)}let ln=H_(location.href);ln.voice&&(YL=r,a(ln.path,{replace:!0})),C(()=>{YL===r&&f()&&!sn()&&(YL=void 0,nn()||cn())}),ue(()=>{for(let e of uL(r))kt({type:`attach`,image:e});let e=Sb(r);e&&(Ee(()=>{kt({type:`input`,text:e.text});for(let t of e.images)kt({type:`attach`,image:t})}),Kt()),rt(),su(r),st(d()),ut=setInterval(()=>d()&&void st(!0),GL),document.addEventListener(`visibilitychange`,ct)});let un=!1;C(()=>{!un&&Y.machines&&(un=!0,p(()=>{tt().then(nt),bt(),(!f()||b().models)&&wt.load()}))});let dn=()=>void st(!1,!0);window.addEventListener(`pagehide`,dn),j(()=>{at(),clearInterval(ut),clearTimeout(vt),clearTimeout(ot),document.removeEventListener(`visibilitychange`,ct),window.removeEventListener(`pagehide`,dn),dn()});let fn=!1;C(()=>{if(f())fn=!0;else if(fn&&Y.machines){if(t.onGone)return t.onGone();q(`That session is gone (deleted, or its machine was revoked).`,`warn`),a(`/`,{replace:!0})}});let pn=()=>Ti(f()?.session).filter(e=>!O()||e.sessionID!==void 0&&ne().has(e.sessionID)),mn=T(()=>new Map(pn().map(e=>[`${e.kind}:${e.id}`,e]))),hn=T((e=[])=>{let t=[...mn().keys()];return t.length===e.length&&t.every((t,n)=>t===e[n])?e:t}),gn=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}),_n=()=>{let e=new Set(pn().map(e=>e.id));return Br(bl(),new Set([r,...ne()]),yn(),gn(),new Set([...Jt(),...Me()]),Fl,El).filter(t=>!e.has(t.key))},vn=()=>(Jc(),I(),Gc.has(te())?Gc.feed(te()).pulse():void 0),[yn,bn]=x(Date.now()),xn=setInterval(()=>bn(Date.now()),1e3);j(()=>clearInterval(xn));let Sn=()=>{if(O()){let e=_()?.find(e=>e.id===r);return e?.state===`working`?(yn(),`Working${e.since?` · ${so(Date.now()-e.since)}`:``}`):void 0}let e=vn();if(!v()||!e?.busy)return;yn();let t=Ma(_(),r),n=Da(_());return`${t??e.label}${e.since?` · ${so(Date.now()-e.since)}`:``}${n?` · ${ja(n)}`:``}`},Cn=()=>Ca(_(),r),wn=()=>{let e=f()?.session;if(!e)return`Not connected`;let t=pn().length;return b().voice?`${nn()&&tn().agent?`${tn().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`},Tn=()=>dt()?.changes?.files.map(e=>e.file)??[];return(()=>{var e=wL(),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(),L(d,n(u,{get when(){return Z()},get children(){return n(z,{icon:`menu`,label:`Open sidebar`,onClick:Df})}}),p),L(p,n(u,{get when(){return ie()},children:e=>(()=>{var t=TL(),r=t.firstChild,i=r.nextSibling;return L(t,n(U,{name:`chevron`,class:`crumb-chev`}),r),L(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&&R(t,`href`,n.e=r),i!==n.t&&R(t,`title`,n.t=i),a!==n.a&&R(t,`aria-label`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),L(p,n(u,{get when(){return m()},get fallback(){return(()=>{var e=EL();return L(e,()=>f()?.session.title||(Y.machines?`Session`:`Loading…`)),e})()},children:e=>[n(ge,{get state(){return e().state}}),n(Nh,{get id(){return e().id},get title(){return e().title},place:`topbar`,class:`title`,get children(){var t=DL(),n=t.firstChild;return n.$$click=()=>Sm({id:e().id,place:`topbar`}),L(n,()=>e().title),D(()=>R(n,`title`,`${e().title} · click to rename`)),t}}),n(Ph,{get id(){return e().id}}),n(pe,{label:`Session actions`,class:`icon-btn small`,items:()=>Tm(e(),{open:!1,place:`topbar`})})]}),null),L(d,n(u,{get when(){return g()},children:e=>(()=>{var t=OL(),r=t.firstChild,i=r.nextSibling,a=i.nextSibling;return L(t,()=>e().machine,i),L(a,()=>e().where),L(t,n(u,{get when(){return e().branch},get children(){return[n(U,{name:`branch`}),H(()=>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&&R(t,`title`,n.e=i),a!==n.t&&R(t,`aria-label`,n.t=a),o!==n.a&&K(r,n.a=o),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),L(d,n(u,{get when(){return S()},children:e=>(()=>{var t=kL(),n=t.firstChild;return L(t,()=>b().harnessName,n),L(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&&K(t,n.e=r),i!==n.t&&R(t,`data-evidence`,n.t=i),a!==n.a&&R(t,`title`,n.a=a),o!==n.o&&R(t,`aria-label`,n.o=o),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),null),L(d,n(YI,{sessionID:r,get harness(){return b().harness},get takesInput(){return i.takesInput}}),null),L(d,n(u,{get when(){return dt()?.changes?.files.length},get children(){var e=dL(),t=e.firstChild;t.firstChild;var n=t.nextSibling.nextSibling;return n.firstChild,e.$$click=()=>Ct(Tn()[0]),L(t,()=>dt().changes.additions,null),L(n,()=>dt().changes.deletions,null),e}}),null),L(d,n(u,{get when(){return rn()},get children(){return n(pD,{})}}),null),L(d,n(u,{get when(){return Z()},get children(){return n(NO,{})}}),null),L(d,n(z,{icon:`rail`,get label(){return s()?`Hide details`:`Show details`},get"aria-pressed"(){return s()},onPointerDown:()=>c=s(),onClick:l}),null),L(d,()=>t.paneTools,null),L(a,n(u,{get when(){return H(()=>!!Z())()&&g()},children:e=>(()=>{var t=jL(),r=t.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return L(i,()=>e().machine),L(a,()=>e().where),L(t,n(u,{get when(){return e().branch},get children(){return[n(U,{name:`branch`}),(()=>{var t=AL();return L(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&&R(t,`title`,n.e=i),a!==n.t&&R(t,`aria-label`,n.t=a),o!==n.a&&K(r,n.a=o),n},{e:void 0,t:void 0,a:void 0}),t})()}),h),L(a,n(u,{get when(){return Cn()},children:e=>(()=>{var t=FL(),i=t.firstChild.nextSibling,a=i.firstChild,o=a.firstChild;return L(o,()=>e().label),L(a,n(u,{get when(){return e().status},get children(){var t=ML();return L(t,()=>e().status),t}}),null),L(a,n(u,{get when(){return H(()=>e().sessionID!==r)()&&e().title},get children(){var t=NL();return t.firstChild,L(t,()=>e().title,null),t}}),null),L(i,n(u,{get when(){return H(()=>!!e().message)()&&e().message!==e().label},get children(){var t=PL();return L(t,()=>e().message),t}}),null),D(()=>R(t,`data-error-session`,e().sessionID)),t})()}),h),L(a,n(u,{get when(){return H(()=>!!y())()&&Y.machines},get children(){return fL()}}),h),h.addEventListener(`scroll`,e=>Be=e.currentTarget.scrollHeight-e.currentTarget.scrollTop-e.currentTarget.clientHeight<80);var C=Re;return typeof C==`function`?he(C,h):Re=h,L(_,n(u,{get when(){return!ve()},get fallback(){return n(ZL,{})},get children(){return[n(u,{get when(){return me()},get fallback(){return IL()},get children(){return[n(u,{get when(){return w()},get children(){var e=pL(),t=e.firstChild.nextSibling;return t.nextSibling,L(e,()=>b().harnessName,t),e}}),n(u,{get when(){return Pe().length||be().length},get fallback(){return n(u,{get when(){return!w()},get children(){return LL()}})},get children(){return[(()=>{var e=mL();return he(Xe,e),e})(),n(ee,{get children(){return[n(A,{get when(){return J().state===`loading`},get children(){return hL()}}),n(A,{get when(){return H(()=>J().state===`done`)()&&Pe().length},get children(){return gL()}}),n(A,{get when(){return J().state===`error`},get children(){var e=_L(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return L(e,()=>J().error,t),n.$$click=()=>void Ge.retry(),e}})]}}),n(PP,{sessionID:r,get blocks(){return Pe()},get ticks(){return Ce()},get actions(){return Gt()},expanded:Fe,onToggle:(e,t)=>Le(e,t),onDetail:(e,t)=>{M.detail(e,t),N()}})]}})]}}),n(o,{get each(){return Ur(be(),Me())},children:e=>(()=>{var t=RL();return L(t,()=>e.text),D(n=>{var r=`note ${e.kind}`,i=e.kind===`err`?`alert`:void 0;return r!==n.e&&K(t,n.e=r),i!==n.t&&R(t,`role`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(Oh,{get decisions(){return Zt(nl(),r)}}),n(o,{get each(){return hn()},children:e=>n(u,{get when(){return mn().get(e)},children:e=>n(kM,{sessionID:r,get blocker(){return e()},rootID:r,get canAnswer(){return H(()=>e().kind===`permission`)()?b().permission:b().form},get harnessName(){return b().harnessName}})})}),n(o,{get each(){return _n()},children:e=>(()=>{var t=zL();return L(t,()=>e.text),D(n=>{var r=e.key,i=e.title;return r!==n.e&&R(t,`data-answered-by`,n.e=r),i!==n.t&&R(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(u,{get when(){return H(()=>!!v())()&&i.streamed()===!1},get children(){return vL()}}),n(u,{get when(){return Sn()},get children(){var e=yL();return e.firstChild.nextSibling,L(e,Sn,null),e}}),n(u,{get when(){return H(()=>!(v()||!f()))()&&m()},get children(){var e=bL(),t=e.firstChild;return L(e,()=>Ie[m().state],t),L(e,()=>ze(m().updated,I()),null),e}})]}})),L(x,n(u,{get when(){return nn()},get children(){return n(SA,{get state(){return tn().voice},get level(){return tn().level},get held(){return tn().held},get ignored(){return tn().ignored},get working(){return v()},get model(){return GA(wt.prefs(),`voice`)},onMute:()=>ry.mute(),onEnd:()=>void ry.end(),onModel:()=>Et(`voice`),get notifyHint(){return dy()},onAllowNotifications:()=>void fy(),get timing(){return tn().timing},get detector(){return tn().detector}})}}),null),L(x,n(u,{get when(){return on()},get children(){var e=xL();return e.$$click=()=>void cn(),e}}),null),L(x,n(u,{get when(){return an()},get children(){var e=SL();return e.firstChild,L(e,an,null),e}}),null),L(x,n(u,{get when(){return se()},children:e=>(()=>{var t=BL(),r=t.firstChild,i=r.firstChild,a=r.nextSibling;return L(t,n(U,{name:`undo`}),r),L(r,()=>iL(e()).text,i),L(r,n(u,{get when(){return iL(e()).files},children:e=>(()=>{var t=VL();return t.firstChild,L(t,e,null),t})()}),i),a.$$click=()=>void Ht(),D(()=>R(t,`data-revert`,e().messageID)),t})()}),null),L(x,n(u,{get when(){return At().show},get fallback(){return(()=>{var e=UL(),t=e.firstChild;return L(t,()=>At().hint),L(e,n(u,{get when(){return jt().showStop},get children(){var e=HL(),t=e.firstChild;return e.$$click=()=>void Qt(),L(e,n(U,{name:`stop`}),t),D(()=>e.disabled=!jt().canStop),e}}),null),e})()},get children(){return n(vA,{get draft(){return Dt().draft},get images(){return Dt().images},get attaching(){return Nt()},get view(){return jt()},get error(){return Dt().error},get voiceOn(){return nn()},get voiceBlocked(){return sn()},get dictating(){return $t().recording},get transcribing(){return $t().transcribing},get metaLeft(){return wn()},get voiceModel(){return H(()=>!!wt.error())()?`unavailable`:GA(wt.prefs(),`voice`)},get workerModel(){return H(()=>!!wt.error())()?`unavailable`:GA(wt.prefs(),`worker`)},onInput:e=>kt({type:`input`,text:e}),onAttach:It,onDetach:e=>{let t=Dt().images.find(t=>t.id===e);t?.preview.startsWith(`blob:`)&&URL.revokeObjectURL(t.preview),kt({type:`detach`,id:e})},onSubmit:()=>void Kt(),onStop:()=>void Qt(),onDictate:()=>void en(),onVoice:()=>void cn(),onModel:e=>Et(e),get showModels(){return b().models},get showVoice(){return b().voice}})}}),null),L(a,n(u,{get when(){return St()},get children(){return n(Zj,{sessionID:r,get file(){return St()},get files(){return H(()=>!!Tn().length)()?Tn():[St()]},onFile:Ct,onClose:()=>Ct(void 0)})}}),null),L(e,n(u,{get when(){return s()},get children(){return[n(u,{get when(){return Z()},get children(){var e=CL();return e.$$click=()=>Ef(!1),e}}),n(u,{get when(){return!Z()},get children(){return n(Qy,{panel:`rail`,label:`Resize details`})}}),n(Xj,{get found(){return f()},get summary(){return dt()},get summaryError(){return pt()},get loading(){return ht()},onFile:e=>Ct(e),onClose:()=>Ef(!1)})]}}),null),L(e,n(qA,{get kind(){return Tt()},models:wt,onClose:()=>Et(void 0)}),null),D(t=>{var n=`session-layout${s()?` with-rail`:``}`,r=i.paneID,a=i.takesInput()?``:void 0;return n!==t.e&&K(e,t.e=n),r!==t.t&&R(e,`data-pane`,t.t=r),a!==t.a&&R(e,`data-pane-focused`,t.a=a),t},{e:void 0,t:void 0,a:void 0}),e})()}function ZL(){return WL()}F([`focusin`,`pointerdown`,`click`]);var QL=J(`<span class=pane-drop-label>`),$L=J(`<div class=pane-drop-area><span class=pane-drop-hint>`),eR=J(`<div aria-hidden=true>`),tR=J(`<div class=pane-dock-map>`),nR=J(`<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.`),rR={left:`Split left`,right:`Split right`,top:`Stack above`,bottom:`Stack below`,center:`Replace`};function iR(e,t){let n=Zf(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: ${rR[t].replace(`Split `,``).replace(`Stack `,``)}`,refused:!1}:n===`added`&&`empty`in e?{text:`Open in a pane`,refused:!1}:{text:rR[t],refused:!1}}function aR(e){let[t,r]=x(),i=t=>e.index===void 0?{empty:!0}:{index:e.index,zone:t},a=t=>{if(!Xf(t))return;t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getBoundingClientRect(),i=e.index===void 0?`center`:Yd(t.clientX-n.left,t.clientY-n.top,n.width,n.height);r(i),t.dataTransfer&&(t.dataTransfer.dropEffect=Kf()?.move||t.dataTransfer.effectAllowed===`move`?`move`:`copy`)},o=()=>t()?iR(i(t()),t()):void 0;return(()=>{var s=eR();return s.addEventListener(`drop`,e=>{if(!Xf(e))return;e.preventDefault(),e.stopPropagation();let n=t()??`center`;r(void 0),$f(e,i(n))}),s.addEventListener(`dragleave`,e=>!e.currentTarget.contains(e.relatedTarget)&&r(void 0)),s.addEventListener(`dragover`,a),s.addEventListener(`dragenter`,a),L(s,n(u,{get when(){return e.label},get children(){var t=QL();return L(t,()=>e.label),t}}),null),L(s,n(u,{get when(){return t()},get children(){var e=$L(),n=e.firstChild;return L(n,()=>o()?.text),D(()=>R(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&&K(s,n.e=r),n.t=Ve(s,i,n.t),a!==n.a&&R(s,`data-zone`,n.a=a),c!==n.o&&R(s,`data-refused`,n.o=c),n},{e:void 0,t:void 0,a:void 0,o:void 0}),s})()}var oR=e=>{if(Ye(e)!==void 0)return`Artifact`;let t=Al(e.sessionID)?.session.title,n=typeof t==`string`&&t?t:`Session`;return e.sideChatID?`Side chat: ${n}`:n};function sR(){let e=Hd,t=()=>e().panes.length,r=()=>rk(e().split,t()),i=n=>{let r=ik(e().split,t(),n);return{"grid-column":`${r.col+1} / span ${r.colSpan}`,"grid-row":`${r.row+1}`}};return(()=>{var a=nR(),s=a.firstChild,c=s.firstChild,l=c.nextSibling;return L(c,(()=>{var e=H(()=>!!Kf()?.label);return()=>e()?`Open “${Kf().label}” in a pane`:`Open in a pane`})()),L(s,n(u,{get when(){return t()},get fallback(){return n(aR,{class:`pane-dock-empty`,label:`No panes open: drop here`})},get children(){var t=tR();return L(t,n(o,{get each(){return e().panes},children:(e,t)=>n(aR,{get index(){return t()},get label(){return oR(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&&xe(t,`grid-template-columns`,e.e=n),i!==e.t&&xe(t,`grid-template-rows`,e.t=i),e},{e:void 0,t:void 0}),t}}),l),a})()}var cR=J(`<div role=separator tabindex=0>`);function lR(e){let[t,n]=x(!1),r=[],i=0,a=0,o,s=()=>tk[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=cR();return d.$$keydown=t=>{let n=sk(e.sizes(),e.index,t.key,t.shiftKey,e.total(),s(),e.axis);n&&(t.preventDefault(),e.onChange(n,!0))},d.$$dblclick=()=>e.onChange(ak(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=ok(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&&K(d,n.e=r),i!==n.t&&R(d,`data-axis`,n.t=i),a!==n.a&&R(d,`aria-orientation`,n.a=a),o!==n.o&&R(d,`aria-label`,n.o=o),s!==n.i&&R(d,`aria-valuenow`,n.i=s),c!==n.n&&R(d,`aria-valuemin`,n.n=c),f!==n.s&&R(d,`aria-valuemax`,n.s=f),n.h=Ve(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})()}F([`pointerdown`,`pointermove`,`pointerup`,`dblclick`,`keydown`]);var uR=J(`<span role=status>Send this to the main session? It is queued and arrives after its current turn; nothing is interrupted.`),dR=J(`<button type=submit class="btn small primary">Send`),fR=J(`<button type=button class="btn small">Back`),pR=J(`<form style=display:flex;flex-direction:column;gap:6px><label class=muted>Message for </label><textarea rows=3></textarea><div>`),mR=J(`<div class=sidechat-bar role=group aria-label="Side chat"><div><strong>Side chat</strong><span class=muted>from </span><span style=margin-left:auto;display:inline-flex;gap:6px;align-items:center><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…`),hR=J(`<p class=muted style=margin:0;font-size:0.8125rem>`),gR=J(`<span role=status>`),_R=J(`<ol aria-label="Copied context"style=margin:0;padding-left:20px;max-height:30vh;overflow:auto;font-size:0.8125rem>`),vR=J(`<li><span class=muted></span><div style=white-space:pre-wrap;overflow-wrap:anywhere>`),yR=J(`<p class=muted role=alert style=margin:0>`),bR=J(`<button type=submit class="btn small">Review`),xR=J(`<button type=button class=btn>Close pane`),SR=J(`<div class=empty><p class=display>Side chat</p><p class=muted role=status>`),CR={flex:`none`,display:`flex`,"flex-direction":`column`,gap:`6px`,padding:`6px 12px`,"border-bottom":`1px solid var(--line)`},wR={display:`flex`,"align-items":`center`,gap:`6px`,"flex-wrap":`wrap`},TR=e=>{let t=Al(e)?.session.title;return typeof t==`string`&&t?t:`the main session`};function ER(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),Wp(e).kind===`launching`?S=setTimeout(E,$p(C++)):C=0};async function E(){try{let e=await B(Qp.one(t.sideChatID));if(!w)return;let n=Up(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.`:W(t))}}ue(E),j(()=>{w=!1,clearTimeout(S)});async function ee(){let t=r();if(t&&!c()){l(!0);try{let e=await(await G(Qp.refresh(t),{method:`POST`,json:{expectedRevision:t.revision}})).json(),n=Up(e.sideChat);n&&T(n),q(qp(e.delivery))}catch(t){t instanceof e&&t.code===`conflict`?(q(`The side chat changed meanwhile. It was reloaded; refresh again.`,`warn`),await E()):q(`Couldn't refresh: ${W(t)}`,`err`)}finally{l(!1)}}}async function te(){let e=r();if(!(!e||c()||Yp(_()))){l(!0);try{await G(Qp.send(e),{method:`POST`,json:{text:_(),confirmed:!0}}),q(`Sent to the main session. It arrives after its current turn.`),v(``),g(!1),m(!1)}catch(e){q(`Couldn't send: ${W(e)}`,`err`)}finally{l(!1)}}}let O=()=>{let e=r();return e?Wp(e):void 0},ne=()=>{let e=O();return e?.kind===`ready`?e.sessionID:void 0},re=()=>{let e=r();return e?Kp(e,y()):void 0};return[(()=>{var e=mR(),i=e.firstChild,a=i.firstChild.nextSibling;a.firstChild;var s=a.nextSibling,l=s.firstChild,y=l.nextSibling,b=y.nextSibling;return Ve(e,CR),L(a,()=>TR(r()?.sourceSessionID??``),null),l.$$click=()=>f(!d()),y.$$click=ee,b.$$click=()=>(m(!p()),g(!1)),L(s,()=>t.paneTools,null),L(s,n(u,{get when(){return!t.paneTools},get children(){return n(z,{icon:`close`,class:`small`,label:`Close pane`,title:`Close pane (the side chat keeps running)`,onClick:()=>t.onClose()})}}),null),L(e,n(u,{get when(){return re()},children:e=>(()=>{var t=hR();return L(t,()=>e().summary,null),L(t,n(u,{get when(){return e().stale},children:e=>[` · `,(()=>{var t=gR();return L(t,e),t})()]}),null),t})()}),null),L(e,n(u,{get when(){return H(()=>!!d())()&&r()},children:e=>(()=>{var t=_R();return L(t,n(o,{get each(){return e().snapshot.items},children:e=>(()=>{var t=vR(),n=t.firstChild,r=n.nextSibling;return L(n,()=>e.role,null),L(n,()=>e.changed?` · changed`:``,null),L(n,()=>e.stale?` · no longer in the main session (earlier copy)`:``,null),L(n,()=>e.clipped?` · shortened`:``,null),L(r,()=>e.text),t})()})),t})()}),null),L(e,n(u,{get when(){return p()},get children(){var e=pR(),i=e.firstChild;i.firstChild;var a=i.nextSibling,o=a.nextSibling;return e.addEventListener(`submit`,e=>{e.preventDefault(),h()?te():Yp(_())||g(!0)}),L(i,()=>TR(r()?.sourceSessionID??``),null),a.$$input=e=>v(e.currentTarget.value),L(e,n(u,{get when(){return H(()=>!!_())()&&Yp(_())},children:e=>(()=>{var t=yR();return L(t,e),t})()}),o),L(o,n(u,{get when(){return h()},get fallback(){return(()=>{var e=bR();return D(()=>e.disabled=!!Yp(_())),e})()},get children(){return[uR(),(()=>{var e=dR();return D(()=>e.disabled=c()),e})(),(()=>{var e=fR();return e.$$click=()=>g(!1),D(()=>e.disabled=c()),e})()]}})),D(e=>{var n=`sidechat-send-${t.sideChatID}`,r=`sidechat-send-${t.sideChatID}`,s=h()||c(),l=wR;return n!==e.e&&R(i,`for`,e.e=n),r!==e.t&&R(a,`id`,e.t=r),s!==e.a&&(a.disabled=e.a=s),e.o=Ve(o,l,e.o),e},{e:void 0,t:void 0,a:void 0,o:void 0}),D(()=>a.value=_()),e}}),null),D(e=>{var t=wR,n=d(),a=!r(),o=!r()||c(),s=p(),u=!r();return e.e=Ve(i,t,e.e),n!==e.t&&R(l,`aria-expanded`,e.t=n),a!==e.a&&(l.disabled=e.a=a),o!==e.o&&(y.disabled=e.o=o),s!==e.i&&R(b,`aria-expanded`,e.i=s),u!==e.n&&(b.disabled=e.n=u),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),e})(),n(u,{get when(){return ne()},keyed:!0,get fallback(){return(()=>{var e=SR(),r=e.firstChild.nextSibling;return L(r,()=>a()??(O()&&O().kind!==`ready`?O().text:`Loading…`)),L(e,n(u,{get when(){return a()},get children(){var e=xR();return e.$$click=()=>t.onClose(),e}}),null),e})()},children:e=>n(XL,{id:e,get visible(){return t.visible},get focused(){return t.focused},get onGone(){return t.onGone},get rail(){return t.rail}})})]}F([`click`,`input`]);var DR=()=>{try{return globalThis.localStorage}catch{return}},[OR,kR]=x(dk(DR())),[AR,jR]=x();function MR(e,t){let n=pk(OR(),e,t),r=AR();if(!r)return n;let[i,a,o]=r.key.split(`:`);return i===e&&Number(a)===t?{...n,[o]:r.sizes}:n}function NR(e,t,n,r,i=!0){if(!i)return void jR({key:`${e}:${t}:${n}`,sizes:r});jR(void 0),kR(i=>fk(DR(),i,e,t,n,r))}var PR=J(`<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>`),FR=J(`<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.`),IR=J(`<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`),LR=J(`<div class=pane-tabs role=tablist aria-label="Open sessions">`),RR=J(`<div><div class=pane-grid>`),zR=J(`<button type=button>`),BR=J(`<div role=presentation><button type=button role=tab>`),VR=J(`<section class=pane tabindex=-1>`),HR=J(`<p class="muted cmp-empty">Loading the artifact…`),UR=i(()=>yN(()=>import(`./ArtifactPane-C9KrBna8.js`).then(e=>({default:e.ArtifactPane})),__vite__mapDeps([0,1,2,3,4]))),WR=6,GR=[{split:`vertical`,label:`Side by side`,icon:`split`},{split:`horizontal`,label:`Stacked`,icon:`stack`},{split:`grid`,label:`Grid`,icon:`grid`}],KR=e=>{let t=Ye(e);return t===void 0?e.sideChatID?`${e.sessionID}#${e.sideChatID}`:e.sessionID:`!${t}`},qR=e=>e.startsWith(`!`)?e.slice(1):void 0,JR=e=>e.split(`#`)[0],YR=e=>encodeURIComponent(e).replace(/%/g,`_`),XR=e=>{let t=Al(e)?.session.title;return typeof t==`string`&&t?t:`Session`},ZR=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function QR(e){let[t,r]=x(!1);we(h(()=>e.routed,e=>{if(e===void 0)return void r(!1);let t=!0;Ud(n=>{let r=st(n,{sessionID:e});return t=r.outcome!==`invalid`,r.layout}),r(!t)})),we(()=>{let e=yl();e.size&&Ud(t=>vc(t,e))});let i=Hd,s=()=>i().panes.length,l=T(()=>i().panes.map(KR),[],{equals:ZR}),d=e=>l().indexOf(e),f=()=>l()[i().focused],m=()=>i().split,g=()=>Z()&&s()>1,[_,v]=x({}),y=e=>{let t=qR(e);return t===void 0?e.includes(`#`)?`Side chat: ${XR(JR(e))}`:XR(JR(e)):`Artifact: ${_()[t]??`…`}`},b=()=>!Z()&&s()>1,S=()=>!!Kf()&&!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=>Ud(t=>et(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(()=>Ud(n=>it(n,t,t+e))),w()},O=e=>{e<0||e>=s()||(Ud(t=>rt(t,e)),s()||a(`/`,{replace:!0}))},ne=e=>{q(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=$O(e);if(n){if(e.preventDefault(),n.type===`cycle`)Ud(e=>ot(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()?rk(m(),s()):{cols:1,rows:1},oe=()=>MR(m(),s()),se=e=>(e===`cols`?ie().w:ie().h)-(A()[e]-1)*WR,ce=(e,t)=>t>1?e.map(e=>`minmax(0, ${e}fr)`).join(` ${WR}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=ik(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)=>NR(m(),s(),e,t,n),N=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()))},pe=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 P(e){let t=()=>d(e.key),r=()=>m()===`horizontal`;return n(u,{get when(){return b()},get children(){var a=PR(),o=a.firstChild;return Oe(o,`dragend`,Yf),o.addEventListener(`dragstart`,n=>{let r=i().panes[t()];(!r||!Jf(n,{target:r,label:y(e.key),move:!0}))&&n.preventDefault()}),L(o,n(U,{name:`grip`})),L(a,n(z,{icon:`chevron`,class:`small flip`,get label(){return r()?`Move pane up`:`Move pane left`},get"aria-keyshortcuts"(){return XO.moveEarlier},get disabled(){return t()<=0},onClick:()=>(E(t()),te(-1))}),null),L(a,n(z,{icon:`chevron`,class:`small`,get label(){return r()?`Move pane down`:`Move pane right`},get"aria-keyshortcuts"(){return XO.moveLater},get disabled(){return t()>=s()-1},onClick:()=>(E(t()),te(1))}),null),L(a,n(z,{icon:`close`,class:`small`,label:`Close pane`,title:`Close pane (the session keeps running)`,get"aria-keyshortcuts"(){return XO.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(XL,{id:e})})},get children(){return[n(u,{get when(){return!s()},get children(){var e=FR();return e.firstChild.nextSibling.nextSibling,L(e,n(u,{get when(){return S()},get children(){return n(aR,{label:`Open in a pane`})}}),null),e}}),(()=>{var e=RR(),t=e.firstChild;L(e,n(u,{get when(){return b()},get children(){var e=IR(),t=e.firstChild,r=t.nextSibling,i=r.firstChild,a=i.nextSibling;return a.nextSibling,e.$$keydown=pe,L(t,n(o,{each:GR,children:e=>(()=>{var t=zR();return t.$$click=()=>Ud(t=>Xe(t,e.split)),L(t,n(U,{get name(){return e.icon}})),D(n=>{var r=e.label,i=e.label,a=m()===e.split;return r!==n.e&&R(t,`aria-label`,n.e=r),i!==n.t&&R(t,`title`,n.t=i),a!==n.a&&R(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})),L(r,s,i),L(r,ct,a),e}}),t),L(e,n(u,{get when(){return g()},get children(){var e=LR();return e.$$keydown=N,L(e,n(o,{get each(){return l()},children:e=>{let t=()=>f()===e,r=()=>y(e);return(()=>{var i=BR(),a=i.firstChild;return a.$$click=()=>E(d(e)),L(a,r),L(i,n(z,{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-${YR(e)}`,s=`pane-${YR(e)}`,c=t(),l=t()?0:-1;return r!==n.e&&K(i,n.e=r),o!==n.t&&R(a,`id`,n.t=o),s!==n.a&&R(a,`aria-controls`,n.a=s),c!==n.o&&R(a,`aria-selected`,n.o=c),l!==n.i&&R(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`?he(r,t):re=t,L(t,n(o,{get each(){return l()},children:e=>{let t=JR(e),r=()=>d(e),i=()=>f()===e,a=()=>!g()||i();return(()=>{var o=VR();return o.$$pointerdown=()=>E(d(e)),o.$$focusin=()=>E(d(e)),L(o,n(u,{get when(){return qR(e)===void 0},get fallback(){return n(c,{get fallback(){return HR()},get children(){return n(UR,{get artifactID(){return qR(e)},get paneTools(){return n(P,{key:e})},onTitle:t=>v(n=>({...n,[qR(e)]:t}))})}})},get children(){return n(u,{get when(){return!e.includes(`#`)},get fallback(){return n(ER,{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(P,{key:e})}})},get children(){return n(XL,{id:t,visible:a,focused:i,onGone:()=>ne(e),rail:()=>!b()||i(),get paneTools(){return n(P,{key:e})}})}})}})),D(t=>{var n=`pane-${YR(e)}`,c=g()?`tabpanel`:`region`,l=g()?`pane-tab-${YR(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&&R(o,`id`,t.e=n),c!==t.t&&R(o,`role`,t.t=c),l!==t.a&&R(o,`aria-labelledby`,t.a=l),u!==t.o&&R(o,`aria-label`,t.o=u),d!==t.i&&R(o,`data-focused`,t.i=d),f!==t.n&&(o.hidden=t.n=f),t.s=Ve(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),L(t,n(u,{get when(){return S()},get children(){return n(o,{get each(){return l()},children:e=>n(aR,{get index(){return d(e)},get style(){return M(d(e))}})})}}),null),L(t,n(o,{get each(){return de(A().cols-1)},children:e=>n(lR,{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),L(t,n(o,{get each(){return de(A().rows-1)},children:e=>n(lR,{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&&K(e,n.e=r),i!==n.t&&R(e,`data-split`,n.t=i),n.a=Ve(t,a,n.a),n},{e:void 0,t:void 0,a:void 0}),e})()]}})}F([`keydown`,`click`,`focusin`,`pointerdown`]);var $R={artifacts:i(()=>yN(()=>import(`./Library-BXbJvTUS.js`),__vite__mapDeps([5,1,3,6]))),teams:i(()=>yN(()=>import(`./TeamsPage-Dgxt8UI3.js`),__vite__mapDeps([7,1,8,9,10]))),watchtower:i(()=>yN(()=>import(`./Watchtower-DJHx6cWw.js`).then(e=>e.t),__vite__mapDeps([11,1,9,8,10,12]))),profiles:i(()=>yN(()=>import(`./ProfilesDestination-D7XyLTJ7.js`),__vite__mapDeps([13,1,8])))},ez=J(`<div class=feature-page><header class=topbar><h1 class=title></h1></header><div class=feature-scroll><div class=feature-body>`);function tz(e){return(()=>{var t=ez(),r=t.firstChild,i=r.firstChild,a=r.nextSibling.firstChild;return L(r,n(u,{get when(){return Z()},get children(){return n(z,{icon:`menu`,label:`Open sidebar`,onClick:Df})}}),i),L(i,()=>e.title),L(r,()=>e.actions,null),L(a,()=>e.children),t})()}var nz=J(`<p class=feature-note> isn't available yet. <a href=/>Back to All sessions`),rz=J(`<p class=muted>Loading…`);function iz(e){let t=T(()=>r.find(t=>t.id===e.id)),i=T(()=>{let e=t();return e&&oe(e,{signedIn:!!X()})===`ok`?$R[e.id]:void 0});return n(u,{get when(){return i()},get fallback(){return n(tz,{get title(){return t()?.label??`Not found`},get children(){var e=nz(),n=e.firstChild;return L(e,()=>t()?.label??`This page`,n),e}})},children:r=>n(c,{get fallback(){return n(tz,{get title(){return t().label},get children(){return rz()}})},get children(){return n(Le,{get component(){return r()},get rest(){return e.rest}})}})})}var az=J(`<span class="badge-pill armed-left"role=timer title="How long this stays armed for a spoken answer">`),oz=J(`<p class="muted small armed-why">Why: `),sz=J(`<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">`),cz=J(`<button type=button>`);function lz(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=gl()?.expiresAt;return e===void 0?``:tn(e,a())},d=async e=>{i(!0);try{await ty(t().id,e)}catch(e){q(W(e),`err`),i(!1)}};return(()=>{var e=sz(),i=e.firstChild,a=i.firstChild.nextSibling.nextSibling;a.firstChild;var s=i.nextSibling,c=s.nextSibling,f=c.nextSibling;return L(a,()=>Nn(t(),Fl,yl()),null),L(i,n(u,{get when(){return l()},get children(){var e=az();return L(e,l),e}}),null),L(s,()=>Fn(t(),Fl,yl())),L(e,n(dh,{get decision(){return t()}}),c),L(e,n(u,{get when(){return H(()=>!!t().recommendation?.why)()&&t().recommendation.why!==fh(t())},get children(){var e=oz();return e.firstChild,L(e,()=>t().recommendation.why,null),e}}),c),L(c,n(o,{get each(){return t().options},children:e=>(()=>{var t=cz();return t.$$click=()=>void d(e.id),L(t,()=>e.label),D(n=>{var i=`btn${e.safe||e.id===`always`?``:` primary`}`,a=r();return i!==n.e&&K(t,n.e=i),a!==n.t&&(t.disabled=n.t=a),n},{e:void 0,t:void 0}),t})()})),L(f,()=>dc(!!Qc()&&!Qc().reason)),D(n=>{var r=t().id,i=t().id,o=Pn(t()),c=t().question;return r!==n.e&&R(e,`data-armed-decision`,n.e=r),i!==n.t&&R(e,`data-decision`,n.t=i),o!==n.a&&R(a,`title`,n.a=o),c!==n.o&&R(s,`title`,n.o=c),n},{e:void 0,t:void 0,a:void 0,o:void 0}),e})()}F([`click`]);var uz=J(`<button type=button class="btn small"aria-label="Restart the Concierge"title="Restart the Concierge (a new session)">Restart`),dz=J(`<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">`),fz=J(`<p role=status data-concierge-notice>`),pz=J(`<div class=concierge-asked aria-label="Decisions from the Concierge"role=group>`),mz=J(`<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>`),hz=J(`<div class=concierge-idle><form class=concierge-composer><textarea rows=1 aria-label="Ask the Concierge"placeholder="The Concierge is not running"disabled>`),gz=J(`<aside class="concierge-panel side"aria-label=Concierge tabindex=-1>`),_z=J(`<section class="concierge-panel page"aria-label=Concierge tabindex=-1>`),vz=J(`<p class="working-line muted small"role=status><span class="spinner small"></span> Working…`),yz=J(`<div class=concierge-scroll>`),bz=J(`<p class="note err"role=alert>Voice: `),xz=J(`<button type=button>`),Sz=J(`<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)">`),Cz=J(`<p class="muted small pad">Loading…`),wz=J(`<p class="muted small pad">`),Tz=J(`<p>`),Ez=3e4,Dz=80,Oz=/^#decision-(dec_[A-Za-z0-9]{1,64})$/,kz=new Set([`starting`,`running`,`waiting_machine`,`backoff`,`failed`]),Az=()=>!!Qc()&&!Qc().reason;function jz(e){let t=ll,r=()=>(Y.machines??[]).map(e=>({id:e.id,name:e.name,online:e.online===!0})),i=()=>r().find(e=>e.id===t()?.machineID),o=()=>pc(t(),i()),s=()=>t()?.state===`running`&&!!t()?.sessionID&&i()?.online!==!1,c=T(()=>$v()),l=T(()=>Sc(nl(),t(),c())),[d,f]=x(!1),[p,m]=x(),g,_=MO(),v=()=>me(`/`);async function y(){f(!0);try{await G(`/api/agent/concierge/restart`,{method:`POST`,json:{}}),q(`Restarting the Concierge`)}catch(e){q(`Could not restart: ${W(e)}`,`err`)}finally{f(!1)}}ue(()=>{if(e.mode!==`side`)return;let t=e=>{e.key!==`Escape`||e.defaultPrevented||be(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})):q(`That Decision is no longer available`)});if(g?.querySelector(`[data-decision="${e}"]`))return t();vu(e).then(e=>{e&&e.state!==`open`&&m(e),t()})}C(h(ie,e=>{let t=Oz.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&&Oz.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=dz(),a=i.firstChild,o=a.firstChild.nextSibling,s=a.nextSibling;return L(i,n(u,{get when(){return e.mode===`page`},get children(){return n(z,{icon:`back`,label:`Back`,onClick:v})}}),a),L(i,n(U,{name:`spark`,class:`concierge-mark`}),a),L(o,()=>Ss(t(),r(),I())),L(i,n(u,{get when(){return H(()=>!!t())()&&kz.has(t().state)},get children(){var e=uz();return e.$$click=()=>void y(),D(()=>e.disabled=d()),e}}),s),L(s,n(U,{name:`settings`})),L(i,n(u,{get when(){return e.mode===`side`},get children(){return n(z,{icon:`close`,label:`Close the Concierge (Esc)`,onClick:v})}}),null),D(()=>R(o,`data-concierge-panel-status`,t()?.state??`none`)),i})(),n(u,{get when(){return o()},get children(){var e=fz();return L(e,o),D(()=>K(e,`concierge-notice${t()?.state===`failed`?` err`:``}`)),e}}),n(u,{get when(){return c()},children:e=>n(lz,{get decision(){return e()}})}),n(u,{get when(){return l().length},get children(){var e=pz();return L(e,n(Oh,{get decisions(){return l()}})),e}}),n(u,{get when(){return p()},keyed:!0,children:e=>(()=>{var t=mz(),r=t.firstChild,i=r.firstChild.nextSibling.nextSibling;i.nextSibling;var a=r.nextSibling,o=a.nextSibling;return L(i,()=>e.state),L(r,n(z,{icon:`close`,label:`Close this Decision`,onClick:()=>m(void 0)}),null),L(a,()=>Fn(e,Fl,yl())),L(t,n(dh,{decision:e}),o),L(o,()=>ns(e)),D(n=>{var r=`Decision (${e.state}): ${e.question}`,i=e.id,o=e.id,s=e.question;return r!==n.e&&R(t,`aria-label`,n.e=r),i!==n.t&&R(t,`data-decision`,n.t=i),o!==n.a&&R(t,`data-closed-decision`,n.a=o),s!==n.o&&R(a,`title`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),n(u,{get when(){return H(()=>!!s())()&&t()?.sessionID},keyed:!0,get fallback(){return(()=>{var e=hz();return e.firstChild.addEventListener(`submit`,e=>e.preventDefault()),e})()},children:t=>n(Mz,{id:t,get autofocus(){return e.mode===`side`}})})];return n(u,{get when(){return e.mode===`side`},get fallback(){return(()=>{var e=_z(),t=g;return typeof t==`function`?he(t,e):g=e,L(e,S),e})()},get children(){var e=gz(),t=g;return typeof t==`function`?he(t,e):g=e,L(e,S),e}})}function Mz(t){let r=t.id,i=()=>Al(r),a=()=>i()?.session.status,s=()=>Po(a()),c=new Vt,[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),Hk(c.rows()))),E=T(()=>Pz(w())),[ee,te]=pi({}),O,ne=!0,re=()=>requestAnimationFrame(()=>O&&(O.scrollTop=O.scrollHeight));C(h(E,()=>ne&&re())),C(()=>{for(let e of os(w(),ol()))vu(e)});let ie=e=>new URLSearchParams(Object.entries(e).flatMap(([e,t])=>t===void 0?[]:[[e,String(t)]])).toString(),ae=new yk(c,e=>B(`${P(r)}/timeline?${ie(e)}`),{limit:Dz,onChange:f});async function k(){try{let{messages:e}=await B(`${P(r)}/messages?limit=200`);for(let t of e??[]){let e=Wt(r,t);e&&c.hubMessage(e)}f()}catch{}}async function A(){try{await ae.first()}catch(e){S(`Could not load the conversation: ${W(e)}`,`err`)}m(!0),await k(),re()}let oe,se=s(),ce=Ol(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=Wt(r,e.message);t&&c.hubMessage(t)}else if(e.type===`turn`&&oe){let{sentAt:t}=oe;oe=void 0,Se(e,t)}else if(e.type===`status`){let t=Po(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)=>(Qv(e),G(`${P(r)}/presence`,{method:`POST`,json:{visible:e},keepalive:t}).catch(()=>{})),de=()=>void M(le(),!le()),fe=()=>void M(!1,!0),N,pe=py,me=()=>pe().phase!==`off`&&pe().sessionID===r,ge=()=>pe().error?.sessionID===r?pe().error.message:void 0;j(ry.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}=O_(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 _e(){me()||(zv(),gy.cancel()),await ry.toggle(r),ry.isOn(r)&&ry.state.phase===`on`&&S(`Voice on. Talk to the Concierge; say “yes” or “no” to answer the Decision it is asking about.`)}let[ve,F]=x(``),[ye,I]=x(!1),be,xe=()=>{be&&(be.style.height=`auto`,be.style.height=`${Math.min(be.scrollHeight,200)}px`)};function Se(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=sg(e);i&&S(i.text,i.kind),f()}async function z(){let t=ve().trim();if(!t||ye())return;let n=$v(),i=ic(t,n);if(i.kind===`answer`){I(!0);try{await ty(i.decisionID,i.option,`text`),F(``),c.upsert({key:`answered:${++b}`,kind:`user`,text:t,at:Date.now(),note:oc(n,i.option)}),f(),ne=!0,re()}catch(t){q(`Not answered: ${W(t)}${t instanceof e&&t.status===403?`. Tap an option on the card.`:``}`,`err`)}finally{I(!1)}return}if(F(``),queueMicrotask(xe),me()){ry.sendTyped(r,t);return}let a=`local:${++b}`,o=Date.now();Ee(()=>{c.upsert({key:a,kind:`user`,text:t,at:o}),_(e=>({...e,[a]:`pending`})),f()}),ne=!0,re();try{let e=await G(`${P(r)}/turn`,{method:`POST`,json:{text:t},headers:{prefer:`respond-async`}}),n=await e.json().catch(()=>({})),i=og(e.status,n);_(e=>({...e,[a]:i===`steered`?`queued`:`sent`})),i===`accepted`?oe={sentAt:o}:Se(n,o)}catch(e){_(e=>({...e,[a]:`failed`})),S(`Could not send: ${W(e)}`,`err`),ve()||F(t)}}return ue(()=>{A(),M(le()),N=setInterval(()=>le()&&void M(!0),Ez),document.addEventListener(`visibilitychange`,de),window.addEventListener(`pagehide`,fe),t.autofocus&&requestAnimationFrame(()=>be?.focus())}),j(()=>{ce(),clearInterval(N),document.removeEventListener(`visibilitychange`,de),window.removeEventListener(`pagehide`,fe),fe()}),[(()=>{var e=yz();e.addEventListener(`scroll`,e=>ne=e.currentTarget.scrollHeight-e.currentTarget.scrollTop-e.currentTarget.clientHeight<80);var t=O;return typeof t==`function`?he(t,e):O=e,L(e,n(u,{get when(){return p()},get fallback(){return Cz()},get children(){return n(u,{get when(){return E().length},get fallback(){return(()=>{var e=wz();return L(e,()=>uc(Az())),e})()},get children(){return n(PP,{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),L(e,n(o,{get each(){return v()},children:e=>(()=>{var t=Tz();return L(t,()=>e.text),D(n=>{var r=`note ${e.kind}`,i=e.kind===`err`?`alert`:void 0;return r!==n.e&&K(t,n.e=r),i!==n.t&&R(t,`role`,n.t=i),n},{e:void 0,t:void 0}),t})()}),null),L(e,n(u,{get when(){return s()},get children(){return vz()}}),null),e})(),(()=>{var e=Sz(),t=e.firstChild,r=t.firstChild,i=r.nextSibling;L(e,n(u,{get when(){return me()},get children(){return n(SA,{get state(){return pe().voice},get level(){return pe().level},get held(){return pe().held},get ignored(){return pe().ignored},get working(){return s()},model:`Concierge`,onMute:()=>ry.mute(),onEnd:()=>void ry.end(),onModel:()=>q(`The Concierge keeps its own model: change it in Settings → Concierge`),get notifyHint(){return dy()},onAllowNotifications:()=>void fy(),get timing(){return pe().timing},get detector(){return pe().detector}})}}),t),L(e,n(u,{get when(){return ge()},get children(){var e=bz();return e.firstChild,L(e,ge,null),e}}),t),t.addEventListener(`submit`,e=>{e.preventDefault(),z()}),r.$$keydown=e=>{e.key===`Enter`&&!e.shiftKey&&!e.isComposing&&!(Z()&&`ontouchstart`in window)&&(e.preventDefault(),z())},r.$$input=e=>{F(e.currentTarget.value),xe()};var a=be;return typeof a==`function`?he(a,r):be=r,L(t,n(u,{get when(){return Az()||me()},get children(){var e=xz();return e.$$click=()=>void _e(),L(e,n(U,{name:`wave`})),D(t=>{var n=`icon-btn concierge-voice${me()?` on`:``}`,r=me(),i=me()?`Stop talking to the Concierge`:`Talk to the Concierge`,a=me()?`End Voice with the Concierge`:`Talk to the Concierge (Voice)`;return n!==t.e&&K(e,t.e=n),r!==t.t&&R(e,`aria-pressed`,t.t=r),i!==t.a&&R(e,`aria-label`,t.a=i),a!==t.o&&R(e,`title`,t.o=a),t},{e:void 0,t:void 0,a:void 0,o:void 0}),e}}),i),L(i,n(U,{name:`send`})),D(e=>{var t=me()?`Voice is on: talk, or type here`:`Ask the Concierge…`,n=!ve().trim()||ye();return t!==e.e&&R(r,`placeholder`,e.e=t),n!==e.t&&(i.disabled=e.t=n),e},{e:void 0,t:void 0}),D(()=>r.value=ve()),e})()]}var Nz={unknown:`link`};function Pz(e){let t=jl,n=[...ol().values()].map(e=>({...e,question:jn(e.question,Fl)})),r=[];for(let i of e)if(!(i.type===`message`&&i.primer)){if(i.type===`message`&&i.direction===`in`&&zo(i.from)){let e=Ko(i.text,t);r.push(e?{...i,summary:e}:i)}else i.type===`message`&&i.text.includes(`dec_`)?r.push({...i,parts:Qo(i.text,n,Nz)}):i.type===`assistant`&&i.text.includes(`dec_`)?r.push({...i,text:$o(i.text,n,Nz)}):i.type===`tools`?r.push({...i,items:i.items.map(e=>typeof e.summary==`string`&&e.summary.includes(`ses_`)?{...e,summary:ts(e.summary,t)}:e)}):r.push(i)}return r}F([`click`,`input`,`keydown`]);var Fz=J(`<main class=entry><p></p><button type=button class=btn>Retry`),Iz=J(`<main class=entry><p class=muted>Loading…`),Lz=J(`<div class=drawer-backdrop>`),Rz=J(`<div class=voice-strip>`),zz=J(`<div class=conn-banner role=status>Reconnecting to the hub…`),Bz=J(`<div role=status aria-live=polite>`),Vz=J(`<p class="muted cmp-empty"data-concierge-wait>Loading…`),Hz=J(`<div><main class=main>`),Uz=J(`<button type=button class="btn small">`),Wz=J(`<div role=status aria-live=polite><span>`),Gz=J(`<header class=topbar><span class="title display grow">Hub`),Kz=J(`<div class=home-shell><div class=home-scroll>`),qz=()=>He().name===`concierge`&&!Z(),Jz=()=>{let e=qb();return e.name===`session`?gs(e.id,ll(),hl(),Y.machines,dl(),dl()?[]:vl()):void 0},Yz=()=>{let e=qb();return Jz()===`session`?e.id:void 0},Xz=()=>Dc(Ic(py().phase===`off`,Yz()),He().name===`concierge`?ll()?.sessionID:void 0);function Zz(){Xl(()=>py().phase!==`off`),C(()=>Zl(Xz()));let[e,t]=x(``),[r,i]=x(!1),o=async()=>{t(``);try{if(!await Rl())return;eu(Xz()),Su(),Fd(),i(!0)}catch(e){t(`Cannot reach the hub: ${e.message}`)}};return C(h(()=>He().name,e=>{e!==`pair`&&!r()&&o(),Z()&&Sf(!1)})),C(()=>{!X()&&r()&&He().name!==`pair`&&i(!1)}),C(()=>{let e=He();e.name===`session`&&yl().has(e.id)&&a(`/concierge`,{replace:!0})}),C(()=>gy.viewing(Fc()??Yz())),ue(()=>j(tT())),ue(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`b`&&(e.preventDefault(),Df())};document.addEventListener(`keydown`,e),j(()=>document.removeEventListener(`keydown`,e))}),C(()=>Lf(qz())),C(()=>{let e=Rf(),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`&&He().name!==`settings`&&a(`/settings/voice#speech`,{replace:!0})}),[n(ee,{get children(){return[n(A,{get when(){return H(()=>He().name===`pair`)()&&He()},children:e=>n(md,{get next(){return e().next},get error(){return e().error}})}),n(A,{get when(){return e()},get children(){var t=Fz(),n=t.firstChild,r=n.nextSibling;return L(n,e),r.$$click=()=>void o(),t}}),n(A,{get when(){return!r()},get children(){return Iz()}}),n(A,{get when(){return H(()=>He().name===`approve`)()&&He()},children:e=>n(gd,{get code(){return e().code}})}),n(A,{when:!0,get children(){var e=Hz(),t=e.firstChild;return L(e,n(u,{get when(){return!Z()||xf()},get children(){return[n(u,{get when(){return Z()},get children(){var e=Lz();return e.$$click=()=>Sf(!1),e}}),n(u,{get when(){return!yf()||Z()},get children(){return[n(JO,{get phone(){return Z()},onClose:()=>Sf(!1),onCollapse:Df}),n(u,{get when(){return!Z()},get children(){return n(Qy,{panel:`side`,label:`Resize sidebar`})}})]}})]}}),t),L(e,n(u,{get when(){return H(()=>!!yf())()&&!Z()},get children(){return n(EO,{onExpand:Df})}}),t),L(t,n(u,{get when(){return H(()=>py().phase!==`off`)()&&qb().name!==`session`},get children(){var e=Rz();return L(e,n(pD,{})),e}}),null),L(t,n(u,{get when(){return Y.connection===`down`},get children(){return zz()}}),null),L(t,n(u,{get when(){return H(()=>Y.connection!==`down`)()&&Gl()},get children(){var e=Bz();return L(e,()=>Gl()===`reconnecting`?`Reconnecting…`:`Updated`),D(()=>K(e,`sync-note ${Gl()}`)),e}}),null),L(t,n(u,{get when(){return H(()=>!(!Kf()||Z()||Yz()))()&&qb().name!==`panes`},get children(){return n(sR,{})}}),null),L(t,n(ee,{get children(){return[n(A,{get when(){return H(()=>!hl())()&&(qb().name===`session`||qb().name===`panes`)||Jz()===`wait`},get children(){return Vz()}}),n(A,{get when(){return Yz()||qb().name===`panes`},get children(){return n(QR,{get routed(){return Yz()}})}}),n(A,{get when(){return H(()=>qb().name===`new`)()&&qb()},children:e=>n(Wb,ce(()=>e()))}),n(A,{get when(){return H(()=>qb().name===`feature`)()&&qb()},children:e=>n(iz,ce(()=>e()))}),n(A,{get when(){return qb().name===`settings`},get children(){return n(BE,{})}}),n(A,{get when(){return qb().name===`concierge`},get children(){return n(jz,{mode:`page`})}}),n(A,{when:!0,get children(){return n(Qz,{})}})]}}),null),L(e,n(u,{get when(){return qz()},get children(){return n(jz,{mode:`side`})}}),null),D(()=>K(e,`shell${yf()&&!Z()?` collapsed`:``}${Z()?` phone`:``}${xf()?` drawer`:``}`)),e}})]}}),n(_m,{}),n(ke,{}),n(u,{get when(){return fe()},children:e=>(()=>{var t=Wz(),r=t.firstChild;return L(r,()=>e().text),L(t,n(u,{get when(){return e().action},get children(){var t=Uz();return t.$$click=()=>{e().action.run(),Be()},L(t,()=>e().action.label),t}}),null),D(()=>K(t,`toast ${e().kind}`)),t})()})]}function Qz(){return(()=>{var e=Kz(),t=e.firstChild;return L(e,n(u,{get when(){return Z()},get children(){var e=Gz(),t=e.firstChild;return L(e,n(z,{icon:`menu`,label:`Open sidebar`,onClick:Df}),t),L(e,n(NO,{}),null),e}}),t),L(t,n(Ky,{})),e})()}F([`click`]),Ae(()=>n(Zz,{}),document.getElementById(`root`)),Id();export{HN as A,Gd as B,ZF as C,zP as D,oF as E,Yf as F,Ol as H,Jf as I,Z as L,Sk as M,sT as N,JN as O,gm as P,Df as R,_F as S,gF as T,kl as U,Y as V,FF as _,sI as a,lF as b,mI as c,oI as d,cI as f,IF as g,LF as h,lI as i,yN as j,WN as k,aI as l,RF as m,dI as n,iI as o,EF as p,uI as r,tI as s,tz as t,fI as u,PF as v,fF as w,cF as x,NF as y,qd as z};
|