@huynle/hub 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/README.md +20 -4
  3. package/package.json +1 -1
  4. package/packages/claude-code/package.json +1 -1
  5. package/packages/cli/dist/hub-cli.js +625 -395
  6. package/packages/cli/package.json +1 -1
  7. package/packages/cli/src/grants-mcp.ts +65 -0
  8. package/packages/cli/src/mcp-operations.ts +49 -0
  9. package/packages/cli/src/mcp.ts +6 -0
  10. package/packages/cli/src/subscriptions-mcp.ts +76 -0
  11. package/packages/cli/src/teams-mcp.ts +5 -3
  12. package/packages/codex/package.json +1 -1
  13. package/packages/node/package.json +1 -1
  14. package/packages/preset/package.json +1 -1
  15. package/packages/protocol/package.json +1 -1
  16. package/packages/protocol/src/index.ts +13 -1
  17. package/packages/protocol/src/teams.ts +4 -0
  18. package/packages/protocol/src/voice-recording.ts +39 -2
  19. package/packages/runtime-openshell/image/entry.sh +3 -1
  20. package/packages/runtime-openshell/image/start.sh +3 -1
  21. package/packages/runtime-openshell/package.json +1 -1
  22. package/packages/runtime-sdk/package.json +1 -1
  23. package/packages/sdk/package.json +1 -1
  24. package/packages/sdk/src/client.ts +13 -0
  25. package/packages/sdk/src/teams.ts +2 -0
  26. package/packages/spoke-sdk/package.json +1 -1
  27. package/src/central/agent/decisions.ts +7 -1
  28. package/src/central/agent/delivery.ts +39 -9
  29. package/src/central/agent/grant-routes.ts +14 -1
  30. package/src/central/agent/grants.ts +23 -0
  31. package/src/central/agent/launch-engine.ts +3 -3
  32. package/src/central/agent/message-limits.ts +3 -0
  33. package/src/central/agent/routes.ts +11 -0
  34. package/src/central/agent/subscriptions.ts +3 -1
  35. package/src/central/config.ts +9 -2
  36. package/src/central/http.ts +135 -24
  37. package/src/central/recording/export.ts +57 -3
  38. package/src/central/recording/index.ts +234 -16
  39. package/src/central/recording/ingest.ts +11 -2
  40. package/src/central/recording/routes.ts +61 -7
  41. package/src/central/recording/schema.ts +66 -2
  42. package/src/central/recording/settings.ts +19 -5
  43. package/src/central/recording/store.ts +19 -0
  44. package/src/central/recording/taps.ts +45 -1
  45. package/src/central/speech/openai.ts +4 -4
  46. package/src/central/speech/openrouter.ts +4 -4
  47. package/src/central/speech/provider.ts +32 -1
  48. package/src/central/speech/service.ts +6 -5
  49. package/src/central/teams/hop-stalls.ts +72 -0
  50. package/src/central/teams/policy.ts +10 -0
  51. package/src/central/teams/routes.ts +2 -0
  52. package/src/central/teams/seats.ts +3 -3
  53. package/src/central/teams/staffing.ts +5 -0
  54. package/src/central/teams/store.ts +5 -2
  55. package/src/central/teams/validation.ts +8 -5
  56. package/src/spoke/spoke.ts +19 -0
  57. package/web/dist/assets/{ArtifactPage-Bz992ZX6.js → ArtifactPage-C5MMqXLN.js} +1 -1
  58. package/web/dist/assets/{ArtifactPane-BJZNixJC.js → ArtifactPane-CXSCmhyJ.js} +1 -1
  59. package/web/dist/assets/{ArtifactWorkbench-Dti3VP07.js → ArtifactWorkbench-S0RxNGWy.js} +1 -1
  60. package/web/dist/assets/{Diagram-B4HdUxw0.js → Diagram-BGmyRb-R.js} +1 -1
  61. package/web/dist/assets/{Library-CpzD2HDW.js → Library-CFmMbXEa.js} +2 -2
  62. package/web/dist/assets/{ProfilesDestination-DlQeogea.js → ProfilesDestination-7jpOc2HM.js} +1 -1
  63. package/web/dist/assets/{TeamsPage-4xdWCaI-.js → TeamsPage-C1NGrUR-.js} +1 -1
  64. package/web/dist/assets/{Watchtower-CpQdIRns.js → Watchtower-DnvlJaU0.js} +2 -2
  65. package/web/dist/assets/{artifacts-But87Jfo.js → artifacts-DlQEYmDl.js} +1 -1
  66. package/web/dist/assets/index-Da8SKXMw.js +33 -0
  67. package/web/dist/assets/{index-BC0O1gfR.css → index-Dyq-jBeE.css} +1 -1
  68. package/web/dist/assets/live-BmqLASSo.js +5 -0
  69. package/web/dist/assets/{pane-layout-BW0RdX5a.js → pane-layout-BAuu_pA3.js} +1 -1
  70. package/web/dist/assets/{renderer2d-IaJiloPi.js → renderer2d-B2Nh39UN.js} +1 -1
  71. package/web/dist/assets/{renderer3d-ZiD1uKGW.js → renderer3d-CTYbljHH.js} +1 -1
  72. package/web/dist/assets/{safe-area-C7IAlkgY.js → safe-area-CkhEclGo.js} +1 -1
  73. package/web/dist/assets/{silero-worker-e802lB5T.js → silero-worker-CC2etKS3.js} +1 -1
  74. package/web/dist/assets/{source-C-De8L3s.js → source-GYayxUxS.js} +1 -1
  75. package/web/dist/assets/{toast-CXTwTvDw.js → toast-q818mjUF.js} +1 -1
  76. package/web/dist/index.html +5 -5
  77. package/web/dist/assets/index-BS6lA6fN.js +0 -33
  78. package/web/dist/assets/live-CVUFIdUX.js +0 -5
@@ -0,0 +1,33 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Diagram-BGmyRb-R.js","assets/ui-CFB4wQfF.js","assets/MediaImage-Ch3ryIdR.js","assets/preload-helper-BLdHbfdN.js","assets/Lightbox-BlbivCkd.js","assets/Lightbox-C8KNKwOA.css","assets/Diagram-7y8kg3og.css","assets/ArtifactPane-CXSCmhyJ.js","assets/ArtifactWorkbench-S0RxNGWy.js","assets/toast-q818mjUF.js","assets/artifacts-DlQEYmDl.js","assets/pane-layout-BAuu_pA3.js","assets/source-GYayxUxS.js","assets/ArtifactWorkbench-9eTj1CeW.css","assets/Library-CFmMbXEa.js","assets/Library-DYsFj_5c.css","assets/TeamsPage-C1NGrUR-.js","assets/plural-Bspvoqfq.js","assets/live-BmqLASSo.js","assets/live-BUofsQpz.css","assets/Watchtower-DnvlJaU0.js","assets/Watchtower-RphjcL0_.css","assets/ProfilesDestination-7jpOc2HM.js"])))=>i.map(i=>d[i]);
2
+ import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as g,Q as _,R as v,S as y,T as b,U as x,V as S,W as C,X as w,Y as T,Z as E,_ as D,a as O,b as k,c as A,d as j,et as M,f as N,g as ee,h as P,i as F,j as te,k as I,l as ne,m as re,n as ie,nt as ae,o as oe,p as se,q as ce,r as L,rt as le,s as ue,t as de,tt as fe,u as R,v as pe,w as me,x as z,y as B,z as he}from"./ui-CFB4wQfF.js";import{$ as ge,A as _e,At as ve,B as V,Bt as ye,C as be,Ct as xe,D as Se,Dt as Ce,E as we,Et as Te,F as Ee,Ft as De,G as H,Gt as Oe,H as U,Ht as ke,It as Ae,J as je,Jt as Me,K as Ne,Kt as Pe,L as Fe,Lt as Ie,M as Le,Mt as Re,N as ze,Nt as Be,O as Ve,Ot as He,P as Ue,Pt as We,Q as Ge,R as W,Rt as Ke,S as qe,St as Je,T as Ye,Tt as Xe,U as G,Ut as Ze,V as K,Vt as Qe,W as $e,Wt as et,X as tt,Xt as nt,Y as rt,Yt as it,Z as at,_ as ot,_t as st,at as ct,b as lt,bt as ut,c as dt,ct as ft,d as pt,dt as mt,et as ht,f as gt,ft as _t,g as vt,gt as yt,h as bt,ht as xt,i as St,it as Ct,j as wt,jt as Tt,k as Et,kt as Dt,l as Ot,lt as kt,m as At,mt as jt,n as Mt,nt as Nt,o as Pt,ot as Ft,p as It,pt as Lt,q as Rt,qt as zt,r as q,rt as Bt,s as Vt,st as Ht,t as Ut,tt as Wt,u as Gt,ut as Kt,v as qt,vt as Jt,w as Yt,wt as Xt,x as Zt,xt as Qt,y as $t,yt as en,z as tn,zt as nn}from"./toast-q818mjUF.js";import{c as rn,d as an,f as on,g as sn,h as cn,i as ln,l as un,m as dn,n as fn,o as pn,r as mn,s as hn,t as gn}from"./pane-layout-BAuu_pA3.js";import{t as _n}from"./plural-Bspvoqfq.js";import{a as vn,c as yn,i as bn,l as xn,o as Sn,r as Cn,s as wn,t as Tn,u as En}from"./artifacts-DlQEYmDl.js";import{_ as Dn,a as On,b as kn,d as An,f as jn,g as Mn,h as Nn,m as Pn,n as Fn,o as In,p as Ln,r as Rn,t as zn,x as Bn,y as Vn}from"./MediaImage-Ch3ryIdR.js";import{t as Hn}from"./preload-helper-BLdHbfdN.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var Un=e=>e==null?``:String(e).trim(),Wn=Object.freeze([[`role`,`Admins first`],[`email`,`Email`],[`lastSeen`,`Last seen`]]),Gn=Object.freeze([[`all`,`All`],[`admins`,`Admins`],[`active`,`Active`],[`disabled`,`Disabled`]]),Kn=Object.freeze({signin:`Signed in`,"signin.denied":`Sign-in refused`,"device.pair":`Paired a device`,"device.revoke":`Revoked a device`,"machine.approve":`Approved a machine`,"machine.deny":`Denied a machine`,"machine.revoke":`Revoked a machine`,"user.role":`Changed a role`,"user.disable":`Disabled a user`,"user.enable":`Enabled a user`,"speech.default":`Changed the server speech default`,"migrate.local":`Moved the hub owner's machines and devices to the first admin`,"app-client.create":`Registered an app client`,"app-client.update":`Changed an app client`,"app-client.secret":`Rotated an app client's secret`,"app-client.delete":`Deleted an app client`,"connect.authorize":`An app asked to connect`,"connect.consent":`Connected an app`,"connect.deny":`Denied an app`,"connect.token":`Issued a connected app's tokens`,"connect.reuse":`Revoked a connected app (token reuse)`,"connect.revoke":`Revoked a connected app`});function qn(e){return e?.user?.role===`admin`}function Jn(e){let t=e?.user,n=e?.auth===`oidc`?`oidc`:`pairing`,r=qn(e);if(n!==`oidc`)return{mode:n,admin:r,title:`This hub`,initial:`H`};let i=Un(t?.name),a=Un(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 Yn=Object.freeze([[`users`,`Users`],[`machines`,`Machines`],[`approvals`,`Approvals`],[`audit`,`Audit log`]]);function Xn(e){return qn(e)?Yn.filter(([t])=>t!==`users`||e?.auth===`oidc`):[]}function Zn(e,t){return qn(e)&&t?.scope===`user`?[`user`,`default`]:[`user`]}function Qn(e){return e&&e.startsWith(`/`)&&!e.startsWith(`//`)&&!e.includes(`\\`)?e:`/`}function $n(e,t){if(e?.mode===`oidc`&&typeof e.signIn==`string`&&e.signIn)return`${e.signIn}?next=${encodeURIComponent(Qn(t))}`}function er(e){let t=e?.auth===`oidc`?Un(e?.user?.email):``;return t?`This machine will belong to you (${t}).`:`This machine will belong to you.`}var tr={stt:[`provider`,`model`,`baseURL`,`language`],tts:[`provider`,`model`,`voice`,`baseURL`,`speed`]};function nr(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 tr[e]){let n=r?s[t]===void 0||s[t]===null:Un(a[t])===Un(o[t]),l=Un(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 rr(e){return{[e]:Object.fromEntries([...tr[e],`apiKey`].map(e=>[e,null]))}}function ir(e){let t=Un(e);if(!t)return`Unknown action`;if(Kn[t])return Kn[t];let n=t.replace(/[._-]+/g,` `).trim().toLowerCase();return n.charAt(0).toUpperCase()+n.slice(1)}function ar(e,t=[]){let n=new Map(t.map(e=>[e.id,Un(e.email)||Un(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:ir(e.action),target:e.target===void 0?void 0:n.get(e.target)??e.target,detail:e.detail}))}var or=e=>(Un(e.email)||Un(e.name)||e.id).toLowerCase();function sr(e,{query:t=``,filter:n=`all`,sort:r=`role`}={}){let i=Un(t).toLowerCase(),a=e=>(!i||`${Un(e.email)} ${Un(e.name)}`.toLowerCase().includes(i))&&(n===`admins`?e.role===`admin`:n===`disabled`?!!e.disabled:n!==`active`||!e.disabled),o=(e,t)=>or(e).localeCompare(or(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 cr(e,t,n){let r=Un(e.email)||Un(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 lr(e){let t=Un(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 ur=Symbol(`store-raw`),dr=Symbol(`store-node`),fr=Symbol(`store-has`),pr=Symbol(`store-self`);function mr(e){let t=e[te];if(!t&&(Object.defineProperty(e,te,{value:t=new Proxy(e,Sr)}),!Array.isArray(e))){let n=Object.keys(e),r=Object.getOwnPropertyDescriptors(e),i=Object.getPrototypeOf(e),a=i!==null&&typeof e==`object`&&!!e&&!Array.isArray(e)&&i!==Object.prototype;if(a){let e=Object.getOwnPropertyDescriptors(i);n.push(...Object.keys(e)),Object.assign(r,e)}for(let i=0,o=n.length;i<o;i++){let o=n[i];a&&o===`constructor`||r[o].get&&Object.defineProperty(e,o,{configurable:!0,enumerable:r[o].enumerable,get:r[o].get.bind(t)})}}return t}function hr(e){let t;return typeof e==`object`&&!!e&&(e[te]||!(t=Object.getPrototypeOf(e))||t===Object.prototype||Array.isArray(e))}function gr(e,t=new Set){let n,r,i,a;if(n=e!=null&&e[ur])return n;if(!hr(e)||t.has(e))return e;if(Array.isArray(e)){Object.isFrozen(e)?e=e.slice(0):t.add(e);for(let n=0,a=e.length;n<a;n++)i=e[n],(r=gr(i,t))!==i&&(e[n]=r)}else{Object.isFrozen(e)?e=Object.assign({},e):t.add(e);let n=Object.keys(e),o=Object.getOwnPropertyDescriptors(e);for(let s=0,c=n.length;s<c;s++)a=n[s],!o[a].get&&(i=e[a],(r=gr(i,t))!==i&&(e[a]=r))}return e}function _r(e,t){let n=e[t];return n||Object.defineProperty(e,t,{value:n=Object.create(null)}),n}function vr(e,t,n){if(e[t])return e[t];let[r,i]=u(n,{equals:!1,internal:!0});return r.$=i,e[t]=r}function yr(e,t){let n=Reflect.getOwnPropertyDescriptor(e,t);return!n||n.get||!n.configurable||t===te||t===dr||(delete n.value,delete n.writable,n.get=()=>e[te][t]),n}function br(e){w()&&vr(_r(e,dr),pr)()}function xr(e){return br(e),Reflect.ownKeys(e)}var Sr={get(e,t,n){if(t===ur)return e;if(t===te)return n;if(t===p)return br(e),n;let r=_r(e,dr),i=r[t],a=i?i():e[t];if(t===dr||t===fr||t===`__proto__`)return a;if(!i){let n=Object.getOwnPropertyDescriptor(e,t);w()&&(typeof a!=`function`||Object.prototype.hasOwnProperty.call(e,t))&&!(n&&n.get)&&(a=vr(r,t,a)())}return hr(a)?mr(a):a},has(e,t){return t===ur||t===te||t===p||t===dr||t===fr||t===`__proto__`||(w()&&vr(_r(e,fr),t)(),t in e)},set(){return!0},deleteProperty(){return!0},ownKeys:xr,getOwnPropertyDescriptor:yr};function Cr(e,t,n,r=!1){if(t===`__proto__`||!r&&e[t]===n)return;let i=e[t],a=e.length;n===void 0?(delete e[t],e[fr]&&e[fr][t]&&i!==void 0&&e[fr][t].$()):(e[t]=n,e[fr]&&e[fr][t]&&i===void 0&&e[fr][t].$());let o=_r(e,dr),s;if((s=vr(o,t,i))&&s.$(()=>n),Array.isArray(e)&&e.length!==a){for(let t=e.length;t<a;t++)(s=o[t])&&s.$();(s=vr(o,`length`,a))&&s.$(e.length)}(s=o[pr])&&s.$()}function wr(e,t){let n=Object.keys(t);for(let r=0;r<n.length;r+=1){let i=n[r];Tr(i)||Cr(e,i,t[i])}}function Tr(e){return e===`__proto__`||e===`constructor`||e===`prototype`}function Er(e,t){if(typeof t==`function`&&(t=t(e)),t=gr(t),Array.isArray(t)){if(e===t)return;let n=0,r=t.length;for(;n<r;n++){let r=t[n];e[n]!==r&&Cr(e,n,r)}Cr(e,`length`,r)}else wr(e,t)}function Dr(e,t,n=[]){let r,i=e;if(t.length>1){r=t.shift();let a=typeof r,o=Array.isArray(e);if(a===`string`&&(r===`__proto__`||t.length>1&&Tr(r)))return;if(Array.isArray(r)){for(let i=0;i<r.length;i++)Dr(e,[r[i]].concat(t),n);return}if(o&&a===`function`){for(let i=0;i<e.length;i++)r(e[i],i)&&Dr(e,[i].concat(t),n);return}if(o&&a===`object`){let{from:i=0,to:a=e.length-1,by:o=1}=r;for(let r=i;r<=a;r+=o)Dr(e,[r].concat(t),n);return}if(t.length>1){Dr(e[r],t,[r].concat(n));return}i=e[r],n=[r].concat(n)}let a=t[0];typeof a==`function`&&(a=a(i,n),a===i)||(r!==void 0||a!=null)&&(a=gr(a),r===void 0||hr(i)&&hr(a)&&!Array.isArray(a)?wr(i,a):Cr(e,r,a))}function Or(...[e,t]){let n=gr(e||{}),r=Array.isArray(n),i=mr(n);function a(...e){he(()=>{r&&e.length===1?Er(n,e[0]):Dr(n,e)})}return[i,a]}var kr=Symbol(`store-root`);function Ar(e){return e===`__proto__`||e===`constructor`||e===`prototype`}function jr(e,t,n,r,i){if(Ar(n))return;let a=t[n];if(e===a)return;let o=Array.isArray(e);if(n!==kr&&(!hr(e)||!hr(a)||o!==Array.isArray(a)||i&&e[i]!==a[i])){Cr(t,n,e);return}if(o){if(e.length&&a.length&&(!r||i&&e[0]&&e[0][i]!=null)){let t,n,o,s,c,l,u,d;for(o=0,s=Math.min(a.length,e.length);o<s&&(a[o]===e[o]||i&&a[o]&&e[o]&&a[o][i]&&a[o][i]===e[o][i]);o++)jr(e[o],a,o,r,i);let f=Array(e.length),p=new Map;for(s=a.length-1,c=e.length-1;s>=o&&c>=o&&(a[s]===e[c]||i&&a[s]&&e[c]&&a[s][i]&&a[s][i]===e[c][i]);s--,c--)f[c]=a[s];if(o>c||o>s){for(n=o;n<=c;n++)Cr(a,n,e[n]);for(;n<e.length;n++)Cr(a,n,f[n]),jr(e[n],a,n,r,i);a.length>e.length&&Cr(a,`length`,e.length);return}for(u=Array(c+1),n=c;n>=o;n--)l=e[n],d=i&&l?l[i]:l,t=p.get(d),u[n]=t===void 0?-1:t,p.set(d,n);for(t=o;t<=s;t++)l=a[t],d=i&&l?l[i]:l,n=p.get(d),n!==void 0&&n!==-1&&(f[n]=a[t],n=u[n],p.set(d,n));for(n=o;n<e.length;n++)n in f?(Cr(a,n,f[n]),jr(e[n],a,n,r,i)):Cr(a,n,e[n])}else for(let t=0,n=e.length;t<n;t++)jr(e[t],a,t,r,i);a.length>e.length&&Cr(a,`length`,e.length);return}let s=Object.keys(e);for(let t=0,n=s.length;t<n;t++)Ar(s[t])||jr(e[s[t]],a,s[t],r,i);let c=Object.keys(a);for(let t=0,n=c.length;t<n;t++)e[c[t]]===void 0&&Cr(a,c[t],void 0)}function Mr(e,t={}){let{merge:n,key:r=`id`}=t,i=gr(e);return e=>{if(!hr(e)||!hr(i))return i;let t=jr(i,{[kr]:e},kr,n,r);return t===void 0?e:t}}var Nr=new WeakMap,Pr={get(e,t){if(t===ur)return e;let n=e[t];if(t===te||t===p||t===dr||t===fr||t===`__proto__`)return n;let r;return hr(n)?Nr.get(n)||(Nr.set(n,r=new Proxy(n,Pr)),r):n},set(e,t,n){return Cr(e,t,gr(n)),!0},deleteProperty(e,t){return Cr(e,t,void 0,!0),!0}};function Fr(e){return t=>{if(hr(t)){let n;(n=Nr.get(t))||Nr.set(t,n=new Proxy(t,Pr)),e(n)}return t}}var Ir={blocked:0,working:1,error:2,idle:3},Lr=e=>Ir[e]??3,Rr=e=>String(e??``).replace(/(.)[\\/]+$/,`$1`);function zr(e){let t=Array.isArray(e?.status)?e.status:[];return t.length?t.some(e=>e.state===`blocked`)?`blocked`:t[0]?.state===`error`?`error`:t.some(e=>e.state===`working`)?`working`:`idle`:e?.blockers?.length?`blocked`:e?.state!==void 0&&e.state in Ir?e.state:`idle`}function Br(e){let t=Array.isArray(e?.status)?e.status:[];return(t.length?t:[{id:e?.id,title:e?.title,blockers:e?.blockers}]).flatMap(e=>(e.blockers??[]).map(t=>({...t,sessionID:e.id,sessionTitle:e.title})))}function Vr(e){let t=`idle`;for(let n of e)Lr(n)<Ir[t]&&(t=n);return t}function Hr(e){if(!e)return;if(e.kind===`thinking`)return`Thinking…`;let t=e.tool||`tool`;return e.summary?`${t} · ${e.summary}`:t}function Ur(e){return String(e??``).normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase()}var Wr=e=>Ur(e).split(/\s+/).filter(Boolean);function Gr(e,t){let n=Wr(t);if(!n.length)return!0;let r=[e.title||`Untitled`,e.projectName,e.project,e.directory].filter(Boolean).map(Ur);return n.every(e=>r.some(t=>t.includes(e)))}function Kr(e,t){let n=Rr(e),r=Rr(t);return n===r?``:n.startsWith(`${r}/`)?n.slice(r.length+1):n}var qr=e=>String(e??``).replace(/(.)[\\/]+$/,`$1`),Jr=e=>qr(e).split(/[\\/]/).pop()||String(e??``),Yr=[`hiddenSessions`,`hiddenWorkspaces`,`pinnedSessions`,`pinnedWorkspaces`],Xr=500,Zr=5e3,Qr=4096,$r=e=>e===`hiddenSessions`?Zr:Xr,ei=(e,t=Xr)=>{if(!Array.isArray(e))return[];let n=[...new Set(e.filter(e=>typeof e==`string`&&e.length>0&&e.length<=Qr))];return n.length>t?n.slice(n.length-t):n};function ti(e){let t=e,n=t&&typeof t==`object`&&t.prefs&&typeof t.prefs==`object`?t.prefs:e??{};return Object.fromEntries(Yr.map(e=>[e,ei(n[e],$r(e))]))}function ni(e){let t=e.trim();return t?t.length>200?{error:`Title is longer than 200 characters`}:{title:t}:{error:`Enter a title`}}function ri(e,t,n){let r;for(let i of e??[])for(let e of i.processes)for(let i of e.sessions)if(i.id===t){r??=i.title??``,i.title=n;for(let e of i.status??[])e.id===t&&(e.title=n)}return r}var ii=class{graceMs;pending=new Map;constructor(e=5e3){this.graceMs=e}set(e,t,n){this.pending.set(e,{title:t,at:n})}has(e){return this.pending.has(e)}drop(e,t){this.pending.get(e)?.title===t&&this.pending.delete(e)}apply(e,t){for(let[n,{title:r,at:i}]of[...this.pending]){let a=ai(e,n);a===r||t-i>this.graceMs?this.pending.delete(n):a!==void 0&&ri(e,n,r)}}},ai=(e,t)=>{for(let n of e??[])for(let e of n.processes)for(let n of e.sessions)if(n.id===t)return n.title??``};function oi(e,t,n,r){if(!Yr.includes(t))throw Error(`unknown prefs list: ${t}`);let i=e[t]??[],a=new Set(i),o=new Set(n.filter(e=>a.has(e)!==r));if(!o.size)return{prefs:e,patch:void 0};let s=r?ei([...i,...o],$r(t)):i.filter(e=>!o.has(e));return{prefs:{...e,[t]:s},patch:{[t]:s}}}var si=e=>{try{let t=JSON.parse(e??`null`);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}};function ci(e,t,n){let r=e!=null||t!=null,i={};for(let[r,a]of[[`pinnedSessions`,e],[`pinnedWorkspaces`,t]]){let e=n[r]??[],t=si(a).filter(t=>!e.includes(t));t.length&&(i[r]=ei([...e,...t]))}return{clear:r,patch:Object.keys(i).length?i:void 0}}var li={working:`working`,blocked:`blocked`};function ui(e){let t=zr(e);return Vr([t,e?.terminal?.status===`blocked`&&t!==`blocked`?`working`:li[e?.terminal?.status??``]??`idle`])}function di(e){return e?.terminal?.status===`blocked`&&zr(e)!==`blocked`}var fi=e=>!!e?.open&&e.terminal?.source===`herdr`&&!!e.terminal.workspaceID,pi=e=>qr(e?.project||e?.directory);function mi(e){return fi(e)?`herdr:${e.terminal.workspaceID}`:pi(e)}var hi=(e,t)=>pi(e)===t||qr(e.directory)===t||fi(e)&&mi(e)===t;function gi(e,t){if(t.sessions.has(e.id))return!0;for(let n of t.workspaces)if(hi(e,n))return!0;return!1}function _i(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 vi(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?_i(e,t):t)}return[...r.values()]}function yi(e){let t=bi(e);return e=>gi(e,t)}var bi=e=>({sessions:new Set(e?.hiddenSessions??[]),workspaces:new Set(e?.hiddenWorkspaces??[])}),xi=e=>e?.terminals?.herdr?.workspaces??[];function Si(e){let t=qr(e.project||e.directory),n=e.project?Kr(e.directory,t):``;return`${e.projectName||Jr(t)}${n?` › ${n}`:``}`}function Ci(e,t,n){let r=Si(t),i=n?.trim()||void 0;return{machine:e,where:r,...i?{branch:i}:{},text:[e,r,i].filter(Boolean).join(` · `)}}function wi(e,t,n){let r=fi(e)?e.terminal.workspace||xi(t).find(t=>t.id===e.terminal.workspaceID)?.label||e.terminal.workspaceID:void 0;return{...e,title:e.title||e.terminal?.title||`Untitled`,updated:e.updated??0,state:ui(e),waitingInTerminal:di(e),blockers:Br(e),exposed:e.exposed!==!1,pinned:n.has(e.id),nowText:Hr(e.now),where:Si(e),workspace:r??(e.projectName||Jr(pi(e))),machineID:t?.id}}var Ti=50,Ei=200;function Di(e){let t=xi(e).map(e=>({kind:`herdr`,key:`herdr:${e.id}`,workspaceID:e.id,label:e.label||e.id,directories:[...e.directories??[]]})),n=new Set(t.flatMap(e=>e.directories.map(qr))),r=vi(e),i=new Map,a=new Map;for(let e of r){let t=qr(e.directory);t&&(i.set(t,Math.max(i.get(t)??0,e.updated??0)),a.set(t,Si(e)))}for(let e of r){let t=qr(e.project);if(!t||a.has(t))continue;let n=Math.max(...r.filter(e=>qr(e.project)===t).map(e=>e.updated??0));i.set(t,n),a.set(t,e.projectName||Jr(t))}let o=[...i.entries()].filter(([e])=>!n.has(e)).sort((e,t)=>t[1]-e[1]).slice(0,Ti).map(([e])=>({kind:`folder`,key:e,label:a.get(e)??Jr(e),directories:[e]}));return{herdr:!!e?.terminals?.herdr,targets:[...t,...o]}}function Oi({target:e,directory:t,title:n,openInHerdr:r}){let i={directory:t},a=String(n??``).trim().slice(0,Ei);return a&&(i.title=a),r&&e?.kind===`herdr`&&e.workspaceID&&(i.herdrWorkspace=e.workspaceID),i}function ki(e){if(typeof e==`string`&&e)return e.includes(`budget`)?`Quota exceeded`:Ai[e]}var Ai={"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 ji(e){return typeof e==`number`&&Number.isInteger(e)&&e>=100&&e<=999?`HTTP ${e}`:void 0}function Mi(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 Ni=e=>typeof e==`string`&&e.trim()?e.trim():void 0,Pi=(e,t)=>e.toLowerCase()===t.toLowerCase(),Fi=(e,t)=>e&&t&&!Pi(e,t)?t:void 0;function Ii(e){let t=ki(e.errorType),n=Ni(e.message),r=ji(e.errorStatus),i=Fi(t,n);return`${t??n??`Error`}${r?` (${r})`:``}${i?`: ${i}`:``}`}function Li(e,t){let n=typeof e.attempt==`number`?` (attempt ${e.attempt})`:``,r=Mi(e.next,t),i=ki(e.errorType),a=Ni(e.message),o=Fi(i,a),s=i?o?`${i} — ${o}`:i:a;return`Retrying${n}${r?` · next in ${r}`:``}${s?`: ${s}`:``}`}var Ri=e=>!!e&&typeof e==`object`&&typeof e.id==`string`;function zi(e,t){let n=Array.isArray(e)?e.filter(Ri):[],r=t?n.find(e=>e.id===t):n[0];if(!r)return;if(r.state===`error`)return Bi(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?Bi(a):void 0}function Bi(e){let t=Ni(e.detail),n=ji(e.errorStatus),r=Ni(e.title);return{sessionID:e.id,...r?{title:r}:{},label:ki(e.errorType)??t??`Error`,...t?{message:t}:{},...n?{status:n}:{},text:Ii({errorType:e.errorType,errorStatus:e.errorStatus,message:t})}}var Vi=e=>Array.isArray(e)?e:[];function Hi(e){return Vi(e).flatMap(e=>(Array.isArray(e.jobs)?e.jobs:[]).map(t=>({...t,sessionID:e.id,sessionTitle:e.title??``})))}function Ui(e){return Hi(e).filter(e=>e.status===`running`).length}function Wi(e,t){let n=Hi(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 Gi(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 Ki(e,t){if(e.status===`running`)return e.started===void 0?`running`:`running · ${Gi(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?Gi(e.ended-e.started):void 0;return n?[n,r].filter(Boolean).join(` · `):[r??`ended`,i].filter(Boolean).join(` · `)}function qi(e){return e<=0?``:`${e} job${e===1?``:`s`}`}function Ji(e,t,n=Date.now()){let r=Vi(e),i=(t?r.find(e=>e.id===t&&e.retry):void 0)??r.find(e=>e.retry);return i?.retry?Li(i.retry,n):void 0}var Yi=[`prompt-tui`,`prompt-web`,`voice`,`answer`,`view`],Xi=36e5,Zi=24*Xi,Qi=e=>typeof e==`object`&&!!e&&!Array.isArray(e),$i=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0;function ea(e){if(!Qi(e))return;let t=Array.isArray(e.buckets)?e.buckets.filter(e=>Array.isArray(e)&&e.length===4&&e.every($i)):[];return{...$i(e.at)?{at:e.at}:{},...Yi.includes(e.kind)?{kind:e.kind}:{},...$i(e.last)?{last:e.last}:{},buckets:t.map(e=>[e[0],e[1],e[2],e[3]])}}function ta(e){let t={};if(!Qi(e))return t;for(let[n,r]of Object.entries(e)){let e=ea(r);e&&(t[n]=e)}return t}var na=(e,t)=>t-e[0]<Zi&&e[0]<=t;function ra(e,t){let n=Array.from({length:24},()=>({human:0,agent:0}));for(let r of e??[]){if(!na(r,t))continue;let e=n[23-Math.floor((t-r[0])/Xi)];e.human+=r[1],e.agent+=r[2]+r[3]}return n}function ia(e,t){let n=0,r=0,i=0;for(let a of e??[])na(a,t)&&(n+=a[1],r+=a[2],i+=a[3]);return{human:n,turns:r,tools:i}}var aa=(e,t)=>{let n=ia(e,t);return n.human+n.turns+n.tools},oa=(e,t)=>`${e} ${t}${e===1?``:`s`}`;function sa(e){return!e.human&&!e.turns&&!e.tools?`No activity in the last 24 h`:`You: ${oa(e.human,`action`)} · Agent: ${oa(e.turns,`turn`)} / ${oa(e.tools,`tool`)} in the last 24 h`}var ca={"prompt-tui":`typed`,"prompt-web":`prompted`,voice:`spoke`,answer:`answered`,view:`opened`},la=(e,t)=>{let n=Math.max(0,Math.round((t-e)/1e3));return n<60?void 0:n<3600?`${Math.round(n/60)}m`:n<86400?`${Math.round(n/3600)}h`:`${Math.round(n/86400)}d`};function ua(e,t,n){let r=la(t,n),i=r?`${r} ago`:`just now`;return e?`You ${ca[e]} ${i}`:`You ${i}`}function da(e,t,n){return`${e?ca[e]:`touched`} ${la(t,n)??`now`}`}function fa(e,t,n,r=new Set,i={}){let a=new Set(t.pinnedSessions),o=new Set(t.hiddenSessions),s=yi(t),c=[];for(let t of e??[])for(let e of vi(t)){if(r.has(e.id))continue;let l=wi(e,t,a),u=l.open?l.terminal?.source===`herdr`?`herdr`:`tui`:`background`,d=n[l.id],f=l.state===`working`?Ji(e.status,void 0,1/0):void 0,p=l.state===`error`?zi(e.status,l.id)?.text??`Error`:void 0,m=i.activity?.[l.id],h=i.intents?.[l.id]?.text;c.push({...l,machineName:t.name,machineOnline:!!t.online,source:u,running:l.state===`working`||l.state===`blocked`,hidden:s(e),archived:o.has(l.id),unread:d!==void 0&&l.updated>d,group:mi(e),jobs:Ui(e.status),...f?{retry:f}:{},...p?{error:p}:{},...m?.at===void 0?{}:{touchedAt:m.last??m.at},...m?.at!==void 0&&m.kind?{touchedKind:m.kind,touchedKindAt:m.at}:{},...m?.buckets.length?{meter:m.buckets}:{},...h?{intent:h}:{}})}return c.sort((e,t)=>t.updated-e.updated)}function 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 ma=[`1h`,`24h`,`7d`],ha={"1h":36e5,"24h":864e5,"7d":6048e5},ga=Object.freeze({query:``,filters:Object.freeze({status:`all`,source:`all`,machine:``,archived:!1,touched:``}),sort:Object.freeze({key:`activity`,dir:`desc`})}),_a=[`status`,`title`,`project`,`server`,`source`,`activity`,`touched`,`busy`],va=[`all`,`needs`,`running`,`idle`],ya=[`all`,`open`,`background`],ba=(e,t)=>e.localeCompare(t,void 0,{sensitivity:`base`}),xa=(e,t)=>t.updated-e.updated,Sa=e=>e.touchedAt??-1/0,Ca=e=>({status:(e,t)=>Ir[e.state]-Ir[t.state]||xa(e,t),title:(e,t)=>ba(e.title,t.title)||xa(e,t),project:(e,t)=>ba(e.workspace,t.workspace)||xa(e,t),server:(e,t)=>ba(e.machineName,t.machineName)||xa(e,t),source:(e,t)=>ba(e.source,t.source)||xa(e,t),activity:(e,t)=>e.updated-t.updated,touched:(e,t)=>Sa(e)-Sa(t)||e.updated-t.updated,busy:(t,n)=>aa(t.meter,e)-aa(n.meter,e)||t.updated-n.updated});function wa(e,t,n){if(t.touched&&(e.touchedAt===void 0||n-e.touchedAt>ha[t.touched]))return!1;let r=t.status===`needs`&&e.state===`blocked`;return!((t.archived?!e.hidden:e.hidden&&!r)||t.status===`needs`&&!Aa(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 Ta(e,t){if(!t.trim()||Gr(e,t))return!0;let n=Ur(t).split(/\s+/).filter(Boolean),r=[e.title,e.workspace,e.where,e.directory,e.machineName].map(Ur);return n.every(e=>r.some(t=>t.includes(e)))}function Ea(e,t,n=Date.now()){let r=Ca(n)[t.sort.key],i=t.sort.dir===`asc`?1:-1;return e.filter(e=>wa(e,t.filters,n)&&Ta(e,t.query)).sort((e,t)=>i*r(e,t))}var Da=(e,t,n)=>t.includes(e)?e:n;function Oa(e){let t;try{if(t=JSON.parse(e??`null`)??{},typeof t!=`object`||Array.isArray(t))return ga}catch{return ga}let n=t.filters??{},r=t.sort??{},i=ga,a=Da(r.key,_a,i.sort.key),o=a===r.key?Da(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:Da(n.status,va,i.filters.status),source:Da(n.source,ya,i.filters.source),machine:typeof n.machine==`string`&&n.machine.length<=200?n.machine:``,archived:n.archived===!0||n.hidden===!0,touched:Da(n.touched,ma,i.filters.touched)},l=Object.keys(c).every(e=>c[e]===i.filters[e]);return l&&s===i.sort?ga:{query:``,filters:l?i.filters:c,sort:s}}function ka(e){return JSON.stringify({filters:e.filters,sort:e.sort})}var Aa=e=>e.state===`blocked`||e.state===`error`&&!e.hidden;function ja(e,{query:t,groupBy:n,sortBy:r,recentLimit:i=20,workingLimit:a=7,now:o=Date.now()}){let s=e.filter(e=>!e.hidden),c=e.filter(Aa),l=r===`title`?(e,t)=>ba(e.title,t.title)||xa(e,t):xa;if(t.trim())return[{id:`results`,title:`Results`,kind:`results`,rows:s.filter(e=>Ta(e,t)).sort(xa)}];let u=new Set,d=e=>{for(let t of e)u.add(t.id);return e},f=[],p=e=>e.rows.length&&f.push(e);p({id:`needs`,title:`Needs you`,kind:`needs`,rows:d(c.sort(xa))});let m=s.filter(e=>!u.has(e.id)&&e.touchedAt!==void 0&&o-e.touchedAt<=6048e5);if(m.length){let e=s.filter(e=>!u.has(e.id)&&e.pinned).sort(l),t=m.filter(e=>!e.pinned).sort((e,t)=>Sa(t)-Sa(e)).slice(0,a);p({id:`working`,title:`Working set`,kind:`working`,rows:d([...e,...t])})}p({id:`running`,title:`Running`,kind:`running`,rows:d(s.filter(e=>!u.has(e.id)&&e.running).sort(xa))}),p({id:`pinned`,title:`Pinned`,kind:`pinned`,rows:d(s.filter(e=>!u.has(e.id)&&e.pinned).sort(l))});let h=new Map;for(let e of s){if(u.has(e.id)||!e.open)continue;let t=n===`machine`?e.machineID:`${e.machineID}\u0000${e.group}`,r=h.get(t);r||(r={title:n===`machine`?e.machineName:e.workspace,key:n===`machine`?e.machineID:e.group,machineID:e.machineID,directory:e.directory,rows:[]},h.set(t,r)),r.rows.push(e)}let g=e=>Math.max(...e.map(e=>e.updated)),_=[...h.values()].sort((e,t)=>r===`title`&&ba(e.title,t.title)||g(t.rows)-g(e.rows));for(let e of _){e.rows.sort(l),d(e.rows);let t=[...e.rows].sort(xa);p({id:`group:${e.machineID}:${e.key}`,title:e.title,kind:`group`,key:e.key,machineID:e.machineID,directory:t[0].directory,rows:e.rows})}return p({id:`recents`,title:`Recents`,kind:`recents`,rows:s.filter(e=>!u.has(e.id)).sort(xa).slice(0,i)}),f}var Ma=864e5;function Na(e,t,n){if(!Number.isInteger(t)||t<1)return[];let r=n-t*Ma;return e.filter(e=>!e.hidden&&!e.running&&!e.pinned&&!e.open&&e.updated<r)}function Pa(e,t){return t.phase!==`off`&&t.sessionID===e.id||e.conversation===!0}function Fa(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 Ia;function La(e){Ia=e}function Ra(e){for(let t of[Ia?.(e.id),e.intent]){let n=t?.trim();if(n&&n!==e.title)return n}}function za(e,t){if(e.state!==`blocked`)return;let n=(e.status??[]).flatMap(e=>e.state===`blocked`&&typeof e.blockedSince==`number`?[e.blockedSince]:[]);if(!n.length)return;let r=Math.max(0,Math.floor((t-Math.min(...n))/1e3));return r<60?`<1m`:r<3600?`${Math.floor(r/60)}m`:r<86400?`${Math.floor(r/3600)}h`:`${Math.floor(r/86400)}d`}var Ba=.75,Va=.05;function Ha(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/Va)/Math.round(1/Va);return Math.min(2,Math.max(Ba,Number(n.toFixed(2))))}function Ua(e){let t=Ha(e);return`${Number.isInteger(t)?t.toFixed(1):String(t)}×`}var Wa={working:`working`,blocked:`blocked`,error:`failed`,idle:`done`},Ga=160,Ka=class{rootID;max;maxSubagents;maxText;items=[];subagents=new Map;seq=0;rootState;rootSince;busyAt;writing;lastAt;constructor(e,{max:t=30,maxSubagents:n=10,maxText:r=4e3}={}){this.rootID=e,this.max=t,this.maxSubagents=n,this.maxText=r}touch(e){e!==void 0&&Number.isFinite(e)&&!((this.lastAt??-1/0)>=e)&&(this.lastAt=e)}reasoning(e,t,n,r=Date.now()){let i=`thinking:${t}`;this.items.some(e=>e.id===i)||this.activity(e,{id:i,kind:`thinking`,state:`running`,at:r});let a=this.items.find(e=>e.id===i);a&&(a.text=`${a.text??``}${n??``}`.slice(-this.maxText)),this.touch(r)}text(e,t,n,r=Date.now()){for(let t of this.items)t.sessionID===e&&t.kind===`thinking`&&t.state===`running`&&(t.state=`done`);if(this.touch(r),e===this.rootID){this.writing={messageID:t,at:r};return}let i=this.subagents.get(e);i||(i={id:e,state:`working`,at:r},this.subagents.set(e,i),this.trim()),i.msg!==t&&(i.out=``),i.msg=t,i.out=`${i.out??``}${n??``}`.slice(-600);let a=i.out.split(`
3
+ `).map(e=>e.trim()).filter(Boolean).at(-1);a&&(i.line=a.length>Ga?`…${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=Wa[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`:Ja(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 Ja(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 ${Ja(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 qa(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 Ja(e){if(e.kind===`thinking`)return`Thinking…`;let t=e.tool||`tool`;return e.summary?`${t} · ${e.summary}`:t}var Ya=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 Xa(){let e=Object.values(Ya),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 Za=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=Ya[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}},Qa=class{ackMs;quietMs;stillMs;enabled=!0;phrases=!0;busy=!1;awaiting;pendingSubagent=!1;lastSay=-1/0;lastSpoke=-1/0;user=!1;agent=!1;cue=!1;pick;constructor({ackMs:e=2500,quietMs:t=3e3,stillMs:n=4e4,pick:r}={}){if(!r){let e=new Za;r=t=>e.pick(t)}this.pick=r,this.ackMs=e,this.quietMs=t,this.stillMs=n}get gated(){return this.user||this.agent||this.cue}heard(e,{tone:t=!0}={}){return this.awaiting=Math.min(this.awaiting??e,e),t&&this.enabled&&!this.user?[{type:`earcon`,name:`heard`}]:[]}awaitReply(e){this.awaiting=e}speechEnded(e){return this.userTalking(!1,e),this.enabled?[{type:`earcon`,name:`heard`}]:[]}working(e,t){e&&!this.busy&&(this.lastSpoke=Math.max(this.lastSpoke,t)),e||(this.awaiting=void 0,this.pendingSubagent=!1),this.busy=e}agentSaid(e){this.lastSay=e,this.spoke(e)}agentSpeaking(e,t){this.agent=e,this.spoke(t)}userTalking(e,t){this.user=e,e||(this.lastSpoke=Math.max(this.lastSpoke,t))}cueSpeaking(e,t){this.cue=e,e||(this.lastSpoke=Math.max(this.lastSpoke,t))}subagentStarted(e){e-this.lastSay>=this.quietMs&&(this.pendingSubagent=!0)}subagentFinished(e){return this.enabled&&!this.user?[{type:`earcon`,name:`done`}]:[]}nextDue(e){if(this.enabled&&this.phrases&&!this.gated){if(this.pendingSubagent)return e;if(this.busy)return Math.min(this.awaiting===void 0?1/0:this.awaiting+this.ackMs,this.lastSpoke+this.stillMs)}}tick(e){return!this.enabled||!this.phrases||this.gated?[]:this.pendingSubagent?this.say(`subagent`,e):this.awaiting!==void 0&&this.busy&&e-this.awaiting>=this.ackMs?this.say(`working`,e):this.busy&&e-this.lastSpoke>=this.stillMs?this.say(`still`,e):[]}spoke(e){this.awaiting=void 0,this.pendingSubagent=!1,this.lastSpoke=Math.max(this.lastSpoke,e)}say(e,t){return this.spoke(t),[{type:`speak`,cue:e,text:this.pick(e)}]}},$a=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}},eo=new Set([`working`,`blocked`]);function to(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`&&!eo.has(t??``)?i.push(e.id):eo.has(t??``)&&!eo.has(e.state)&&a.push(e.id)}for(let[e,t]of r)eo.has(t)&&a.push(e);return{started:i,finished:a}}function no(e){return(e??[]).some(e=>e.state===`working`)}var ro=Object.freeze([`openrouter`,`openai-compatible`]),io={stt:[`provider`,`model`,`baseURL`,`language`],tts:[`provider`,`model`,`voice`,`baseURL`,`speed`]},ao=e=>e==null?``:String(e).trim();function oo(e){let t={};for(let n of[`stt`,`tts`]){let r=e?.[n]??{};t[n]=Object.fromEntries(io[n].map(e=>[e,ao(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 io[r]){if(e===`baseURL`&&ao(a.provider)!==`openai-compatible`)continue;let t=ao(a[e]);t!==ao(i[e])&&(o[e]=t===``?null:e===`speed`?Number(t):t)}a.apiKey?.action===`set`?o.apiKey=ao(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(ro.includes(ao(r.provider))||i(`provider`,`Choose a provider.`),ao(r.model)||i(`model`,`Enter a model.`),ao(r.provider)===`openai-compatible`){let e=ao(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`){ao(r.voice)||i(`voice`,`Enter a voice.`);let e=ao(r.speed);e&&!(Number(e)>=.25&&Number(e)<=4)&&i(`speed`,`Use a number from 0.25 to 4.`)}r.apiKey?.action===`set`&&!ao(r.apiKey.value)&&i(`apiKey`,`Paste the new key, or cancel.`)}return t}function lo(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 uo=/^(localhost|127(?:\.\d{1,3}){3}|\[::1\])$/i;function fo(e,t){if(!e||e.stt&&e.tts)return;let n=!1;try{n=uo.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 po=()=>({machines:void 0,reads:{},activity:{},intents:{},prefs:ti({}),prefsSource:`unknown`,prefsPending:0,prefsStale:!1,connection:`connecting`,enrollmentRev:0}),mo=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function ho(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 go(e,t){if(!mo(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 ho(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 ho(e.machines,t.sessionID,e=>{e.conversation=t.on,n=!0}),n}case`reads`:return mo(t.reads)?(e.reads=Object.fromEntries(Object.entries(t.reads).filter(e=>typeof e[1]==`number`)),!0):!1;case`activity`:{let n=ea(t.activity);return typeof t.sessionID!=`string`||!n?!1:(e.activity[t.sessionID]=n,!0)}case`prefs`:return e.prefsSource===`hub`?e.prefsPending?(e.prefsStale=!0,!0):(e.prefs=ti(t.prefs),!0):!1;case`enrollment`:return e.enrollmentRev++,!0;case`handoff`:return typeof t.sessionID==`string`&&(e.notice={kind:`handoff`,sessionID:t.sessionID,at:Date.now()},!0);default:return!1}}function _o(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??vo(e,t)}function vo(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=yo(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 yo(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 bo(e){return(e??[]).some(e=>e.state===`working`||e.state===`blocked`)}var xo=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 Ka(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(!mo(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 mo(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 So(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 Co=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=So(e)===So(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(So(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 wo(e,t){return t===`scope`&&e===`live`?{connection:`live`,reconnecting:!1}:{connection:`connecting`,reconnecting:e!==`connecting`}}var To=e=>e===`app:concierge`||e===`app concierge`,Eo=/^(ses_[A-Za-z0-9]+)(?: \(sub ses_[A-Za-z0-9]+\))? (.*)$/,Do=/^[!+-] (.*)$/,Oo=/^… (\d+) more updates not listed$/,ko=2,Ao={permission:`needs a permission`,question:`has a question`};function jo(e,t){let n=/^machine \S+ (online|offline)$/.exec(e);if(n)return`a machine went ${n[1]}`;let r=Eo.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} ${Ao[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 Mo(e,t){if(typeof e!=`string`)return;let[n=``,...r]=e.split(`
4
+ `),i=/^Concierge digest \(.*?\) b\d+ .*?: (.*)$/.exec(n);if(i)return`Digest: ${i[1]}`;if(!/^Concierge update b\d+ /.test(n))return;if(/ changes were missed | some changes were missed/.test(n))return`Update: some changes were missed — catching up`;let a=[],o=0;for(let e of r){let n=Oo.exec(e);n&&(o+=Number(n[1]));let r=Do.exec(e);r&&(a.length<ko?a.push(jo(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 No=60,Po=/(`[^`]*`|\]\([^)]*\)|<[a-z][a-z0-9+.-]*:[^>\s]*>|\b[a-z][a-z0-9+.-]*:\/\/[^\s<>()]+)|(?<![\w#/[(])((?:Decision )?)(dec_[A-Za-z0-9]{1,64})(?!\w)/g,Fo=e=>{let t=Intl.Segmenter;return t?Array.from(new t(void 0,{granularity:`grapheme`}).segment(e),e=>e.segment):Array.from(e)},Io=e=>{let t=e.replace(/\s+/g,` `).trim(),n=Fo(t);return n.length>No?`${n.slice(0,59).join(``)}…`:t};function Lo(e){if(!e.includes(`dec_`))return[];let t=new Set;for(let n of e.matchAll(Po))!n[1]&&n[3]&&t.add(n[3]);return[...t]}function Ro(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(Po)){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 “${Io(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 zo(e,t,n={}){return Ro(e,t,n).map(e=>e.href?`[${Bo(e.text)}](${e.href})`:e.text).join(``)}var Bo=e=>e.replace(/[\\`*_[\]<>~=]/g,`\\$&`);function Vo(e,t){return e.replace(/(?<![\w/])ses_[A-Za-z0-9]{1,64}(?!\w)/g,e=>t(e)??e)}function Ho(e){if(e.state===`expired`)return`Expired without an answer`;if(e.state===`closed`)return e.closed?.reason?`Closed: ${e.closed.reason}`:`Closed`;let t=e.answer,n=t?.option===void 0?t?.text:e.options.find(e=>e.id===t.option)?.label??t.option;return!t||n===void 0?`Answered`:t.answeredBy===`app`?`Answered “${n}” by ${ye(e)}`:t.answeredBy===`timeout`?`Answered “${n}” when it timed out`:`You answered “${n}”`}var Uo=2e3,Wo=6e4,Go=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(Uo*2**(t-1),Wo)})}return}finally{this.running--,this.asking.delete(e),this.queue.shift()?.()}}};function Ko(e,t){let n=new Set;for(let r of e)if((r.type===`assistant`?r.live!==!0:r.type===`message`&&!r.primer&&!To(r.from))&&typeof r.text==`string`)for(let e of Lo(r.text))t.has(e)||n.add(e);return[...n]}var qo=new Set([`disabled`,`starting`,`running`,`waiting_machine`,`backoff`,`failed`,`stopping`]),Jo=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Yo=e=>typeof e==`string`,Xo=e=>typeof e==`number`&&Number.isFinite(e);function Zo(e){if(Jo(e)&&Yo(e.state)&&qo.has(e.state))return{state:e.state,...Yo(e.reason)?{reason:e.reason.slice(0,200)}:{},...Yo(e.sessionID)?{sessionID:e.sessionID}:{},hiddenSessionIDs:Array.isArray(e.hiddenSessionIDs)?e.hiddenSessionIDs.filter(Yo):[],...Yo(e.launchID)?{launchID:e.launchID}:{},...Yo(e.machineID)?{machineID:e.machineID}:{},generation:Xo(e.generation)?e.generation:0,since:Xo(e.since)?e.since:0,...Xo(e.nextAttemptAt)?{nextAttemptAt:e.nextAttemptAt}:{}}}function Qo(e){if(!Jo(e)||!Jo(e.settings))return;let t=Zo(e.status);if(!t)return;let n=Array.isArray(e.machines)?e.machines.filter(Jo).filter(e=>Yo(e.id)&&Yo(e.name)).map(e=>({id:e.id,name:e.name,eligible:e.eligible===!0,online:e.online===!0,...Yo(e.reason)?{reason:e.reason}:{},roots:Array.isArray(e.roots)?e.roots.filter(Yo):[]})):[];return{settings:e.settings,status:t,machines:n}}function $o(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 es=4e3,ts=(e,t,n)=>e||t&&n;function ns(e,t,n,r,i,a){return $o(t,r,a).has(e)?`concierge`:!n||i===!1&&!rs(e,r)?`wait`:`session`}var rs=(e,t)=>(t??[]).some(t=>(t.processes??[]).some(t=>(t.sessions??[]).some(t=>t.id===e))),is=e=>`concierge.hidden.${e??`local`}`;function as(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 os(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 ss=e=>e<6e4?`${Math.max(1,Math.ceil(e/1e3))} s`:`${Math.ceil(e/6e4)} min`;function cs(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 ${ss(e.nextAttemptAt-n)}`;case`failed`:return`Failed${e.reason?`: ${e.reason}`:``}`;case`stopping`:return`Stopping`}}function ls(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 us=(e,t)=>{let n=t.replace(/\/+$/,``);return e===n||e.startsWith(`${n}/`)};function ds(e,t){if(!e.machineID)return`Pick a machine`;let n=t.find(t=>t.id===e.machineID);if(!n)return`That machine is not yours any more: pick another`;if(!n.eligible&&n.online)return`${n.name} cannot host the Concierge: ${n.reason??`not eligible`}`;if(!e.directory)return`Pick a directory (a git repo on ${n.name})`;if(n.roots.length&&!n.roots.some(t=>us(e.directory,t)))return`The directory must be under one of ${n.name}'s workspace roots: ${n.roots.join(`, `)}`}var fs=e=>({allow:[`answer`,`deny`,`approve`],projects:[...e],permissions:{allow:[`read`,`edit`],never:[`shell:git push*`,`shell:rm *`]},allowAlways:!1,expires:`7d`,maxActionsPerHour:60}),ps=[`answer`,`deny`,`approve`,`stop`,`prompt`];function ms(e,t){let n=e??fs(t?[t]:[]);return{projects:[...n.projects],allow:[...n.allow],permit:n.permissions.allow.join(`
5
+ `),never:n.permissions.never.join(`
6
+ `),expires:n.expires,maxActionsPerHour:String(n.maxActionsPerHour)}}var hs=e=>e.split(`
7
+ `).map(e=>e.trim()).filter(Boolean),gs=/^(\d+)(h|d)$/;function _s(e){let t={},n=[...new Set(e.projects.map(e=>e.trim()).filter(Boolean))];n.length||(t.projects=`Pick at least one project`),ps.filter(t=>e.allow.includes(t)).length||(t.allow=`Pick at least one action`);let r=e.expires.trim(),i=gs.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=>ps.includes(e)),projects:n,permissions:{allow:hs(e.permit),never:hs(e.never)},allowAlways:!1,expires:r,maxActionsPerHour:s}}}function vs(e){let t=hs(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 ys(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 bs(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 xs(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 Ss(e,t){let n=st(e,t);return n?`expires in ${n}`:`expired`}var Cs=[`machineID`,`directory`,`model`,`grant`,`connectors`,`timeZone`,`quietHours`,`quietAllowsUrgent`,`digests`];function ws(e,t){let n={};for(let r of Cs)JSON.stringify(e[r])!==JSON.stringify(t[r])&&(n[r]=t[r]===void 0?null:t[r]);return{...n,expectedRevision:e.revision}}var Ts=`__other__`,Es=e=>(e??``).replace(/\/+$/,``);function Ds(e,t){if(!e)return{projects:[],roots:[]};let n=[...new Set(e.roots.map(Es).filter(Boolean))],r=(t??[]).find(t=>t.id===e.id)?.processes.flatMap(e=>e.sessions.map(e=>Es(e.project)||Es(e.directory)))??[],i=[...new Set(r)].filter(e=>e.startsWith(`/`)&&(!n.length||n.some(t=>us(e,t)))).sort();return{projects:i,roots:n.filter(e=>!i.includes(e))}}function Os(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(Es).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 ks=(e,t)=>e?t.includes(e)?e:Ts:``;function As(e,t,n,r){if(e.machineID===t.id)return e;let{projects:i,roots:a}=Ds(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 js=(e,t)=>e.model!==void 0&&!t.includes(e.model)?{...e,model:void 0}:e,Ms=/^[A-Za-z0-9._-]{1,80}\/[!-~]{1,200}$/;function Ns(e){let t=Jo(e)&&Array.isArray(e.models)?e.models:[],n=new Map;for(let e of t){if(!Jo(e)||!Yo(e.providerID)||!Yo(e.modelID)||e.enabled===!1)continue;let t=`${e.providerID}/${e.modelID}`;Ms.test(t)&&!n.has(t)&&n.set(t,{value:t,label:Yo(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 Ps(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 Fs=new Set([`yes`,`approve`,`go ahead`,`do it`]),Is=new Set([`no`,`deny`,`don't`,`dont`,`hold`]),Ls=new Set([`um`,`umm`,`uh`,`uhm`,`uhh`,`er`,`erm`,`hm`,`hmm`,`ah`,`please`]),Rs=80;function zs(e){if(typeof e!=`string`||e.length>Rs||/[??]/.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&&Ls.has(t[n]);)n++;for(;r>n&&Ls.has(t[r-1]);)r--;let i=t.slice(n,r).join(` `);if(Fs.has(i))return`yes`;if(Is.has(i))return`no`}function Bs(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 Vs(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 Hs(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 Us(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 Ws(e,t){if(!t||t.tier!==`confirm`||t.state!==`open`)return{kind:`speech`};let n=zs(e),r=n&&Us(t,n);return n&&r?{kind:`answer`,decisionID:t.id,option:r,intent:n}:{kind:`speech`}}var Gs=60;function Ks(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>Gs?`${n.slice(0,59).join(``)}…`:n.join(``)}” by text: ${e.options.find(e=>e.id===t)?.label??t}`}var qs=e=>e&&e.state!==`disabled`?!0:`hidden`,Js={starting:`starting`,backoff:`restarting soon`,waiting_machine:`waiting for its machine`,stopping:`stopping`};function Ys(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 (${Js[e.state]}${c})`,s?`attention`:`busy`];return{label:l,title:`${l} — ${n?`close`:`open`} it`,indicator:u,...i>0?{count:s}:{}}}var Xs=e=>e?`Ask what needs you, or start Voice and talk.`:`Ask what needs you.`,Zs=e=>`${e?`Say or type`:`Type`} “yes” or “no” (or tap). Anything else goes to the Concierge.`,Qs=`The Concierge is off. Turn it on in Settings → Concierge.`;function $s(e,t){if(!e||e.state===`disabled`)return Qs;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 ec(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=Ws(a,t.armed());return o.kind===`speech`?e(r,i):(await t.answer(o.decisionID,o.option),Response.json({inboxID:`decision:${o.decisionID}`}))}}var tc=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function nc(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 rc(e,t,n){return n===void 0||!e||e.sessionID===t.sessionID?n:null}function ic(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=fn(n,e))}return n}function ac(e,t){if(e&&e.expiresAt!==void 0)return Math.max(0,e.expiresAt-t)}function oc(e,t){return e&&e.expiresAt!==void 0&&e.expiresAt<=t?null:e}var sc=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 cc(e,t,n){return Hs(e,t,{tiers:`all`}).filter(e=>e.id!==n?.id)}var lc=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 uc(e){let t=e.find(e=>e.focused);return t?.visible?t:void 0}function dc(e,t=gn){let n=[],r=uc(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 fc(e,t,n){let r=t.length?dc(t):n?[n]:[],[i]=r;return i?r.length>1?{lite:e,session:i,sessions:r}:{lite:e,session:i}:{lite:e}}function pc(e,t,n=gn){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 mc(e){return uc(e)?.sessionID}function hc(e,t){return uc(e)?.paneID===t}var gc=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}},[_c,vc]=u(0),yc=new lc(()=>vc(e=>e+1));function bc(){return _c(),yc.views()}var xc=()=>mc(bc()),Sc=(e,t)=>fc(e,bc(),t);function Cc(e,t=()=>!0){let n=yc.register(e,t);return{paneID:n,focus:()=>void yc.focus(n),takesInput:()=>hc(bc(),n),streamed:()=>kc(e),release:()=>yc.release(n)}}var wc=new gc,[Tc,Ec]=u(0);function Dc(e){wc.opened(e),Ec(e=>e+1)}function Oc(e){wc.message(e)&&Ec(e=>e+1)}function kc(e){return Tc(),wc.covers(e)}var Ac=`x-hub-recording`,jc=`x-hub-segment`,Mc=`x-hub-tts-ref`,Nc=`x-hub-recording-audio`,Pc={retentionMs:6048e5,userBytes:524288e3,recordingBytes:157286400,segmentBytes:2097152,segmentsPerRecording:5e3,eventsPerBatch:200,batchBytes:262144,keepaliveBatchBytes:61440,eventsPerRecording:5e4,eventBytesPerRecording:33554432,recordingsStored:200,activePerUser:4,maxDurationMs:144e5,idleEndMs:6e5,sweepMs:9e5,textChars:2e3,utteranceChars:4e3,replyChars:32e3,messageChars:300,consoleBufferEvents:2e3,flushMs:5e3,flushEvents:100,hubFlushMs:2e3,hubFlushEvents:100},Fc={clipsPerRecording:200,clipPreMs:3e3,clipPostMs:2e3,clipBytes:196608,clipGapMs:2e3,repliesPerRecording:2e3,replyBytes:1048576,userHeadroomBytes:52428800,recordingHeadroomBytes:15728640,tracesPerMinute:30,logsPerMinute:20},Ic=[`vad.trace`,`audio.clip`,`device.info`,`resource.timing`,`console.log`],Lc=6e4,Rc=1e4,zc=[`echoCancellation`,`noiseSuppression`,`autoGainControl`,`sampleRate`,`channelCount`];function Bc(e){let t;try{t=new URL(e,`http://local`).pathname}catch{return}if(t===`/api/transcribe`)return`transcribe`;if(t===`/api/speak`)return`speak`;if(/^\/api\/recordings\/[^/]+\/events$/.test(t))return`events`;if(/^\/api\/recordings\//.test(t))return`recording`;if(/^\/api\/sessions\/[^/]+\/utterance$/.test(t))return`utterance`}var Vc=e=>{let t=[...e].sort((e,t)=>e-t),n=t.length/2;return Math.round(t.length%2?t[Math.floor(n)]:(t[n-1]+t[n])/2)},Hc=e=>e.slice(0,Pc.messageChars);function Uc(e){if(e instanceof Error)return`${e.name}: ${e.message}`;if(typeof e==`string`)return e;try{return JSON.stringify(e)??String(e)}catch{return String(e)}}var Wc=e=>typeof e==`string`?e.split(/[/?#]/).filter(Boolean).at(-1)??``:``,Gc=class{record;env;now;timers;logsPerMinute;last=``;track;wake;unhook=[];interval;seen=new WeakSet;logged=[];repeats=new Map;inLog=!1;running=!1;constructor(e){this.record=e.record,this.env=e.env??globalThis,this.now=e.now??(()=>Date.now()),this.timers=e.timers!==!1,this.logsPerMinute=e.logsPerMinute??Fc.logsPerMinute}async start(){if(this.running)return;this.running=!0;for(let e of this.entries())this.seen.add(e);this.hookConsole();let e=()=>void this.snapshot(`change`);this.listen(this.env.navigator?.connection,`change`,e),this.listen(this.env.navigator?.mediaDevices,`devicechange`,e),this.listen(this.env.document,`visibilitychange`,e),this.listen(this.env.window,`error`,e=>this.windowError(e)),this.listen(this.env.window,`unhandledrejection`,e=>this.log(`unhandled`,e?.reason instanceof Error?`${e.reason.name}: ${e.reason.message}`:Uc(e?.reason),`window`));let t=await this.env.navigator?.getBattery?.().catch?.(()=>void 0);t&&this.running&&(this.listen(t,`chargingchange`,e),this.listen(t,`levelchange`,e)),this.timers&&(this.interval=setInterval(()=>this.flushTiming(),Lc)),await this.snapshot(`start`,t)}stop(){if(this.running){this.flushTiming(),this.running=!1;for(let e of this.unhook.splice(0))e();this.interval!==void 0&&clearInterval(this.interval),this.interval=void 0}}micTrack(e,t){let n={};for(let t of zc)e[t]!==void 0&&typeof e[t]==(t.endsWith(`Rate`)||t.endsWith(`Count`)?`number`:`boolean`)&&(n[t]=e[t]);t&&(n.label=t),this.track=n,this.snapshot(`change`)}wakeLock(e){this.wake=e,this.snapshot(`change`)}log(e,t,n){if(!this.running)return;let r=Hc(t),i=`${e}\n${r}`,a=this.now(),o=this.repeats.get(i);if(o&&a-o.at<Rc){o.count++;return}for(;this.logged.length&&a-this.logged[0]>=6e4;)this.logged.shift();if(this.logged.length>=this.logsPerMinute)return;this.logged.push(a),this.repeats.set(i,{at:a,count:0}),this.repeats.size>200&&this.repeats.delete(this.repeats.keys().next().value);let s=o?o.count+1:0;this.record(`console.log`,{level:e,message:r,...s>1?{count:s}:{},...n?{source:n}:{}})}flushTiming(){if(!this.running)return;let e=new Map;for(let t of this.entries()){if(this.seen.has(t))continue;this.seen.add(t);let n=Bc(String(t.name??``));if(!n)continue;let r=e.get(n);r||e.set(n,r={durations:[],ttfb:[],bytes:0}),typeof t.duration==`number`&&r.durations.push(t.duration),typeof t.responseStart==`number`&&typeof t.requestStart==`number`&&t.responseStart>0&&t.requestStart>0&&r.ttfb.push(t.responseStart-t.requestStart),typeof t.transferSize==`number`&&(r.bytes+=t.transferSize)}for(let[t,n]of e)n.durations.length&&this.record(`resource.timing`,{route:t,n:n.durations.length,medianMs:Vc(n.durations),maxMs:Math.round(Math.max(...n.durations)),...n.ttfb.length?{medianTtfbMs:Vc(n.ttfb)}:{},bytes:Math.round(n.bytes)})}entries(){try{return this.env.performance?.getEntriesByType?.(`resource`)??[]}catch{return[]}}listen(e,t,n){e?.addEventListener&&(e.addEventListener(t,n),this.unhook.push(()=>e.removeEventListener?.(t,n)))}hookConsole(){let e=this.env.console;if(e)for(let t of[`error`,`warn`]){let n=e[t];if(typeof n!=`function`)continue;let r=(...r)=>{if(n.apply(e,r),!this.inLog){this.inLog=!0;try{this.log(t,r.map(Uc).join(` `),`console`)}catch{}finally{this.inLog=!1}}};e[t]=r,this.unhook.push(()=>{e[t]===r&&(e[t]=n)})}}windowError(e){let t=Wc(e?.filename),n=String(e?.message??(e?.error instanceof Error?e.error.message:`error`));this.log(`error`,t?`${n} (${t}${typeof e?.lineno==`number`?`:${e.lineno}`:``})`:n,`window`)}async snapshot(e,t){if(!this.running)return;let n={};try{let e=await this.env.navigator?.mediaDevices?.enumerateDevices?.()??[],t=t=>e.filter(e=>e.kind===t).slice(0,20).map(e=>({kind:t,...typeof e.label==`string`&&e.label?{label:e.label.slice(0,120)}:{}})),r=t(`audioinput`),i=t(`audiooutput`);r.length&&(n.inputs=r),i.length&&(n.outputs=i)}catch{}this.track&&(n.track=this.track);let r=this.env.navigator?.connection;if(r){let e={};typeof r.effectiveType==`string`&&(e.effectiveType=r.effectiveType.slice(0,60));for(let t of[`rtt`,`downlink`])typeof r[t]==`number`&&Number.isFinite(r[t])&&(e[t]=r[t]);typeof r.saveData==`boolean`&&(e.saveData=r.saveData),n.network=e}typeof this.env.document?.visibilityState==`string`&&(n.visibility=this.env.document.visibilityState.slice(0,60)),this.wake!==void 0&&(n.wakeLock=this.wake);let i=t??await this.env.navigator?.getBattery?.().catch?.(()=>void 0);if(i&&typeof i.level==`number`&&(n.battery={level:Math.round(i.level*100)/100,...typeof i.charging==`boolean`?{charging:i.charging}:{}}),!this.running)return;let a=JSON.stringify(n);(e!==`change`||a!==this.last)&&(this.last=a,this.record(`device.info`,{reason:e,...n}))}},J=(e,t=[])=>({required:e,optional:t}),Kc={state:J([`state`]),detector:J([`mode`],[`avgMs`]),"speech.start":J([`bargeIn`]),"speech.end":J([`segment`,`durationMs`,`speechMs`,`forced`]),"segment.closed":J([`segment`,`bytes`,`durationMs`,`speechMs`,`forced`]),"stt.sent":J([`segment`,`bytes`]),"stt.received":J([`segment`,`text`],[`junk`,`empty`,`failed`,`audio`,`junkReason`,`held`,`speechMs`]),"utterance.held":J([`text`]),"utterance.merged":J([`segments`,`pauseMs`]),"utterance.sent":J([`text`,`segments`,`reason`,`holdMs`]),"utterance.accepted":J([`inboxID`]),"utterance.failed":J([`message`],[`status`]),"utterance.command":J([`command`,`text`]),heard:J([`inboxID`]),"say.received":J([`messageID`,`ordinal`,`chars`,`sentences`,`muted`],[`seq`]),"tts.sentence.queued":J([`ref`,`text`]),"tts.request":J([`ref`]),"tts.first.byte":J([`ref`]),"tts.sentence.played":J([`ref`]),"tts.sentence.ended":J([`ref`,`playedMs`,`completed`],[`durationMs`]),"barge.in":J([`cause`,`spoken`,`unplayed`,`mutedMessages`],[`playing`]),"cue.played":J([`cue`],[`name`,`text`]),mic:J([`live`],[`reason`]),control:J([`action`],[`on`]),"turn.timing":J([`firstAudio`],[`speechEnd`,`transcript`,`accepted`,`firstSay`,`firstByte`]),"turn.predict":J([`ms`,`silenceMs`,`decision`],[`p`,`error`]),"vad.near":J([`ms`,`threshold`,`echoGuard`,`mode`,`reason`],[`voicedMs`,`peakProb`,`peakDb`]),"vad.summary":J([`frames`,`framesAboveStart`,`framesAboveSpeakingStart`,`msEchoGuard`,`mode`,`sensitivity`],[`maxProb`,`p90Prob`,`maxDb`,`noiseFloorDb`,`nearDropped`]),"stt.slow":J([`segment`,`ms`]),mark:J([`via`],[`note`]),"vad.trace":J([`reason`,`mode`,`frameMs`,`scale`,`values`,`threshold`,`guard`]),"audio.clip":J([`clip`,`for`,`preMs`,`postMs`,`bytes`]),"device.info":J([`reason`],[`outputs`,`inputs`,`track`,`network`,`visibility`,`wakeLock`,`battery`]),"resource.timing":J([`route`,`n`,`medianMs`,`maxMs`],[`medianTtfbMs`,`bytes`]),"console.log":J([`level`,`message`],[`count`,`source`]),"decision.voice":J([`decisionID`,`option`,`outcome`]),"clock.sync":J([`t0`,`t1`,`hubAt`]),error:J([`where`,`message`])},qc=Pc,Jc=60,Yc={"stt.received":{text:qc.textChars,failed:qc.messageChars,held:qc.utteranceChars,junkReason:Jc},"utterance.held":{text:qc.utteranceChars},"utterance.sent":{text:qc.utteranceChars},"utterance.failed":{message:qc.messageChars},"utterance.command":{text:qc.utteranceChars},"tts.sentence.queued":{text:qc.textChars},"cue.played":{text:qc.textChars},"turn.predict":{error:qc.messageChars},mark:{note:qc.textChars},"console.log":{message:qc.messageChars,source:Jc},error:{message:qc.messageChars}},Xc={smart:`finished`,"smart-fallback":`hold`},Zc=new Set([`vad.near`,`vad.summary`,`stt.slow`,`mark`]),Qc=[`junkReason`,`held`,`speechMs`],$c=new Set(Ic);function el(e,t){let n=e;if(!$c.has(n.kind)||t?.includes(`dev.v1`)){if(!t?.includes(`turn.predict`)){if(n.kind===`turn.predict`)return;n.kind===`utterance.sent`&&typeof n.reason==`string`&&Xc[n.reason]&&(n={...n,reason:Xc[n.reason]})}if(!t?.includes(`capture.v2`)){if(Zc.has(n.kind)||n.kind===`utterance.command`&&n.command===`mark`)return;if(n.kind===`stt.received`&&Qc.some(e=>e in n)){let e={...n};for(let t of Qc)delete e[t];n=e}}return n}}function tl(e,t){if(e.length<=t)return e;let n=e.slice(0,t),r=n.charCodeAt(n.length-1);return r>=55296&&r<=56319?n.slice(0,-1):n}function nl(e,t){let n=Kc[e],r={kind:e};for(let[i,a]of Object.entries(t)){if(a===void 0)continue;if(!n.required.includes(i)&&!n.optional.includes(i))throw Error(`${e}: unknown field ${i}`);let t=Yc[e]?.[i];r[i]=t!==void 0&&typeof a==`string`?tl(a,t):a}for(let t of n.required)if(r[t]===void 0)throw Error(`${e}: missing field ${t}`);if(e===`barge.in`){let e=e=>({...e,text:tl(e.text,qc.textChars)}),t=r.spoken;r.spoken={text:tl(t.text,qc.replyChars),estimated:t.estimated},r.playing&&=e(r.playing),r.unplayed=r.unplayed.slice(0,al).map(e),r.mutedMessages=r.mutedMessages.slice(0,al)}return r}var rl=e=>`${e.messageID}:${e.ordinal}:${e.seq??``}:${e.i}`;function il(e){let t=e||``,n=/Android/i.test(t)?`android`:/iPhone|iPad|iPod/i.test(t)?`ios`:`desktop`;return`${n}-${n===`ios`?/CriOS/.test(t)?`chrome`:/FxiOS/.test(t)?`firefox`:`safari`:/Firefox\//.test(t)?`firefox`:/SamsungBrowser/.test(t)?`samsung`:/Edg\//.test(t)?`edge`:/Chrome\//.test(t)?`chrome`:/Safari\//.test(t)?`safari`:`other`}`.slice(0,60)}var al=20,ol=14;function sl(e,t,n){let r=n&&n>0?n:e.length/ol*1e3,i=r>0?Math.min(1,Math.max(0,t/r)):0;if(i>=1)return e.trim();let a=i*e.length,o=0;for(let t=0;t<=e.length;t++)t<e.length&&!/\s/.test(e[t])||Math.abs(t-a)<Math.abs(o-a)&&(o=t);return e.slice(0,o).trim()}function cl(e){let{cause:t,completed:n,playing:r,unplayed:i}=e,a=new Set([...r?[r.ref.messageID]:[],...i.map(e=>e.ref.messageID)]),o=e.turnRunning===!1?e.mutedMessages.filter(e=>a.has(e)):e.mutedMessages;if(!r&&!i.length&&!o.length)return;let s=new Set([...r?[r.ref.messageID]:[],...i.map(e=>e.ref.messageID),...o]),c=n.filter(e=>s.has(e.ref.messageID)).map(e=>e.text.trim());return r&&c.push(sl(r.text,r.playedMs,r.durationMs)),nl(`barge.in`,{cause:t,...r?{playing:{ref:r.ref,text:r.text,playedMs:Math.round(r.playedMs),...r.durationMs===void 0?{}:{durationMs:Math.round(r.durationMs)}}}:{},spoken:{text:c.filter(Boolean).join(` `),estimated:!!r},unplayed:i.map(e=>({ref:e.ref,text:e.text})),mutedMessages:[...o]})}function ll(e,t){if((e===200||e===201)&&typeof t?.recording?.id==`string`){let e=Array.isArray(t.features)?t.features.filter(e=>typeof e==`string`):void 0;return{kind:`started`,recording:t.recording,audio:t.audio!==!1,...typeof t.hubAt==`number`?{hubAt:t.hubAt}:{},...e?{features:e}:{},...t.developer===!0?{developer:!0}:{}}}return e===404||e===405||e===501||e===409&&t?.code===`recording_off`?{kind:`off`}:e===0?{kind:`failed`,reason:`offline`}:e===429&&t?.code===`rate_limited`?{kind:`failed`,reason:`${t.limit??qc.activePerUser} recordings are already running`}:e===429&&t?.code===`limit`?{kind:`failed`,reason:`${t.limit??qc.recordingsStored} recordings stored; delete some in Settings → Voice`}:{kind:`failed`,reason:typeof t?.error==`string`&&t.error?t.error:`HTTP ${e}`}}var ul=new TextEncoder,dl=e=>ul.encode(e).length,fl=dl(`{"events":[]}`),pl=e=>e.kind===`clock.sync`,ml=e=>Math.max(0,Math.round(e*10)/10);function hl(e,t){let n=[],r=fl;for(let i of e){if(n.length&&i.seq!==n[n.length-1].seq+1)break;let e=dl(JSON.stringify(i))+ +!!n.length;if(r+e>t)break;n.push(i),r+=e}let i=e.length-n.length,a=n[n.length-1];if(!i||!a)return n;let o={seq:a.seq+1,t:a.t,kind:`error`,where:`upload`,message:`dropped ${i} events at page close`};return r+1+dl(JSON.stringify(o))<=t&&n.push(o),n}var gl=class{deps;limits;now;setTimer;clearTimer;seq=0;pending=[];batch;sending=!1;ready=!1;flushTimer;retryTimer;attempt=0;acked=0;flushTarget=0;waiters=[];kickQueued=!1;dropped=0;audio;stopped=!1;constructor(e){this.deps=e,this.limits={...Pc,...e.limits},this.now=e.now??(()=>performance.now()),this.setTimer=e.setTimer??((e,t)=>setTimeout(e,t)),this.clearTimer=e.clearTimer??(e=>clearTimeout(e))}get buffered(){return this.pending.length+(this.batch?.length??0)}record(e){return this.add(e,!0)}add(e,t){if(this.stopped)return;let n=++this.seq,r=ml(this.now()),i={...e,seq:n,t:r},a=dl(JSON.stringify(i));for(fl+a>this.limits.batchBytes&&(i={seq:n,t:r,kind:`error`,where:`upload`,message:`event too large: ${e.kind}`},a=dl(JSON.stringify(i))),this.pending.push({e:i,bytes:a});t&&this.pending.length>this.limits.consoleBufferEvents;)this.pending.shift(),this.dropped++;return this.ready&&!pl(i)&&this.scheduled(),n}open(e){this.stopped||this.ready||(this.ready=!0,e&&this.record(nl(`clock.sync`,e)),this.pending.some(e=>!pl(e.e))&&this.scheduled())}flush(){let e=this.lastActiveSeq();if(this.stopped||e<=this.acked)return Promise.resolve();this.flushTarget=Math.max(this.flushTarget,e);let t=new Promise(t=>this.waiters.push({target:e,resolve:t}));return this.kick(),t}discard(){this.halt()}close(){if(this.stopped)return;let e=[...this.batch??[],...this.pending.map(e=>e.e)],t=this.ready;if(this.halt(),!t||!e.length)return;let n=hl(e,this.limits.keepaliveBatchBytes);n.length&&this.deps.send(n,{keepalive:!0}).catch(()=>{})}halt(){this.stopped=!0,this.pending=[],this.batch=void 0,this.clearTimer(this.flushTimer),this.clearTimer(this.retryTimer),this.flushTimer=this.retryTimer=void 0,this.settle()}lastActiveSeq(){for(let e=this.pending.length-1;e>=0;e--)if(!pl(this.pending[e].e))return this.pending[e].e.seq;let e=this.batch??[];for(let t=e.length-1;t>=0;t--)if(!pl(e[t]))return e[t].seq;return 0}activePending(){let e=0;for(let t of this.pending)pl(t.e)||e++;return e}scheduled(){if(this.activePending()>=this.limits.flushEvents){if(this.kickQueued)return;this.kickQueued=!0,queueMicrotask(()=>{this.kickQueued=!1,this.kick()})}else this.flushTimer===void 0&&(this.flushTimer=this.setTimer(()=>{this.flushTimer=void 0,this.kick()},this.limits.flushMs))}take(){let e=[],t=fl;for(;this.pending.length&&e.length<this.limits.eventsPerBatch;){let n=this.pending[0],r=n.bytes+ +!!e.length;if(e.length&&t+r>this.limits.batchBytes)break;e.push(n.e),t+=r,this.pending.shift()}return e}kick(){if(!(!this.ready||this.stopped||this.sending||this.retryTimer!==void 0)){if(!this.batch){if(!this.pending.some(e=>!pl(e.e)))return;this.batch=this.take()}this.clearTimer(this.flushTimer),this.flushTimer=void 0,this.sending=!0,this.send(this.batch)}}async send(e){let t=this.now(),n;try{n=await this.deps.send(e,{})}catch{n={status:0}}if(this.sending=!1,this.stopped||this.batch!==e)return;let r=this.now(),{status:i,body:a}=n;if(i>=200&&i<300){if(this.batch=void 0,this.attempt=0,this.acked=Math.max(this.acked,e[e.length-1].seq),typeof a?.hubAt==`number`&&this.add(nl(`clock.sync`,{t0:ml(t),t1:ml(r),hubAt:a.hubAt}),!1),typeof a?.audio==`boolean`&&a.audio!==this.audio&&(this.audio=a.audio,this.deps.onAudio?.(a.audio)),this.dropped){let e=this.dropped;this.dropped=0,this.add(nl(`error`,{where:`upload`,message:`dropped ${e} events (offline too long)`}),!1)}}else if(i===400)this.batch=void 0,this.attempt=0,this.acked=Math.max(this.acked,e[e.length-1].seq);else if(i===404||i===409||i===413){let e=typeof a?.code==`string`?a.code:i===404?`gone`:i===413?`limit`:`ended`;this.halt(),this.deps.onStop?.({status:i,code:e,...typeof a?.reason==`string`?{reason:a.reason}:{}});return}else{let e=(this.deps.backoffMs??(e=>Math.min(3e4,1e3*2**e)))(this.attempt++);this.retryTimer=this.setTimer(()=>{this.retryTimer=void 0,this.kick()},e);return}this.settle(),this.acked<this.flushTarget||this.activePending()>=this.limits.flushEvents?this.kick():this.activePending()>0&&this.flushTimer===void 0&&this.scheduled()}settle(){let e=this.waiters;this.waiters=[];for(let t of e)this.stopped||t.target<=this.acked?t.resolve():this.waiters.push(t)}},_l=1048576,vl={label:`Record voice conversations (developer)`,description:`Saves your voice segments, transcripts, replies, timing and Concierge actions on this hub, for 7 days. Only you can see them.`,details:[`While Voice mode runs on this device: each speech segment exactly as sent to speech-to-text, what was heard and sent, the replies and what was actually spoken before you interrupted, the timing, and the Concierge's tool calls and Decisions. Not recorded: costs, other sessions' text, the replies' audio.`,`Applies the next time Voice mode starts; a device shows ● Recording while it records. Kept 7 days, then deleted; at most ${qc.userBytes/_l} MB in all (${qc.recordingBytes/_l} MB per recording, ${qc.recordingsStored} recordings).`,`Secrets in known token formats are scrubbed from the text. Audio is kept even when a secret is scrubbed from the text, and secrets spoken in a way the patterns do not match stay in the text and the audio.`,`Recordings are not encrypted at rest: whoever runs this hub can read them on its disk or database. Delete is immediate.`]},yl={label:`Developer mode`,description:`Records much more of each voice conversation, for debugging Voice: raw audio, reply audio and diagnostics. This is more private data. It turns recording on.`,details:[`Also kept, only while a recording runs: raw microphone audio around near-misses and marks (5 s clips, not only what was sent to speech-to-text), the reply audio as you heard it, the speech detector's frame traces, your audio devices, microphone settings, network, battery and screen state, console errors and warnings, request timings, and per turn the model, agent and token counts (never the prompt text).`,`The same limits as recordings: 7 days, ${qc.userBytes/_l} MB in all and ${qc.recordingBytes/_l} MB per recording, counted together; near the limit the extra audio stops first, segments and events go on.`,`Turning it off stops the extras at once; what was kept is deleted with its recording. Turning recording off turns Developer mode off too.`]};function bl(e){let t=[`B`,`KB`,`MB`,`GB`],n=Math.max(0,e),r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${r===0||n>=10?String(Math.round(n)):n.toFixed(1)} ${t[r]}`}var xl=e=>`${bl(e.bytes)} of ${bl(e.capBytes)}`;function Sl(e){let t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t} s`;let n=Math.floor(t/60);return n<60?`${n} min`:`${Math.floor(n/60)} h${n%60?` ${n%60} min`:``}`}var Cl={date:e=>new Date(e).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),time:e=>new Date(e).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})};function wl(e){let t=e?.name?.trim().replace(/^@+/,``);if(t)return`@${t}`;let n=e?.directory?.replace(/[/\\]+$/,``).split(/[/\\]/).pop();return n?`OpenCode session · ${n}`:`OpenCode session`}function Tl(e,t,n=Cl,r=()=>wl(void 0)){let i=e.state===`active`;return{kind:e.kind===`concierge`?`Concierge`:`Voice`,title:e.sessionTitle||r(e.sessionID),device:e.deviceName||`a device`,started:`${n.date(e.startedAt)} ${n.time(e.startedAt)}`,time:n.time(e.startedAt),length:i?`${Sl(t-e.startedAt)} · recording now`:Sl((e.endedAt??t)-e.startedAt),segments:`${e.segments} segment${e.segments===1?``:`s`}`,size:bl(e.bytes),expires:`deleted on ${n.date(e.expiresAt)}`,active:i,...e.audio?{}:{note:`no audio (storage full)`}}}function El(e,t,n){let r=e?`${e}${t?`+`:``} recording${e===1&&!t?``:`s`}`:`No recordings`;return n?`${r} · ${xl(n)}`:r}var Dl=e=>{let t=new Date(e);return`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()}`};function Ol(e,t,n=Cl.date){let r=Dl(e);if(r===Dl(t))return`Today`;let i=new Date(t);return i.setDate(i.getDate()-1),r===Dl(i.getTime())?`Yesterday`:n(e)}function kl(e){return e.title.trim().toLowerCase()===e.kind.toLowerCase()?{kind:e.kind}:{kind:e.kind,title:e.title}}function Al(e){let t=e,n=new Set;return{get:()=>t,set(e){t=e;for(let e of[...n])e()},subscribe(e){return n.add(e),()=>n.delete(e)}}}var jl={on:!1,audio:!0},Ml=Al(jl),Nl=e=>`${e.audio?`Recording`:`Recording · no audio (storage full)`}${e.developer?` · developer`:``}`,Pl=e=>e.on?` · recording`:``,Fl=Al({}),Il=5e3,Ll=new Set([`stored`,`skipped-cap`,`failed`,`off`]),Rl=e=>e&&Ll.has(e)?e:void 0,zl=()=>{let e=globalThis.crypto;if(e?.randomUUID)return e.randomUUID();let t=Array.from({length:32},()=>Math.floor(Math.random()*16).toString(16)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-4${t.slice(13,16)}-a${t.slice(17,20)}-${t.slice(20)}`},Bl=(e,t=!1)=>({method:`POST`,credentials:`same-origin`,headers:{"content-type":`application/json`},body:JSON.stringify(e),...t?{keepalive:!0}:{}}),Vl;function Hl(e){e?.type===`recording`&&(e.settings&&typeof e.settings.enabled==`boolean`&&Ul(e.settings),Vl?.onMessage(e))}function Ul(e){Fl.set({supported:!0,settings:e}),e.enabled?e.developer!==!0&&Vl?.recordingID&&Vl.onMessage({type:`recording`,recordingID:Vl.recordingID,developer:!1}):Vl?.turnedOff()}function Wl(e){return Vl?.mark(`button`,e)??!1}var Gl=`Marked`;function Kl(e,t){Vl?.event(e,t)}var ql=class{fetch;now;epoch;limits;take;running=!1;rolled=!1;sessionID=``;client={};retried=new Set;audio=!0;track;wake;onNote;constructor(e={}){this.fetch=e.fetch??((e,t)=>globalThis.fetch(e,{credentials:`same-origin`,...t})),this.now=e.now??(()=>performance.now()),this.epoch=e.epoch??(()=>Date.now()),this.limits=e.limits}get recordingID(){let e=this.take;return e?.id&&!e.uploader.stopped?e.id:void 0}get active(){return this.recordingID!==void 0}get marks(){return this.active&&this.take?.features?.includes(`capture.v2`)===!0}mark(e,t){if(!this.marks)return!1;let n=this.event(`mark`,t?{via:e,note:t}:{via:e});return this.onNote?.(Gl),n!==void 0&&this.developer&&this.onMarked?.(n),!0}get buffered(){return this.take?.uploader.buffered??0}start(e,t={}){if(this.running)return;this.running=!0,this.rolled=!1,this.sessionID=e;let n=globalThis.navigator;this.client={platform:il(n?.userAgent??``),...t},Vl=this,this.indicate(jl),this.begin()}event(e,t){try{let n=this.take;if(!n)return;let r=n.developer?n.features:n.features?.filter(e=>e!==`dev.v1`),i=el(nl(e,t),r);return i?n.uploader.record(i):void 0}catch{return}}get developer(){let e=this.take;return this.active&&e?.developer===!0&&e.features?.includes(`dev.v1`)===!0}onMarked;clip(e,t,n,r){let i=this.take,a=this.recordingID;if(!i||!a||!this.developer||i.clips>=Fc.clipsPerRecording||n.byteLength>Fc.clipBytes)return;let o=++i.clips;this.event(`audio.clip`,{clip:o,for:{kind:e,seq:t},preMs:r.preMs,postMs:r.postMs,bytes:n.byteLength}),this.fetch(`/api/recordings/${encodeURIComponent(a)}/clips/${o}`,{method:`PUT`,credentials:`same-origin`,headers:{"content-type":`audio/wav`},body:n}).catch(()=>{})}micTrack(e,t){this.track={settings:e,...t?{label:t}:{}},this.take?.probe?.micTrack(e,t)}wakeLock(e){this.wake=e,this.take?.probe?.wakeLock(e)}record(e){try{this.take?.uploader.record(e)}catch{}}barge(e){let t=cl(e);t&&this.record(t)}audioResult(e){return Rl(e?.get?.(Nc))}transcribeHeaders(e){let t=this.recordingID;return t?{[Ac]:t,[jc]:String(e)}:{}}speakHeaders(e){let t=this.recordingID;return t&&e?{[Ac]:t,[Mc]:rl(e)}:{}}segmentAudio(e,t,n){let r=this.recordingID;t===`failed`&&r&&!this.retried.has(e)&&(this.retried.add(e),this.fetch(`/api/recordings/${encodeURIComponent(r)}/segments/${e}`,{method:`PUT`,credentials:`same-origin`,headers:{"content-type":`audio/wav`},body:n}).catch(()=>{}))}async stop({keepalive:e=!1,reason:t=`stopped`}={}){if(!this.running)return;this.running=!1,Vl===this&&(Vl=void 0);let n=this.take;this.take=void 0,this.indicate(jl),n&&(this.stopProbe(n),e?(n.uploader.close(),n.id&&this.end(n.id,t,!0)):(await n.started,n.id&&!n.uploader.stopped&&(await Promise.race([n.uploader.flush(),new Promise(e=>setTimeout(e,Il))]),n.uploader.close(),await this.end(n.id,t,!1))))}turnedOff(){let e=this.take;e&&(this.stopProbe(e),e.uploader.discard(),this.take=void 0,this.indicate(jl))}onMessage(e){if(e?.type!==`recording`)return;e.settings?.enabled===!1&&this.turnedOff();let t=this.take;if(t?.id&&e.recordingID===t.id){if(typeof e.audio==`boolean`&&this.audioChanged(t,e.audio),e.developer===!1&&t.developer){t.developer=!1,this.stopProbe(t);let e=Ml.get();e.on&&e.recordingID===t.id&&this.indicate({...e,developer:!1})}if(e.state===`deleted`)this.stopProbe(t),t.uploader.discard(),this.take=void 0,this.indicate(jl);else if(e.state===`ended`){if(e.reason===`conversation_off`)return;t.uploader.discard(),this.ended(t,{status:409,code:`recording_ended`,...typeof e.reason==`string`?{reason:e.reason}:{}})}}}begin(){let e;e={uploader:new gl({send:(t,{keepalive:n})=>this.sendEvents(e,t,!!n),now:this.now,onStop:t=>this.ended(e,t),onAudio:t=>this.audioChanged(e,t),...this.limits?{limits:this.limits}:{}}),started:Promise.resolve(),clips:0},this.take=e,e.started=this.open(e).catch(()=>e.uploader.discard())}async open(e){let t;try{let n=await this.fetch(`/api/settings/recording`);if(n.status===404||n.status===405)return Fl.set({supported:!1}),e.uploader.discard();if(n.ok){let{settings:e}=await n.json();e&&Fl.set({supported:!0,settings:e}),t=e?.enabled}}catch{}if(t===!1||this.take!==e||!this.running)return e.uploader.discard();let n={perf:this.now(),epoch:this.epoch()},r=this.now(),i=0,a;try{let e=await this.fetch(`/api/recordings`,Bl({sessionID:this.sessionID,clientID:zl(),anchor:n,client:this.client}));i=e.status,a=await e.json().catch(()=>({}))}catch{}let o=this.now(),s=ll(i,a);if(s.kind!==`started`){e.uploader.discard(),s.kind===`failed`&&t===!0&&this.take===e&&this.running&&this.onNote?.(`Not recording: ${s.reason}`);return}e.id=s.recording.id,e.features=s.features,e.developer=s.developer===!0,this.audio=s.audio,e.uploader.open(s.hubAt===void 0?void 0:{t0:r,t1:o,hubAt:s.hubAt});let c=e.features?.includes(`capture.v2`)===!0;this.take===e&&this.running&&(this.indicate({on:!0,audio:this.audio,sessionID:this.sessionID,recordingID:e.id,...c?{marks:c}:{},...this.developer?{developer:!0}:{}}),this.developer&&this.startProbe(e))}startProbe(e){try{let t=new Gc({record:(e,t)=>void this.event(e,t)});e.probe=t,this.track&&t.micTrack(this.track.settings,this.track.label),this.wake!==void 0&&t.wakeLock(this.wake),t.start().catch(()=>{})}catch{}}stopProbe(e){try{e.probe?.stop()}catch{}e.probe=void 0}async sendEvents(e,t,n){let r=await this.fetch(`/api/recordings/${encodeURIComponent(e.id??``)}/events`,Bl({events:t},n));return{status:r.status,body:await r.json().catch(()=>({}))}}end(e,t,n){return this.fetch(`/api/recordings/${encodeURIComponent(e)}/end`,Bl({reason:t},n)).then(()=>{},()=>{})}ended(e,t){if(this.take!==e)return;this.stopProbe(e),this.take=void 0;let n=t.reason;if(n===`max_duration`&&this.running&&!this.rolled){this.rolled=!0,this.indicate(jl),this.begin();return}let r=t.code===`limit`||n===`limit`?`Recording stopped: limit reached`:void 0;this.indicate(r?{...jl,note:r}:jl),r&&this.onNote?.(r)}audioChanged(e,t){if(this.take!==e||t===this.audio)return;this.audio=t;let n=Ml.get();n.on&&n.recordingID===e.id&&this.indicate({...n,audio:t})}indicate(e){Ml.set(e)}};async function Jl(e,t,n={}){let r=await(n.fetch??((e,t)=>globalThis.fetch(e,{credentials:`same-origin`,...t})))(`/api/recordings/${encodeURIComponent(e)}/segments/${t}`);if(!r.ok){let e=await r.json().catch(()=>({}));throw Error(typeof e.error==`string`&&e.error?e.error:`HTTP ${r.status}`)}let i=await r.blob(),a=(n.createURL??(e=>URL.createObjectURL(e)))(i),o=n.revokeURL??(e=>URL.revokeObjectURL(e)),s=!1,c=()=>{s||(s=!0,o(a))},l=(n.audio??(()=>new Audio))();l.addEventListener(`ended`,c),l.addEventListener(`error`,c),l.src=a;try{await l.play()}catch(e){throw c(),e}}var[Y,Yl]=Or(po()),Xl=new xo,[Zl,Ql]=u(0),$l=Zl,[X,eu]=u(),[tu,nu]=u(),[ru,iu]=u(),[au,ou]=u([]),[su,cu]=u([]),[lu,uu]=u(new Map),du=lu,fu=200;function pu(e){e.length&&uu(t=>{let n=new Map(t);for(let t of e)n.delete(t.id),n.set(t.id,t);for(;n.size>fu;)n.delete(n.keys().next().value);return n})}var[mu,hu]=u(),[gu,_u]=u(!1),[vu,yu]=u(!1),bu=()=>ts(gu(),vu(),Y.machines!==void 0),[xu,Su]=u();ce(()=>x(()=>{let e=xu(),t=ac(e,Date.now());if(t===void 0)return;let n=setTimeout(()=>Su(t=>t===e?oc(t,Date.now()):t),t+50);M(()=>clearTimeout(n))}));var Cu=ce(()=>C(()=>{let e=X();if(!e)return[];try{return os(localStorage.getItem(is(e.user?.id)))}catch{return[]}}));ce(()=>x(()=>{let e=mu(),t=X();if(gu()&&t)try{localStorage.setItem(is(t.user?.id),JSON.stringify((e?.hiddenSessionIDs??[]).slice(-20)))}catch{}}));var wu=ce(()=>C(()=>$o(mu(),Y.machines,gu()?[]:Cu()),void 0,{equals:(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e))}));Gt(()=>wu());var[Tu,Eu]=u([]),[Du,Ou]=u(new Map),ku=new Set;async function Au(){try{Ou(new Map(Ce(await G(`/api/agent/grants`)).map(e=>[e.id,e])))}catch{}}var ju=e=>Du().get(e),Mu=new Set;function Nu(e){return Mu.add(e),()=>Mu.delete(e)}var Pu=ce(()=>C(e=>pa(e,fa(Y.machines,Y.prefs,Y.reads,wu(),{activity:Y.activity,intents:Y.intents})))),Fu=e=>_o(Y.machines,e),Iu=e=>wu().has(e)?`the Concierge`:Fu(e)?.session.title||void 0,[Lu,Ru]=u(new Map);async function zu(){try{let e=await G(`/api/agent/who`),t=Array.isArray(e?.sessions)?e.sessions:[];Ru(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 Bu(e){if(wu().has(e))return We(e,void 0,!0);let t=Fu(e)?.session,n=Lu().get(e);if(!n)for(let t of du().values())t.from.kind===`session`&&t.from.sessionID===e&&t.from.name&&(n=t.from.name);return We(e,{name:n,title:t?.title,directory:typeof t?.project==`string`&&t.project||t?.directory})}var Vu=new ii;Ne(()=>{dt().name!==`pair`&&(ld(),eu(void 0),Hu())});function Hu(){let e=location.pathname+location.search;Vt(`/pair${e===`/`||e.startsWith(`/pair`)?``:`?next=${K(e)}`}`,{replace:!0})}async function Uu(){if(X())return!0;let e=await fetch(`/api/me`,{credentials:`same-origin`});if(e.status===401)return Hu(),!1;if(!e.ok)throw Error(`HTTP ${e.status}`);return eu(await e.json()),!0}async function Wu(){if(tu()!==void 0)return tu()??null;try{let e=await fetch(`/api/auth`,{credentials:`same-origin`}),t=e.ok?await e.json():null;return nu(t),t}catch{return null}}var Gu,Ku,qu=1e3,Ju=()=>!1,Yu={lite:!1},[Xu,Zu]=u(``),Qu,$u=!1,ed=new Co({setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e),open:(e,t)=>sd(e,t),close:()=>od(),keepOpen:()=>Ju()});function td(e){Ju=e}function nd(e){Yu=e,ed.setScope(e)}var rd=!1;function id(){rd||(rd=!0,document.addEventListener(`visibilitychange`,()=>document.visibilityState===`hidden`?ed.hidden():ed.visible()),window.addEventListener(`pageshow`,e=>{e.persisted&&ed.state!==`stopped`&&ed.reopen()}),window.addEventListener(`online`,()=>ed.state===`open`&&Y.connection===`down`&&ed.reopen()))}function ad(e={lite:!1}){ed.state===`stopped`&&(id(),Yu=e,ed.start(e),gu()||(bd(),setTimeout(()=>!gu()&&yu(!0),es)),document.visibilityState===`hidden`&&ed.hidden())}function od(){clearTimeout(Ku),Gu?.close(),Gu=void 0,ed.state===`paused`&&Yl(`connection`,`paused`)}function sd(e,t){clearTimeout(Ku),Gu?.close();let n=wo(Y.connection,t);$u=n.reconnecting,n.reconnecting&&cd(`reconnecting`),Yl(`connection`,n.connection),Dc(Yu);let r=new EventSource(e,{withCredentials:!0});Gu=r,r.onopen=()=>{qu=1e3,Yl(`connection`,`live`),$u&&cd(`updated`,2e3),$u=!1,Fd(),hd(),dd(),pd(),Ad(),Td(),zu(),Au(),bd()},r.onerror=async()=>{Gu===r&&(Yl(`connection`,`down`),(await fetch(`/api/me`,{credentials:`same-origin`}).catch(()=>void 0))?.status===401?(ld(),eu(void 0),Hu()):r.readyState===EventSource.CLOSED&&Gu===r&&(Gu=void 0,Ku=setTimeout(()=>ed.state===`open`&&ed.reopen(),qu),qu=Math.min(3e4,qu*2)))},r.addEventListener(`ping`,()=>ed.received()),r.onmessage=e=>{ed.received(e.lastEventId||void 0);let t;try{t=JSON.parse(e.data)}catch{return}ud(t)}}function cd(e,t){clearTimeout(Qu),Zu(e),t&&(Qu=setTimeout(()=>Zu(``),t))}function ld(){ed.stop(),Gu?.close(),Gu=void 0,clearTimeout(Ku)}function ud(e){he(()=>{if(Oc(e),e.type===`prefs`?(Yl(Fr(t=>go(t,e))),Y.prefsStale&&!Y.prefsPending&&Id()):e.type===`catalog`?Yl(Fr(t=>{go(t,e),Vu.apply(t.machines,Date.now())})):Yl(Fr(t=>go(t,e))),e.type===`status`){let t=Fu(e.sessionID);!Xl.has(e.sessionID)&&t&&Xl.feed(e.sessionID)}if(Xl.apply(e)!==void 0&&Ql(e=>e+1),e.type===`enrollment`&&Ad(),e.type===`intent`&&typeof e.sessionID==`string`&&md(e.sessionID),e.type===`recording`&&Hl(e),e.type===`decision`){let t=Pe(e.decision);if(t){wd.event(t);let e=Qe(su(),t);e&&q(e),cu(e=>ke(e,t)),pu([t])}}if(e.type===`concierge`){let t=Zo(e.status);t&&(Su(e=>rc(mu(),t,e)),hu(t),_u(!0),_d++);let n=Bs(e.armed);n!==void 0&&(Sd.event(),Su(n))}if(e.type===`agent`){let t=xe(e.entry);t&&Eu(e=>Ht(e,t)),t?.grant&&!Du().has(t.grant)&&!ku.has(t.grant)&&(ku.add(t.grant),Au())}if(e.type===`resync`&&(hd(),dd(),pd(),Id(),Ad(),Td(),zu(),Au(),bd()),e.type===`handoff`&&(dt().name!==`session`||dt().id!==e.sessionID)){let t=Fu(e.sessionID);q(`Handed off: ${t?.session.title||e.sessionID}`,``,{label:`Open`,run:()=>Vt(`/s/${K(e.sessionID)}`)})}});for(let t of Mu)t(e)}async function dd(){try{let{activity:e}=await G(`/api/activity/mine`);Yl(`activity`,ta(e))}catch{}}var fd=e=>{let t=e;return t&&typeof t.text==`string`&&t.text&&t.source!==`title`?{text:t.text,...typeof t.source==`string`?{source:t.source}:{}}:void 0};async function pd(){try{let{intents:e}=await G(`/api/intents/mine`),t={};for(let[n,r]of Object.entries(e??{})){let e=fd(r);e&&(t[n]=e)}Yl(`intents`,t)}catch{}}async function md(e){try{let{intent:t}=await G(`/api/agent/sessions/${K(e)}/intent`),n=fd(t);Yl(`intents`,Fr(t=>{n?t[e]=n:delete t[e]}))}catch{}}async function hd(){try{let{reads:e}=await G(`/api/reads`);Yl(`reads`,e??{})}catch{}}async function gd(e,t=!1){try{let{reads:n}=await(await V(`${H(e)}/read`,{method:`POST`,json:t?{open:!0}:{}})).json();n&&typeof n==`object`&&Yl(`reads`,n)}catch{}}var _d=0,vd,yd;function bd(){return vd?(yd??=vd.then(()=>(yd=void 0,bd())),yd):(vd=xd().finally(()=>vd=void 0),vd)}async function xd(){let e=_d;try{let t=Qo(await G(`/api/agent/concierge`));t&&e===_d&&hu(t.status)}catch(t){t instanceof W&&t.status===404&&e===_d&&hu(void 0);return}finally{_u(!0)}await Cd()}var Sd=new sc;async function Cd(){let e=Sd.begin();try{let t=Bs((await G(`/api/agent/concierge/arm`)).armed);Sd.fresh(e)&&t!==void 0&&Su(oc(t,Date.now()))}catch(t){Sd.fresh(e)&&t instanceof W&&(t.status===404||t.status===403)&&Su(void 0)}}var wd=new Ke;async function Td(){let e=wd.begin();try{let{decisions:t}=await G(`/api/decisions?state=open`),n=wd.settle(e,(t??[]).map(Pe).filter(e=>!!e));if(!n)return;cu(n),pu(n)}catch(t){wd.fail(e),t instanceof W&&t.status===404&&cu([])}}var Ed=new Go({fetch:e=>G(`/api/decisions/${K(e)}`),parse:e=>Pe(e?.decision)??void 0,status:e=>e instanceof W?e.status:void 0});function Dd(e){let t=lu().get(e);return t?Promise.resolve(t):Ed.recall(e).then(t=>(t&&!lu().has(e)&&pu([t]),t))}function Od(e){wd.event(e),cu(t=>ke(t,e)),pu([e])}function kd(e){let t=su().find(t=>t.id===e);t&&wd.event({...t,state:`closed`}),cu(t=>t.filter(t=>t.id!==e)),Td()}async function Ad(){if(!qn(X()))ou([]);else try{ou((await G(`/api/enrollments`)).enrollments??[])}catch{ou([])}}async function jd(){try{iu((await G(`/api/settings/speech`)).ready??null)}catch{iu(null)}}var Md=`voice.viewPrefs`,Nd=!1,Pd=()=>Y.prefsSource===`hub`||Y.prefsSource===`local`;async function Fd(){if(!(Pd()||Nd)){Nd=!0;try{Yl({prefs:ti(await G(`/api/prefs/view`)),prefsSource:`hub`})}catch(e){if(e instanceof W&&e.status===404){let e;try{e=JSON.parse(localStorage.getItem(Md)??`null`)}catch{}Yl({prefs:ti(e),prefsSource:`local`})}else Yl(`prefsSource`,`error`)}finally{Nd=!1}Pd()&&await Ld()}}async function Id(){Yl({prefsStale:!1,prefsSource:`unknown`}),await Fd()}async function Ld(){let{clear:e,patch:t}=ci(localStorage.getItem(`voice.pins`),localStorage.getItem(`voice.pinnedWorkspaces`),Y.prefs);e&&(t&&(Yl(`prefs`,e=>({...e,...t})),!(await Rd(t)).ok)||(localStorage.removeItem(`voice.pins`),localStorage.removeItem(`voice.pinnedWorkspaces`)))}async function Rd(e){if(Y.prefsSource===`local`)return localStorage.setItem(Md,JSON.stringify(Y.prefs)),{ok:!0};Yl(`prefsPending`,e=>e+1);try{let t=await(await V(`/api/prefs/view`,{method:`PUT`,json:e})).json().catch(()=>void 0);return Y.prefsPending===1&&t&&!Y.prefsStale&&Yl(`prefs`,ti(t)),{ok:!0}}catch(e){return{ok:!1,error:e}}finally{Yl(`prefsPending`,e=>e-1),!Y.prefsPending&&Y.prefsStale&&Id()}}function zd(e,t,n,r={}){Bd(e,[t],n,r)}function Bd(e,t,n,{message:r,undo:i=!1}={}){if(!Pd()){q(`Your view settings are still loading. Try again in a moment.`,`err`),Fd();return}let a=new Set(Y.prefs[e]),o=t.filter(e=>a.has(e)!==n),{prefs:s,patch:c}=oi(Y.prefs,e,o,n);c&&(Yl(`prefs`,s),r&&q(r,``,i?{label:`Undo`,run:()=>Bd(e,o,!n)}:void 0),Rd(c).then(({ok:t,error:r})=>{t||(Yl(`prefs`,oi(Y.prefs,e,o,!n).prefs),q(`Could not save that change: ${U(r)}`,`err`))}))}async function Vd(e,t){try{return await V(`${H(e)}/expose`,{method:`POST`,json:{on:t}}),q(t?`Voice enabled`:`Voice disabled`),!0}catch(e){return q(`Could not ${t?`enable`:`disable`} Voice: ${U(e)}`,`err`),!1}}async function Hd(e,t){let n=ni(t);if(`error`in n)return q(n.error,`err`),!1;let{title:r}=n,i=Fu(e)?.session.title;if(i===r)return!1;Vu.set(e,r,Date.now()),Yl(Fr(t=>void ri(t.machines,e,r)));try{let t=await(await V(`${H(e)}/rename`,{method:`POST`,json:{title:r}})).json().catch(()=>void 0),n=typeof t?.title==`string`&&t.title?t.title:r;return n!==r&&Fu(e)?.session.title===r&&(Vu.drop(e,r),Vu.set(e,n,Date.now()),Yl(Fr(t=>void ri(t.machines,e,n)))),!0}catch(t){return Vu.drop(e,r),i!==void 0&&Fu(e)?.session.title===r&&Yl(Fr(t=>void ri(t.machines,e,i))),q(`Could not rename: ${U(t)}`,`err`),!1}}var[Ud,Wd]=u(new Set),Gd=e=>Ud().has(e),Kd=(e,t)=>Wd(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r}),qd=6e4;async function Jd(e){if(Gd(e))return;let t=Fu(e)?.session.title;Kd(e,!0);let n=!1;try{let r=await(await V(`${H(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()+qd,i=()=>{let n=Fu(e)?.session.title;n!==void 0&&n!==t?(Kd(e,!1),q(`Renamed to “${n}”`)):Date.now()>=r?Kd(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}Vu.set(e,i,Date.now()),Yl(Fr(t=>void ri(t.machines,e,i))),q(`Renamed to “${i}”`)}catch(e){q(`Could not auto-name: ${U(e)}`,`err`)}finally{n||Kd(e,!1)}}async function Yd(e){try{await V(`${H(e)}/error/dismiss`,{method:`POST`,json:{}})}catch(e){q(`Could not dismiss the error: ${U(e)}`,`err`)}}async function Xd(e){try{let{stopped:t}=await(await V(`${H(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: ${U(e)}`,`err`)}}var Zd=I(`<svg viewBox="72 51 368 368"aria-hidden=true><g transform="translate(0 20.7)"><g stroke=currentColor stroke-width=22 stroke-linecap=round><line x1=256 y1=256 x2=256 y2=90></line><line x1=256 y1=256 x2=399.8 y2=339></line><line x1=256 y1=256 x2=112.2 y2=339></line></g><g fill=currentColor><circle cx=256 cy=90 r=40></circle><circle cx=399.8 cy=339 r=40></circle><circle cx=112.2 cy=339 r=40></circle></g><circle class=hub-mark-gap cx=256 cy=256 r=71></circle><circle class=hub-mark-hub cx=256 cy=256 r=60>`);function Qd(e){let t=()=>e.size??18;return(()=>{var n=Zd();return s(r=>{var i=`hub-mark${e.class?` ${e.class}`:``}`,a=t(),o=t();return i!==r.e&&b(n,`class`,r.e=i),a!==r.t&&b(n,`width`,r.t=a),o!==r.a&&b(n,`height`,r.a=o),r},{e:void 0,t:void 0,a:void 0}),n})()}var $d=I(`<p class=error role=alert>`),ef=I(`<form class="card stack"novalidate><div class=field><label for=pair-code>Pairing code</label><input id=pair-code class=pair-code type=text inputmode=numeric autocomplete=one-time-code maxlength=6></div><p class="small muted">In OpenCode run /hub → Pair a phone on a computer connected to this hub to get a 6-digit code. For the very first device, use the code printed in the hub's log.</p><div class=field><label for=pair-name>Device name</label><input id=pair-name type=text maxlength=64></div><button type=submit class="btn primary">Pair`),tf=I(`<p class=muted>Sign in to see and control your own OpenCode sessions.`),nf=I(`<a class="btn primary signin">Sign in with Google`),rf=I(`<details class=card><summary>Have a pairing code?`),af=I(`<main class=entry><h1 class="display brand-big"> Hub`),of=I(`<p class=muted>Loading…`),sf=I(`<p class=muted>Pair this browser with your hub to see and control your OpenCode sessions.`),cf=I(`<p>A terminal on <strong></strong> asks to act as you through the hub CLI.`),lf=I(`<p class="small muted">Code <!> · requested <!>. Approve only if you ran <span class=mono>hub login</span> yourself and this code matches the one in your terminal.`),uf=I(`<fieldset class=stack><legend class=small>What it may do`),df=I(`<p class=small>Launch is ticked: the terminal can start sessions in a repository once you also create a grant with verb launch for it.`),ff=I(`<div class=row><button type=button class="btn primary">Approve</button><button type=button class="btn danger">Deny`),pf=I(`<p role=status>`),mf=I(`<main class=entry><h1 class=display>CLI login for </h1><div class="card stack"><a class=btn href=/>Back to sessions`),hf=I(`<label class=check><input type=checkbox><span><span class=mono></span> `),gf=I(`<main class=entry><p class=muted>Loading…`),_f=I(`<strong>`),vf=I(`<p>`),yf=I(`<p class="small muted">Approve only if this code matches the one shown in OpenCode.`),bf=I(`<p class=small>`),xf=I(`<main class=entry><h1 class=display>Approve machine</h1><div class="card stack"><a class=btn href=/>Back to sessions`),Sf=I(`<p>No code given.`),Cf=I(`<strong class=mono>`),wf=I(`<main class=entry><h1 class=display>Connect an app</h1><div class="card stack"><p role=status data-consent-missing></p><a class=btn href=/>Back to sessions`),Tf=I(`<p><strong></strong> wants to use this hub as <!>.`),Ef=I(`<p class="small muted">After you decide, your browser goes back to <span class=mono data-consent-origin></span>. Approve only if you started this from that app.`),Df=I(`<fieldset class=stack><legend class=small>What it may do (untick what it should not)`),Of=I(`<p class="small muted">Acting still needs a grant from you (Settings → Agents &amp; access). You can revoke this app there at any time.`),kf=I(`<main class="entry consent"><h1 class=display>Connect </h1><div class="card stack">`),Af=I(`<p class=small data-consent-current>It is already connected with <!>. Approving replaces that.`),jf=I(`<span class="badge-pill warn"title="Only within a grant you create">acts in your sessions`);function Mf(){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 Nf(e){let[t,i]=u(),[a,o]=u(!1),[c,d]=u(``),[f,p]=u(Mf()),[m,h]=u(e.error?`Sign-in did not work: ${e.error}`:``),[g,_]=u(!1);fe(async()=>{let[t,n]=await Promise.all([fetch(`/api/me`,{credentials:`same-origin`}).catch(()=>void 0),Wu()]);if(t?.ok)return eu(await t.json()),Vt(e.next,{replace:!0});i($n(n??void 0,e.next)),o(!0)});let v=async t=>{t.preventDefault();let n=c().replace(/\D/g,``);if(n.length!==6)return h(`Enter the 6-digit code.`);_(!0),h(``);try{await V(`/api/pair`,{method:`POST`,json:{code:n,deviceName:f().trim()||Mf()}}),eu(void 0),Vt(e.next,{replace:!0})}catch(e){h(e instanceof W&&e.status===401?`That code is wrong or expired. Get a fresh one and try again.`:U(e)),_(!1)}},x=()=>(()=>{var e=ef(),t=e.firstChild,r=t.firstChild.nextSibling,i=t.nextSibling.nextSibling,a=i.firstChild.nextSibling,o=i.nextSibling;return e.addEventListener(`submit`,v),r.$$input=e=>d(e.currentTarget.value),a.$$input=e=>p(e.currentTarget.value),y(e,n(l,{get when(){return m()},get children(){var e=$d();return y(e,m),e}}),o),s(()=>o.disabled=g()),s(()=>r.value=c()),s(()=>a.value=f()),e})();return(()=>{var i=af(),o=i.firstChild,c=o.firstChild;return y(o,n(Qd,{class:`brand-mark`,size:30}),c),y(i,n(l,{get when(){return a()},get fallback(){return of()},get children(){return n(l,{get when(){return t()},get fallback(){return[sf(),r(x)]},get children(){return[tf(),(()=>{var e=nf();return s(()=>b(e,`href`,t())),e})(),(()=>{var t=rf();return t.firstChild,y(t,x,null),s(()=>t.open=!!e.error),t})()]}})}}),null),i})()}function Pf(e){let t=mt(e.login),[r,i]=u(t.filter(e=>e.checked).map(e=>e.scope)),[a,o]=u(``),[c,d]=u(``),[f,p]=u(!1),h=()=>e.login.userCode,g=async t=>{let n=t===`approve`?Kt(r()):{ok:!0,body:{}};if(!n.ok)return o(n.error);p(!0);try{await V(`/api/cli-logins/${K(h())}/${t}`,{method:`POST`,json:n.body}),d(t===`approve`?`The terminal on ${e.login.clientName} is logged in as you, with ${r().join(`, `)}.${r().includes(`sessions:launch`)?` To launch, it also needs a grant with verb launch (Settings → Agents).`:``} You can revoke it in Settings → Agents.`:`Denied the CLI login for ${e.login.clientName}.`)}catch(e){o(e instanceof W&&e.status===404?`No pending request with code ${h()}. It may have expired or been answered already.`:U(e)),p(!1)}};return(()=>{var o=mf(),u=o.firstChild;u.firstChild;var d=u.nextSibling,p=d.firstChild;return y(u,()=>e.login.clientName,null),y(d,n(l,{get when(){return!c()},get fallback(){return(()=>{var e=pf();return y(e,c),e})()},get children(){return[(()=>{var t=cf(),n=t.firstChild.nextSibling;return y(n,()=>e.login.clientName),t})(),(()=>{var t=lf(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(t,h,n),y(t,()=>R(e.login.created),r),t})(),(()=>{var e=uf();return e.firstChild,y(e,n(m,{each:t,children:e=>(()=>{var t=hf(),n=t.firstChild,a=n.nextSibling,o=a.firstChild;return o.nextSibling,n.addEventListener(`change`,t=>i(t.currentTarget.checked?[...r(),e.scope]:r().filter(t=>t!==e.scope))),y(o,()=>e.scope),y(a,()=>e.label,null),y(a,()=>e.requested?` (requested)`:``,null),s(()=>n.disabled=f()),s(()=>n.checked=e.checked),t})()}),null),e})(),n(l,{get when(){return r().includes(`sessions:launch`)},get children(){return df()}}),(()=>{var e=ff(),t=e.firstChild,n=t.nextSibling;return t.$$click=()=>void g(`approve`),n.$$click=()=>void g(`deny`),s(e=>{var r=f(),i=f();return r!==e.e&&(t.disabled=e.e=r),i!==e.t&&(n.disabled=e.t=i),e},{e:void 0,t:void 0}),e})(),n(l,{get when(){return a()},get children(){var e=pf();return y(e,a),e}})]}}),p),o})()}function Ff(e){let[t,r]=u(),[i,a]=u(!e.code);return fe(async()=>{if(e.code){try{r(Xe(await(await V(`/api/cli-logins/${K(e.code.toUpperCase())}`)).json()))}catch{}a(!0)}}),n(l,{get when(){return i()},get fallback(){return gf()},get children(){return n(l,{get when(){return t()},get fallback(){return n(If,{get code(){return e.code}})},children:e=>n(Pf,{get login(){return e()}})})}})}function If(e){let t=()=>e.code.toUpperCase(),[i,a]=u(``),[o,c]=u(``),[d,f]=u(!1),[p,m]=u(!qn(X()));fe(async()=>{await Ad(),m(!0)});let h=()=>au().find(e=>e.userCode===t()),g=()=>`No pending request with code ${t()}. It may have expired or been answered already.`,_=async e=>{f(!0);let n=h()?.machineName;try{await V(`/api/enrollments/${K(t())}/${e}`,{method:`POST`,json:{}}),c(e===`approve`?`${n??`The machine`} is approved and belongs to you. It will connect in a few seconds.`:`Denied ${n??`the request with code ${t()}`}.`)}catch(e){a(e instanceof W&&e.status===404?g():U(e)),f(!1)}};return(()=>{var e=xf(),a=e.firstChild.nextSibling,c=a.firstChild;return y(a,n(l,{get when(){return!o()},get fallback(){return(()=>{var e=pf();return y(e,o),e})()},get children(){return n(l,{get when(){return t()},get fallback(){return Sf()},get children(){return n(l,{get when(){return p()},get fallback(){return of()},get children(){return n(l,{get when(){return!qn(X())||h()},get fallback(){return(()=>{var e=vf();return y(e,g),e})()},get children(){return[(()=>{var e=vf();return y(e,n(l,{get when(){return h()},get fallback(){return[`A machine showing code `,(()=>{var e=Cf();return y(e,t),e})(),` wants to connect to this hub.`]},get children(){return[(()=>{var e=_f();return y(e,()=>h().machineName),e})(),` wants to connect to this hub.`]}})),e})(),(()=>{var e=yf(),t=e.firstChild;return y(e,(()=>{var e=r(()=>!!h());return()=>e()?`Code ${h().userCode} · requested ${R(h().created)}. `:``})(),t),e})(),(()=>{var e=bf();return y(e,()=>er(X())),e})(),(()=>{var e=ff(),t=e.firstChild,n=t.nextSibling;return t.$$click=()=>void _(`approve`),n.$$click=()=>void _(`deny`),s(e=>{var r=d(),i=d();return r!==e.e&&(t.disabled=e.e=r),i!==e.t&&(n.disabled=e.t=i),e},{e:void 0,t:void 0}),e})(),n(l,{get when(){return i()},get children(){var e=pf();return y(e,i),e}})]}})}})}})}}),c),e})()}function Lf(e){let[t,r]=u(),[i,a]=u(``);return fe(async()=>{try{let t=ht(await(await V(`/api/connect/flows/${K(e.flow)}`)).json());t?r(t):a(`The hub sent a request this console cannot show.`)}catch(e){a(e instanceof W&&e.status===404?`This request expired: start again from the app.`:U(e))}}),n(l,{get when(){return t()},get fallback(){return(()=>{var e=wf(),t=e.firstChild.nextSibling.firstChild;return y(t,()=>i()||`Loading…`),e})()},children:e=>n(Rf,{get flow(){return e()}})})}function Rf(e){let t=at(e.flow),[i,a]=u(t.map(e=>e.scope)),[o,c]=u(``),[d,f]=u(``),[p,h]=u(!1),g=()=>{let e=Jn(X());return e.mode===`oidc`?e.title:`you`},_=async t=>{let n=t===`approve`?tt(e.flow,i()):{ok:!0,body:{}};if(!n.ok)return c(n.error);h(!0),c(``);try{let r=await(await V(`/api/connect/flows/${K(e.flow.id)}/${t}`,{method:`POST`,json:n.body})).json();if(typeof r.redirect!=`string`)throw Error(`The hub did not say where to go next`);f(t===`approve`?`Connected. Taking you back to ${e.flow.client.redirectOrigin}…`:`Denied. Taking you back to ${e.flow.client.redirectOrigin}…`),location.assign(r.redirect)}catch(e){c(e instanceof W&&e.status===404?`This request expired: start again from the app.`:U(e)),h(!1)}};return(()=>{var c=kf(),u=c.firstChild;u.firstChild;var f=u.nextSibling;return y(u,()=>e.flow.client.name,null),y(f,n(l,{get when(){return!d()},get fallback(){return(()=>{var e=pf();return y(e,d),e})()},get children(){return[(()=>{var t=Tf(),n=t.firstChild,r=n.nextSibling.nextSibling;return r.nextSibling,y(n,()=>e.flow.client.name),y(t,g,r),t})(),(()=>{var t=Ef(),n=t.firstChild.nextSibling;return y(n,()=>e.flow.client.redirectOrigin),t})(),n(l,{get when(){return e.flow.connection},children:e=>(()=>{var t=Af(),n=t.firstChild.nextSibling;return n.nextSibling,y(t,()=>e().scopes.join(`, `)||`no scopes`,n),t})()}),(()=>{var e=Df();return e.firstChild,y(e,n(m,{each:t,children:e=>(()=>{var t=hf(),o=t.firstChild,c=o.nextSibling,u=c.firstChild;return u.nextSibling,o.addEventListener(`change`,t=>a(t.currentTarget.checked?[...i(),e.scope]:i().filter(t=>t!==e.scope))),y(u,()=>e.scope),y(c,(()=>{var t=r(()=>e.label!==e.scope);return()=>t()?e.label:``})(),null),y(c,n(l,{get when(){return e.act},get children(){return jf()}}),null),s(t=>{var n=p(),r=e.scope;return n!==t.e&&(o.disabled=t.e=n),r!==t.t&&b(o,`data-consent-scope`,t.t=r),t},{e:void 0,t:void 0}),s(()=>o.checked=e.checked),t})()}),null),e})(),Of(),(()=>{var e=ff(),t=e.firstChild,n=t.nextSibling;return t.$$click=()=>void _(`approve`),n.$$click=()=>void _(`deny`),s(e=>{var r=p(),i=p();return r!==e.e&&(t.disabled=e.e=r),i!==e.t&&(n.disabled=e.t=i),e},{e:void 0,t:void 0}),e})(),n(l,{get when(){return o()},get children(){var e=$d();return y(e,o),e}})]}})),s(()=>b(c,`data-consent`,e.flow.id)),c})()}z([`input`,`click`]);var zf=I(`<svg class=activity-meter height=16 role=img data-activity-meter><title></title><rect class=meter-base x=0 y=11 height=0.5>`),Bf=I(`<svg><rect class=meter-agent width=3></svg>`,!1,!0,!1),Vf=I(`<svg><rect class=meter-human y=12 width=3 height=4></svg>`,!1,!0,!1),Hf=4,Uf=11,Wf=4,Gf=(e,t,n)=>e<=0||t<=0?0:Math.max(Wf,Math.round(n*Math.log2(1+e)/Math.log2(1+t)));function Kf(e){let t=()=>ra(e.buckets,e.now),i=()=>sa(ia(e.buckets,e.now)),a=()=>Math.max(0,...t().map(e=>e.agent)),o=24*Hf;return(()=>{var e=zf(),c=e.firstChild,l=c.nextSibling;return b(e,`width`,o),b(e,`viewBox`,`0 0 ${o} 16`),y(c,i),b(l,`width`,o),y(e,n(m,{get each(){return t()},children:(e,t)=>[r(()=>r(()=>e.agent>0)()&&(()=>{var n=Bf();return s(r=>{var i=t()*Hf,o=Uf-Gf(e.agent,a(),Uf),s=Gf(e.agent,a(),Uf);return i!==r.e&&b(n,`x`,r.e=i),o!==r.t&&b(n,`y`,r.t=o),s!==r.a&&b(n,`height`,r.a=s),r},{e:void 0,t:void 0,a:void 0}),n})()),r(()=>r(()=>e.human>0)()&&(()=>{var e=Vf();return s(()=>b(e,`x`,t()*Hf)),e})())]}),null),s(()=>b(e,`aria-label`,i())),e})()}var qf=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window&&window.isSecureContext;function Jf(e){let t=`=`.repeat((4-e.length%4)%4),n=atob((e+t).replace(/-/g,`+`).replace(/_/g,`/`));return Uint8Array.from(n,e=>e.charCodeAt(0))}var Yf=(e,t)=>!e||e.byteLength!==t.byteLength?!1:new Uint8Array(e).every((e,n)=>e===t[n]),[Xf,Zf]=u(0),[Qf,$f]=u(new Set),ep=()=>`Notification`in window?Notification.permission:`default`;async function tp(){if(`serviceWorker`in navigator)return await navigator.serviceWorker.getRegistration(`/`).catch(()=>void 0)??void 0}async function np(){if(qf())return await(await tp())?.pushManager.getSubscription()??void 0}async function rp(e){let t=await G(`/api/push/prefs${e?`?endpoint=${encodeURIComponent(e)}`:``}`);return $f(new Set(t.muted??[])),t}async function ip(){let e=qf(),t=e?await tp():void 0,n=await t?.pushManager.getSubscription().catch(()=>null)??void 0,r=await rp(n?.endpoint).catch(()=>void 0);return{env:{supported:e,permission:ep(),worker:!!t,...n?{endpoint:n.endpoint}:{},hubSubscribed:!!r?.subscribed,hubSubscriptions:r?.subscriptions??0},view:r}}async function ap(){let{publicKey:e}=await G(`/api/push/key`),t=Jf(e);await tp()||await navigator.serviceWorker.register(`/sw.js`,{scope:`/`});let n=await navigator.serviceWorker.ready,r=await n.pushManager.getSubscription();return r&&!Yf(r.options?.applicationServerKey,t)&&(await r.unsubscribe(),r=null),r??=await n.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:t}),await V(`/api/push/subscribe`,{method:`POST`,json:{subscription:r.toJSON()}}),r}async function op(){if(!qf())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 ap()}async function sp(){let e=await np();e&&(await V(`/api/push/unsubscribe`,{method:`POST`,json:{endpoint:e.endpoint}}).catch(()=>{}),await e.unsubscribe().catch(()=>{}))}async function cp(e){return(await V(`/api/push/test`,{method:`POST`,json:e?{kind:e}:{}})).json()}async function lp(e,t){let n=Qf(),r=new Set(n);t?r.add(e):r.delete(e),$f(r);try{let n=await(await V(`/api/push/mute`,{method:`PUT`,json:{sessionID:e,muted:t}})).json();$f(new Set(n.muted)),q(t?`Notifications muted for this session`:`Notifications on for this session`)}catch(e){$f(n),q(e instanceof Error?e.message:String(e),`err`)}}async function up(){let{env:e}=await ip().catch(()=>({env:void 0}));e&&Yt(e)&&await ap().then(()=>Zf(e=>e+1),e=>console.warn(`push re-subscribe:`,e?.message??e))}function dp(){`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&&Vt(e.pathname+e.search)}for(let e of fp)e(t)}))}var fp=new Set;function pp(e){return fp.add(e),()=>fp.delete(e)}function mp(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 hp=e=>e===`left`||e===`right`?`vertical`:`horizontal`;function gp(e,t,n,r){let i=r?t+1:t;if(i<=1)return`single`;let a=hp(n);return i===2?a:e===`grid`?`grid`:e===a?r&&i>=gn?`grid`:a:`grid`}function _p(e,t,n,r){return r===`grid`&&n===`bottom`?Math.min(e,t+2):n===`left`||n===`top`?t:t+1}var vp=(e,t)=>Number.isInteger(t)&&t>=0&&t<e.panes.length;function yp(e,t,n){if(!vp(e,t))return{layout:e,outcome:`invalid`};let r=()=>({layout:on(e.split,e.panes,t),outcome:`focused`});if(`empty`in n)return r();let{index:i,zone:a}=n;if(!vp(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:on(e.split,n,i),outcome:`moved`}}let s=e.panes.filter((e,n)=>n!==t),c=gp(e.split,e.panes.length,a,!1),l=_p(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:on(c,u,l),outcome:d?`focused`:`moved`}}function bp(e,t,n){let r=dn(t);if(!r)return{layout:e,outcome:`invalid`};let i=e.panes.findIndex(e=>un(e,r));if(i>=0)return yp(e,i,n);let a=e.panes.length;if(!a)return{layout:on(e.split,[r],0),outcome:`added`};let{index:o,zone:s}=`empty`in n?{index:a-1,zone:`right`}:n;if(!vp(e,o))return{layout:e,outcome:`invalid`};if(s===`center`)return{layout:on(e.split,e.panes.map((e,t)=>t===o?r:e),o),outcome:`replaced`};if(a>=gn)return{layout:e,outcome:`limit`};let c=gp(e.split,a,s,!0),l=_p(a,o,s,c);return{layout:on(c,[...e.panes.slice(0,l),r,...e.panes.slice(l)],l),outcome:`added`}}var xp={side:{min:180,max:480,default:235},rail:{min:220,max:640,default:260}},Sp=`hub.panels`,Cp=(e,{min:t,max:n})=>Math.min(n,Math.max(t,e));function wp(e,t,n){let{min:r,max:i}=xp[e];return{min:r,max:Math.max(r,Math.min(i,Math.floor(t-420-n)))}}var Tp={min:320,max:440,share:.4};function Ep(e,t,n){let r=e=>t-(n.concierge&&e?Tp.min:0),i=Cp(e.side,wp(`side`,r(n.side),n.rail?xp.rail.min:0)),a=Cp(e.rail,wp(`rail`,r(n.rail),n.side?i:0));if(!n.concierge)return{side:i,rail:a};let o=Math.min(Tp.max,Math.floor(t*Tp.share)),s=t-420-(n.side?i:0)-(n.rail?a:0);return{side:i,rail:a,concierge:Math.max(Tp.min,Math.min(o,s))}}function Dp(e,t,n,r,i){let a=r?64:16,o=e===`side`?`ArrowRight`:`ArrowLeft`,s=e===`side`?`ArrowLeft`:`ArrowRight`;if(n===o)return Cp(t+a,i);if(n===s)return Cp(t-a,i);if(n===`Home`)return i.min;if(n===`End`)return i.max}function Op(e,t,n,r){let i=e===`side`?t+n:t-n;return e===`side`&&i<r.min-48?{collapse:!0}:{width:Cp(Math.round(i),r)}}var kp=(e,t)=>{let{min:n,max:r,default:i}=xp[e];return typeof t==`number`&&Number.isFinite(t)?Cp(Math.round(t),{min:n,max:r}):i};function Ap(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:kp(`side`,n.side),rail:kp(`rail`,n.rail)}}function jp(e,t,n){try{e.setItem(Sp,JSON.stringify({...Ap(e),[t]:kp(t,n)}))}catch{}}var Mp=window.matchMedia(`(max-width: 760px)`),[Np,Pp]=u(Mp.matches);Mp.addEventListener(`change`,()=>{Pp(Mp.matches),Hp(!Mp.matches&&localStorage.getItem(Ip)!==`0`)});var Z=Np,Fp=`hub.sidebar.collapsed`,Ip=`hub.rail.open`,[Lp,Rp]=u(localStorage.getItem(Fp)===`1`),[zp,Bp]=u(!1),[Vp,Hp]=u(!Mp.matches&&localStorage.getItem(Ip)!==`0`);function Up(e){Rp(e),localStorage.setItem(Fp,e?`1`:`0`)}function Wp(e){Hp(e),Np()||localStorage.setItem(Ip,e?`1`:`0`)}function Gp(){Np()?Bp(!zp()):Up(!Lp())}var[Kp,qp]=u(window.innerWidth);window.addEventListener(`resize`,()=>qp(window.innerWidth));var[Jp,Yp]=u(Ap(localStorage)),[Xp,Zp]=u(!1),[Qp,$p]=u(),[em,tm]=u(!1),nm=()=>Ep(Jp(),Kp(),{side:!Lp()&&!Np(),rail:Xp(),concierge:em()&&!Np()});function rm(e){let t=nm(),n=e===`side`?Xp()?t.rail:0:!Lp()&&!Np()?t.side:0;return wp(e,Kp()-(t.concierge??0),n)}function im(e,t,n=!0){Yp(n=>({...n,[e]:t})),n&&jp(localStorage,e,t)}var am=`application/x-hub-pane`,[om,sm]=u(),cm=``,lm=0,um=om,dm=()=>typeof globalThis.crypto?.randomUUID==`function`?crypto.randomUUID():`${Date.now()}-${Math.random()}`;function fm(e,t){let n=e.dataTransfer;return Z()||!n?!1:(n.clearData(),cm=dm(),n.setData(am,cm),n.effectAllowed=t.move?`move`:`copyMove`,cancelAnimationFrame(lm),lm=requestAnimationFrame(()=>sm(t)),!0)}function pm(){cancelAnimationFrame(lm),lm=0,cm=``,sm(void 0)}function mm(e){return!!om()&&[...e.dataTransfer?.types??[]].includes(`application/x-hub-pane`)}function hm(e){let t=om();return t?bp(xn(),t.target,e).outcome:void 0}function gm(e,t){let{layout:n,outcome:r}=bp(xn(),e,t);if(r===`limit`&&q(vn,`warn`),r===`limit`||r===`invalid`)return r;En(()=>n);let i=n.panes[n.focused],a=i&&!i.sideChatID?i.sessionID:void 0,o=dt();return o.name!==`session`&&o.name!==`panes`?Vt(a?Ot(a):`/panes`):o.name===`session`&&!a&&!n.panes.some(e=>e.sessionID===o.id&&!e.sideChatID)&&Vt(`/panes`,{replace:!0}),r}function _m(e,t){let n=om(),r=n&&e.dataTransfer?.getData(`application/x-hub-pane`)===cm;return pm(),r?gm(n.target,t):`invalid`}function vm(e,t){let n=xn();return gm(e,n.panes.length?{index:n.focused,zone:t}:{empty:!0})}if(typeof document<`u`){let e=()=>om()&&pm();document.addEventListener(`dragend`,e,!0),document.addEventListener(`drop`,()=>queueMicrotask(e)),document.addEventListener(`mousemove`,t=>t.buttons===0&&e(),{passive:!0})}var ym=e=>!!e&&typeof e==`object`&&!Array.isArray(e),bm=e=>typeof e==`string`&&e.length>0,xm=e=>typeof e==`number`&&Number.isFinite(e),Sm=new Set([`online`,`offline`,`archived`,`deleted`,`unknown`]),Cm=new Set([`current`,`left`,`missing`]),wm=new Set([`open`,`in_progress`,`blocked`,`done`,`cancelled`]),Tm=new Set([`done`,`cancelled`]),Em=e=>xm(e)&&e>=0?e:0;function Dm(e){if(!ym(e)||!bm(e.memberID)||!bm(e.sessionID)||!bm(e.role))return;let t=ym(e.session)&&typeof e.session.state==`string`?e.session:void 0,n=ym(e.assignments)?e.assignments:{};return{memberID:e.memberID,sessionID:e.sessionID,role:e.role,master:e.master===!0,presence:Sm.has(e.presence)?e.presence:`unknown`,generation:xm(e.generation)?e.generation:1,...t?{session:{state:t.state,online:t.online===!0,...bm(t.machineID)?{machineID:t.machineID}:{},...bm(t.name)?{name:t.name}:{},...xm(t.lastSeen)?{lastSeen:t.lastSeen}:{}}}:{},workload:{open:Em(n.open),in_progress:Em(n.in_progress),blocked:Em(n.blocked)},...ym(e.blockers)&&e.blockers.reported===!0&&xm(e.blockers.count)?{blockers:e.blockers.count}:{}}}function Om(e){if(ym(e)&&bm(e.memberID)&&bm(e.supervisorMemberID)&&xm(e.order))return{memberID:e.memberID,supervisorMemberID:e.supervisorMemberID,order:e.order,member:Cm.has(e.member)?e.member:`missing`,supervisor:Cm.has(e.supervisor)?e.supervisor:`missing`}}function km(e){if(ym(e)&&bm(e.id)&&bm(e.memberID)&&bm(e.title)&&wm.has(e.status))return{id:e.id,memberID:e.memberID,title:e.title,status:e.status,...bm(e.ref)?{ref:e.ref}:{},assignee:Cm.has(e.assignee)?e.assignee:`missing`,...Array.isArray(e.stale)?{stale:e.stale.filter(bm)}:{}}}function Am(e){if(ym(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 jm=(e,t)=>Array.isArray(e)?e.map(t).filter(e=>e!==void 0):[];function Mm(e){if(!ym(e)||!ym(e.workspace)||!ym(e.members)||!ym(e.supervision))return;let t=e.workspace;if(!bm(t.id)||typeof t.title!=`string`||!bm(t.state)||!xm(t.revision)||!xm(e.supervision.revision))return;let n=ym(e.assignments)?e.assignments:{},r=Am(e.decisions),i=Am(e.artifacts);return{workspace:{id:t.id,title:t.title,state:t.state,revision:t.revision,...bm(t.masterMemberID)?{masterMemberID:t.masterMemberID}:{}},revision:e.supervision.revision,members:jm(e.members.items,Dm),membersTruncated:e.members.truncated===!0,links:jm(e.supervision.links,Om),linksTruncated:e.supervision.truncated===!0,assignments:jm(n.items,km),assignmentsTruncated:n.truncated===!0,sections:{...r?{decisions:r}:{},...i?{artifacts:i}:{}}}}function Nm(e){return ym(e)?{items:jm(e.items,e=>ym(e)&&bm(e.id)&&typeof e.title==`string`&&bm(e.state)&&xm(e.revision)?{id:e.id,title:e.title,...bm(e.description)?{goal:e.description}:{},state:e.state,revision:e.revision}:void 0),...bm(e.cursor)?{cursor:e.cursor}:{}}:{items:[]}}function Pm(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 Fm(e){let{links:t,stale:n}=Pm(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)Tm.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 Im(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}=Pm(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 sn(o,t.memberID,t.supervisorMemberID)}function Lm(e,t){return e===void 0&&t===void 0?0:e===void 0?t-1:t===void 0?e+1:(e+t)/2}var Rm=(e,t)=>e.flat.find(e=>e.member.memberID===t),zm=(e,t)=>t.supervisorMemberID===void 0?e.roots:Rm(e,t.supervisorMemberID).children,Bm=(e,t)=>{let n=e.children.filter(e=>e.member.memberID!==t);return n.length?n[n.length-1].order+1:0};function Vm(e,t,n){if(!Rm(e,t))return;if(`root`in n)return{memberID:t,supervisorMemberID:null};if(n.memberID===t)return;let r=Rm(e,n.memberID);if(!r)return;if(n.position===`inside`)return{memberID:t,supervisorMemberID:r.member.memberID,order:Bm(r,t)};if(r.supervisorMemberID===void 0)return{memberID:t,supervisorMemberID:null};let i=zm(e,r).filter(e=>e.member.memberID!==t),a=i.indexOf(r),o=n.position===`before`?Lm(i[a-1]?.order,r.order):Lm(r.order,i[a+1]?.order);return{memberID:t,supervisorMemberID:r.supervisorMemberID,order:o}}function Hm(e,t,n){let r=Rm(e,t);if(!r)return;let i=zm(e,r),a=i.indexOf(r),o=r.supervisorMemberID;switch(n){case`indent`:{let e=i[a-1];return e?{memberID:t,supervisorMemberID:e.member.memberID,order:Bm(e)}:void 0}case`outdent`:{if(o===void 0)return;let n=Rm(e,o);if(n.supervisorMemberID===void 0)return{memberID:t,supervisorMemberID:null};let r=zm(e,n);return{memberID:t,supervisorMemberID:n.supervisorMemberID,order:Lm(n.order,r[r.indexOf(n)+1]?.order)}}case`up`:return o===void 0||a===0?void 0:{memberID:t,supervisorMemberID:o,order:Lm(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:Lm(i[a+1].order,i[a+2]?.order)};case`detach`:return o===void 0?void 0:{memberID:t,supervisorMemberID:null}}}function Um(e,t){return{memberID:e.memberID,supervisorMemberID:e.supervisorMemberID,...e.order!==void 0&&e.supervisorMemberID!==null?{order:e.order}:{},expectedRevision:t}}var Wm={self:`A member cannot supervise itself.`,master:`The master is the root of the workspace and cannot be supervised.`,cycle:`That would make a supervision loop.`,depth:`Supervision is at most ${cn.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.`},Gm=e=>Wm[e];function Km(e,t){let n=Im(t,e);return n===`unchanged`?{kind:`done`}:n===`unknown`?{kind:`dropped`,reason:`Your change was not applied: a member it moves is no longer in the workspace.`}:n?{kind:`dropped`,reason:`Your change was not applied after the workspace changed elsewhere. ${Wm[n]}`}:{kind:`reapply`,body:Um(e,t.revision)}}function qm(e){let t=e.details?.violation;if(e.status===400&&(t===`cycle`||t===`depth`))return Wm[t];switch(e.code){case`conflict`:return`The workspace changed elsewhere. Reloaded it.`;case`forbidden`:return`Not allowed${e.message?`: ${e.message}`:`.`}`;case`not_found`:return`That workspace or member no longer exists.`;case`unsupported`:return`This hub does not support ${typeof e.details?.feature==`string`?e.details.feature:`this`} yet.`;case`offline`:return`The machine is offline. Try again when it is back.`;case`rate_limited`:return`A workspace limit was reached.`}return e.message||`HTTP ${e.status}`}function Jm(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 Ym(e,t){let n=Jm(e,t);if(!n)return{found:!1};let{machine:r,process:i,session:a}=n,o=a.parentID,s=o?Jm(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 Xm(e,t,n){let r=Ym(n,e.member.sessionID),i=e.supervisorMemberID?t.members.find(t=>t.memberID===e.supervisorMemberID):void 0,a=i?Ym(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 Zm={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 Qm(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:Zm[e.presence]}),n}var $m=e=>e.length>1?e.replace(/\/+$/,``):e,eh=(e,t)=>{let n=$m(e),r=$m(t);return n===r||n.startsWith(`${r}/`)};function th(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=>eh(n,e))}}))}var nh=e=>typeof e==`object`&&!!e&&!Array.isArray(e),rh=e=>typeof e==`string`&&e.length>0,ih=e=>typeof e==`number`&&Number.isFinite(e),ah=[`launching`,`ready`,`failed`,`unknown`];function oh(e){if(nh(e)&&rh(e.id)&&typeof e.text==`string`)return{id:e.id,role:rh(e.role)?e.role:`message`,text:e.text,...ih(e.at)?{at:e.at}:{},...e.clipped===!0?{clipped:!0}:{},...e.changed===!0?{changed:!0}:{},...e.stale?{stale:!0}:{}}}function sh(e){if(!nh(e)||!rh(e.id)||!rh(e.workspaceID)||!rh(e.sourceSessionID)||!ih(e.revision))return;let t=e.snapshot;if(!nh(t)||!ih(t.generation)||!ih(t.takenAt))return;let n=nh(e.launch)&&rh(e.launch.state)?e.launch:void 0;return{id:e.id,workspaceID:e.workspaceID,sourceSessionID:e.sourceSessionID,...rh(e.sessionID)?{sessionID:e.sessionID}:{},...rh(e.machineID)?{machineID:e.machineID}:{},revision:e.revision,status:ah.includes(e.status)?e.status:`unknown`,...n?{launch:{state:n.state,...rh(n.outcome)?{outcome:n.outcome}:{},...rh(n.reason)?{reason:n.reason}:{}}}:{},snapshot:{generation:t.generation,takenAt:t.takenAt,omitted:ih(t.omitted)?t.omitted:0,items:Array.isArray(t.items)?t.items.map(oh).filter(e=>e!==void 0):[]},...typeof e.stale==`boolean`?{stale:e.stale}:{}}}function ch(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 lh(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 uh(e,t){let n=e.snapshot,r=[`${_n(n.items.length,`message`)} from the main session`,`copied ${lh(n.takenAt,t)}`];return n.generation>1&&r.push(`refreshed ${_n(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 dh(e){let t=nh(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${rh(t.message)?`: ${t.message}`:`.`}`:`Context refreshed.`}var fh=9900;function ph(e){if(!e.trim())return`Write what to send to the main session.`;if(e.length>9900)return`At most ${fh} characters.`}var mh=encodeURIComponent,hh=e=>`/api/agent/workspaces/${mh(e.workspaceID)}/side-chats/${mh(e.id)}`,gh={one:e=>`/api/agent/side-chats/${mh(e)}`,create:e=>`/api/agent/workspaces/${mh(e)}/side-chats`,refresh:e=>`${hh(e)}/refresh`,send:e=>`${hh(e)}/send`},_h=e=>Math.min(3e4,2e3*2**Math.max(0,e)),vh=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function yh(e,t){return t?{sourceSessionID:e,bindingID:t}:{sourceSessionID:e}}function bh(e){return(vh(e)&&Array.isArray(e.bindings)?e.bindings:[]).flatMap(e=>vh(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 xh(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 Sh=`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 Ch(e){return e.status===0?`The hub can't be reached. Check your connection and try again.`:e.status===422&&e.details?.feature===`sideChatHost`?Sh: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 wh=I(`<label><span>Workspace</span><select aria-label=Workspace><option value>Choose a workspace…`),Th=I(`<p class=cmp-note role=status>`),Eh=I(`<label><span>Host repository</span><select aria-label="Host repository"><option value>Choose a repository…`),Dh=I(`<p class="cmp-note err"role=alert>`),Oh=I(`<form class=cmp-start aria-label="Start a side chat"><p class=muted>A new session that starts from a copy of <strong></strong>'s recent messages, on a workspace's host repository. The main session keeps working; you send things back to it explicitly.</p><div class=cmp-actions><button type=submit class="btn primary"></button><button type=button class=btn>Cancel`),kh=I(`<p class=muted role=status>Loading workspaces…`),Ah=I(`<p class=cmp-note role=status>You have no active workspaces. A side chat runs in a workspace: create one and bind a repository to it first.`),jh=I(`<option>`),[Mh,Nh]=u(),Ph=(e,t={})=>Nh({sessionID:e,...t});function Fh(){return n(l,{get when(){return Mh()},keyed:!0,children:e=>n(Rh,{request:e,onClose:()=>Nh(void 0)})})}var Ih=()=>`console-sidechat-${[...crypto.getRandomValues(new Uint8Array(12))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`,Lh=e=>e instanceof W?{status:e.status,...e.code?{code:e.code}:{},message:e.message,...e.details?{details:e.details}:{}}:{status:e instanceof tn?0:-1,message:e instanceof Error?e.message:String(e)};function Rh(e){let[t,i]=u(),[a,o]=u(),[c,d]=u(e.request.workspaceID??``),[f,p]=u(),[h,g]=u(``),[_,v]=u(!1),[x,S]=u(),w,T=()=>{let t=Fu(e.request.sessionID)?.session.title;return typeof t==`string`&&t?t:e.request.sessionID};async function E(e){if(p(void 0),g(``),e)try{p(bh(await G(`/api/agent/workspaces/${K(e)}/bindings`)))}catch(e){p([]),S(Ch(Lh(e)))}}fe(async()=>{try{i(Nm(await G(`/api/agent/workspaces?state=active&limit=50`)).items)}catch(e){i([]),o(Ch(Lh(e)))}c()&&E(c())});let D=C(()=>f()?xh(f(),h()||void 0):void 0);async function O(t){t.preventDefault();let n=c(),r=D();if(!n||!r||r.kind===`pick`||_())return;let i=yh(e.request.sessionID,r.kind===`ready`?r.bindingID:void 0),a=JSON.stringify([n,i]);w?.body!==a&&(w={body:a,value:Ih()}),v(!0),S(void 0);try{let t=sh((await(await V(`/api/agent/workspaces/${K(n)}/side-chats`,{method:`POST`,json:i,headers:{"idempotency-key":w.value}})).json()).sideChat);if(!t)throw new W(502,`The hub answered a side chat this console can't read.`);e.onClose(),yn(e.request.sessionID,t.id)&&q(`Side chat started beside the main session.`)}catch(e){e instanceof tn||(w=void 0),S(Ch(Lh(e)))}finally{v(!1)}}return n(de,{open:!0,title:`Start a side chat`,get onClose(){return e.onClose},get children(){var i=Oh(),o=i.firstChild,u=o.firstChild.nextSibling,p=o.nextSibling,v=p.firstChild,C=v.nextSibling;return i.addEventListener(`submit`,O),y(u,T),y(i,n(l,{get when(){return t()},get fallback(){return kh()},get children(){return n(l,{get when(){return!a()},get fallback(){return(()=>{var e=Dh();return y(e,a),e})()},get children(){return n(l,{get when(){return t().length},get fallback(){return Ah()},get children(){var e=wh(),r=e.firstChild.nextSibling;return r.firstChild,r.addEventListener(`change`,e=>{d(e.currentTarget.value),S(void 0),E(e.currentTarget.value)}),y(r,n(m,{get each(){return t()},children:e=>(()=>{var t=jh();return y(t,()=>e.title||e.id),s(()=>t.value=e.id),t})()}),null),s(()=>r.value=c()),e}})}})}}),p),y(i,n(l,{get when(){return D()?.kind===`none`},get children(){var e=Th();return y(e,Sh),e}}),p),y(i,n(l,{get when(){return r(()=>!!f())()&&f().length>1},get children(){var e=Eh(),t=e.firstChild.nextSibling;return t.firstChild,t.addEventListener(`change`,e=>g(e.currentTarget.value)),y(t,n(m,{get each(){return f()},children:e=>(()=>{var t=jh();return y(t,(()=>{var t=r(()=>!!e.label);return()=>t()?`${e.label} (${e.repo})`:e.repo})()),s(()=>t.value=e.id),t})()}),null),s(()=>t.value=h()),e}}),p),y(i,n(l,{get when(){return x()},get children(){var e=Dh();return y(e,x),e}}),p),y(v,()=>_()?`Starting…`:`Start side chat`),B(C,`click`,e.onClose,!0),s(e=>{var t=!c()||!D()||D().kind===`pick`||_(),n=_();return t!==e.e&&(v.disabled=e.e=t),n!==e.t&&b(v,`aria-busy`,e.t=n),e},{e:void 0,t:void 0}),i}})}z([`click`]);var[zh,Bh]=u(),Vh=(e,t)=>zh()?.id===e&&zh()?.place===t;function Hh(e,t){if(!e.length)return;let n=t?`Archived`:`Unarchived`,r=e.length===1?`${n} “${e[0].title}”`:`${n} ${e.length} sessions`;Bd(`hiddenSessions`,e.map(e=>e.id),t,{message:r,undo:!0})}function Uh(e,{open:t=!0,place:n}={}){return[...t?[{label:`Open`,run:()=>Vt(Ot(e.id))}]:[],...n===`topbar`?[]:[{label:`Open beside`,run:()=>wn(e.id)}],{label:`Start side chat…`,run:()=>Ph(e.id)},...n?[{label:`Rename…`,run:()=>Bh({id:e.id,place:n})}]:[],{label:Gd(e.id)?`Naming…`:`Auto-name`,run:()=>void Jd(e.id),disabled:Gd(e.id)},{label:e.pinned?`Unpin`:`Pin`,run:()=>zd(`pinnedSessions`,e.id,!e.pinned)},{label:e.archived?`Unarchive`:`Archive`,run:()=>Hh([e],!e.archived)},...e.running?[{label:`Stop`,run:()=>void Xd(e.id),danger:!0}]:[],...e.state===`error`?[{label:`Dismiss error`,run:()=>void Yd(e.id)}]:[],`sep`,{label:e.exposed?`Disallow Voice`:`Allow Voice`,run:()=>void Vd(e.id,!e.exposed)},Qf().has(e.id)?{label:`Unmute notifications`,run:()=>void lp(e.id,!1)}:{label:`Mute notifications`,run:()=>void lp(e.id,!0)},...n!==`topbar`&&!Z()?[`sep`,...[`left`,`right`,`top`,`bottom`].map(t=>({label:`Open in pane → ${t}`,run:()=>void vm({sessionID:e.id},t)}))]:[]]}var Wh=I(`<button type=button class="link-btn small clamp-toggle">`),Gh=I(`<span>`),Kh=I(`<p>`),qh=I(`<span class="muted small cut-note"data-cut>… cut at <!> characters (of <!>)`),Jh=I(`<span class="muted small cut-note"data-more>+<!> more <!> not stored`),Yh=I(`<dt>Requested by`),Xh=I(`<dd>`),Zh=I(`<dt>Proposes`),Qh=I(`<dt>Action`),$h=I(`<dd class=mono data-action>`),eg=I(`<dt>`),tg=I(`<span class="muted small cut-note"data-incomplete>The hub received this request already shortened`),ng=I(`<dd data-resources>`),rg=I(`<dt>Always saves`),ig=I(`<dd data-saves>`),ag=I(`<dt>Shown from`),og=I(`<dd class=muted>`),sg=I(`<dt>Prompt`),cg=I(`<dt>Form`),lg=I(`<dt>Answer`),ug=I(`<dd data-answer>`),dg=I(`<dt>Outside its grant`),fg=I(`<dl class="escalation-details decision-details small">`),pg=I(`<dt>Session`),mg=I(`<dd><a>`),hg=I(`<span class=decision-answer-field><span class=muted>:</span> `),gg=I(`<dt>Purpose`),_g=I(`<dd data-purpose> <span class=muted>(<!>)`),vg={label:Bu,blockers:e=>Br(Fu(e)?.session)};function yg(e){let[t,i]=u(!1),a=T(),o=C(()=>e.reveal?Ie(e.text):e.text),c=C(()=>De(o(),{chars:e.chars,lines:e.lines})),d=()=>t()||!c().cut?o():c().text,f=()=>n(l,{get when(){return c().cut},get children(){var n=Wh();return n.$$click=()=>i(!t()),b(n,`aria-controls`,`clamp-${a}`),y(n,()=>t()?`Show less`:`Show all`),s(r=>{var i=t(),a=`${t()?`Show less`:`Show all`} of ${e.what??`the text`}`;return i!==r.e&&b(n,`aria-expanded`,r.e=i),a!==r.t&&b(n,`aria-label`,r.t=a),r},{e:void 0,t:void 0}),n}});return n(l,{get when(){return e.tag===`span`},get fallback(){return[(()=>{var n=Kh();return b(n,`id`,`clamp-${a}`),y(n,d),s(r=>{var i=e.class,a=c().cut&&!t()?``:void 0;return i!==r.e&&k(n,r.e=i),a!==r.t&&b(n,`data-clamped`,r.t=a),r},{e:void 0,t:void 0}),n})(),r(f)]},get children(){return[(()=>{var n=Gh();return b(n,`id`,`clamp-${a}`),y(n,d),s(r=>{var i=e.class,a=c().cut&&!t()?``:void 0;return i!==r.e&&k(n,r.e=i),a!==r.t&&b(n,`data-clamped`,r.t=a),r},{e:void 0,t:void 0}),n})(),r(()=>f())]}})}var bg={live:`Live request`,request:`The hub's record of the request`,text:`From the request text`},xg=new Set([`bash`,`shell`]),Sg=e=>e&&xg.has(e)?`the command`:`the request`,Cg=e=>e.toLocaleString(`en-US`);function wg(e){let t=()=>e.detail.cut?.find(t=>t.field===e.field&&t.index===e.index);return n(l,{get when(){return t()},children:e=>(()=>{var t=qh(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(t,()=>Cg(Eg),n),y(t,()=>Cg(e().length),r),t})()})}function Tg(e){return n(l,{get when(){return e.count},get children(){var t=Jh(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(t,()=>Cg(e.count),n),y(t,()=>e.count===1?`item`:`items`,r),t}})}var Eg=2e3,Dg={stop:`Stop the session`,deny:`Deny its permission request`,prompt:`Send a prompt as you`,answer:`Answer its form as you`},Og=e=>e.verb===`answer`&&e.cancel?`Dismiss its form`:Dg[e.verb??``]??e.verb;function kg(e){let t=C(()=>Ae(e.decision,e.context??vg));return n(l,{get when(){return t()},children:t=>(()=>{var i=fg();return y(i,n(l,{get when(){return t().requester},get children(){return[Yh(),(()=>{var n=Xh();return y(n,()=>t().requester),s(()=>b(n,`title`,Tt(e.decision))),n})()]}}),null),y(i,n(l,{get when(){return t().verb},get children(){return[Zh(),(()=>{var e=Xh();return y(e,()=>Og(t())),s(()=>b(e,`data-verb`,t().verb)),e})()]}}),null),y(i,n(l,{get when(){return t().target},children:e=>[pg(),(()=>{var t=mg(),n=t.firstChild;return y(n,()=>e().label),s(t=>{var r=Ot(e().id),i=e().id;return r!==t.e&&b(n,`href`,t.e=r),i!==t.t&&b(n,`title`,t.t=i),t},{e:void 0,t:void 0}),t})()]}),null),y(i,n(l,{get when(){return t().action},get children(){return[Qh(),(()=>{var e=$h();return y(e,()=>t().action,null),y(e,()=>t().always?` (always)`:``,null),e})()]}}),null),y(i,n(l,{get when(){return t().resources.length},get children(){return[(()=>{var e=eg();return y(e,()=>t().resources.length===1?`Resource`:`Resources`),e})(),(()=>{var e=ng();return y(e,n(m,{get each(){return t().resources},children:(e,r)=>[n(yg,{tag:`span`,class:`escalation-resource mono`,text:e,chars:240,lines:4,get what(){return Sg(t().action)},reveal:!0}),n(wg,{get detail(){return t()},field:`resources`,get index(){return r()}})]}),null),y(e,n(Tg,{get count(){return t().resourcesMore}}),null),y(e,n(l,{get when(){return t().incomplete},get children(){return tg()}}),null),e})()]}}),null),y(i,n(l,{get when(){return t().saves?.length},get children(){return[rg(),(()=>{var e=ig();return y(e,n(m,{get each(){return t().saves},children:(e,r)=>[n(yg,{tag:`span`,class:`escalation-resource mono`,text:e,chars:240,lines:4,what:`the saved pattern`,reveal:!0}),n(wg,{get detail(){return t()},field:`save`,get index(){return r()}})]}),null),y(e,n(Tg,{get count(){return t().savesMore}}),null),e})()]}}),null),y(i,n(l,{get when(){return r(()=>!!t().source)()&&(t().action||t().resources.length||t().form)},get children(){return[ag(),(()=>{var e=og();return y(e,()=>bg[t().source]),s(()=>b(e,`data-source`,t().source)),e})()]}}),null),y(i,n(l,{get when(){return t().text},get children(){return[sg(),(()=>{var e=Xh();return y(e,n(yg,{class:`decision-prompt mono`,get text(){return t().text},chars:400,lines:6,what:`the prompt`,reveal:!0})),e})()]}}),null),y(i,n(l,{get when(){return t().formID},get children(){return[cg(),(()=>{var e=Xh();return y(e,()=>t().form??t().formID),e})()]}}),null),y(i,n(l,{get when(){return t().answer?.length},get children(){return[lg(),(()=>{var e=ug();return y(e,n(m,{get each(){return t().answer},children:e=>(()=>{var t=hg(),r=t.firstChild,i=r.firstChild;return r.nextSibling,y(r,()=>e.key,i),y(t,n(yg,{tag:`span`,class:`decision-answer-value mono`,get text(){return e.value},chars:240,lines:4,get what(){return`the answer to ${e.key}`},reveal:!0}),null),t})()})),e})()]}}),null),y(i,n(l,{get when(){return t().outsideGrant},get children(){return[dg(),(()=>{var e=Xh();return y(e,()=>t().outsideGrant),e})()]}}),null),y(i,n(l,{get when(){return t().purpose},children:e=>[gg(),(()=>{var t=_g(),n=t.firstChild,r=n.nextSibling,i=r.firstChild.nextSibling;return i.nextSibling,y(t,()=>e().text,n),y(r,()=>e().by,i),t})()]}),null),s(e=>{var n=t().kind,r=t().kind===`permission`?``:void 0,a=t().source===`live`?``:void 0;return n!==e.e&&b(i,`data-decision-detail`,e.e=n),r!==e.t&&b(i,`data-escalation`,e.t=r),a!==e.a&&b(i,`data-live`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),i})()})}var Ag=(e,t=vg)=>Ae(e,t)?.purpose?.text;z([`click`]);var jg=I(`<span class="badge-pill agent-request"title="An agent asked to act outside its grant">Agent request`),Mg=I(`<span>`),Ng=I(`<p role=timer>`),Pg=I(`<div role=radiogroup aria-label=Options class=choice-group>`),Fg=I(`<p class="muted small decision-why">Why: `),Ig=I(`<input type=text class=decision-note aria-label="Note (optional)"placeholder="Note (optional)">`),Lg=I(`<p class="muted small decision-tier">`),Rg=I(`<div role=group><p class="blocker-head decision-head"><strong>Decision</strong> <span class=muted>from </span></p><p class="blocker-text decision-question"></p><form class=form-card novalidate><fieldset><div class=row><button type=submit class="btn small primary">Answer`),zg=I(`<a>`),Bg=I(`<label class=text-field><span class=field-title>Your answer</span><textarea rows=2 aria-label="Your answer">`),Vg=I(`<span class="badge-pill safe"title="A timeout may pick this option">safe`),Hg=I(`<span class="badge-pill recommended">Recommended`),Ug=I(`<label><input type=radio><span>`),Wg={low:`Low urgency`,normal:``,high:`Urgent`};function Gg(e){let i=()=>e.decision,[a,o]=u(),[c,d]=u(``),[f,p]=u(!1),[h,g]=u(Date.now()),_=setInterval(()=>i().deadline!==void 0&&g(Date.now()),1e3);M(()=>clearInterval(_));let v=()=>Pt().searchParams.get(`decision`)===i().id,x;fe(()=>{v()&&x?.scrollIntoView({block:`center`})});let S=()=>i().sessionID?Fu(i().sessionID):void 0,C=async e=>{e.preventDefault();let t=nn(i(),a(),c());if(!t.ok)q(t.problem,`err`);else{p(!0);try{let{decision:e}=await(await V(`/api/decisions/${K(i().id)}/answer`,{method:`POST`,json:t.body})).json();q(`Answer sent`),e?Od(e):kd(i().id)}catch(e){if(e instanceof W&&e.status===409&&e.code===`gone`){q(`Already answered or expired`),kd(i().id);return}q(U(e),`err`),p(!1)}}},w=e=>i().recommendation?.option===e;return(()=>{var u=Rg(),p=u.firstChild,g=p.firstChild.nextSibling.nextSibling;g.firstChild;var _=p.nextSibling,T=_.nextSibling,E=T.firstChild,D=E.firstChild,O=x;return typeof O==`function`?t(O,u):x=u,y(g,()=>ve(i(),Bu,wu()),null),y(p,n(l,{get when(){return jt(i())},get children(){return jg()}}),null),y(p,n(l,{get when(){return Wg[i().urgency]},get children(){var e=Mg();return y(e,()=>Wg[i().urgency]),s(()=>k(e,`badge-pill urgency ${i().urgency}`)),e}}),null),y(p,n(l,{get when(){return r(()=>!!e.showSession)()&&S()},children:e=>[` · `,(()=>{var t=zg();return y(t,()=>e().session.title||e().session.id),s(()=>b(t,`href`,Ot(e().session.id))),t})()]}),null),y(_,()=>Re(i(),Bu,wu())),y(u,n(kg,{get decision(){return i()}}),T),y(u,n(l,{get when(){return et(i(),h())},get children(){var e=Ng();return y(e,()=>et(i(),h())),s(()=>k(e,`decision-deadline small${i().escalatedAt!==void 0||i().deadline<=h()?` overdue`:``}`)),e}}),T),T.addEventListener(`submit`,e=>void C(e)),y(E,n(l,{get when(){return i().options.length},get fallback(){return(()=>{var e=Bg(),t=e.firstChild.nextSibling;return t.$$input=e=>d(e.currentTarget.value),s(()=>t.value=c()),e})()},get children(){return[(()=>{var e=Pg();return y(e,n(m,{get each(){return i().options},children:e=>(()=>{var t=Ug(),r=t.firstChild,c=r.nextSibling;return r.addEventListener(`change`,()=>o(e.id)),y(c,()=>e.label),y(t,n(l,{get when(){return e.safe},get children(){return Vg()}}),null),y(t,n(l,{get when(){return w(e.id)},get children(){return Hg()}}),null),s(n=>{var a=`choice${w(e.id)?` recommended`:``}`,o=`d-${i().id}`;return a!==n.e&&k(t,n.e=a),o!==n.t&&b(r,`name`,n.t=o),n},{e:void 0,t:void 0}),s(()=>r.value=e.id),s(()=>r.checked=a()===e.id),t})()})),e})(),n(l,{get when(){return r(()=>!!i().recommendation?.why)()&&i().recommendation.why!==Ag(i())},get children(){var e=Fg();return e.firstChild,y(e,()=>i().recommendation.why,null),e}}),(()=>{var e=Ig();return e.$$input=e=>d(e.currentTarget.value),s(()=>e.value=c()),e})()]}}),D),y(E,n(l,{get when(){return zt(i())},get children(){var e=Lg();return y(e,()=>zt(i())),e}}),D),s(e=>{var t=`card decision urgency-${i().urgency}${v()?` targeted`:``}`,n=`Decision: ${i().question}`,r=i().id,a=Tt(i()),o=i().question,s=f();return t!==e.e&&k(u,e.e=t),n!==e.t&&b(u,`aria-label`,e.t=n),r!==e.a&&b(u,`data-decision`,e.a=r),a!==e.o&&b(g,`title`,e.o=a),o!==e.i&&b(_,`title`,e.i=o),s!==e.n&&(E.disabled=e.n=s),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),u})()}function Kg(e){let t=C(()=>new Map(e.decisions.map(e=>[e.id,e]))),r=C((e=[])=>{let n=[...t().keys()];return n.length===e.length&&n.every((t,n)=>t===e[n])?e:n});return n(m,{get each(){return r()},children:r=>n(l,{get when(){return t().get(r)},children:t=>n(Gg,{get decision(){return t()},get showSession(){return e.showSession}})})})}z([`input`]);var qg=I(`<span class="naming muted small"role=status><span class="spinner small"aria-hidden=true></span>Naming…`),Jg=I(`<span class=rename-wrap><input type=text aria-label="Session title"><button type=button class="icon-btn small auto-name-btn"aria-label=Auto-name title="Let OpenCode name this session">✨`),Yg,Xg=0;function Zg(e){return n(l,{get when(){return Vh(e.id,e.place)},get fallback(){return e.children},get children(){return n($g,{get id(){return e.id},get title(){return e.title},get place(){return e.place},get class(){return e.class}})}})}function Qg(e){return n(l,{get when(){return Gd(e.id)},get children(){return qg()}})}function $g(e){let n,r=!1,i=Yg&&Yg.id===e.id&&Yg.place===e.place?Yg.value:void 0,a=()=>{r||(r=!0,Yg=void 0,Bh(void 0),Jd(e.id))},o=t=>{if(r)return;r=!0;let i=n.value;Yg=void 0,Bh(void 0),t&&i.trim()&&i.trim()!==e.title&&Hd(e.id,i)};return fe(()=>{Xg++,n.focus(),i===void 0&&n.select()}),M(()=>{if(Xg--,setTimeout(()=>{Xg>0||(Yg=void 0,zh()?.id===e.id&&zh()?.place===e.place&&Bh(void 0))},0),r)return;r=!0;let t=zh();t?.id===e.id&&t.place===e.place&&(Yg={id:e.id,place:e.place,value:n.value})}),(()=>{var r=Jg(),c=r.firstChild,l=c.nextSibling;c.addEventListener(`blur`,()=>o(!0)),c.$$keydown=e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),o(!0)):e.key===`Escape`&&(e.preventDefault(),o(!1))},c.$$mousedown=e=>e.stopPropagation(),c.$$click=e=>e.stopPropagation();var u=n;return typeof u==`function`?t(u,c):n=c,b(c,`maxlength`,200),l.$$click=e=>{e.preventDefault(),e.stopPropagation(),a()},l.$$mousedown=e=>{e.preventDefault(),e.stopPropagation()},s(()=>k(c,`rename-field${e.class?` ${e.class}`:``}`)),s(()=>c.value=i??e.title),r})()}z([`click`,`mousedown`,`keydown`]);var e_=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()}},t_={phase:`off`,voice:`off`,level:0,held:``,paused:!1},n_=class{deps;state=t_;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({...t_,phase:`starting`,sessionID:e,voice:`starting`});let i=await this.deps.expose(e);if(t!==this.run)return;if(!i)return this.set({...t_,error:{sessionID:e,message:`Could not turn Voice on for this session.`}});let a=this.deps.create(e,{state:e=>t===this.run&&this.set({...this.state,voice:e,paused:e===`paused`}),level:e=>t===this.run&&this.set({...this.state,level:e}),held:e=>t===this.run&&this.set({...this.state,held:e}),ignored:e=>t===this.run&&this.set({...this.state,ignored:e}),timing:e=>t===this.run&&this.set({...this.state,timing:e}),detector:e=>t===this.run&&this.set({...this.state,detector:e}),turn:e=>t===this.run&&this.set({...this.state,turn:e}),front:e=>t===this.run&&this.set({...this.state,front:e}),user:t=>this.sinks.get(e)?.user(t)??`voice:${++this.bubbles}`,tick:(t,n)=>this.sinks.get(e)?.tick(t,n),agent:t=>this.sinks.get(e)?.agent(t),note:(i,a)=>{if((a===`err`||a===`gesture`)&&t===this.run&&this.state.phase===`starting`){n=i,r=a===`gesture`;return}if(a===`gesture`&&t===this.run&&this.state.phase===`on`){let t=this.stop(),n=this.run;t.then(()=>n===this.run&&this.set({...t_,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(t_))}});this.conversation=a;let o=await a.start();if(t===this.run){if(!o)return this.run++,this.conversation=void 0,this.set({...t_,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(t_),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()}},r_=3e3,i_=`Voice mode on`,a_=`Voice mode paused · unlock to talk`,o_={starting:`starting`,listening:`listening`,hearing:`listening`,transcribing:`thinking`,sent:`thinking`,speaking:`speaking`,paused:`muted`,suspended:`paused`,off:`off`},s_=(e,t,n,r=``)=>({sessionID:e,title:n===`suspended`?a_:i_,body:`${t} · ${o_[n]??n}${r}`}),c_=class{controller;surface;options;shown;shownAt=0;timer;mediaFor;now;setTimer;clearTimer;unsubscribe;constructor(e,t,n){this.controller=e,this.surface=t,this.options=n,this.now=n.now??Date.now,this.setTimer=n.setTimer??((e,t)=>setTimeout(e,t)),this.clearTimer=n.clearTimer??(e=>clearTimeout(e)),this.unsubscribe=e.subscribe(()=>this.refresh())}needsPermission(){return this.controller.state.phase===`on`&&!this.surface.allowed()}async endFromNotification(e){this.controller.state.phase!==`off`&&this.controller.state.sessionID===e&&await this.controller.end()}refresh(){let e=this.controller.state;if(e.phase!==`on`||!e.sessionID)return this.clear();let t=e.sessionID,n=this.options.title(t),r=this.options.suffix?.()??``,i=`${t}\n${r}`;if(this.mediaFor!==i&&(this.mediaFor=i,this.surface.media({title:i_,artist:`${n}${r}`},()=>void this.controller.end())),!this.surface.allowed())return;let a=s_(t,n,e.voice,r);if(this.shown&&this.shown.sessionID===a.sessionID&&this.shown.body===a.body)return this.cancel();let o=a.title!==this.shown?.title,s=this.shown?.sessionID===t&&!o?this.shownAt+r_-this.now():0;if(s<=0)return this.show(a);this.timer===void 0&&(this.timer=this.setTimer(()=>{this.timer=void 0,this.refresh()},s))}dispose(){this.unsubscribe(),this.cancel(),this.surface.close(),this.mediaFor&&this.surface.media(null),this.shown=this.mediaFor=void 0}show(e){this.cancel(),this.surface.show(e),this.shown=e,this.shownAt=this.now()}clear(){this.cancel(),this.shown&&this.surface.close(),this.mediaFor&&this.surface.media(null),this.shown=this.mediaFor=void 0}cancel(){this.timer!==void 0&&(this.clearTimer(this.timer),this.timer=void 0)}},l_=3e4,u_=1e4;function d_(e,{setTimer:t=(e,t)=>setTimeout(e,t),clearTimer:n=e=>clearTimeout(e)}={}){let r=new Map,i=1,a=e=>{let t=r.get(e);if(t)return r.delete(e),n(t.timer),t};return e.onmessage=e=>{let t=e.data;if(t.type!==`result`&&t.type!==`fail`)return;let n=a(t.id);t.type===`result`?n?.resolve({p:t.p,ms:t.ms}):n?.reject(Error(t.message||`turn detection failed`))},{get pending(){return r.size},predict(n){return new Promise((o,s)=>{let c=i++,l=t(()=>a(c)?.reject(Error(`the turn model did not answer`)),u_);r.set(c,{resolve:o,reject:s,timer:l}),e.postMessage({type:`predict`,id:c,samples:n},[n.buffer])})},fail(e){for(let t of[...r.keys()])a(t)?.reject(e)}}}var f_;function p_(){return f_??=m_().catch(e=>{throw f_=void 0,e}),f_}function m_(){return new Promise((e,t)=>{let n;try{n=new Worker(new URL(`/assets/smart-turn-worker-DaVJPdvJ.js`,``+import.meta.url),{type:`module`,name:`smart-turn`})}catch(e){return t(e)}let r,i=!1,a=e=>{r?.fail(e),n.terminate(),f_=void 0,i||t(e)},o=setTimeout(()=>a(Error(`the turn model took too long to load`)),l_);n.onerror=e=>{e.preventDefault(),clearTimeout(o),a(Error(e.message||`the turn detection worker failed`))},n.onmessage=t=>{let s=t.data;s.type===`ready`?(clearTimeout(o),i=!0,r=d_(n),e(r)):s.type===`error`&&(clearTimeout(o),a(Error(s.message||`the turn model could not load`)))}})}var h_=16e3,g_=8*h_,__=400;1+Math.floor(g_/160),27/Math.log(6.4);var v_=new Float64Array(__),y_=new Float64Array(__);for(let e=0;e<__;e++)v_[e]=Math.cos(2*Math.PI*e/__),y_[e]=-Math.sin(2*Math.PI*e/__);var b_=Object.freeze([`timers`,`smart`]);function x_(e){return e===`smart`?`smart`:`timers`}var S_=Object.freeze({threshold:.5,graceMs:150,recheckMs:400,fallbackMs:3e3,slowMs:1500}),C_=5e3;function w_(e,t){if(!t.length)return Math.min(C_,e);let n=[...t].sort((e,t)=>e-t),r=n.length>>1,i=n.length%2?n[r]:(n[r-1]+n[r])/2;return Math.min(C_,Math.max(e,2*i))}var T_=Object.freeze([{key:`voiceTurn.threshold`,field:`threshold`,min:.01,max:.99},{key:`voiceTurn.grace`,field:`graceMs`,min:0,max:2e3},{key:`voiceTurn.recheck`,field:`recheckMs`,min:100,max:5e3},{key:`voiceTurn.fallback`,field:`fallbackMs`,min:500,max:1e4},{key:`voiceTurn.slow`,field:`slowMs`,min:500,max:C_}]);function E_(e,t){let n=T_.find(t=>t.key===e);if(!n||t==null||t.trim()===``)return;let r=Number(t);if(Number.isFinite(r))return Math.min(n.max,Math.max(n.min,r))}function D_(...e){let t={...S_};for(let n of T_)for(let r of e){let e=E_(n.key,r(n.key));if(e!==void 0){t[n.field]=e;break}}return t}var O_=class{ring=new Float32Array(g_);write=0;filled=0;get durationMs(){return this.filled/h_*1e3}push(e){let t=e.length>128e3?e.subarray(e.length-g_):e,n=Math.min(t.length,g_-this.write);this.ring.set(t.subarray(0,n),this.write),n<t.length&&this.ring.set(t.subarray(n),0),this.write=(this.write+t.length)%g_,this.filled=Math.min(g_,this.filled+t.length)}snapshot(){let e=new Float32Array(this.filled),t=(this.write-this.filled+g_)%g_,n=Math.min(this.filled,g_-t);return e.set(this.ring.subarray(t,t+n)),n<this.filled&&e.set(this.ring.subarray(0,this.filled-n),n),e}keepLast(e){this.filled=Math.min(this.filled,Math.max(0,Math.round(e/1e3*h_)))}reset(){this.write=0,this.filled=0}};function k_(e){if(!e)return``;if(e.decision===`timer-fallback`||e.p===void 0)return e.error===`loading`?`turn: model loading`:e.error===`slow`?`turn: timers (slow)`:`turn: timers`;let t=`turn ${Math.round(e.p*100)}%`;return e.decision===`send`?`${t} → sending`:e.decision===`fallback`?`${t} → sending (quiet too long)`:t}var A_=1500;function j_({mode:e,load:t,env:n=globalThis}){if(e!==`smart`)return!1;let r=()=>void t().catch(()=>{});if(n.requestIdleCallback)n.requestIdleCallback(r,{timeout:5e3});else if(n.setTimeout)n.setTimeout(r,A_);else return!1;return!0}var M_=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(e){for(let t of[...this.listeners])t(e)}get size(){return this.listeners.size}};async function N_(e){return new Blob([await new Response(e??null).arrayBuffer()],{type:`audio/mpeg`})}var P_=[`image/png`,`image/jpeg`,`image/webp`,`image/gif`],F_={maxImages:4,maxSide:1600,perImageBase64:18e4,totalBase64:7e5},I_=[.85,.72,.6,.48,.36],L_=[1,.75,.55,.4,.28,.2],R_=class extends Error{constructor(e=`This image is too large to attach, even after shrinking it`){super(e),this.name=`ImageTooLargeError`}},z_=e=>4*Math.ceil(e/3),B_=e=>P_.includes(e);function V_(e,t,n=F_){if(e>=n.maxImages)return`Attach at most ${n.maxImages} images to a message`;if(!B_(t))return`Only PNG, JPEG, WebP or GIF images can be attached`}function H_(e,t=F_){return Math.max(0,Math.min(t.perImageBase64,t.totalBase64-e))}function U_(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 W_(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 G_(e,t,n,r=F_){if(t<=0)throw new R_(`No room for another image in this message`);let i=U_(e.width,e.height,r.maxSide);for(let r of L_){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}]:[],...I_.map(e=>({type:`image/jpeg`,quality:e,width:a,height:o}))];for(let e of s){let r=await n(e);if(z_(r.size)<=t)return{blob:r,request:e}}}throw new R_}var K_=()=>({draft:``,images:[],pending:[],stopping:!1});function q_(e,t){switch(t.type){case`input`:return{...e,draft:t.text,error:void 0};case`attach`:return e.images.length>=F_.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,F_.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 J_(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 Y_(e,t){return e===202?t.mode===`turn`?`accepted`:`steered`:`result`}function X_(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 Z_(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 Q_=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)}},$_=-19.5,ev=-50,tv=20,nv=9,rv=2,iv=60,av=.4,ov=.1,sv=-70,cv=-10,lv=e=>e>0?20*Math.log10(e):-1/0,uv=e=>e>0?-.691+10*Math.log10(e):-1/0;function dv(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 fv(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 pv(e,t){if(!e.length)return-1/0;let[n,r]=dv(t),i=fv(fv(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(av*t),s=Math.round(ov*t);if(i.length<o){let e=uv(a[i.length]/i.length);return e>sv?e:-1/0}let c=[];for(let e=0;e+o<=i.length;e+=s){let t=(a[e+o]-a[e])/o;uv(t)>sv&&c.push(t)}if(!c.length)return-1/0;let l=e=>e.reduce((e,t)=>e+t,0)/e.length,u=uv(l(c))+cv,d=c.filter(e=>uv(e)>u);return uv(l(d.length?d:c))}function mv(e){let t=0;for(let n=0;n<e.length;n++)t=Math.max(t,Math.abs(e[n]));return lv(t)}function hv(e,t){let n=10**(ev/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 gv(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,rv/1e3*t)),n=Math.exp(-1/Math.max(1,iv/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 _v(e,t,n){let r=hv(e,t),i=pv(r,t);if(!Number.isFinite(i))return{samples:r,gainDb:0,loudness:i};let a=10**(-1/20),o=Math.min(tv,-1-mv(r)+nv),s=Math.min(n-i,o),c=gv(r,t,10**(s/20),a);for(let e=0;e<3;e++){let e=n-pv(c,t);if(e<.1||s>=o)break;s=Math.min(s+e,o),c=gv(r,t,10**(s/20),a)}return{samples:c,gainDb:s,loudness:i}}function vv(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 yv=`voice.replyLoudness`,bv=8;function xv(e){try{let t=JSON.parse(e.getItem(yv)??`{}`);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}function Sv(e,t){let n=xv(e)[t];return Array.isArray(n)?n.filter(e=>typeof e==`number`&&Number.isFinite(e)):[]}function Cv(e,t,n){if(!(!Number.isFinite(n)||n<-50||n>0))try{let r=xv(e),i=[...Sv(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-bv)))delete r[e];e.setItem(yv,JSON.stringify(r))}catch{}}var wv=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 Tv(e,t){let n=[];try{t!==void 0&&(n=Sv(e,t))}catch{n=[]}return n.length?Math.min(-14,Math.max(-26,wv(n))):$_}var Ev={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}]},Dv=`hub-cues-v2`,Ov=[`hub-cues-v1`],kv=`x-hub-cue-target`,Av=1,jv=`https://hub-cues.invalid`,Mv=e=>`${jv}/${encodeURIComponent(e)}/`,Nv=(e,t)=>`${Mv(e)}${encodeURIComponent(t)}`;async function Pv(){try{let e=globalThis.caches;return e?await e.open(Dv):void 0}catch{return}}function Fv(e,t){e.defaultPlaybackRate=t,e.playbackRate=t,e.preservesPitch=!0,e.webkitPreservesPitch=!0}var Iv=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))}},Lv=class{synthesize;speed;onSpeaking;onPlayed;normalize;target;phrases=new Map;urls=new Map;key=Promise.resolve(void 0);audio;ctx;loading=new AbortController;memory;speaking=!1;constructor({synthesize:e,speed:t,onSpeaking:n,onPlayed:r,audio:i,normalize:a,target:o,memory:s=Iv}){this.synthesize=e,this.speed=t,this.onSpeaking=n,this.onPlayed=r,this.normalize=a,this.target=o,this.memory=s,this.audio=i??new Audio}unlock(){let e=globalThis,t=e.AudioContext||e.webkitAudioContext;t&&((!this.ctx||this.ctx.state===`closed`)&&(this.ctx=new t),this.ctx.resume?.().catch(()=>{}))}play(e){for(let t of e??[])t.type===`earcon`?this.earcon(t.name):t.type===`speak`&&this.say(t.text)}earcon(e){let t=this.ctx,n=Ev[e];if(!t||!n||t.state===`closed`)return;let r=t.currentTime+.01;for(let e of n){if(e.gap){r+=e.gap/1e3;continue}let n=t.createOscillator(),i=t.createGain(),a=r+(e.ms??0)/1e3;n.type=`sine`,n.frequency.value=e.freq??440,i.gain.setValueAtTime(1e-4,r),i.gain.exponentialRampToValueAtTime(.12,r+.012),i.gain.exponentialRampToValueAtTime(1e-4,a),n.connect(i).connect(t.destination),n.start(r),n.stop(a+.02),r=a}this.onPlayed?.({cue:`earcon`,name:e})}async prefetch(e,t){this.key=Promise.resolve(t).catch(()=>void 0);let n=[...e],{signal:r}=this.loading;await Promise.all([this.prune(),...Array.from({length:Math.min(2,n.length)},async()=>{for(let e=n.shift();e!==void 0&&!r.aborted;e=n.shift())await this.phrase(e).catch(()=>void 0)})])}ready(e){return this.urls.has(e)}phrase(e){let t=this.phrases.get(e);return t||(t=this.load(e),this.phrases.set(e,t),t.catch(()=>this.phrases.delete(e))),t}async load(e){let{signal:t}=this.loading,n=await this.key,r=n?await Pv():void 0,i=n?Nv(n,e):``,a=this.target?.(n)??-19.5,o=e=>!this.normalize||Math.abs((e??NaN)-a)<=Av,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(kv);l=t==null?void 0:Number(t)}if(!c||!o(l)){let n=c??await this.synthesize(e,t);c=n;let o={};if(this.normalize)try{c=await this.normalize(n,a),o[kv]=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 Pv():void 0;if(!t||!e)return;let n=globalThis.caches;for(let e of Ov)await n?.delete(e).catch(()=>!1);try{for(let n of await t.keys())n.url.startsWith(Mv(e))||await t.delete(n)}catch{}}say(e){let t=this.urls.get(e);return t?this.playURL(t,e):(this.earcon(`pending`),this.phrase(e).catch(()=>{}),Promise.resolve())}async playURL(e,t){let n=this.audio;this.setSpeaking(!0),n.src=e,n.volume=1,Fv(n,this.speed?.()??1);let r=new Promise(e=>{n.onended=n.onpause=n.onerror=()=>e()});await n.play().then(()=>!0,()=>!1)&&(t!==void 0&&this.onPlayed?.({cue:`phrase`,text:t}),await r),n.onended=n.onpause=n.onerror=null,this.setSpeaking(!1)}stop(){this.audio.paused||this.audio.pause(),this.setSpeaking(!1)}setSpeaking(e){e!==this.speaking&&(this.speaking=e,this.onSpeaking?.(e))}close(){this.stop(),this.loading.abort(),this.loading=new AbortController,this.ctx?.close?.().catch(()=>{}),this.ctx=void 0}},Rv=new Set([`um`,`umm`,`uh`,`uhh`,`uhm`,`erm`,`er`,`eh`,`ah`,`hmm`,`hm`,`mm`,`mmm`,`mhm`,`mm-hmm`,`uh-huh`]),zv=new Set([...Rv,`and`,`but`,`so`,`or`,`because`,`cause`,`then`,`with`,`to`,`the`,`a`,`an`,`of`,`for`,`if`,`that`,`like`,`maybe`]),Bv=new Map([[`stop`,`interrupt`],[`cancel`,`interrupt`],[`never mind`,`interrupt`],[`nevermind`,`interrupt`],[`stop that`,`interrupt`],[`hold on`,`interrupt`],[`pause listening`,`pause`]]),Vv=new Set([`mark`,`mark that`,`bookmark`]);function Hv(e){return String(e??``).toLowerCase().replace(/[^\p{L}\p{N}'\s-]+/gu,` `).split(/\s+/).map(e=>e.replace(/^[-']+|[-']+$/g,``)).filter(Boolean)}function Uv(e,{mark:t=!1}={}){let n=Hv(e).join(` `);return t&&Vv.has(n)?`mark`:Bv.get(n)}function Wv(e){return Hv(e).every(e=>Rv.has(e))}function Gv(e){let t=String(e??``).trim(),n=Hv(t);return!n.length||zv.has(n[n.length-1])||/(\.\.\.|…|[,;:\-–—])["'”’)\]]*$/.test(t)?!1:/[.?!]["'”’)\]]*$/.test(t)?!0:n.length>=3}var Kv=new Set([`e.g.`,`i.e.`,`mr.`,`mrs.`,`ms.`,`dr.`,`st.`,`vs.`,`cf.`,`prof.`,`jr.`,`sr.`,`approx.`,`no.`,`fig.`]),qv=/[.?!…]+["'”’)\]]*(?=\s|$)/g;function Jv(e,{minChars:t=4,maxChars:n=300,speakable:r}={}){let i=String(e??``),a=(r?r(i):i).replace(/```[\s\S]*?(?:```|$)/g,`
8
+ (code omitted)
9
+ `).split(/\r?\n/).map(e=>e.replace(/\s+/g,` `).trim()).filter(Boolean).flatMap(Yv),o=[],s=``;for(let e of a){let n=s?`${s} ${e}`:e;n.length<t?s=n:(o.push(n),s=``)}return s&&(o.length?o[o.length-1]+=` ${s}`:o.push(s)),o.flatMap(e=>Xv(e,n))}function Yv(e){let t=[],n=0;for(let r of e.matchAll(qv)){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(Kv.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 Xv(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 Zv=16e3;function Qv(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 $v(e,t){return vv(Qv(e,t,Zv),Zv)}function ey(e){return{audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,...e?{deviceId:{exact:e}}:{}}}}var ty=Object.freeze({minSpeechMs:300,endSilenceMs:350,trailingKeepMs:200,preRollMs:300,holdMs:1600,finishedHoldMs:1e3}),ny=ty.trailingKeepMs,ry=120,iy=4,ay=e=>e.reduce((e,t)=>e+t.ms,0);function oy(e,t){for(;e.length>1&&ay(e)-e[0].ms>=t;)e.shift()}var sy=class{sampleRate;minSpeechMs;endSilenceMs;preRollMs;maxSegmentMs;onsetGapMs;minVoicedRatio;state=`silence`;abandoned=void 0;broken=!1;preroll=[];frames=[];segmentMs=0;onsetMs=0;voicedMs=0;gapMs=0;silenceMs=0;constructor({sampleRate:e,minSpeechMs:t=ty.minSpeechMs,endSilenceMs:n=ty.endSilenceMs,preRollMs:r=ty.preRollMs,maxSegmentMs:i=6e4,onsetGapMs:a=ry,minVoicedRatio:o=0}){this.sampleRate=e,this.minSpeechMs=t,this.endSilenceMs=n,this.preRollMs=r,this.maxSegmentMs=i,this.onsetGapMs=a,this.minVoicedRatio=o,this.reset()}get active(){return this.state===`speech`}reset(){this.state=`silence`,this.abandoned=void 0,this.preroll=[],this.frames=[],this.segmentMs=0,this.onsetMs=0,this.voicedMs=0,this.gapMs=0,this.silenceMs=0}process(e,t){let n={samples:Float32Array.from(e),ms:e.length/this.sampleRate*1e3},r=[];if(this.abandoned=void 0,this.state===`silence`)t?(this.state=`onset`,this.frames=[...this.preroll,n],this.segmentMs=ay(this.frames),this.preroll=[],this.onsetMs=this.voicedMs=n.ms,this.gapMs=0,this.broken=!1):(this.preroll.push(n),oy(this.preroll,this.preRollMs));else if(this.state===`onset`)this.frames.push(n),this.segmentMs+=n.ms,this.onsetMs+=n.ms,t?(this.voicedMs+=n.ms,this.gapMs>0&&(this.broken=!0),this.gapMs=0):((this.gapMs+=n.ms)>this.onsetGapMs||this.voicedMs<this.minVoicedRatio*this.onsetMs)&&(this.abandoned={reason:this.gapMs>this.onsetGapMs?`gap`:`ratio`,onsetMs:this.onsetMs,voicedMs:this.voicedMs,broken:this.broken},this.preroll=this.frames,oy(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-ny;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}}},cy=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-iy: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}}},ly=class{sendFn;holdMs;finishedHoldMs;maxUtteranceMs;onHeld;onSend;onMerge;setTimer;clearTimer;now;nextID=1;pending=[];text=``;ms=0;segments=[];lastEnd=0;speaking=!1;endedAt=0;timer;smart;predict;onPredict;turn;predictTimes=[];mark;constructor({send:e,holdMs:t=ty.holdMs,finishedHoldMs:n=ty.finishedHoldMs,maxUtteranceMs:r=6e4,onHeld:i,onSend:a,onMerge:o,setTimer:s=(e,t)=>setTimeout(e,t),clearTimer:c=e=>clearTimeout(e),now:l=()=>Date.now(),smart:u,predict:d,onPredict:f,mark:p}){this.sendFn=e,this.holdMs=t,this.finishedHoldMs=n,this.maxUtteranceMs=r,this.onHeld=i,this.onSend=a,this.onMerge=o,this.setTimer=s,this.clearTimer=c,this.now=l,this.smart=u,this.predict=d,this.onPredict=f,this.mark=p,this.reset()}get held(){return this.text}get busy(){return!!this.text||this.pending.length>0}reset(){this.cancelHold(),this.endTurn(),this.pending=[],this.text=``,this.ms=0,this.segments=[],this.speaking=!1,this.onHeld?.(``)}speechStarted(){this.speaking=!0,this.cancelHold(),this.endTurn()}segmentEnded(e){this.speaking=!1,this.endedAt=this.now();let t=this.nextID++;return this.pending.push({id:t,ms:e,endedAt:this.endedAt}),this.startTurn(),t}startTurn(){this.endTurn();let e=this.predict?this.smart?.():void 0;if(!e)return;let t={params:e,mode:`predicting`,decidedAt:0,lastMs:0,timers:[]};this.turn=t,t.timers.push(this.setTimer(()=>{this.turn===t&&t.mode!==`timers`&&t.mode!==`complete`&&(t.mode=`fallback`,this.evaluate())},e.fallbackMs)),this.score(t)}score(e){let t=this.now(),n=!1,r=this.setTimer(()=>{n||this.turn!==e||(n=!0,this.toTimers(e,`slow`,t))},w_(e.params.slowMs,this.predictTimes));e.timers.push(r);let i;try{i=this.predict()}catch(i){n=!0,this.clearTimer(r),this.toTimers(e,String(i?.message??i),t);return}i.then(({p:i,ms:a})=>{if(this.predictTimes.push(this.now()-t),this.predictTimes.length>9&&this.predictTimes.shift(),n||this.turn!==e||e.mode===`fallback`)return;n=!0,this.clearTimer(r),e.lastP=i,e.lastMs=a;let o=Math.max(0,this.now()-this.endedAt);i>=e.params.threshold?(e.mode=`complete`,e.decidedAt=this.now(),this.onPredict?.({p:i,ms:a,silenceMs:o,decision:`send`}),this.evaluate()):(e.mode=`hold`,this.onPredict?.({p:i,ms:a,silenceMs:o,decision:`hold`}),e.timers.push(this.setTimer(()=>{this.turn===e&&e.mode===`hold`&&this.score(e)},e.params.recheckMs)))},i=>{n||this.turn!==e||e.mode===`fallback`||(n=!0,this.clearTimer(r),this.toTimers(e,String(i?.message??i),t))})}toTimers(e,t,n){this.clearTurnTimers(e),e.mode=`timers`,this.onPredict?.({ms:Math.max(0,this.now()-n),silenceMs:Math.max(0,this.now()-this.endedAt),decision:`timer-fallback`,error:t}),this.evaluate()}clearTurnTimers(e){for(let t of e.timers)this.clearTimer(t);e.timers.length=0}endTurn(){this.turn&&this.clearTurnTimers(this.turn),this.turn=void 0}evaluateSmart(e){if(e.mode===`fallback`)return this.onPredict?.({...e.lastP===void 0?{}:{p:e.lastP},ms:e.lastMs,silenceMs:Math.max(0,this.now()-this.endedAt),decision:`fallback`}),this.flush(`smart-fallback`);if(e.mode!==`complete`)return;let t=e.params.graceMs-(this.now()-e.decidedAt);if(t<=0)return this.flush(`smart`);this.timer=this.setTimer(()=>{this.timer=void 0,this.flush(`smart`)},t)}transcribed(e,t){let n=this.pending.find(t=>t.id===e);if(n){for(n.text=String(t??``).replace(/\s+/g,` `).trim();this.pending[0]?.text!==void 0;)this.apply(this.pending.shift());this.evaluate()}}apply({id:e,text:t,ms:n,endedAt:r}){let i=Uv(t,{mark:this.mark?.()===!0});if(i===`mark`)return this.sent(t,[e],`command`);i?(this.cancelHold(),this.text=``,this.ms=0,this.segments=[],this.sent(t,[e],`command`)):Wv(t)||(this.text&&this.onMerge&&this.onMerge({segments:[...this.segments,e],pauseMs:Math.max(0,r-n-this.lastEnd)}),this.text=this.text?`${this.text} ${t}`:t,this.ms+=n,this.segments.push(e),this.lastEnd=r,this.ms>=this.maxUtteranceMs&&this.flush(`max`))}sent(e,t,n){this.onSend?.({text:e,segments:t,reason:n,holdMs:Math.max(0,this.now()-this.endedAt)}),this.sendFn(e)}evaluate(){if(this.onHeld?.(this.text),!this.text||this.speaking||this.pending.length)return;if(this.cancelHold(),this.turn&&this.turn.mode!==`timers`)return this.evaluateSmart(this.turn);let e=Gv(this.text),t=e?`finished`:`hold`,n=(e?this.finishedHoldMs:this.holdMs)-(this.now()-this.endedAt);if(n<=0)return this.flush(t);this.timer=this.setTimer(()=>{this.timer=void 0,this.flush(t)},n)}flush(e){this.cancelHold(),this.endTurn();let t=this.text,n=this.segments;this.text=``,this.ms=0,this.segments=[],t&&this.sent(t,n,e),this.onHeld?.(``)}cancelHold(){this.timer!==void 0&&this.clearTimer(this.timer),this.timer=void 0}},uy=2,dy=class{synth;play;stop;onState;onError;onPlay;onEnd;now;items=[];generation=0;controller=new AbortController;speaking=!1;playing=!1;current;constructor({synth:e,play:t,stop:n,onState:r,onError:i,onPlay:a,onEnd:o,now:s=()=>Date.now()}){this.synth=e,this.play=t,this.stop=n,this.onState=r,this.onError=i,this.onPlay=a,this.onEnd=o,this.now=s}enqueue(e){for(let t of e){let e=typeof t==`string`?{text:t}:t,n=String(e.text??``).trim();n&&this.items.push(e.ref===void 0?{text:n}:{text:n,ref:e.ref})}this.items.length&&(this.speaking?this.prefetch():this.run(this.generation))}prefetch(){for(let e of this.items.slice(0,this.playing?uy:3))this.fetch(e)}clear(){let e=this.current,t=this.items.map(({text:e,ref:t})=>t===void 0?{text:e}:{text:e,ref:t});if(this.current=void 0,this.generation++,this.controller.abort(),this.controller=new AbortController,this.items=[],this.playing=!1,this.stop(),this.setSpeaking(!1),!e)return{dropped:t};let n=Math.max(0,this.now()-e.at);return this.onEnd?.(e.item,{playedMs:n,completed:!1}),{playing:{...e.item,playedMs:n},dropped:t}}fetch(e){e&&!e.audio&&(e.audio=e.ref===void 0?this.synth(e.text,this.controller.signal):this.synth(e.text,this.controller.signal,e.ref),e.audio.catch(()=>{}))}async run(e){for(this.setSpeaking(!0);e===this.generation&&this.items.length;){let t=this.items[0];this.prefetch();let n;try{n=await t.audio}catch(n){if(e!==this.generation)return;this.items.shift(),this.onError?.(n,t.text);continue}if(e!==this.generation)return;this.items.shift(),this.playing=!0,this.prefetch();let r=t.ref===void 0?{text:t.text}:{text:t.text,ref:t.ref};this.current={item:r,at:this.now()},this.onPlay?.(r);let i=!0;try{await this.play(n)}catch(n){i=!1,e===this.generation&&this.onError?.(n,t.text)}finally{if(e===this.generation){this.playing=!1;let e=this.current;this.current=void 0,e&&this.onEnd?.(e.item,{playedMs:Math.max(0,this.now()-e.at),completed:i})}}}e===this.generation&&this.setSpeaking(!1)}setSpeaking(e){e!==this.speaking&&(this.speaking=e,this.onState?.(e))}},fy=class{parts=new Map;limit;speakable;constructor({limit:e=50,speakable:t}={}){this.limit=e,this.speakable=t}split(e){return Jv(e,this.speakable?{speakable:this.speakable}:{})}get size(){return this.parts.size}accept(e){let t=this.take(e);return t&&{sentences:t.sentences,text:t.text}}take(e){let t=String(e.text??``),n=e.messageID??``,r=e.ordinal??0;if(typeof e.seq!=`number`){let e=this.split(t);return{sentences:e,items:e.map((e,t)=>({text:e,ref:{messageID:n,ordinal:r,i:t}})),text:t,muted:!1}}let i=`${n} ${r}`,a=this.parts.get(i);if(a||(a={messageID:n,next:0,held:new Map,texts:[],muted:!1},this.parts.set(i,a),this.parts.size>this.limit&&this.parts.delete(this.parts.keys().next().value)),e.seq<a.next||a.held.has(e.seq))return;a.held.set(e.seq,t);let o=[];for(;a.held.has(a.next);)o.push({seq:a.next,text:a.held.get(a.next)}),a.held.delete(a.next++);if(!o.length)return;a.texts.push(...o.map(e=>e.text));let s=a.muted?[]:o.flatMap(e=>this.split(e.text).map((t,i)=>({text:t,ref:{messageID:n,ordinal:r,seq:e.seq,i}})));return{sentences:s.map(e=>e.text),items:s,text:a.texts.join(` `),muted:a.muted}}mute(){let e=new Set;for(let t of this.parts.values())!t.muted&&t.messageID&&e.add(t.messageID),t.muted=!0;return[...e]}},py=class{pending={};turn;now;last;constructor({now:e=()=>Date.now()}={}){this.now=e}mark(e,t=this.now()){switch(e){case`speechEnd`:return this.pending={speechEnd:t},!0;case`transcript`:return this.pending.speechEnd!==void 0&&(this.pending.transcript=t,!0);case`accepted`:return this.turn={...this.pending,accepted:t},this.pending={},!0;case`firstSay`:return!this.turn||this.turn.firstSay!==void 0?!1:(this.turn.firstSay=t,!0);case`firstByte`:return this.turn?.firstSay===void 0||this.turn.firstByte!==void 0?!1:(this.turn.firstByte=t,!0);case`firstAudio`:return this.turn?.firstSay!==void 0&&(this.last={...this.turn,firstAudio:t},this.turn=void 0,!0)}}},my=e=>`${(e/1e3).toFixed(1)} s`;function hy(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} ${my(n-i)}`),i=n)}return{summary:`last turn: ${my(e.firstAudio-t)} to first audio`,detail:r.join(` · `)}}var gy=12,_y=e=>String(e??``).replace(/\s+/g,` `).trim();function vy(e,t){let n=_y(e),r=_y(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>=gy;e--)if(n.endsWith(r.slice(0,e)))return{mode:`update`,text:n+r.slice(e)};return{mode:`new`,text:t}}function yy(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 by=Object.freeze({nearMinMs:150,probMargin:.2,dbMargin:3,runGapMs:100,minOnsetVoicedMs:60,nearGapMs:500,nearPerMinute:20,summaryMs:1e4}),xy=Object.freeze({preFrames:48,postFrames:16,perMinute:30,gapMs:1e3}),Sy=(e,t)=>Math.round(e*10**t)/10**t,Cy=100,wy=()=>({ms:0,frames:0,probFrames:0,hist:new Uint32Array(101),maxProb:0,maxDb:-1/0,aboveStart:0,aboveSpeaking:0,guardMs:0,near:0,dropped:0,close:!1,mode:`energy`}),Ty=class{onNear;onSummary;clock=0;run;onset;sent=[];window=wy();quietAt;onTrace;recent=[];trace;traced=[];constructor({onNear:e,onSummary:t,onTrace:n}){this.onNear=e,this.onSummary=t,this.onTrace=n}reset(){this.run=void 0,this.onset=void 0}frame(e){this.clock+=e.ms;let t=e.mode===`silero`?e.prob??0:e.db,n=e.guarded?e.speakingThreshold:e.startThreshold,r=e.mode===`silero`?by.probMargin:by.dbMargin;this.tally(e,t,n-r),this.onTrace&&this.traceFrame({value:e.mode===`silero`?Math.round(Math.min(1,Math.max(0,t))*100):Math.round(t),guard:e.guarded,threshold:e.mode===`silero`?Math.round(n*100):Math.round(n),mode:e.mode,ms:e.ms}),this.track(e,t,n,n-r),this.onTrace&&(e.before!==`speech`&&e.after===`speech`?this.startTrace(`speech.start`):e.before===`speech`&&e.after!==`speech`&&this.startTrace(`speech.end`)),this.window.ms>=by.summaryMs&&this.summarize()}traceFrame(e){this.recent.push(e),this.recent.length>xy.preFrames&&this.recent.shift();let t=this.trace;if(!t||(t.frames.push(e),--t.left>0))return;this.trace=void 0;let n=t.frames.at(-1);this.onTrace?.({reason:t.reason,mode:n.mode,frameMs:Math.round(n.ms*10)/10,scale:n.mode===`silero`?`p100`:`db`,values:t.frames.map(e=>e.value),threshold:n.threshold,guard:t.frames.map(e=>e.guard?`1`:`0`).join(``)})}startTrace(e){if(this.trace)return;for(;this.traced.length&&this.clock-this.traced[0]>=6e4;)this.traced.shift();let t=this.traced.at(-1);t!==void 0&&this.clock-t<xy.gapMs||this.traced.length>=xy.perMinute||(this.traced.push(this.clock),this.trace={reason:e,frames:[...this.recent],left:xy.postFrames})}track(e,t,n,r){if(e.before===`silence`&&e.after===`onset`?(this.run=void 0,this.onset={ms:0,lastMs:this.clock,peak:t,threshold:n,guarded:e.guarded,mode:e.mode}):this.onset&&e.before===`onset`&&(this.onset.peak=Math.max(this.onset.peak,t),this.onset.guarded||=e.guarded),e.after===`speech`&&(this.onset=void 0),e.abandoned){let t=this.onset;if(this.onset=void 0,t&&e.abandoned.voicedMs>=by.minOnsetVoicedMs){let n=e.abandoned.reason===`ratio`&&e.abandoned.broken?`voiced-ratio`:`short-onset`;this.near({...t,ms:e.abandoned.onsetMs},n,e.abandoned.voicedMs)}}else e.before!==`silence`||e.after!==`silence`?this.run=void 0:t>=r?(this.run||={ms:0,lastMs:this.clock-e.ms,peak:t,threshold:n,guarded:e.guarded,mode:e.mode},this.run.ms+=this.clock-this.run.lastMs,this.run.lastMs=this.clock,this.run.peak=Math.max(this.run.peak,t),this.run.guarded||=e.guarded,this.run.threshold=Math.max(this.run.threshold,n)):this.run&&this.clock-this.run.lastMs>by.runGapMs&&this.endRun()}endRun(){let e=this.run;this.run=void 0,e&&e.ms>=by.nearMinMs&&this.near(e,`below-threshold`)}near(e,t,n){for(this.window.close=!0;this.sent.length&&this.clock-this.sent[0]>=6e4;)this.sent.shift();let r=this.sent.at(-1);if(r!==void 0&&this.clock-r<by.nearGapMs||this.sent.length>=by.nearPerMinute){this.window.dropped++;return}this.sent.push(this.clock),this.window.near++,this.onTrace&&this.startTrace(`vad.near`);let i=e.mode===`silero`?{peakProb:Sy(e.peak,3)}:{peakDb:Sy(e.peak,1)};this.onNear?.({ms:Math.round(e.ms),...n===void 0?{}:{voicedMs:Math.round(n)},...i,threshold:Sy(e.threshold,e.mode===`silero`?3:1),echoGuard:e.guarded,mode:e.mode,reason:t})}tally(e,t,n){let r=this.window;if(r.ms+=e.ms,r.frames++,r.mode=e.mode,r.floorDb=e.floorDb,r.maxDb=Math.max(r.maxDb,e.db),e.guarded&&(r.guardMs+=e.ms),e.mode===`silero`){let t=Math.min(1,Math.max(0,e.prob??0));r.probFrames++,r.hist[Math.round(t*Cy)]++,r.maxProb=Math.max(r.maxProb,t)}t>=e.startThreshold&&r.aboveStart++,t>=e.speakingThreshold&&r.aboveSpeaking++,t>=n&&(r.close=!0)}summarize(){let e=this.window;this.window=wy();let t=!e.close&&!e.aboveStart&&!e.aboveSpeaking&&!e.near&&!e.dropped,n=e.floorDb,r=this.quietAt!==void 0&&n!==void 0&&Math.abs(n-this.quietAt)<by.dbMargin;if(t&&r)return;this.quietAt=t?n:void 0;let i=e.probFrames>0?{maxProb:Sy(e.maxProb,3),p90Prob:Sy(Ey(e.hist,e.probFrames,.9),3)}:{};this.onSummary?.({frames:e.frames,...i,...Number.isFinite(e.maxDb)?{maxDb:Sy(e.maxDb,1)}:{},...n!==void 0&&Number.isFinite(n)?{noiseFloorDb:Sy(n,1)}:{},framesAboveStart:e.aboveStart,framesAboveSpeakingStart:e.aboveSpeaking,msEchoGuard:Math.round(e.guardMs),...e.dropped?{nearDropped:e.dropped}:{},mode:e.mode})}};function Ey(e,t,n){let r=Math.ceil(n*t),i=0;for(let t=0;t<e.length;t++)if(i+=e[t],i>=r)return t/Cy;return 1}var Dy=16e3,Oy=512/Dy*1e3,ky=Object.freeze({startProb:.6,endProb:.35,speakingStartProb:.85,minSpeechMs:250,endSilenceMs:ty.endSilenceMs,maxSegmentMs:6e4,gateDb:3,energyMarginDb:10,energyMinSpeechMs:ty.minSpeechMs}),Ay=Object.freeze([`low`,`normal`,`high`]);function jy(e){return Ay.includes(e)?e:`normal`}var My=Object.freeze({low:Object.freeze({...ky,startProb:.75,endProb:.45,speakingStartProb:.92,minSpeechMs:350,gateDb:6,energyMarginDb:13,energyMinSpeechMs:400}),normal:ky,high:Object.freeze({...ky,startProb:.45,endProb:.25,speakingStartProb:.75,minSpeechMs:180,gateDb:0,energyMarginDb:7,energyMinSpeechMs:250})});function Ny(e){return My[jy(e)]}var Py=.75,Fy=class{speaking=!1;segmenter;current;constructor(e,t=Dy){this.current=e,this.segmenter=new sy({sampleRate:t,endSilenceMs:e.endSilenceMs,maxSegmentMs:e.maxSegmentMs})}get params(){return this.current}set params(e){this.current=e,this.segmenter.endSilenceMs=e.endSilenceMs,this.segmenter.maxSegmentMs=e.maxSegmentMs}get state(){return this.segmenter.state}get active(){return this.segmenter.active}get abandoned(){return this.segmenter.abandoned}reset(){this.segmenter.reset()}process(e,t){let n=this.current;this.segmenter.minSpeechMs=n.minSpeechMs,this.segmenter.minVoicedRatio=Py;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)}},Iy=class{from;ratio;input=new Float32Array;pos=0;out=new Float32Array(512);filled=0;constructor(e){this.from=e,this.ratio=e/Dy}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}},Ly=64,Ry=class{sampleRate=Dy;stats={frames:0,avgMs:0,maxMs:0,skipped:0};resampler;meter;vad;onEvents;onLevel;onChunk;warn;now;model;queue=[];inFlight=0;generation=0;warned=new Set;speakingOn=!1;tail=0;capture;constructor({sampleRate:e,params:t=ky,onEvents:n,onLevel:r,onChunk:i,warn:a=e=>console.warn(e),now:o=()=>performance.now(),onNear:s,onSummary:c,onTrace:l}){(s||c||l)&&(this.capture=new Ty({onNear:s,onSummary:c,onTrace:l})),this.resampler=new Iy(e),this.meter=new cy({marginDb:t.energyMarginDb}),this.vad=new Fy(t),this.onEvents=n,this.onLevel=r,this.onChunk=i,this.warn=a,this.now=o}get classifier(){return this.model}set classifier(e){this.model=e}get mode(){return this.model?`silero`:`energy`}get params(){return this.vad.params}set params(e){this.vad.params=e,this.meter.marginDb=e.energyMarginDb}get speaking(){return this.speakingOn}set speaking(e){this.speakingOn&&!e&&(this.tail=Math.ceil(400/Oy)),this.speakingOn=e}get active(){return this.vad.active}reset(){this.generation++,this.queue=[],this.inFlight=0,this.vad.reset(),this.capture?.reset()}push(e){for(let t of this.resampler.push(e))this.chunk(t)}chunk(e){this.onChunk?.(e);let t=this.speakingOn||this.tail>0;!this.speakingOn&&this.tail>0&&this.tail--,this.meter.speaking=t;let n=this.vad.state===`speech`,{db:r,floor:i,level:a,voiced:o}=this.meter.measure(e,Oy,n);this.onLevel?.(a);let s={chunk:e,energyVoiced:o,guarded:t,db:r,floor:i};this.queue.push(s),this.model&&this.inFlight>=Ly&&this.drop(`stalled`);let c=this.model;if(!c)s.energy=!0;else if(!n&&r<i+this.vad.params.gateDb+(t?this.meter.speakingBoostDb:0))s.prob=0,this.stats.skipped++;else{let t=this.generation,n=this.now();this.inFlight++,c(e).then(e=>{t===this.generation&&(this.inFlight--,this.record(this.now()-n),s.prob=e,this.drain())},e=>{t===this.generation&&(this.inFlight--,s.energy=!0,this.model===c&&this.drop(e?.message??String(e)),this.drain())})}this.drain()}drop(e){this.model=void 0,this.generation++,this.inFlight=0;for(let e of this.queue)e.prob===void 0&&(e.energy=!0);this.warnOnce(`failed`,`Voice: on-device speech detection stopped (${e}); using the energy detector`)}record(e){let t=this.stats;t.frames++,t.avgMs+=(e-t.avgMs)/t.frames,t.maxMs=Math.max(t.maxMs,e)}drain(){let e=[];for(;this.queue.length&&(this.queue[0].energy||this.queue[0].prob!==void 0);){let t=this.queue.shift();this.vad.speaking=t.guarded;let n=this.vad.state;e.push(...t.energy?this.vad.processEnergy(t.chunk,t.energyVoiced):this.vad.process(t.chunk,t.prob)),this.capture&&this.captured(t,n)}e.length&&this.onEvents(e)}captured(e,t){let n=this.vad.params,r=this.vad.abandoned,i={ms:Oy,db:e.db,floorDb:e.floor,guarded:e.guarded,before:t,after:this.vad.state,...r?{abandoned:r}:{}};if(e.energy){let t=Math.max(e.floor+this.meter.marginDb,this.meter.minDb);this.capture.frame({...i,mode:`energy`,startThreshold:t,speakingThreshold:t+this.meter.speakingBoostDb})}else this.capture.frame({...i,mode:`silero`,prob:e.prob??0,startThreshold:n.startProb,speakingThreshold:n.speakingStartProb})}warnOnce(e,t){this.warned.has(e)||(this.warned.add(e),this.warn(t))}},zy=`voice.speed`,By=`voice.cues`,Vy=`voice.background`,Hy=`voice.micDevice`,Uy=`voice.sensitivity`,Wy=`voice.turnDetection`,Gy=`voice.front`,Ky,qy,Jy={get speed(){return Ha(localStorage.getItem(zy))},set speed(e){localStorage.setItem(zy,String(Ha(e))),Fv(Xy(),Ha(e))},get cues(){return localStorage.getItem(By)!==`0`},set cues(e){localStorage.setItem(By,e?`1`:`0`)},get background(){return localStorage.getItem(Vy)===`1`},set background(e){localStorage.setItem(Vy,e?`1`:`0`)},get sensitivity(){return Ky??=jy(localStorage.getItem(Uy))},set sensitivity(e){Ky=jy(e),localStorage.setItem(Uy,Ky)},get turnDetection(){return qy??=x_(localStorage.getItem(Wy))},set turnDetection(e){qy=x_(e),localStorage.setItem(Wy,qy)},get front(){return localStorage.getItem(Gy)!==`0`},set front(e){localStorage.setItem(Gy,e?`1`:`0`)},get smartTurn(){let e=new URLSearchParams(location.search);return D_(t=>e.get(t),e=>localStorage.getItem(e))},setSmartTurnKnob(e,t){let n=E_(e,t);return n===void 0?localStorage.removeItem(e):localStorage.setItem(e,String(n)),n===void 0?``:String(n)}},Yy;function Xy(){return Yy||(Yy=new Audio,Yy.preload=`none`,Yy.volume=1,Fv(Yy,Jy.speed),Yy)}function Zy(){let e=Xy();e.paused&&(e.muted=!0,e.play().catch(()=>{}).finally(()=>{e.pause(),e.muted=!1}))}var Qy,$y=new Set,eb={get(){return Qy??=localStorage.getItem(Hy)??``},set(e){Qy=e,localStorage.setItem(Hy,e);for(let t of[...$y])t(e)},subscribe(e){return $y.add(e),()=>{$y.delete(e)}}};async function tb(){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 nb(e,t){let n=await navigator.mediaDevices.getUserMedia(ey(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 rb=6e4;function ib(){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 ab({transcribe:e,deviceId:t=eb.get(),onTick:n}){if(!navigator.mediaDevices?.getUserMedia||!window.MediaRecorder)throw Error(`This browser cannot record here (the microphone needs HTTPS).`);let r;try{r=await navigator.mediaDevices.getUserMedia(ey(t||void 0))}catch(e){let t=e;throw Error(t.name===`NotAllowedError`?`Microphone permission was denied. Allow it in the browser's site settings.`:`Microphone: ${t.message}`)}let i=ib(),a=new MediaRecorder(r,i?{mimeType:i}:void 0),o=[],s=Date.now();a.ondataavailable=e=>e.data.size&&o.push(e.data);let c=!1,l=new Promise((t,n)=>{a.onstop=async()=>{if(clearInterval(u),clearTimeout(d),r.getTracks().forEach(e=>e.stop()),c)return t(``);let s=new Blob(o,{type:(a.mimeType||i||`audio/webm`).split(`;`)[0]});if(!s.size)return t(``);try{let{text:n}=await e(s);t(String(n??``).trim())}catch(e){let t=e;n(Error(t.status===413?`That recording was too long.`:`Transcription failed: ${t.message}`))}}});a.start();let u=setInterval(()=>n?.(Math.max(0,Math.ceil((rb-(Date.now()-s))/1e3))),1e3),d=setTimeout(()=>a.state===`recording`&&a.stop(),rb);return{finish(){return a.state===`recording`&&a.stop(),l},cancel(){c=!0,a.state===`recording`&&a.stop()}}}var ob=Xy(),[sb,cb]=u(eb.get());function lb(e){cb(e),eb.set(e)}function ub(e){return ab({deviceId:sb(),...e?{onTick:e}:{},transcribe:async e=>(await V(`/api/transcribe`,{method:`POST`,body:e,headers:{"content-type":e.type}})).json()})}function db(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 fb(e){return e.audioState===`suspended`||e.error===`NotAllowedError`&&!e.activated&&e.micPermission!==`denied`}var pb=512,mb=Object.freeze({preMs:3e3,postMs:2e3,gapMs:2e3}),hb=class{sampleRate;buffer;total=0;pending=[];constructor({sampleRate:e=16e3,capacityMs:t}){this.sampleRate=e,this.buffer=new Float32Array(Math.ceil(t/1e3*e))}get position(){return this.total}push(e){for(let t=0;t<e.length;t+=pb)this.write(e,t,Math.min(e.length,t+pb))}write(e,t,n){let r=this.buffer.length;for(let i=t;i<n;i++)this.buffer[(this.total+i-t)%r]=e[i];if(this.total+=n-t,!this.pending.length)return;let i=this.pending.filter(e=>e.to<=this.total);if(i.length){this.pending=this.pending.filter(e=>e.to>this.total);for(let e of i)e.done(this.read(e.from,e.to),{preMs:e.preMs,postMs:e.postMs})}}clip(e,t,n){let r=e=>Math.round(e/this.sampleRate*1e3),i=this.buffer.length,a=Math.min(Math.round(t/1e3*this.sampleRate),i),o=Math.max(0,Math.min(Math.round(e/1e3*this.sampleRate),this.total,i-a-pb));this.pending.push({from:this.total-o,to:this.total+a,preMs:r(o),postMs:r(a),done:n})}reset(){this.pending=[]}read(e,t){let n=this.buffer.length,r=new Float32Array(t-e);for(let i=e;i<t;i++)r[i-e]=this.buffer[i%n];return r}},gb=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(`.`)),_b=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`]),vb=[/^(?:subtitles?|captions?|subtitled|captioned|transcribed|transcription|translated|translation)\b.*\bby\b/,/\bamara\s*\.?\s*org\b/,/^sous-titr/,/^untertitel\b/],yb=/^(?:\[[^\]]*\]|\([^)]*\)|\*[^*]*\*|♪[^♪]*♪|\s)+$/u;function bb(e){return e.toLowerCase().replace(/[^\p{L}\p{N}'\s]+/gu,` `).replace(/\s+/g,` `).trim()}function xb(e,{speechMs:t}={}){let n=String(e??``).trim();if(!n)return`empty`;if(!/[\p{L}\p{N}]/u.test(n))return`no words`;if(yb.test(n))return`sound`;let r=bb(n);if(r.replace(/\s/g,``).length<2)return`too short`;if(_b.has(r)||_b.has(r.replace(/ /g,``))||vb.some(e=>e.test(r)||e.test(n.toLowerCase())))return`noise`;let i=r.split(` `),a=i.some(e=>gb.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 Sb=3e4,Cb;function wb(){return Cb??=Tb().catch(e=>{throw Cb=void 0,e}),Cb}function Tb(){return new Promise((e,t)=>{let n;try{n=new Worker(new URL(`/assets/silero-worker-CC2etKS3.js`,``+import.meta.url),{type:`module`,name:`silero-vad`})}catch(e){return t(e)}let r=new Map,i=1,a=!1,o=e=>{for(let t of r.values())t.reject(e);r.clear(),n.terminate(),Cb=void 0,a||t(e)},s=setTimeout(()=>o(Error(`the speech model took too long to load`)),Sb);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 Eb=()=>Object.assign(Error(`The download was aborted`),{name:`AbortError`}),Db=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 Eb();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 Ob(e,t){let n=new Db;if(!e)return n.end(),n;let r=e.getReader(),i=()=>{n.fail(Eb()),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?Eb():e)}finally{t?.removeEventListener(`abort`,i)}})(),n}async function kb(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 Ab(e){try{return e.MediaSource?.isTypeSupported?.(`audio/mpeg`)===!0}catch{return!1}}var jb=24e3,Mb=1,Nb=2;async function Pb(e){let t=globalThis,n=t.OfflineAudioContext||t.webkitOfflineAudioContext;if(!n)throw Error(`No OfflineAudioContext here`);let r=new n(1,1,jb),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 Fb(e,t){let{samples:n,rate:r}=await Pb(await e.arrayBuffer()),i=_v(n,r,t);return new Blob([vv(i.samples,r)],{type:`audio/wav`})}function Ib(e){try{return Tv(localStorage,e)}catch{return Tv({getItem:()=>null,setItem:()=>{}},e)}}var Lb=0,Rb=e=>{let t=globalThis;t.requestIdleCallback?t.requestIdleCallback(e,{timeout:5e3}):setTimeout(e,500)};function zb(e,t){!t||!e.length||Lb>=Nb||(Lb++,Rb(()=>{(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 Pb(n.buffer);if(i.length<a*Mb)return;Cv(localStorage,t,pv(i,a))}catch{}finally{Lb--}})()}))}var Bb=500,Vb=8e3,Hb=e=>Math.min(Vb,Bb*2**Math.max(0,e)),Ub=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)}},Wb=2500,Gb=3e3,Kb=!1,qb=2,Jb=`Tap to start Voice mode`,Yb=`GestureRequired`,Xb=500,Zb=500,Qb=3e3,$b=()=>navigator.userActivation?.hasBeenActive??!0;async function ex(){try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return`unknown`}}var tx=`Voice front unavailable, talking to the session directly`,nx={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`},rx=.01,ix=ty.minSpeechMs+ty.preRollMs,ax=50,ox=2e3,sx=mb.preMs+mb.postMs+1e3,cx=()=>new URL(`/assets/vad-worklet-BfxJhrXy.js`,``+import.meta.url).href,lx=class{sessionID;transport;unsubscribe;player;ui;opts;rec;heldText=``;ring;lastClipAt=-1/0;spoken=[];playingRef;reachedEnd=!1;active=!1;paused=!1;agent;front=!1;frontWanted=!1;frontFallback=!1;inflight=0;sent=new Map;typed=new Set;typing=0;heardAt=0;lastStatus;cuePicker=new Za({ready:e=>this.cuePlayer?.ready(e)??!1});scheduler=new Qa({pick:e=>this.cuePicker.pick(e)});cuePlayer;voiceKey;onVisibility;liveness=new Ub({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=Ab(window);says;turns;cueClock;speechEndedAt;silence;silenceURL;wakeLock;warnedAutoplay=!1;state;ignoredTimer;sensitivity=`normal`;cueSpeaking=!1;attempt=0;turnAudio=new O_;smartModel;smartLoading=!1;smartError;warnedSmart=!1;constructor({sessionID:e,transport:t,player:n,ui:r,options:i={}}){this.sessionID=e,this.transport=t,this.player=n,this.ui=r;let{recorder:a,speakable:o,...s}=i;this.says=new fy(o?{speakable:o}:{}),this.opts={cues:!0,background:!1,speed:()=>1,title:()=>`OpenCode session`,sensitivity:()=>`normal`,turnDetection:()=>`timers`,smartTurnParams:()=>S_,smartTurn:p_,warn:e=>console.warn(e),front:()=>!0,voiceKey:async()=>void 0,...s},this.rec=a,a&&(this.ring=new hb({capacityMs:sx})),a&&(a.onNote=e=>this.ui.note(e)),a&&(a.onMarked=e=>this.devClip(`mark`,e)),this.turns=new py({now:a?()=>performance.now():()=>Date.now()}),this.lastStatus=i.status,this.scheduler.enabled=this.opts.cues!==!1,this.scheduler.working(no(i.status),Date.now()),this.cuePlayer=new Lv({synthesize:async(e,t)=>N_(await this.transport.speak(e,t?{signal:t}:{})),speed:this.opts.speed,normalize:Fb,target:Ib,onSpeaking:e=>{this.cueSpeaking=e,this.guardEcho(),this.scheduler.cueSpeaking(e,Date.now()),this.cueClock.poke()},...a?{onPlayed:e=>this.rec?.event(`cue.played`,e)}:{}}),this.cueClock=new $a({scheduler:this.scheduler,play:e=>this.cuePlayer.play(e),ready:()=>this.active&&!this.paused}),this.onVisibility=()=>{let e=document.visibilityState===`visible`;this.liveness.visibility(e,Date.now()),this.active&&(e?(this.opts.background||this.lockScreen(),this.recover()):this.opts.background&&!this.paused&&this.silence?.play().catch(()=>{}))},this.follow()}onWake=()=>{this.active&&document.visibilityState===`visible`&&this.recover()};onTrackMute=()=>this.liveness.muted(!0,Date.now());onTrackUnmute=()=>{this.liveness.muted(!1,Date.now()),this.recover()};onTrackEnded=()=>this.liveness.ended(Date.now());follow(){this.unsubscribe??=this.transport.events(e=>this.onEvent(e))}unfollow(){this.unsubscribe?.(),this.unsubscribe=void 0}get working(){return no(this.lastStatus)}get speaking(){return!!this.queue?.speaking}async start(){if(this.active)return!0;this.follow();let e=this.attempt+1,t=await this.begin();return!t&&!this.active&&e===this.attempt&&this.unfollow(),t}async begin(){let e=++this.attempt,t=()=>e!==this.attempt;this.ui.state(`starting`),this.cuePlayer.unlock(),this.opts.background&&this.startSilence();let n=window;if(!navigator.mediaDevices?.getUserMedia||!(n.AudioContext||n.webkitAudioContext))return this.ui.note(`This browser cannot listen here (the microphone needs HTTPS).`,`err`),this.ui.state(`off`),!1;let r;try{r=await navigator.mediaDevices.getUserMedia(ey(this.opts.deviceId))}catch(e){if(t())return!1;let n=e;return fb({error:n.name,micPermission:await ex(),activated:$b()})?this.ui.note(Jb,`gesture`):this.ui.note(n.name===`NotAllowedError`?`Microphone permission was denied. Allow it in the browser's site settings.`:`Microphone: ${n.message}`,`err`),this.ui.state(`off`),this.stopSilence(),!1}if(t())return r.getTracks().forEach(e=>e.stop()),!1;this.stream=r;let i;try{this.frontWanted=this.opts.front();let e;({agent:e,front:i}=await this.transport.conversation(!0,{front:this.frontWanted})),this.agent=e}catch(e){return this.release(),this.stopSilence(),t()||(this.ui.note(`Could not start Voice mode: ${e.message}`,`err`),this.ui.state(`off`)),!1}if(t())return this.release(),await this.transport.conversation(!1).catch(()=>{}),!1;this.active=!0,typeof i!=`boolean`&&(this.frontWanted=!1),this.setFront(i===!0),this.rec?.start(this.sessionID,{detector:`energy`,sensitivity:this.opts.sensitivity(),cues:this.opts.cues!==!1,background:!!this.opts.background,streaming:this.streaming,timings:{...ty,...this.smartTimings()}}),this.prefetchCues();try{await this.listen()}catch(e){return t()||(e.name===Yb?this.ui.note(Jb,`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(),Zb),this.cueClock.poke(),this.refresh(),!0)}prefetchCues(){this.opts.cues!==!1&&this.scheduler.enabled&&this.scheduler.phrases&&this.cuePlayer.prefetch(Xa(),this.voiceKey=this.cueKey())}async cueKey(){try{return await this.opts.voiceKey()}catch{return}}async listen(){let e=window,t=e.AudioContext||e.webkitAudioContext,n=this.ctx=new t;if(await Promise.race([n.resume().catch(()=>{}),new Promise(e=>setTimeout(e,Xb))]),fb({audioState:n.state,activated:$b()}))throw Object.assign(Error(Jb),{name:Yb});if(this.liveness.start(Date.now()),n.onstatechange=()=>this.liveness.audio(n.state,Date.now()),this.watchTrack(this.stream),this.source=n.createMediaStreamSource(this.stream),this.sink=n.createGain(),this.sink.gain.value=0,this.sink.connect(n.destination),n.audioWorklet&&`AudioWorkletNode`in window){await n.audioWorklet.addModule(this.opts.workletURL??cx());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 Ry({sampleRate:n.sampleRate,params:Ny(this.sensitivity),onEvents:e=>this.vadEvents(e),onLevel:e=>this.ui.level(e),onChunk:e=>{this.turnAudio.push(e),this.ring?.push(e)},...this.rec?{onNear:e=>{let t=this.rec?.event(`vad.near`,{...e});typeof t==`number`&&this.devClip(`vad.near`,t)},onSummary:e=>this.rec?.event(`vad.summary`,{...e,sensitivity:this.sensitivity}),onTrace:e=>{this.rec?.developer&&this.rec.event(`vad.trace`,{...e,values:[...e.values]})}}:{}});this.detected({mode:`energy`}),this.wantSmartTurn(),wb().then(e=>{this.vad===r&&(e.reset(),r.classifier=t=>e.classify(t),this.detected({mode:`silero`}))},e=>{Kb||console.warn(`Voice: on-device speech detection unavailable (${e?.message??e}); using the energy detector`),Kb=!0}),this.endpointer=new ly({send:e=>void this.deliver(e),onHeld:e=>{this.ui.held?.(e),e&&e!==this.heldText&&this.rec?.event(`utterance.held`,{text:e}),this.heldText=e},onSend:e=>{this.turnAudio.reset(),this.rec?.event(`utterance.sent`,{text:e.text,segments:[...e.segments],reason:e.reason,holdMs:Math.round(e.holdMs)})},...this.rec?{onMerge:e=>this.rec?.event(`utterance.merged`,{segments:[...e.segments],pauseMs:Math.round(e.pauseMs)})}:{},smart:()=>this.opts.turnDetection()===`smart`?this.opts.smartTurnParams():void 0,predict:()=>this.predictTurn(),onPredict:e=>this.turnPredicted(e),mark:()=>this.rec?.marks===!0}),this.queue=new dy({synth:(e,t,n)=>this.synth(e,t,n),play:e=>this.play(e),stop:()=>{this.player.paused||this.player.pause()},onState:e=>{this.guardEcho(),this.scheduler.agentSpeaking(e,Date.now()),e&&this.cuePlayer.stop(),this.cueClock.poke(),this.refresh()},onError:e=>{e?.name!==`AbortError`&&(this.ui.note(`Could not read the reply aloud: ${e?.message}`,`err`),this.rec?.event(`error`,{where:`tts`,message:String(e?.message??e)}))},...this.rec?{now:()=>performance.now(),onPlay:e=>this.playingRef=e.ref,onEnd:(e,t)=>this.sentenceEnded(e,t)}:{}})}wantSmartTurn(){this.smartModel||this.smartLoading||this.smartError||this.opts.turnDetection()!==`smart`||(this.smartLoading=!0,this.opts.smartTurn().then(e=>{this.smartLoading=!1,this.active&&(this.smartModel=e)},e=>{this.smartLoading=!1,this.smartError=String(e?.message??e),this.warnSmart(`Voice: Smart Turn unavailable (${this.smartError}); using the timers`)}))}predictTurn(){if(!this.smartModel)return Promise.reject(Error(this.smartError??`loading`));let e=this.turnAudio.snapshot(),t=0;for(let n=0;n<e.length;n++)t=Math.max(t,Math.abs(e[n]));return t<rx?Promise.reject(Error(`no speech`)):this.smartModel.predict(e)}turnPredicted(e){this.ui.turn?.(k_(e)),this.rec?.event(`turn.predict`,{...e.p===void 0?{}:{p:Math.round(e.p*1e3)/1e3},ms:Math.round(e.ms),silenceMs:Math.round(e.silenceMs),decision:e.decision,...e.error===void 0?{}:{error:e.error}}),e.decision===`timer-fallback`&&e.error&&e.error!==`loading`&&e.error!==`no speech`&&this.warnSmart(`Voice: Smart Turn fell back to the timers (${e.error})`)}warnSmart(e){this.warnedSmart||(this.warnedSmart=!0,this.opts.warn(e))}smartTimings(){if(this.opts.turnDetection()!==`smart`)return{};let e=this.opts.smartTurnParams();return{smartTurn:1,smartThreshold:e.threshold,smartGraceMs:e.graceMs,smartRecheckMs:e.recheckMs,smartFallbackMs:e.fallbackMs,smartSlowMs:e.slowMs}}devClip(e,t){let n=this.rec;if(!n?.developer||!n.clip||!this.ring)return;let r=Date.now();r-this.lastClipAt<mb.gapMs||(this.lastClipAt=r,this.ring.clip(mb.preMs,mb.postMs,(r,i)=>{this.active&&n.clip?.(e,t,$v(r,this.ring.sampleRate),i)}))}detected(e){this.ui.detector?.(e),this.rec?.event(`detector`,e.avgMs===void 0?{mode:e.mode}:{mode:e.mode,avgMs:Math.round(e.avgMs*10)/10})}playerMs(e){let t=this.player.currentTime;return Number.isFinite(t)&&t>0?t*1e3:e}playerDuration(){let e=this.player.duration;return Number.isFinite(e)&&e>0?Math.round(e*1e3):void 0}sentenceEnded(e,t){if(this.playingRef===e.ref&&(this.playingRef=void 0),!e.ref)return;let n=this.playerDuration(),r=t.completed&&this.reachedEnd;this.rec?.event(`tts.sentence.ended`,{ref:e.ref,playedMs:Math.round(this.playerMs(t.playedMs)),...n===void 0?{}:{durationMs:n},completed:r}),r&&(this.spoken.push({ref:e.ref,text:e.text}),this.spoken.length>ax&&this.spoken.shift())}guardEcho(){this.vad&&(this.vad.speaking=!!this.queue?.speaking||this.cueSpeaking)}frame(e){if(!this.active||(this.liveness.frame(Date.now()),!this.vad||this.paused||!this.liveness.live))return;this.wantSmartTurn();let t=this.opts.sensitivity();t!==this.sensitivity&&(this.sensitivity=t,this.vad.params=Ny(t)),this.vad.push(e)}vadEvents(e){let t=this.vad;if(this.active&&t&&!this.paused&&this.liveness.live)for(let n of e){if(n.type===`start`)this.endpointer.busy||this.turnAudio.keepLast(ix),this.rec?.event(`speech.start`,{bargeIn:!!this.queue?.speaking||this.cueSpeaking}),this.endpointer.speechStarted(),this.scheduler.userTalking(!0,Date.now()),this.cuePlayer.stop(),this.queue.speaking?this.hushReplies(`speech`):this.recordBarge(`speech`,void 0,this.says.mute());else{this.speechEndedAt=Date.now(),this.markTurn(`speechEnd`),this.cuePlayer.play(this.scheduler.speechEnded(this.speechEndedAt));let e=this.endpointer.segmentEnded(n.durationMs),r={segment:e,durationMs:Math.round(n.durationMs),speechMs:Math.round(n.speechMs),forced:n.forced};this.rec?.event(`speech.end`,r);let i=$v(n.samples,t.sampleRate);this.rec?.event(`segment.closed`,{...r,bytes:i.byteLength}),this.transcribe(e,i,n.speechMs),this.detected({mode:t.mode,...t.mode===`silero`?{avgMs:t.stats.avgMs}:{}})}this.cueClock.poke(),this.refresh()}}async transcribe(e,t,n){this.inflight++,this.refresh();let r=``,i,a;this.rec?.event(`stt.sent`,{segment:e,bytes:t.byteLength});let o=Date.now(),s=this.rec?setTimeout(()=>this.rec?.event(`stt.slow`,{segment:e,ms:Date.now()-o}),ox):void 0;try{let n=this.rec?.transcribeHeaders(e),i=await this.transport.transcribe(new Blob([t],{type:`audio/wav`}),n?{headers:n}:{});a=this.rec?.audioResult(i.headers),r=i.text??``}catch(e){i=e.message,this.active&&this.ui.note(`Transcription failed: ${i}`,`err`),this.rec?.event(`error`,{where:`stt`,message:String(i)})}finally{clearTimeout(s),this.inflight--}if(!this.active)return;let c=r,l=xb(r,{speechMs:n});l&&(r.trim()&&this.showIgnored(r.trim()),r=``),this.rec&&(this.rec.event(`stt.received`,{segment:e,text:c,...l&&c.trim()?{junk:!0}:{},...!c.trim()&&i===void 0?{empty:!0}:{},...i===void 0?{}:{failed:i},...a?{audio:a}:{},...l&&c.trim()?{junkReason:l}:{},...this.endpointer?.held?{held:this.endpointer.held}:{},speechMs:Math.round(n)}),this.rec.segmentAudio(e,a,t)),r.trim()&&this.markTurn(`transcript`),this.endpointer?.transcribed(e,r),this.refresh()}showIgnored(e){clearTimeout(this.ignoredTimer),this.ui.ignored?.(e),this.ignoredTimer=setTimeout(()=>this.ui.ignored?.(``),Gb)}async deliver(e,t=!1){let n=Uv(e,{mark:this.rec?.marks===!0});if(n&&this.rec?.event(`utterance.command`,{command:n,text:e}),n===`mark`){this.rec?.mark?.(`voice`);return}if(n===`pause`)return this.ui.note(`Paused listening.`),this.stop();if(n===`interrupt`){this.hushReplies(`command`),this.ui.note(`“${e}” — interrupting.`);try{await this.transport.interrupt()}catch(e){this.ui.note(`Could not interrupt: ${e.message}`,`err`),this.rec?.event(`error`,{where:`send`,message:e.message})}return}let r=this.ui.user(e);t&&this.typing++,this.scheduler.awaitReply(t?Date.now():this.speechEndedAt??Date.now()),this.cueClock.poke();try{let{inboxID:n}=await this.transport.utterance(e);this.markTurn(`accepted`),typeof n==`string`&&this.rec?.event(`utterance.accepted`,{inboxID:n}),this.sent.get(n)===`heard`?this.ui.tick(r,`heard`):(this.ui.tick(r,`sent`),t&&this.typed.add(n)),this.sent.set(n,r)}catch(e){let t=e;this.rec?.event(`utterance.failed`,{...typeof t.status==`number`?{status:t.status}:{},message:String(t.message)}),this.ui.tick(r,`failed`),this.ui.note(t.status===409?t.message:`Could not send: ${t.message}`,`err`)}finally{t&&this.typing--}}sendTyped(e){return this.hushReplies(`typed`),this.rec?.event(`utterance.sent`,{text:e,segments:[],reason:`typed`,holdMs:0}),this.deliver(e,!0)}hushReplies(e){let t=this.queue?.clear();this.recordBarge(e,t,this.says.mute())}recordBarge(e,t,n){if(!this.rec)return;let r=t?.playing?.ref?{ref:t.playing.ref,text:t.playing.text,playedMs:this.playerMs(t.playing.playedMs),durationMs:this.playerDuration()}:void 0;this.rec.barge({cause:e,completed:this.spoken,...r?{playing:r.durationMs===void 0?{ref:r.ref,text:r.text,playedMs:r.playedMs}:r}:{},unplayed:(t?.dropped??[]).flatMap(e=>e.ref?[{ref:e.ref,text:e.text}]:[]),mutedMessages:n,turnRunning:no(this.lastStatus)}),this.spoken=[]}onEvent(e){if(e.type===`reset`)return this.reset();if(e.sessionID===this.sessionID){if(e.type===`status`&&typeof e.state==`string`)return this.onStatus([{id:this.sessionID,state:e.state}]);if(e.type===`heard`){typeof e.inboxID==`string`&&this.rec?.event(`heard`,{inboxID:e.inboxID});let t=this.sent.get(e.inboxID);t!==void 0&&t!==`heard`?this.ui.tick(t,`heard`):this.sent.set(e.inboxID,`heard`),this.heardAt=Date.now();let n=this.typed.delete(e.inboxID)||t===void 0&&this.typing>0;this.active&&!this.paused&&this.cuePlayer.play(this.scheduler.heard(this.heardAt,{tone:n})),this.cueClock.poke(),this.refresh(),setTimeout(()=>this.refresh(),2550)}else if(e.type===`say`){if(!this.active)return;let t=this.says.take(e);if(!t)return;if(this.rec){this.rec.event(`say.received`,{messageID:String(e.messageID??``),ordinal:typeof e.ordinal==`number`?e.ordinal:0,chars:String(e.text??``).length,sentences:t.muted?this.says.split(String(e.text??``)).length:t.items.length,muted:t.muted});for(let e of t.items)this.rec.event(`tts.sentence.queued`,{ref:e.ref,text:e.text})}this.scheduler.agentSaid(Date.now()),this.cuePlayer.stop(),this.cueClock.poke(),this.ui.agent({messageID:e.messageID,text:t.text}),t.sentences.length&&this.markTurn(`firstSay`),this.queue?.enqueue(t.items)}else e.type===`conversation`&&e.on&&this.active?typeof e.front==`boolean`&&this.setFront(e.front):e.type===`conversation`&&!e.on&&this.active&&(this.ui.note(`Voice mode was turned off.`),this.stop({post:!1}))}}reset(){this.active&&(this.queue?.clear(),this.cuePlayer.stop(),this.cueClock.poke(),this.refresh())}setFront(e){let t=this.frontWanted&&!e,n=e!==this.front||t!==this.frontFallback;this.front=e,this.frontFallback=t,this.scheduler.phrases=!e,n&&(this.ui.front?.({on:e,fallback:t}),t&&this.ui.note(tx),!e&&this.active&&this.prefetchCues(),this.cueClock.poke())}onStatus(e){let t=Date.now(),{started:n,finished:r}=to(this.lastStatus,e,this.sessionID);if(this.lastStatus=e,this.scheduler.working(no(e),t),this.active){for(let e=0;e<n.length;e++)this.scheduler.subagentStarted(t);r.length&&!this.paused&&this.cuePlayer.play(this.scheduler.subagentFinished(t)),this.cueClock.poke()}}setCues(e){this.rec?.event(`control`,{action:`cues`,on:e}),this.scheduler.enabled=e,e?this.active&&this.prefetchCues():this.cuePlayer.stop(),this.cueClock.poke()}setBackground(e){this.opts.background=e,this.active&&(this.rec?.event(`control`,{action:`background`,on:e}),e?(this.wakeLock?.release().catch(()=>{}),this.wakeLock=void 0,this.startSilence(),this.mediaSession()):(this.stopSilence(),this.clearMediaSession(),this.lockScreen()))}pause(){this.active&&!this.paused&&(this.paused=!0,this.rec?.event(`control`,{action:`pause`}),this.cueClock.stop(),this.hushReplies(`pause`),this.cuePlayer.stop(),this.endpointer?.reset(),this.vad?.reset(),this.turnAudio.reset(),this.stream?.getAudioTracks().forEach(e=>e.enabled=!1),this.silence?.pause(),navigator.mediaSession&&(navigator.mediaSession.playbackState=`paused`),this.ui.level(0),this.refresh())}resume(){this.active&&this.paused&&(this.paused=!1,this.rec?.event(`control`,{action:`resume`}),this.stream?.getAudioTracks().forEach(e=>e.enabled=!0),this.ctx?.resume().catch(()=>{}),this.opts.background&&(this.silence?.play().catch(()=>{}),navigator.mediaSession&&(navigator.mediaSession.playbackState=`playing`)),this.cueClock.poke(),this.refresh())}mediaSession(){navigator.mediaSession&&(navigator.mediaSession.playbackState=this.paused||!this.liveness.live?`paused`:`playing`)}watchTrack(e){this.unwatchTrack();let t=e.getAudioTracks?.()[0];if(t)try{this.rec?.micTrack?.({...t.getSettings?.()??{}},t.label)}catch{}t?.addEventListener&&(this.track=t,t.addEventListener(`mute`,this.onTrackMute),t.addEventListener(`unmute`,this.onTrackUnmute),t.addEventListener(`ended`,this.onTrackEnded),t.muted&&this.liveness.muted(!0,Date.now()),t.readyState===`ended`&&this.liveness.ended(Date.now()))}unwatchTrack(){let e=this.track;this.track=void 0,e?.removeEventListener&&(e.removeEventListener(`mute`,this.onTrackMute),e.removeEventListener(`unmute`,this.onTrackUnmute),e.removeEventListener(`ended`,this.onTrackEnded))}checkMic(){if(!this.active)return;let e=Date.now();this.liveness.tick(e),!(this.liveness.live||document.visibilityState===`visible`||e-this.lastResumeTry<Qb)&&(this.lastResumeTry=e,this.ctx&&this.ctx.state!==`running`&&this.ctx.resume().catch(()=>{}),this.opts.background&&!this.paused&&this.silence?.play().catch(()=>{}))}livenessChanged(e,t){this.active&&(this.rec?.event(`mic`,t?{live:e,reason:t}:{live:e}),e?(clearTimeout(this.recoverTimer),this.recoverTimer=void 0,this.recoverAttempt=0,this.cuePlayer.earcon(`resumed`),this.cueClock.poke()):(this.vad?.reset(),this.turnAudio.reset(),this.ui.level(0),this.cuePlayer.earcon(`paused`),this.lastResumeTry=Date.now(),this.liveness.wantsRecovery&&this.scheduleRecover()),this.opts.background&&this.mediaSession(),this.refresh())}scheduleRecover(){this.recoverTimer===void 0&&this.active&&(this.recoverTimer=setTimeout(()=>{this.recoverTimer=void 0,this.recover()},Hb(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,Xb))])}async reacquire(){let e;try{e=await navigator.mediaDevices.getUserMedia(ey(this.opts.deviceId))}catch(e){if(!this.active)return;fb({error:e.name,micPermission:await ex(),activated:$b()})&&this.ui.note(Jb,`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([$v(new Float32Array(16e3*qb),16e3)],{type:`audio/wav`})),t=new Audio(e);t.loop=!0,t.setAttribute(`aria-hidden`,`true`),this.silence=t,this.silenceURL=e}this.silence.play().catch(()=>{})}stopSilence(){this.silence&&=(this.silence.pause(),this.silence.removeAttribute(`src`),this.silence.load(),this.silenceURL&&URL.revokeObjectURL(this.silenceURL),this.silenceURL=void 0)}hush(){if(this.paused)return this.resume();this.rec?.event(`control`,{action:`hush`}),this.hushReplies(`hush`),this.cuePlayer.stop()}async synth(e,t,n){let r=this.rec?.speakHeaders(n);n&&this.rec?.event(`tts.request`,{ref:n});let i=Ob(await this.transport.speak(e,{signal:t,...r&&Object.keys(r).length?{headers:r}:{}})??null,t);return i.firstByte.then(()=>{this.markTurn(`firstByte`),n&&this.rec?.event(`tts.first.byte`,{ref:n})},()=>{}),i.whole().then(async e=>zb(e,await(this.voiceKey??=this.cueKey()))).catch(()=>{}),i}async play(e){let t=this.player,n=new AbortController,r;try{if(this.streaming){if(await e.firstByte,e.done&&!e.chunks.length)return;let i=new MediaSource;r=URL.createObjectURL(i),t.src=r,this.feedSource(i,e,n.signal)}else{let n=await e.whole();if(!n.length)return;r=URL.createObjectURL(new Blob(n,{type:`audio/mpeg`})),t.src=r}this.reachedEnd=!1;let i=new Promise(e=>{t.onended=()=>{this.reachedEnd=!0,e()},t.onpause=t.onerror=()=>e()});if(!await t.play().then(()=>!0,()=>!1)){this.warnedAutoplay||this.ui.note(`The browser blocked audio playback. Tap the mic to allow it.`),this.warnedAutoplay=!0;return}this.playingRef&&this.rec?.event(`tts.sentence.played`,{ref:this.playingRef}),this.markTurn(`firstAudio`),await i}finally{n.abort(),t.onended=t.onpause=t.onerror=null,r&&URL.revokeObjectURL(r)}}async feedSource(e,t,n){try{if(e.readyState!==`open`&&await new Promise(t=>e.addEventListener(`sourceopen`,t,{once:!0})),n.aborted)return;let r=e.addSourceBuffer(`audio/mpeg`);!await kb(t,{append:e=>new Promise((t,n)=>{r.addEventListener(`updateend`,()=>t(),{once:!0}),r.addEventListener(`error`,()=>n(Error(`Could not decode the reply audio`)),{once:!0}),r.appendBuffer(e)}),end:()=>{e.readyState===`open`&&!r.updating&&e.endOfStream()}},n)&&!n.aborted&&e.readyState===`open`&&!r.updating&&e.endOfStream()}catch{}}markTurn(e){if(!this.turns.mark(e))return;try{performance.mark(nx[e])}catch{}let t=e===`firstAudio`?hy(this.turns.last):void 0;t&&this.ui.timing?.(t);let n=this.turns.last;if(e===`firstAudio`&&n?.firstAudio!==void 0&&this.rec){let e=e=>n[e]===void 0?{}:{[e]:Math.round(n[e]*10)/10};this.rec.event(`turn.timing`,{...e(`speechEnd`),...e(`transcript`),...e(`accepted`),...e(`firstSay`),...e(`firstByte`),firstAudio:Math.round(n.firstAudio*10)/10})}}refresh(){if(!this.active)return;let e=this.paused?`paused`:this.liveness.live?this.queue?.speaking?`speaking`:this.vad?.active?`hearing`:this.inflight>0||this.endpointer?.held?`transcribing`:Date.now()-this.heardAt<Wb?`sent`:`listening`:`suspended`;e!==this.state&&(this.state=e,this.ui.state(e),this.rec?.event(`state`,{state:e}))}async lockScreen(){if(`wakeLock`in navigator&&document.visibilityState===`visible`&&(!this.wakeLock||this.wakeLock.released))try{this.wakeLock=await navigator.wakeLock.request(`screen`),this.rec?.wakeLock?.(!0)}catch{}}release(){this.unwatchTrack(),this.stream?.getTracks().forEach(e=>e.stop()),this.stream=void 0}async stop({post:e=!0,keepalive:t=!1}={}){this.attempt++,this.unfollow();let n=this.active;this.active=!1,this.paused=!1,this.state=void 0,document.removeEventListener(`visibilitychange`,this.onVisibility),window.removeEventListener?.(`pageshow`,this.onWake),window.removeEventListener?.(`focus`,this.onWake),clearInterval(this.micTimer),clearTimeout(this.recoverTimer),this.micTimer=this.recoverTimer=void 0,this.recoverAttempt=0,this.ctx&&(this.ctx.onstatechange=null),this.cueClock.stop(),this.cuePlayer.close(),this.stopSilence(),this.opts.background&&this.clearMediaSession(),this.hushReplies(`stop`),this.endpointer?.reset(),this.vad?.reset(),this.turnAudio.reset(),(this.front||this.frontFallback)&&this.ui.front?.({on:!1,fallback:!1}),this.front=this.frontWanted=this.frontFallback=!1,this.scheduler.phrases=!0,this.smartModel=void 0,this.smartError=void 0,this.warnedSmart=!1;try{this.source?.disconnect(),this.tap?.disconnect(),this.tap&&`port`in this.tap&&(this.tap.port.onmessage=null),this.sink?.disconnect()}catch{}this.ctx?.close().catch(()=>{}),this.ctx=this.source=this.tap=this.sink=this.vad=void 0,this.release(),this.wakeLock&&this.rec?.wakeLock?.(!1),this.wakeLock?.release().catch(()=>{}),this.wakeLock=void 0,this.ring?.reset(),this.ui.level(0),this.ui.held?.(``),this.ui.turn?.(``),clearTimeout(this.ignoredTimer),this.ui.ignored?.(``),this.ui.state(`off`),this.ui.ended(),this.rec&&(this.rec.event(`state`,{state:`off`}),this.rec.stop({keepalive:t,reason:e?`stopped`:`conversation_off`})),e&&n&&await this.transport.conversation(!1,t?{keepalive:t}:void 0).catch(()=>{})}};function ux({api:e,sessionID:t,events:n}){let r=`/api/sessions/${encodeURIComponent(t)}`;return{async conversation(t,n){let i=n?.front===void 0?{on:t}:{on:t,front:n.front},a=await e(`${r}/conversation`,{method:`POST`,json:i,...n?.keepalive===void 0?{}:{keepalive:n.keepalive}});return t?a.json():{on:t}},async utterance(t){return(await e(`${r}/utterance`,{method:`POST`,json:{text:t}})).json()},async interrupt(){await e(`${r}/interrupt`,{method:`POST`,json:{}})},async transcribe(t,n){let r=await e(`/api/transcribe`,{method:`POST`,body:t,headers:{"content-type":t.type||`audio/wav`,...n?.headers},...n?.signal?{signal:n.signal}:{}}),{text:i}=await r.json();return{text:i??``,headers:r.headers}},async speak(t,n){let r=n?.headers;return(await e(`/api/speak`,{method:`POST`,json:{text:t},...n?.signal?{signal:n.signal}:{},...r&&Object.keys(r).length?{headers:{...r}}:{}})).body},events:n??(()=>()=>{})}}async function dx(e){try{let{tts:t}=await(await e(`/api/settings/speech`)).json();return t?.voice?[t.provider,t.model,t.voice,t.speed??``,t.baseURL??``].join(`|`):void 0}catch{return}}function fx(e,t){return n=>e.subscribe(e=>`sessionID`in e&&e.sessionID===t&&n(e))}var px=class extends lx{constructor({sessionID:e,api:t,events:n,player:r,ui:i,options:a={}}){super({sessionID:e,transport:ux({api:t,sessionID:e,...n?{events:n}:{}}),player:r,ui:i,options:{speakable:Bn,voiceKey:()=>dx(t),workletURL:`/vad-worklet.js`,...a}})}},[mx,hx]=u(Date.now());setInterval(()=>xu()&&hx(Date.now()),1e3);var[gx,_x]=u(!1),vx=e=>_x(e),yx=()=>Vs(su(),xu(),Math.max(mx(),Date.now())),bx=(e,t)=>su().find(t=>t.id===e)?.options.find(e=>e.id===t)?.label??t;async function xx(e,t,n){let r=bx(e,t);try{let{decision:i}=await(await V(`/api/decisions/${K(e)}/answer`,{method:`POST`,json:{option:t,...n?{via:n}:{}}})).json().catch(()=>({}));i?Od(i):kd(e),q(`Answered “${r}”${n?` by ${n}`:``}`)}catch(t){throw t instanceof W&&t.status===409&&t.code===`gone`?(kd(e),new W(409,`Already answered or expired`)):t}}function Sx(e){return ec(V,{sessionID:e,current:()=>mu()?.sessionID,armed:()=>yx(),present:()=>gx()&&document.visibilityState===`visible`,answer:async(e,t)=>{try{await xx(e,t,`voice`),Kl(`decision.voice`,{decisionID:e,option:t,outcome:`answered`})}catch(n){let r=n instanceof W&&n.status===403;throw Kl(`decision.voice`,{decisionID:e,option:t,outcome:r?`refused`:`failed`}),Object.assign(Error(r?`Not answered by voice: ${n.message}. Tap an option on the card.`:`Not answered: ${n instanceof Error?n.message:String(n)}`),{status:409})}}})}var Cx=new M_,wx=new n_({async expose(e){let t=()=>Fu(e)?.session.exposed!==!1;if(t())return!0;if(!await Vd(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 px({sessionID:e,api:Sx(e),events:fx(Cx,e),player:ob,ui:t,options:{cues:Jy.cues,background:Jy.background,speed:()=>Jy.speed,sensitivity:()=>Jy.sensitivity,turnDetection:()=>Jy.turnDetection,smartTurnParams:()=>Jy.smartTurn,front:()=>Jy.front,title:()=>Fu(e)?.session.title||`OpenCode session`,status:Fu(e)?.session.status,deviceId:sb()||void 0,recorder:new ql}}),stopPlayback:()=>{ob.paused||ob.pause()},notify:(e,t)=>q(e,t===`err`?`err`:``)}),[Tx,Ex]=u(0);wx.subscribe(()=>Ex(e=>e+1)),j_({mode:Jy.turnDetection,load:p_});var Dx=`voice-mode`,Ox=Promise.resolve(),kx=e=>{Ox=Ox.then(async()=>{let t=`serviceWorker`in navigator?await navigator.serviceWorker.getRegistration(`/`):void 0;t&&await e(t)}).catch(()=>{})},Ax={allowed:()=>`Notification`in window&&Notification.permission===`granted`&&`serviceWorker`in navigator,show:e=>kx(t=>t.showNotification(e.title,{body:e.body,tag:Dx,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:()=>kx(async e=>(await e.getNotifications({tag:Dx})).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{}}},jx=new c_(wx,Ax,{title:e=>Fu(e)?.session.title||`OpenCode session`,suffix:()=>Pl(Ml.get())});Ml.subscribe(()=>jx.refresh()),pp(e=>{e?.type===`voice-end`&&typeof e.sessionID==`string`&&jx.endFromNotification(e.sessionID)});function Mx(){return Tx(),jx.needsPermission()}async function Nx(){try{await op()}catch(e){q(e instanceof Error?e.message:String(e),`err`)}jx.refresh(),Ex(e=>e+1)}function Px(){return Tx(),wx.state}var Fx=()=>{let e=Px().sessionID;return e?Fu(e)?.session.title||`Session`:``};Nu(e=>{e.type===`say`||e.type===`heard`||e.type===`conversation`?Cx.emit(e):e.type===`status`&&typeof e.sessionID==`string`&&Array.isArray(e.sessions)&&wx.onStatus(e.sessionID,e.sessions)}),window.addEventListener(`pagehide`,()=>{wx.stop({keepalive:!0}),Ax.close()});var Ix=new Q_,Lx=new e_({record:e=>ub(e),deliver:(e,t)=>void Ix.append(e,t),notify:(e,t)=>q(e,t),hold:()=>wx.hold()}),[Rx,zx]=u(0);Lx.subscribe(()=>zx(e=>e+1));function Bx(e){return Rx(),Lx.forSession(e)}var Vx=I(`<div class=banner><span></span><a class="btn small"href=/settings/machines>Review`),Hx=I(`<div class=banner><span><strong>Set up speech</strong> · </span><a class="btn small"href=/settings/voice#speech>Set up`),Ux=I(`<section class=decisions aria-label=Decisions><h2 class=section-title>`),Wx=I(`<select aria-label=Server><option value>All servers`),Gx=I(`<select class=chip-window aria-label="Touched within">`),Kx=I(`<div class=bulk-bar role=region aria-label="Selected sessions"><span> selected</span><button type=button class="btn small"></button><button type=button class="btn small">Clear selection`),qx=I(`<div class=empty><p class=display>No machines yet</p><p class=muted>In OpenCode run /hub → Connect to a hub…, then approve it here.`),Jx=I(`<ul class=home-list>`),Yx=I(`<div class=home><header class=home-head><h1 class=display>All sessions</h1><a class="btn primary"href=/new> New session</a></header><div class=home-tools><label class=search><input type=search placeholder="Search title, project, folder or server"aria-label="Search sessions"></label><button type=button class="btn small">Archive inactive…</button></div><div class=chips role=group aria-label=Filters><button type=button class=chip data-chip=touched title="Sessions you prompted, spoke to, answered or opened">Touched by me</button></div><p class="count muted"role=status>`),Xx=I(`<option>`),Zx=I(`<button type=button class=chip>`),Qx=I(`<p class="muted small offline-line"><strong></strong> · offline · seen `),$x=I(`<form class=archive-inactive><label class=field><span>Inactive for more than (days)</span><input type=number min=1 step=1 inputmode=numeric></label><p class="muted small"> without activity for more than <!> (not running, pinned or open in a terminal). Archived sessions leave your lists on every device; nothing is deleted and you can unarchive them under Archived.</p><div class=dialog-actions><button type=button class=btn>Cancel</button><button type=submit class="btn primary">`),eS=I(`<table class=sessions-table><thead><tr><th class=col-pick><input type=checkbox aria-label="Select all shown sessions"></th><th class=col-now>Now</th><th class=col-actions><span class=sr-only>Actions</span></th></tr></thead><tbody>`),tS=I(`<th><button type=button class=th-btn><span class=sort-mark aria-hidden=true>`),nS=I(`<tr><td colspan=11 class="muted empty-cell">No sessions match.`),rS=I(`<span class=jobs-badge>`),iS=I(`<a>`),aS=I(`<span class=unread-dot role=img aria-label=Unread>`),oS=I(`<tr><td class=col-pick><input type=checkbox></td><td class=col-status><span class=sr-only></span></td><td class=col-title></td><td class=col-project></td><td class=col-server><span></span></td><td class=col-source></td><td class=col-busy></td><td class=col-touched></td><td class=col-activity></td><td></td><td class=col-actions>`),sS=I(`<span class=row-sub data-row-sub>`),cS=I(`<span class=waiting-since>`),lS=I(`<a class=home-item-link><span class=home-item-text><span class=home-item-title></span><span>`),uS=I(`<li>`),dS=I(`<span class=home-item-link>`),fS=I(`<span class="home-item-sub muted"data-row-sub>`),pS=`hub.table`;function mS(e){$l();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=Xl.has(e.id)?Xl.feed(e.id):void 0,r=n?.pulse(),i=e.jobs?` · ${qi(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: ${qi(e.jobs)}`:`Working`}var hS=[[`status`,`Status`],[`title`,`Title`],[`project`,`Project`],[`server`,`Server`],[`source`,`Open in`],[`busy`,`24 h`],[`touched`,`Last touched`],[`activity`,`Last activity`]],gS={busy:`Activity in the last 24 h (sort: most active). Upper bars: the agent; lower marks: you`,touched:`When you last prompted, spoke to, answered or opened the session`},_S={"1h":`1 h`,"24h":`24 h`,"7d":`7 days`},vS=[[`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}]],yS={touched:`24h`};function bS(){let[e,t]=u(Oa(localStorage.getItem(pS))),[i,a]=u(``),o=e=>{t(e),localStorage.setItem(pS,ka(e))},c=C(()=>Ea(Pu(),{...e(),query:i()},N())),[d,f]=u(new Set),p=C(()=>c().filter(e=>d().has(e.id))),h=(e,t)=>{let n=new Set(d());t?n.add(e):n.delete(e),f(n)},g=e=>f(e?new Set(c().map(e=>e.id)):new Set),_=()=>{Hh(p(),!e().filters.archived),f(new Set)},[v,x]=u(!1),S=()=>Y.machines??[],w=t=>Object.keys(t).every(n=>e().filters[n]===t[n]),T=t=>{let n=e().filters,r=Object.fromEntries(Object.keys(t).map(e=>[e,ga.filters[e]]));o({...e(),filters:w(t)?{...n,...r}:{...n,...t}})},E=t=>{let n=e().sort;o({...e(),sort:{key:t,dir:n.key===t?n.dir===`asc`?`desc`:`asc`:t===`activity`||t===`touched`||t===`busy`?`desc`:`asc`}})},D=()=>fo(ru()??void 0,X()?.publicURL);return(()=>{var t=Yx(),u=t.firstChild,f=u.firstChild.nextSibling,C=f.firstChild,O=u.nextSibling,k=O.firstChild,A=k.firstChild,j=k.nextSibling,M=O.nextSibling,ee=M.firstChild,P=M.nextSibling;return y(f,n(L,{name:`plus`}),C),y(t,n(l,{get when(){return au().length},get children(){var e=Vx(),t=e.firstChild;return y(t,(()=>{var e=r(()=>au().length===1);return()=>e()?`${au()[0].machineName} wants to connect.`:`${au().length} machines want to connect.`})()),e}}),O),y(t,n(l,{get when(){return D()},get children(){var e=Hx(),t=e.firstChild;return t.firstChild.nextSibling,y(t,()=>D().reason,null),e}}),O),y(t,n(l,{get when(){return su().length},get children(){var e=Ux(),t=e.firstChild;return y(t,(()=>{var e=r(()=>su().length===1);return()=>e()?`A decision waits for you`:`${su().length} decisions wait for you`})()),y(e,n(Kg,{get decisions(){return su()},showSession:!0}),null),e}}),O),y(k,n(L,{name:`search`}),A),A.$$input=e=>a(e.currentTarget.value),j.$$click=()=>x(!0),y(O,n(l,{get when(){return S().length>1},get children(){var t=Wx();return t.firstChild,t.addEventListener(`change`,t=>o({...e(),filters:{...e().filters,machine:t.currentTarget.value}})),y(t,n(m,{get each(){return S()},children:e=>(()=>{var t=Xx();return y(t,()=>e.name),s(()=>t.value=e.id),t})()}),null),s(()=>t.value=e().filters.machine),t}}),null),ee.$$click=()=>o({...e(),filters:{...e().filters,touched:e().filters.touched?``:yS.touched}}),y(M,n(l,{get when(){return e().filters.touched},get children(){var t=Gx();return t.addEventListener(`change`,t=>o({...e(),filters:{...e().filters,touched:t.currentTarget.value}})),y(t,n(m,{each:ma,children:e=>(()=>{var t=Xx();return t.value=e,y(t,()=>`within ${_S[e]}`),t})()})),s(()=>t.value=e().filters.touched),t}}),null),y(M,n(m,{each:vS,children:([e,t,n])=>(()=>{var r=Zx();return r.$$click=()=>T(n),b(r,`data-chip`,e),y(r,t),s(()=>b(r,`aria-pressed`,w(n))),r})()}),null),y(t,n(l,{get when(){return p().length},get children(){var t=Kx(),n=t.firstChild,r=n.firstChild,i=n.nextSibling,a=i.nextSibling;return y(n,()=>p().length,r),i.$$click=_,y(i,()=>e().filters.archived?`Unarchive`:`Archive`),a.$$click=()=>g(!1),t}}),P),y(P,(()=>{var t=r(()=>Y.machines===void 0);return()=>t()?`Loading…`:Fa(c().length,Pu().filter(e=>!e.hidden).length,su().length,e().filters.status===`needs`)})()),y(t,n(l,{get when(){return r(()=>!!Y.machines)()&&Y.machines.length===0},get children(){return qx()}}),null),y(t,n(l,{get when(){return Z()},get fallback(){return n(CS,{get rows(){return c()},get table(){return e()},sortBy:E,get picked(){return d()},pick:h,pickAll:g})},get children(){var e=Jx();return y(e,n(m,{get each(){return c()},children:e=>n(wS,{row:e})})),e}}),null),y(t,n(m,{get each(){return S().filter(e=>!e.online)},children:e=>(()=>{var t=Qx(),n=t.firstChild;return n.nextSibling,y(n,()=>e.name),y(t,()=>R(e.lastSeen,N()),null),t})()}),null),y(t,n(SS,{get open(){return v()},get rows(){return Pu()},onClose:()=>x(!1)}),null),s(()=>b(ee,`aria-pressed`,e().filters.touched!==``)),s(()=>A.value=i()),t})()}var xS=30;function SS(e){let[t,i]=u(String(xS)),a=C(()=>e.open?Na(e.rows,Number(t()),N()):[]),o=()=>a().length,c=()=>{Hh(a(),!0),e.onClose()};return n(de,{get open(){return e.open},title:`Archive inactive sessions`,get onClose(){return e.onClose},get children(){var n=$x(),a=n.firstChild,l=a.firstChild.nextSibling,u=a.nextSibling,d=u.firstChild,f=d.nextSibling;f.nextSibling;var p=u.nextSibling.firstChild,m=p.nextSibling;return n.addEventListener(`submit`,e=>{e.preventDefault(),o()&&c()}),l.$$input=e=>i(e.currentTarget.value),y(u,(()=>{var e=r(()=>o()===1);return()=>e()?`1 session`:`${o()} sessions`})(),d),y(u,(()=>{var e=r(()=>Number(t())===1);return()=>e()?`1 day`:`${t()||`?`} days`})(),f),B(p,`click`,e.onClose,!0),y(m,(()=>{var e=r(()=>o()===1);return()=>e()?`Archive 1 session`:`Archive ${o()} sessions`})()),s(()=>m.disabled=!o()),s(()=>l.value=t()),n}})}function CS(e){let t=()=>e.rows.length>0&&e.rows.every(t=>e.picked.has(t.id)),i=t=>e.table.sort.key===t?e.table.sort.dir===`asc`?`ascending`:`descending`:`none`;return(()=>{var a=eS(),o=a.firstChild,c=o.firstChild,u=c.firstChild,d=u.firstChild,f=u.nextSibling,p=o.nextSibling;return d.addEventListener(`change`,t=>e.pickAll(t.currentTarget.checked)),y(c,n(m,{each:hS,children:([t,n])=>(()=>{var a=tS(),o=a.firstChild,c=o.firstChild;return k(a,`col-${t}`),o.$$click=()=>e.sortBy(t),y(o,n,c),y(c,(()=>{var n=r(()=>e.table.sort.key===t);return()=>n()?e.table.sort.dir===`asc`?`↑`:`↓`:``})()),s(e=>{var n=i(t),r=gS[t];return n!==e.e&&b(a,`aria-sort`,e.e=n),r!==e.t&&b(o,`title`,e.t=r),e},{e:void 0,t:void 0}),a})()}),f),y(p,n(m,{get each(){return e.rows},get fallback(){return nS()},children:t=>(()=>{var i=oS(),a=i.firstChild,o=a.firstChild,c=a.nextSibling,u=c.firstChild,d=c.nextSibling,f=d.nextSibling,p=f.nextSibling,m=p.firstChild,h=p.nextSibling,g=h.nextSibling,_=g.nextSibling,v=_.nextSibling,x=v.nextSibling,S=x.nextSibling;return i.$$click=e=>!e.target.closest(`button,a,select,input`)&&Vt(Ot(t.id)),o.addEventListener(`change`,n=>e.pick(t.id,n.currentTarget.checked)),y(c,n(A,{get state(){return t.state}}),u),y(u,()=>ue[t.state]),y(c,n(l,{get when(){return t.error},children:e=>n(ie,{get text(){return e()}})}),null),y(c,n(l,{get when(){return t.jobs},get children(){var e=rS();return y(e,()=>t.jobs),s(n=>{var r=qi(t.jobs),i=qi(t.jobs);return r!==n.e&&b(e,`title`,n.e=r),i!==n.t&&b(e,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),e}}),null),y(d,n(l,{get when(){return Pa(t,Px())},get children(){return n(ne,{})}}),null),y(d,n(Zg,{get id(){return t.id},get title(){return t.title},place:`table`,get children(){var e=iS();return y(e,()=>t.title),s(()=>b(e,`href`,Ot(t.id))),e}}),null),y(d,n(Qg,{get id(){return t.id}}),null),y(d,n(l,{get when(){return t.unread},get children(){return aS()}}),null),y(d,n(l,{get when(){return Ra(t)},children:e=>(()=>{var t=sS();return y(t,e),s(()=>b(t,`title`,e())),t})()}),null),y(f,()=>t.where),y(m,()=>t.machineName),y(h,()=>oe[t.source]),y(g,n(Kf,{get buckets(){return t.meter},get now(){return N()}})),y(_,(()=>{var e=r(()=>!!t.touchedKindAt);return()=>e()?da(t.touchedKind,t.touchedKindAt,N()):``})()),y(v,()=>R(t.updated,N())),y(x,n(l,{get when(){return za(t,N())},children:e=>(()=>{var t=cS();return y(t,e),s(()=>b(t,`title`,`Waiting for you for ${e()}`)),t})()}),null),y(x,()=>mS(t),null),y(S,n(O,{get label(){return`More actions for ${t.title}`},class:`icon-btn small`,items:()=>Uh(t,{place:`table`})})),s(e=>{var n=`${t.unread?`unread`:``}`,r=`Select ${t.title}`,a=t.directory,s=t.machineOnline?``:`muted`,c=t.touchedKindAt?ua(t.touchedKind,t.touchedKindAt,N()):`Not touched by you in 30 days`,l=`col-now ${t.error?`error`:`muted`}`,u=t.error;return n!==e.e&&k(i,e.e=n),r!==e.t&&b(o,`aria-label`,e.t=r),a!==e.a&&b(f,`title`,e.a=a),s!==e.o&&k(m,e.o=s),c!==e.i&&b(_,`title`,e.i=c),l!==e.n&&k(x,e.n=l),u!==e.s&&b(x,`title`,e.s=u),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),s(()=>o.checked=e.picked.has(t.id)),i})()})),s(()=>d.checked=t()),a})()}function wS(e){let t=()=>e.row;return(()=>{var e=uS();return y(e,n(l,{get when(){return!Vh(t().id,`phone`)},get fallback(){return(()=>{var e=dS();return y(e,n(A,{get state(){return t().state}}),null),y(e,n(Zg,{get id(){return t().id},get title(){return t().title},place:`phone`,children:null}),null),e})()},get children(){var e=lS(),r=e.firstChild,i=r.firstChild,a=i.nextSibling;return y(e,n(A,{get state(){return t().state}}),r),y(e,n(l,{get when(){return t().error},children:e=>n(ie,{get text(){return e()}})}),r),y(i,n(l,{get when(){return Pa(t(),Px())},get children(){return n(ne,{})}}),null),y(i,()=>t().title,null),y(i,n(Qg,{get id(){return t().id}}),null),y(i,n(l,{get when(){return t().unread},get children(){return aS()}}),null),y(r,n(l,{get when(){return Ra(t())},children:e=>(()=>{var t=fS();return y(t,e),t})()}),a),y(a,n(l,{get when(){return za(t(),N())},children:e=>(()=>{var t=cS();return y(t,e),t})()}),null),y(a,()=>mS(t())||`${t().where} · ${t().machineName} · ${t().touchedKindAt?ua(t().touchedKind,t().touchedKindAt,N()):R(t().updated,N())}`,null),s(n=>{var r=Ot(t().id),i=`home-item-meta ${t().error?`error`:`muted`}`;return r!==n.e&&b(e,`href`,n.e=r),i!==n.t&&k(a,n.t=i),n},{e:void 0,t:void 0}),e}}),null),y(e,n(O,{get label(){return`More actions for ${t().title}`},class:`icon-btn small`,items:()=>Uh(t(),{place:`phone`})}),null),s(()=>k(e,`home-item${t().unread?` unread`:``}`)),e})()}z([`input`,`click`]);var TS=I(`<div role=separator aria-orientation=vertical tabindex=0>`);function ES(e){let t=0,n=0,r=0,i,a=()=>nm()[e.panel],o=()=>rm(e.panel),c=()=>{r=0,i!==void 0&&im(e.panel,i,!1)},l=()=>{r&&cancelAnimationFrame(r),r=0,i=void 0,$p(void 0),document.documentElement.classList.remove(`resizing`)},u=(t,n,r)=>{t.hasPointerCapture(n)&&t.releasePointerCapture(n),l(),im(e.panel,r)};return fe(()=>e.panel===`rail`&&Zp(!0)),M(()=>{e.panel===`rail`&&Zp(!1),Qp()===e.panel&&l()}),(()=>{var l=TS();return l.$$keydown=t=>{let n=Dp(e.panel,a(),t.key,t.shiftKey,o());n!==void 0&&(t.preventDefault(),im(e.panel,n))},l.$$dblclick=()=>im(e.panel,xp[e.panel].default),l.addEventListener(`pointercancel`,t=>Qp()===e.panel&&u(t.currentTarget,t.pointerId,i??a())),l.$$pointerup=t=>Qp()===e.panel&&u(t.currentTarget,t.pointerId,i??a()),l.$$pointermove=a=>{if(Qp()!==e.panel)return;let s=Op(e.panel,t,a.clientX-n,o());`collapse`in s?(u(a.currentTarget,a.pointerId,t),Up(!0)):(i=s.width,r||=requestAnimationFrame(c))},l.$$pointerdown=r=>{r.button===0&&(r.preventDefault(),r.currentTarget.setPointerCapture(r.pointerId),t=a(),n=r.clientX,$p(e.panel),document.documentElement.classList.add(`resizing`))},s(t=>{var n=`panel-handle${Qp()===e.panel?` dragging`:``}`,r=e.panel,i=e.label,s=a(),c=o().min,u=o().max;return n!==t.e&&k(l,t.e=n),r!==t.t&&b(l,`data-panel`,t.t=r),i!==t.a&&b(l,`aria-label`,t.a=i),s!==t.o&&b(l,`aria-valuenow`,t.o=s),c!==t.i&&b(l,`aria-valuemin`,t.i=c),u!==t.n&&b(l,`aria-valuemax`,t.n=u),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),l})()}z([`pointerdown`,`pointermove`,`pointerup`,`dblclick`,`keydown`]);var DS={service:`background service`,standalone:`standalone`};function OS(e){return(e??[]).map(e=>{let t=!!e.online,n=e.processes.find(e=>e.kind===`service`)??e.processes[0],r=t?n?[DS[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 kS(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 AS(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 jS(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:AS(e,i?.machine===t?{key:i.key,dir:i.dir}:{},a?.machine===t?a:void 0)??o}function MS(e,t){let n=Ur(t).split(/\s+/).filter(Boolean);return n.length?e.filter(e=>{let t=[e.label,...e.directories].map(Ur);return n.every(e=>t.some(t=>t.includes(e)))}):[...e]}var NS=`hub.newSession`;function PS(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 FS(e,t){try{e.setItem(NS,JSON.stringify({machine:t.machine,key:t.key,dir:t.dir}))}catch{}}var IS=`hub.railCollapsed`;function LS(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 RS(e,t){let n=LS(e);n.has(t)?n.delete(t):n.add(t);try{e.setItem(IS,JSON.stringify([...n]))}catch{}return n}var zS=0,BS=e=>e.reduce((e,t)=>e+t.data.length,0);async function VS(e,t){let n=V_(t.length,e.type);if(n)throw Error(n);let r=await HS(e);try{let n=e.type!==`image/jpeg`&&WS(r),{blob:i,request:a}=await G_({width:r.width,height:r.height,keepPng:n},H_(BS(t)),e=>GS(r,e)),o=await KS(i);return{id:`img${++zS}`,mime:a.type,data:o.slice(o.indexOf(`,`)+1),name:W_(e.name||`image`,a.type),preview:URL.createObjectURL(i)}}finally{`close`in r&&r.close()}}async function HS(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 US(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 WS(e){let t=Math.max(1,Math.min(64,e.width)),n=Math.max(1,Math.min(64,e.height)),[,r]=US(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 GS(e,t){let[n,r]=US(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 KS(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 qS(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 JS=new Map;function YS(e,t){JS.set(e,t)}function XS(e){let t=JS.get(e);return JS.delete(e),t}var ZS=I(`<li class="attachment busy"aria-label="Preparing image"><span class="spinner small">`),QS=I(`<ul class=attachments aria-label="Attached images">`),$S=I(`<span class="spinner small">`),eC=I(`<form class="composer new-composer"><div class=composer-box><textarea rows=3 aria-label="Describe a task or ask a question"placeholder="Describe a task or ask a question"></textarea><input type=file class=sr-only tabindex=-1 aria-hidden=true data-testid=new-attach-input multiple><div class=composer-actions><button type=button class=icon-btn aria-label="Attach images"></button><span class=grow></span><button type=submit class="send icon-send"aria-label="Start session">`),tC=I(`<span class="meta-chip readonly"title="Branch of this folder"><span class="chip-text mono">`),nC=I(`<label class="meta-chip toggle-chip"><input type=checkbox><span class=chip-text>Open in Herdr tab`),rC=I(`<div class=env-meta role=group aria-label="Where the session runs">`),iC=I(`<p data-new-dir>`),aC=I(`<p class="small new-need-project"role=alert data-need-project>Choose a project first: the session starts in one of <!>'s folders.`),oC=I('<p class="small warn"> has no background service connected; start `opencode serve --service` there to create sessions.'),sC=I(`<p class=error role=alert>`),cC=I(`<div class=new-session><header class=topbar><h1 class=title>New session</h1></header><div class="column narrow new-column"><p class="display greeting">What should we work on?`),lC=I(`<p class=muted>No machine is connected to this hub yet.`),uC=I(`<li class=attachment><img><button type=button class=attachment-remove>`),dC=I(`<span aria-hidden=true>`),fC=I(`<span class=chip-text>`),pC=I(`<button type=button aria-haspopup=dialog aria-label="Choose project folder"><span class=chip-text>`),mC=I(`<div class="menu folder-menu"role=dialog aria-label="Choose project folder"><input class=folder-search type=search placeholder="Search folders"aria-label="Search folders"><div class=folder-list role=listbox aria-label=Folders>`),hC=I(`<p class="muted small pad">No folder matches.`),gC=I(`<div class=menu-section> · Herdr`),_C=I(`<button type=button role=option class=menu-item><span class=menu-check></span><span class=menu-label></span><span class="menu-hint mono">`);function vC(e){let i=PS(localStorage),a=()=>Y.machines??[],o=C(()=>OS(a())),[c,f]=u(),p=()=>{let t=c();return t&&o().some(e=>e.id===t&&e.online)?t:kS(o(),e.machine,i?.machine)},h=()=>o().find(e=>e.id===p()),g=()=>a().find(e=>e.id===p()),_=C(()=>{let t=g();if(!t)return[];let n=Di(t).targets;return e.key&&e.dir&&t.id===e.machine&&!n.some(t=>t.key===e.key)&&n.push({kind:`folder`,key:e.key,label:j(e.dir),directories:[e.dir]}),n}),[v,x]=u(),[S,w]=u(!1),T=()=>jS(_(),p(),{...v()?{chosen:v()}:{},switched:S(),linked:{machine:e.machine,key:e.key,dir:e.dir},...i?{remembered:i}:{}}),E=()=>_().find(e=>e.key===T()?.key),D=e=>e.directories.length?e.directories:_().filter(e=>e.kind===`folder`).flatMap(e=>e.directories),A=()=>{let e=T(),t=E();return!e||!t?``:e.dir&&D(t).includes(e.dir)?e.dir:D(t)[0]??``},M=(e,t)=>e?.processes.flatMap(e=>e.sessions).filter(e=>!e.parentID&&e.directory===t).sort((e,t)=>(t.updated??0)-(e.updated??0))[0],[N]=d(()=>{let e=M(g(),A());return e?e.id:void 0},async e=>(await G(`${H(e)}/summary`).catch(()=>({}))).branch),[ee,P]=u(!0),te=()=>!!h()?.herdr&&E()?.kind===`herdr`&&ee(),[I,ne]=u(``),[re,ie]=u([]),[ae,oe]=u(!1),[se,ce]=u(``),[le,ue]=u(!1),de=Promise.resolve(),R=e=>{de=de.then(async()=>{oe(!0);try{for(let t of e)try{let e=await VS(t,re());ie(t=>[...t,e])}catch(e){ce(U(e))}}finally{oe(!1)}})},pe=()=>!le()&&!ae()&&!!h()?.canCreate&&!!A()&&(!!I().trim()||re().length>0),[me,z]=u(!1),B,he=async()=>{let e=h(),t=E(),n=A();if(!n&&e&&!le()&&(I().trim()||re().length>0))z(!0),B?.focus();else if(pe()&&e&&t){ue(!0),ce(``);try{let r=Oi({target:t,directory:n,openInHerdr:te()}),i=await(await V(`/api/machines/${K(e.id)}/sessions`,{method:`POST`,json:r})).json();FS(localStorage,{machine:e.id,key:t.key,dir:n}),YS(i.sessionID,{text:I().trim(),images:re()}),Vt(Ot(i.sessionID),{replace:!0}),i.warning?q(`Session created, but Herdr didn't open it: ${i.warning}`,`warn`):i.openedIn===`herdr`&&q(`Opened in Herdr · ${t.label}`)}catch(t){ce(t instanceof W&&t.status===409?`The background service on ${e.name} isn't connected. Start it, then try again.`:`Could not create the session: ${U(t)}`),ue(!1)}}},ge=()=>[{section:`Choose environment`},...o().map(e=>({label:e.name,hint:e.online?e.canCreate?e.detail:`${e.detail} · no background service`:`offline`,checked:e.id===p(),disabled:e.disabled,run:()=>{e.id!==p()&&(w(!0),x(void 0),f(e.id))}}))],_e,ve;fe(()=>_e?.focus());let ye=()=>{_e.style.height=`auto`,_e.style.height=`${Math.min(_e.scrollHeight,320)}px`};return(()=>{var e=cC(),i=e.firstChild,a=i.firstChild,c=i.nextSibling;return c.firstChild,y(i,n(l,{get when(){return Z()},get children(){return n(F,{icon:`menu`,label:`Open sidebar`,onClick:Gp})}}),a),y(c,n(l,{get when(){return o().length},get fallback(){return lC()},get children(){return[(()=>{var e=eC(),r=e.firstChild,i=r.firstChild,a=i.nextSibling,o=a.nextSibling.firstChild,c=o.nextSibling.nextSibling;e.addEventListener(`drop`,e=>{let t=qS(e.dataTransfer);t.length&&(e.preventDefault(),R(t))}),e.addEventListener(`dragover`,e=>[...e.dataTransfer?.types??[]].includes(`Files`)&&e.preventDefault()),e.addEventListener(`submit`,e=>{e.preventDefault(),he()}),y(r,n(l,{get when(){return re().length||ae()},get children(){var e=QS();return y(e,n(m,{get each(){return re()},children:e=>(()=>{var t=uC(),r=t.firstChild,i=r.nextSibling;return i.$$click=()=>ie(t=>t.filter(t=>t.id!==e.id)),y(i,n(L,{name:`close`})),s(t=>{var n=e.preview,a=e.name,o=e.name,s=`Remove ${e.name}`;return n!==t.e&&b(r,`src`,t.e=n),a!==t.t&&b(r,`alt`,t.t=a),o!==t.a&&b(r,`title`,t.a=o),s!==t.o&&b(i,`aria-label`,t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),null),y(e,n(l,{get when(){return ae()},get children(){return ZS()}}),null),e}}),i),i.$$keydown=e=>{e.key===`Enter`&&!e.shiftKey&&!e.isComposing&&!(matchMedia(`(max-width: 760px)`).matches&&`ontouchstart`in window)&&(e.preventDefault(),he())},i.addEventListener(`paste`,e=>{let t=qS(e.clipboardData);t.length&&(e.preventDefault(),R(t))}),i.$$input=e=>{ne(e.currentTarget.value),ye()};var u=_e;typeof u==`function`?t(u,i):_e=i,a.addEventListener(`change`,e=>{let t=[...e.currentTarget.files??[]];e.currentTarget.value=``,t.length&&R(t)});var d=ve;return typeof d==`function`?t(d,a):ve=a,o.$$click=()=>ve.click(),y(o,n(L,{name:`plus`})),y(c,n(l,{get when(){return le()},get fallback(){return n(L,{name:`send`})},get children(){return $S()}})),s(e=>{var t=P_.join(`,`),n=re().length>=F_.maxImages||ae(),r=pe()||A()?`Start session`:`Choose a project first`,i=!pe(),s=!pe();return t!==e.e&&b(a,`accept`,e.e=t),n!==e.t&&(o.disabled=e.t=n),r!==e.a&&b(c,`title`,e.a=r),i!==e.o&&(c.disabled=e.o=i),s!==e.i&&b(c,`aria-disabled`,e.i=s),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),s(()=>i.value=I()),e})(),(()=>{var e=rC();return y(e,n(O,{label:`Choose environment`,class:`meta-chip env-chip`,align:`left`,items:ge,get text(){return[n(L,{name:`cloud`}),(()=>{var e=dC();return s(()=>k(e,`online-dot${h()?.online?` on`:``}`)),e})(),(()=>{var e=fC();return y(e,()=>h()?.name??`No environment`),e})(),n(L,{name:`down`,class:`chip-caret`})]}}),null),y(e,n(yC,{get targets(){return _()},get current(){return T()},get dir(){return A()},get disabled(){return!h()},get asked(){return r(()=>!!me())()&&!A()},buttonRef:e=>B=e,foldersOf:D,onPick:(e,t)=>x({machine:p(),key:e,dir:t})}),null),y(e,n(l,{get when(){return r(()=>!!A())()&&N()},get children(){var e=tC(),t=e.firstChild;return y(e,n(L,{name:`branch`}),t),y(t,N),e}}),null),y(e,n(l,{get when(){return r(()=>!!h()?.herdr)()&&E()?.kind===`herdr`},get children(){var e=nC(),t=e.firstChild;return t.addEventListener(`change`,e=>P(e.currentTarget.checked)),s(()=>b(e,`title`,`Open the new session in a new tab of the Herdr workspace ${E().label}`)),s(()=>t.checked=ee()),e}}),null),e})(),(()=>{var e=iC();return y(e,(()=>{var e=r(()=>!!A());return()=>e()?A():r(()=>!!h())()?`Choose one of ${h().name}'s projects`:``})()),s(t=>{var n=`small muted new-dir${A()?` mono`:``}`,r=A()||void 0;return n!==t.e&&k(e,t.e=n),r!==t.t&&b(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e})(),n(l,{get when(){return r(()=>!(!me()||A()))()&&h()},get children(){var e=aC(),t=e.firstChild.nextSibling;return t.nextSibling,y(e,()=>h().name,t),e}}),n(l,{get when(){return r(()=>!!h())()&&!h().canCreate},get children(){var e=oC(),t=e.firstChild;return y(e,()=>h().name,t),e}}),n(l,{get when(){return se()},get children(){var e=sC();return y(e,se),e}})]}}),null),e})()}function yC(e){let[i,o]=u(!1),[c,d]=u(``),[f,p]=u({top:0,left:0}),h,g,_,v=()=>MS(e.targets,c()),x=()=>e.targets.some(t=>t.key===e.current?.key),S=()=>{let t=e.targets.find(t=>t.key===e.current?.key);return t?t.kind===`herdr`&&e.dir?`${t.label} · ${j(e.dir)}`:t.label:e.targets.length?`Choose a project`:`No folder`},C=()=>{let e=h.getBoundingClientRect();p({top:e.bottom+4,left:e.left}),d(``),o(!i()),i()&&queueMicrotask(()=>_?.focus())},w=e=>{i()&&!h.contains(e.target)&&!g?.contains(e.target)&&o(!1)},T=e=>{i()&&e.key===`Escape`&&!ee(g)&&(o(!1),h.focus())};fe(()=>{document.addEventListener(`mousedown`,w),document.addEventListener(`keydown`,T)}),M(()=>{document.removeEventListener(`mousedown`,w),document.removeEventListener(`keydown`,T)});let E=(t,n)=>{e.onPick(t,n),o(!1)};return[(()=>{var r=pC(),a=r.firstChild;return r.$$click=C,t(t=>{h=t,e.buttonRef?.(t)},r),y(r,n(L,{name:`folder`}),a),y(a,S),y(r,n(L,{name:`down`,class:`chip-caret`}),null),s(t=>{var n=`meta-chip folder-chip${x()?``:` unset`}${e.asked?` asked`:``}`,a=i(),o=e.dir||`Choose a folder`,s=e.disabled;return n!==t.e&&k(r,t.e=n),a!==t.t&&b(r,`aria-expanded`,t.t=a),o!==t.a&&b(r,`title`,t.a=o),s!==t.o&&(r.disabled=t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),r})(),n(l,{get when(){return i()},get children(){return n(pe,{get children(){var i=mC(),o=i.firstChild,u=o.nextSibling,p=g;typeof p==`function`?t(p,i):g=i,o.$$keydown=t=>{let n=v()[0];t.key===`Enter`&&n&&(t.preventDefault(),E(n.key,e.foldersOf(n)[0]??``))},o.$$input=e=>d(e.currentTarget.value);var h=_;return typeof h==`function`?t(h,o):_=o,y(u,n(l,{get when(){return v().length},get fallback(){return hC()},get children(){return n(m,{get each(){return v()},children:t=>n(l,{get when(){return r(()=>t.kind===`herdr`)()&&e.foldersOf(t).length>1},get fallback(){return(()=>{var n=_C(),i=n.firstChild,a=i.nextSibling,o=a.nextSibling;return n.$$click=()=>E(t.key,e.foldersOf(t)[0]??``),y(i,()=>e.current?.key===t.key?`✓`:``),y(a,()=>t.label),y(o,(()=>{var n=r(()=>t.kind===`herdr`);return()=>n()?`Herdr`:e.foldersOf(t)[0]??``})()),s(r=>{var i=e.current?.key===t.key,a=e.foldersOf(t)[0];return i!==r.e&&b(n,`aria-selected`,r.e=i),a!==r.t&&b(n,`title`,r.t=a),r},{e:void 0,t:void 0}),n})()},get children(){return[(()=>{var e=gC(),n=e.firstChild;return y(e,()=>t.label,n),e})(),n(m,{get each(){return e.foldersOf(t)},children:n=>(()=>{var r=_C(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling;return r.$$click=()=>E(t.key,n),b(r,`title`,n),y(i,()=>e.current?.key===t.key&&e.dir===n?`✓`:``),y(a,()=>j(n)),y(o,n),s(()=>b(r,`aria-selected`,e.current?.key===t.key&&e.dir===n)),r})()})]}})})}})),s(e=>{var t=`${f().top}px`,n=`${f().left}px`;return t!==e.e&&a(i,`top`,e.e=t),n!==e.t&&a(i,`left`,e.t=n),e},{e:void 0,t:void 0}),s(()=>o.value=c()),i}})}})]}z([`input`,`keydown`,`click`]);var bC={name:`home`},xC=ce(()=>C(()=>{let e=dt();return e.name===`concierge`?Z()?e:bC:bC=e})),SC=e=>String(e??``).normalize(`NFD`).replace(/[\u0300-\u036f]/g,``).toLowerCase();function CC(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 wC(e){let t=e?.note;return!Array.isArray(e)&&typeof t==`string`&&t.trim()?t.trim():void 0}var TC=e=>e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;function EC(e,t,{current:n=``,limit:r=200,grouped:i=!1}={}){let a=String(t??``).trim(),o=SC(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=SC(e.id),r=`${n} ${SC(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(TC(t.option.id))||e.set(TC(t.option.id),e.size);u.sort((t,n)=>e.get(TC(t.option.id))-e.get(TC(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 DC(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 OC=I(`<input type=search class=picker-search autofocus>`),kC=I(`<button type=button class="btn small">Retry`),AC=I(`<p class="muted small"role=status>`),jC=I(`<p class="muted small picker-note">`),MC=I(`<li><button type=button><span class=po-name>Use “<!>”</span><span class="po-id muted">as a custom `),NC=I(`<ul class=picker-list role=listbox>`),PC=I(`<div class="picker-group muted small">`),FC=I(`<span class="po-id muted">`),IC=I(`<span class=po-mark>✓ Current`),LC=I(`<li><button type=button><span class=po-name>`);function RC(t){let[i,a]=u(``),[o,c]=u(),[d,f]=u(``),[p,h]=u(``),[g,_]=u(0),v=()=>{let e=t.request;e&&(c(void 0),f(``),h(``),e.load().then(e=>{if(Array.isArray(e))return c(e);h(e.note??``),c(e.options)},e=>f(U(e))))};x(e(()=>t.request,e=>{e&&(a(``),_(0),v())}));let S=C(()=>EC(o()??[],i(),{current:t.request?.current,grouped:t.request?.grouped})),w=()=>[...S().items.map(e=>e.id),...S().custom?[S().custom]:[]],T=e=>{let n=t.request;t.onClose(),n?.onPick(e)},E=()=>t.request?.noun??`option`;return n(de,{get open(){return!!t.request},get title(){return t.request?.title??``},get onClose(){return t.onClose},class:`picker`,get children(){return[(()=>{var e=OC();return e.$$keydown=e=>{let t={ArrowDown:1,ArrowUp:-1};if(e.key in t)e.preventDefault(),_(DC(g(),t[e.key],w().length));else if(e.key===`Enter`){e.preventDefault();let t=w()[g()];t&&T(t)}},e.$$input=e=>{a(e.currentTarget.value),_(0)},s(t=>{var n=`Search or type a ${E()}`,r=`Search ${E()}s`;return n!==t.e&&b(e,`placeholder`,t.e=n),r!==t.t&&b(e,`aria-label`,t.t=r),t},{e:void 0,t:void 0}),s(()=>e.value=i()),e})(),(()=>{var e=AC();return y(e,(()=>{var e=r(()=>!!d());return()=>e()?`Couldn't load the ${E()} list: ${d()}. Type any ${E()}.`:r(()=>o()===void 0)()?`Loading ${E()}s…`:r(()=>!o().length)()?`No suggestions. Type any ${E()}.`:`${S().total} ${S().total===1?E():`${E()}s`}`})(),null),y(e,n(l,{get when(){return d()},get children(){return[` `,(()=>{var e=kC();return e.$$click=v,e})()]}}),null),e})(),n(l,{get when(){return p()},get children(){var e=jC();return y(e,p),e}}),(()=>{var e=NC();return y(e,n(m,{get each(){return S().items},children:(e,i)=>(()=>{var a=LC(),o=a.firstChild,c=o.firstChild;return y(a,n(l,{get when(){return r(()=>!!t.request?.grouped)()&&(i()===0||TC(S().items[i()-1].id)!==TC(e.id))},get children(){var t=PC();return y(t,()=>TC(e.id)||`Other`),t}}),o),o.$$click=()=>T(e.id),y(c,()=>e.id),y(o,n(l,{get when(){return e.name},get children(){var t=FC();return y(t,()=>e.name),t}}),null),y(o,n(l,{get when(){return e.current},get children(){return IC()}}),null),s(t=>{var n=`picker-opt${g()===i()?` active`:``}`,r=!!e.current;return n!==t.e&&k(o,t.e=n),r!==t.t&&b(o,`aria-selected`,t.t=r),t},{e:void 0,t:void 0}),a})()}),null),y(e,n(l,{get when(){return S().custom},get children(){var e=MC(),t=e.firstChild,n=t.firstChild,r=n.firstChild.nextSibling;r.nextSibling;var i=n.nextSibling;return i.firstChild,t.$$click=()=>T(S().custom),y(n,()=>S().custom,r),y(i,E,null),s(()=>k(t,`picker-opt${g()===S().items.length?` active`:``}`)),e}}),null),e})()]}})}z([`input`,`keydown`,`click`]);var zC=I(`<div class=chips role=group aria-label="Which speech settings"><button type=button class=chip>Yours</button><button type=button class=chip>Server default`),BC=I(`<div class="speech-panel stack">`),VC=I(`<p class=error>`),HC=I(`<p class=muted>Loading…`),UC=I(`<p class="small inherit">`),WC=I(`<p class="small muted">`),GC=I(`<p class=field-error>`),KC=I(`<div class=field><label>`),qC=I(`<input type=text autocomplete=off autocapitalize=off>`),JC=I(`<div class=row><button type=button class="btn small">Browse…`),YC=I(`<input type=password autocomplete=new-password placeholder="Paste the new key"aria-label="New API key">`),XC=I(`<div class=row><button type=button class="btn small">Cancel`),ZC=I(`<div class="field key-field"><span class=field-label>API key`),QC=I(`<p>`),$C=I(`<button type=button class="btn small">Undo`),ew=I(`<button type=button class="btn small danger">Clear`),tw=I(`<div class=row><button type=button class="btn small">`),nw=I(`<fieldset class="card speech-card"><legend>`),rw=I(`<div class="row reset-row"><span class="small muted grow"></span><button type=button class="btn small">Reset to server default`),iw=I(`<option>`),aw=I(`<select>`),ow=I(`<p class="small muted">The server default is used by everyone on this hub for whatever they have not set themselves. Their own keys stay private.`),sw=I(`<button type=button class=btn>Preview voice`),cw=I(`<form class=stack novalidate><div class=row><button type=submit class="btn primary">Save</button></div><p role=status>`),lw=I(`<div class=banner><div><strong>Speech is not set up yet</strong><p class=small></p><p class="small muted">OpenRouter covers both directions with one key (openrouter.ai/keys). Or point both at your own OpenAI-compatible servers.`),uw=[[`openrouter`,`OpenRouter`],[`openai-compatible`,`OpenAI-compatible`]],dw={settings:`from settings`,config:`from hub.json`,env:`from env`,user:`yours`},fw={user:`/api/settings/speech`,default:`/api/settings/speech/default`},pw={stt:`Speech-to-text`,tts:`Text-to-speech`};function mw(){let[e,t]=u(`user`),[r,i]=u(!1),[a,o]=u(),[c,d]=u(``),f=async t=>{o(void 0),d(``);try{let n=await G(fw[t]);t===`user`&&i(Zn(X(),n).length>1),e()===t&&o(n)}catch(e){d(e instanceof W&&e.status===403?t==="default"?`Only admins can change the server default.`:`This account cannot change speech settings.`:e instanceof W&&e.status===404?`This hub does not support speech settings.`:`Could not load speech settings: ${U(e)}`)}};fe(()=>void f(`user`));let p=n=>{n!==e()&&(t(n),f(n))};return(()=>{var t=BC();return y(t,n(l,{get when(){return r()},get children(){var t=zC(),n=t.firstChild,r=n.nextSibling;return n.$$click=()=>p(`user`),r.$$click=()=>p(`default`),s(t=>{var i=e()===`user`,a=e()==="default";return i!==t.e&&b(n,`aria-pressed`,t.e=i),a!==t.t&&b(r,`aria-pressed`,t.t=a),t},{e:void 0,t:void 0}),t}}),null),y(t,n(l,{get when(){return!c()},get fallback(){return(()=>{var e=VC();return y(e,c),e})()},get children(){return n(l,{get when(){return a()},get fallback(){return HC()},keyed:!0,children:t=>n(hw,{settings:t,get scope(){return e()},onSaved:e=>o(e)})})}}),null),t})()}function hw(e){let[t,a]=Or(oo(e.settings)),[o,c]=u({}),[d,f]=u({text:``,kind:``}),[p,h]=u(!1),[g,v]=u(),x=()=>e.scope===`user`?nr(e.settings):void 0,S=()=>e.scope===`user`?fo(e.settings.ready,X()?.publicURL):void 0,C=()=>Object.keys(so(e.settings,gr(t))).length>0,w={},T=e=>(w[e]??=G(`/api/settings/speech/models?kind=${e}`).then(e=>({options:CC(e),note:wC(e)})),w[e].catch(()=>delete w[e]),w[e]),E=(e,t,r,i,a)=>{let s=()=>x()?.[e]?.[t];return(()=>{var c=KC(),u=c.firstChild;return b(u,`for`,`sp-${e}-${t}`),y(u,r),y(c,i,null),y(c,n(l,{get when(){return s()?.inherited},get children(){var e=UC();return y(e,()=>s().note),e}}),null),y(c,n(l,{when:a,get children(){var e=WC();return y(e,a),e}}),null),y(c,n(l,{get when(){return o()[`${e}.${t}`]},get children(){var n=GC();return y(n,()=>o()[`${e}.${t}`]),n}}),null),c})()},D=(e,n,r={})=>(()=>{var s=qC();return b(s,`id`,`sp-${e}-${n}`),b(s,`spellcheck`,!1),i(s,_(r,{get value(){return t[e][n]},get"aria-invalid"(){return!!o()[`${e}.${n}`]},onInput:t=>a(e,n,t.currentTarget.value)}),!1,!1),s})(),O=(e,n,r,i,o)=>(()=>{var s=JC(),c=s.firstChild;return y(s,()=>D(e,n,{placeholder:`Choose or type a ${i}`}),c),c.$$click=()=>v({title:r,noun:i,current:t[e][n]??``,load:o,grouped:n===`model`,onPick:t=>a(e,n,t)}),s})(),A=i=>{let c=e.settings[i].apiKey??{set:!1,source:`none`},u=()=>x()?.[i].apiKey,d=()=>t[i].apiKey,f=()=>x()?!u()?.inherited&&c.set:c.set&&c.source===`settings`;return(()=>{var e=ZC();return e.firstChild,y(e,n(l,{get when(){return d().action===`set`},get fallback(){return[(()=>{var e=QC();return y(e,(()=>{var e=r(()=>d().action===`clear`);return()=>e()?`Key will be removed when you save.`:r(()=>!!u()?.inherited)()?u().note:r(()=>!!c.set)()?`Key set${c.last4?` ••••${c.last4}`:``} (${dw[c.source]??c.source})`:`No key set`})()),s(()=>k(e,`key-summary${u()?.inherited&&d().action!==`clear`?` inherit`:``}`)),e})(),(()=>{var e=tw(),t=e.firstChild;return t.$$click=()=>a(i,`apiKey`,{action:`set`,value:``}),y(t,(()=>{var e=r(()=>!!u()?.inherited);return()=>e()?`Use your own key`:c.set?`Replace`:`Add key`})()),y(e,n(l,{get when(){return d().action===`clear`},get children(){var e=$C();return e.$$click=()=>a(i,`apiKey`,{action:`keep`,value:``}),e}}),null),y(e,n(l,{get when(){return r(()=>d().action!==`clear`)()&&f()},get children(){var e=ew();return e.$$click=()=>a(i,`apiKey`,{action:`clear`,value:``}),e}}),null),e})()]},get children(){return[(()=>{var e=YC();return e.$$input=e=>a(i,`apiKey`,`value`,e.currentTarget.value),b(e,`id`,`sp-${i}-apiKey`),s(()=>e.value=d().value),e})(),(()=>{var e=XC(),t=e.firstChild;return t.$$click=()=>a(i,`apiKey`,{action:`keep`,value:``}),e})()]}}),null),y(e,n(l,{get when(){return o()[`${i}.apiKey`]},get children(){var e=GC();return y(e,()=>o()[`${i}.apiKey`]),e}}),null),e})()},j=async t=>{if(await P(`Reset ${pw[t].toLowerCase()} to the server default? Your own ${pw[t].toLowerCase()} settings are removed.`,`Reset`,{danger:!0}))try{let n=await(await V(fw.user,{method:`PUT`,json:rr(t)})).json().catch(()=>({})),r=n?.stt&&n?.tts?n:await G(fw.user);iu(r.ready??null),e.onSaved(r),q(`${pw[t]} reset to the server default`)}catch(e){q(`Could not reset: ${U(e)}`,`err`)}},M=i=>(()=>{var o=nw(),c=o.firstChild;return y(c,()=>pw[i]),y(o,n(l,{get when(){return x()},children:e=>(()=>{var t=rw(),n=t.firstChild,a=n.nextSibling;return y(n,(()=>{var t=r(()=>!!e().own[i]);return()=>t()?`${e().own[i]} of your own setting${e().own[i]===1?``:`s`}`:`All from the server default`})()),a.$$click=()=>void j(i),s(()=>a.disabled=!e().own[i]),t})()}),null),y(o,()=>E(i,`provider`,`Provider`,(()=>{var e=aw();return e.addEventListener(`change`,e=>a(i,`provider`,e.currentTarget.value)),b(e,`id`,`sp-${i}-provider`),y(e,n(m,{each:uw,children:([e,t])=>(()=>{var n=iw();return n.value=e,y(n,t),n})()}),null),y(e,n(l,{get when(){return!uw.some(([e])=>e===t[i].provider)},get children(){var e=iw();return y(e,()=>t[i].provider||`—`),s(()=>e.value=t[i].provider),e}}),null),s(()=>e.value=t[i].provider),e})()),null),y(o,n(l,{get when(){return t[i].provider===`openai-compatible`},get children(){return E(i,`baseURL`,`Base URL`,D(i,`baseURL`,{inputmode:`url`,placeholder:`http://host:port/v1`}))}}),null),y(o,()=>E(i,`model`,`Model`,O(i,`model`,i===`stt`?`Speech-to-text model`:`Text-to-speech model`,`model`,()=>T(i))),null),y(o,n(l,{when:i===`tts`,get fallback(){return E(i,`language`,`Language (optional)`,D(i,`language`,{placeholder:`auto, e.g. en`}))},get children(){return[r(()=>E(i,`voice`,`Voice`,O(i,`voice`,`Voice`,`voice`,async()=>CC(lo(e.settings.voiceHints,t.tts.model))))),r(()=>E(i,`speed`,`Server-side speed (optional)`,D(i,`speed`,{inputmode:`decimal`,placeholder:`default`}),`0.25–4, applied by the TTS provider. Your device's voice speed is separate.`))]}}),null),y(o,()=>A(i),null),o})(),N=async n=>{n.preventDefault();let r=gr(t),i=co(r);if(c(i),Object.keys(i).length)return f({text:`Fix the highlighted fields.`,kind:`error`});let o=so(e.settings,r);if(!Object.keys(o).length)return f({text:`Nothing to save.`,kind:`muted`});h(!0),f({text:`Saving…`,kind:`muted`});try{let t=await(await V(fw[e.scope],{method:`PUT`,json:o})).json().catch(()=>({})),n=t?.stt&&t?.tts?t:await G(fw[e.scope]);e.scope===`user`?iu(n.ready??null):jd(),a(Mr(oo(n))),e.onSaved(n),q(e.scope==="default"?`Server default saved`:`Speech settings saved`)}catch(e){let t=e.field;t&&c({[t]:U(e)}),f({text:`Could not save: ${U(e)}`,kind:`error`})}finally{h(!1)}},ee=async()=>{f({text:C()?`Previewing the saved voice (save to hear your changes)…`:`Previewing…`,kind:`muted`});let e;try{let t=await(await V(`/api/settings/speech/test`,{method:`POST`,json:{kind:`tts`,text:`Hi! This is how replies will sound.`}})).blob();if(e=URL.createObjectURL(t),ob.src=e,Fv(ob,Jy.speed),!await ob.play().then(()=>!0,()=>!1))throw Error(`the browser blocked playback`);f({text:`Playing preview.`,kind:`muted`}),await new Promise(e=>ob.onended=ob.onpause=ob.onerror=()=>e()),f({text:``,kind:``})}catch(e){f({text:`Preview failed: ${U(e)}`,kind:`error`})}finally{ob.onended=ob.onpause=ob.onerror=null,e&&URL.revokeObjectURL(e)}};return(()=>{var t=cw(),r=t.firstChild,i=r.firstChild,a=r.nextSibling;return t.$$input=()=>f({text:C()?`Unsaved changes.`:``,kind:`muted`}),t.addEventListener(`submit`,N),y(t,n(l,{get when(){return e.scope==="default"},get children(){return ow()}}),r),y(t,n(l,{get when(){return S()},children:e=>(()=>{var t=lw(),r=t.firstChild,i=r.firstChild.nextSibling;return i.nextSibling,y(i,()=>e().reason),y(r,n(l,{get when(){return e().storage},get children(){var t=WC();return y(t,()=>e().storage),t}}),null),t})()}),r),y(t,()=>M(`stt`),r),y(t,()=>M(`tts`),r),y(r,n(l,{get when(){return e.scope===`user`},get children(){var e=sw();return e.$$click=()=>void ee(),e}}),null),y(a,()=>d().text),y(t,n(RC,{get request(){return g()},onClose:()=>v(void 0)}),null),s(e=>{var t=p(),n=`small ${d().kind}`;return t!==e.e&&(i.disabled=e.e=t),n!==e.t&&k(a,e.t=n),e},{e:void 0,t:void 0}),t})()}z([`click`,`input`]);var gw=I(`<p class="small muted">This hub does not record voice conversations.`),_w=I(`<ul class=switches><li id=set-recording><label class=switch><span class=notify-kind><span></span><span class="small muted"></span></span><input type=checkbox role=switch data-recording-switch></label><ul class="recording-details small muted"></ul></li><li id=set-developer><label class=switch><span class=notify-kind><span></span><span class="small muted"></span></span><input type=checkbox role=switch data-developer-switch></label><ul class="recording-details small muted">`),vw=I(`<div class=recording-head><span class=grow></span><a class="btn small"href=/api/recordings/export download>Export all</a><button type=button class="btn small danger">Delete all`),yw=I(`<p class="small muted recording-empty">No recordings.`),bw=I(`<button type=button class="btn small recording-more-page">Show more`),xw=I(`<div class=recording-pane data-recording-pane role=region aria-label="Your recordings"tabindex=0>`),Sw=I(`<details class="notify-group recording-fold"id=recordings data-recording-fold><summary><h4>Recordings</h4><span class="small muted notify-group-summary"data-recording-summary data-recording-usage></span></summary><div class=recording-fold-body>`),Cw=I(`<section class=settings-section id=recording aria-labelledby=h-recording><h3 class=section-title id=h-recording>Recording`),ww=I(`<li>`),Tw=I(`<div class=recording-day><h5 class=recording-day-title></h5><ul class=recording-list>`),Ew=I(`<span class=recording-name>`),Dw=I(`<select class=recording-segment aria-label=Segment title="Segment to play">`),Ow=I(`<button type=button class="btn small recording-play"aria-label="Play segment">▶ Play`),kw=I(`<li><div class=recording-main><div class=recording-title><span class=recording-kind></span></div><div class="small muted recording-meta"> · <!> · <span></span> · <!> · <!> · </div></div><div class=recording-actions>`),Aw=I(`<option>/`),jw=I(`<a class="btn small"download>Export`),Mw=I(`<button type=button class="btn small danger"data-recording-focus>Delete`),Nw=50,Pw=200;function Fw(e){let t=Fu(e)?.session,n=Bu(e);return wl({...n.startsWith(`@`)?{name:n}:{},...typeof t?.project==`string`&&t.project||t?.directory?{directory:typeof t?.project==`string`&&t.project||t.directory}:{}})}var Iw=e=>Tl(e,N(),void 0,Fw);function Lw(){let[e,i]=u(void 0),[a,o]=u(),[c,d]=u(),[f,p]=u([]),[h,g]=u(),[_,v]=u(!1),[x,S]=u(!1),[w,T]=u(!1);async function E(){try{let e=await(await V(`/api/settings/recording`)).json();i(!0),o(e.settings),d(e.usage),Fl.set({supported:!0,settings:e.settings})}catch(e){e instanceof W&&(e.status===404||e.status===405)?(i(!1),Fl.set({supported:!1})):q(`Could not load the recording setting: ${U(e)}`,`err`)}}async function D(e=!1){try{let t=e?h():void 0,n=e?Nw:Math.min(Pw,Math.max(Nw,f().length)),r=await(await V(`/api/recordings?limit=${n}${t?`&cursor=${K(t)}`:``}`)).json();p(e?[...f(),...r.recordings]:r.recordings),d(r.usage),g(r.next)}catch(e){e instanceof W&&e.status===404||q(`Could not list the recordings: ${U(e)}`,`err`)}finally{S(!0)}}fe(async()=>{await E(),e()&&await D()});let O;M(Nu(e=>{e.type===`recording`&&(e.settings&&typeof e.settings.enabled==`boolean`&&o(e.settings),clearTimeout(O),O=setTimeout(()=>void D(),300))})),M(()=>clearTimeout(O));async function k(e,t=`enabled`){let n=a();if(!n)return;let r=e.checked;v(!0);try{let e=await(await V(`/api/settings/recording`,{method:`PUT`,json:{[t]:r,expectedRevision:n.revision}})).json();o(e.settings),Ul(e.settings),q(t===`developer`?r?`Developer mode on from the next Voice start (recording too)`:`Developer mode off: the extras stop now`:r?`Recording on from the next Voice start`:`Recording off`)}catch(r){e.checked=t===`developer`?n.developer===!0:n.enabled,r instanceof W&&r.status===409?(q(`The setting changed on another device; it is reloaded. Try again.`,`err`),await E()):q(`Could not change the recording setting: ${U(r)}`,`err`)}finally{v(!1)}}async function A(e){let t=Iw(e);if(await P(`Delete this recording? ${t.kind} · ${t.title}, ${t.started}: its audio and events are deleted now.`,`Delete`,{danger:!0}))try{await V(`/api/recordings/${K(e.id)}`,{method:`DELETE`});let t=f().findIndex(t=>t.id===e.id),n=f()[t+1]??f()[t-1];p(f().filter(t=>t.id!==e.id)),c()&&d({...c(),bytes:Math.max(0,c().bytes-e.bytes)}),q(`Recording deleted`),ee(n?.id),D()}catch(e){q(`Could not delete the recording: ${U(e)}`,`err`)}}let j;function ee(e){requestAnimationFrame(()=>{((e?document.querySelector(`[data-recording-row="${CSS.escape(e)}"] [data-recording-focus], [data-recording-row="${CSS.escape(e)}"] [aria-haspopup="menu"]`):null)??j)?.focus()})}let F=C(()=>new Map(f().map(e=>[e.id,e]))),te=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),I=C(()=>[...new Set(f().map(e=>Dl(e.startedAt)))],[],{equals:te});async function ne(){let e=f().length;if(await P(`Delete all ${e} recording${e===1?``:`s`}${h()?` (and the ones not listed yet)`:``}? Their audio and events are deleted now.`,`Delete all`,{danger:!0}))try{let{deleted:t}=await(await V(`/api/recordings`,{method:`DELETE`})).json();p([]),g(void 0),q(`${t??e} recording${(t??e)===1?``:`s`} deleted`),D()}catch(e){q(`Could not delete the recordings: ${U(e)}`,`err`)}}return(()=>{var i=Cw();return i.firstChild,y(i,n(l,{get when(){return e()===!1},get children(){return gw()}}),null),y(i,n(l,{get when(){return r(()=>!!e())()&&a()},get children(){return[(()=>{var e=_w(),t=e.firstChild,r=t.firstChild,i=r.firstChild,o=i.firstChild,c=o.nextSibling,l=i.nextSibling,u=r.nextSibling,d=t.nextSibling.firstChild,f=d.firstChild,p=f.firstChild,h=p.nextSibling,g=f.nextSibling,v=d.nextSibling;return y(o,()=>vl.label),y(c,()=>vl.description),l.addEventListener(`change`,e=>void k(e.currentTarget)),y(u,n(m,{get each(){return vl.details},children:e=>(()=>{var t=ww();return y(t,e),t})()})),y(p,()=>yl.label),y(h,()=>yl.description),g.addEventListener(`change`,e=>void k(e.currentTarget,`developer`)),y(v,n(m,{get each(){return yl.details},children:e=>(()=>{var t=ww();return y(t,e),t})()})),s(e=>{var t=_(),n=_();return t!==e.e&&(l.disabled=e.e=t),n!==e.t&&(g.disabled=e.t=n),e},{e:void 0,t:void 0}),s(()=>l.checked=a().enabled),s(()=>g.checked=a().developer===!0),e})(),(()=>{var e=Sw(),i=e.firstChild,a=i.firstChild.nextSibling,o=i.nextSibling;return e.addEventListener(`toggle`,e=>T(e.currentTarget.open)),y(a,()=>El(f().length,!!h(),c())),y(o,n(l,{get when(){return f().length},get children(){var e=vw(),t=e.firstChild.nextSibling.nextSibling;return t.$$click=()=>void ne(),e}}),null),y(o,n(l,{get when(){return r(()=>!!x())()&&!f().length},get children(){return yw()}}),null),y(o,n(l,{get when(){return f().length},get children(){var e=xw(),r=j;return typeof r==`function`?t(r,e):j=e,y(e,n(m,{get each(){return I()},children:e=>{let t=C(()=>f().filter(t=>Dl(t.startedAt)===e).map(e=>e.id),[],{equals:te}),r=()=>{let e=F().get(t()[0]??``);return e?Ol(e.startedAt,N()):``};return(()=>{var i=Tw(),a=i.firstChild,o=a.nextSibling;return b(i,`data-recording-day`,e),y(a,r),y(o,n(m,{get each(){return t()},children:e=>n(l,{get when(){return F().get(e)},children:e=>n(Rw,{get recording(){return e()},onDelete:()=>void A(e())})})})),i})()}}),null),y(e,n(l,{get when(){return h()},get children(){var e=bw();return e.$$click=()=>void D(!0),e}}),null),e}}),null),s(()=>e.open=w()),e})()]}}),null),i})()}function Rw(e){let t=()=>Iw(e.recording),[i,a]=u(1),[o,c]=u(!1),d=()=>e.recording.segments;async function f(){c(!0);try{await Jl(e.recording.id,i())}catch(e){q(`Could not play segment ${i()}: ${U(e)}`,`err`)}finally{c(!1)}}let p=()=>`/api/recordings/${K(e.recording.id)}/export`,h=()=>{let e=document.createElement(`a`);e.href=p(),e.download=``,document.body.append(e),e.click(),e.remove()},g=()=>kl(t());return(()=>{var c=kw(),u=c.firstChild,_=u.firstChild,v=_.firstChild,x=_.nextSibling,S=x.firstChild,C=S.nextSibling,w=C.nextSibling.nextSibling,T=w.nextSibling.nextSibling,E=T.nextSibling.nextSibling;E.nextSibling;var D=u.nextSibling;return y(v,()=>g().kind),y(_,n(l,{get when(){return g().title},get children(){var e=Ew();return y(e,()=>g().title),e}}),null),y(x,()=>t().time,S),y(x,()=>t().device,C),y(w,()=>t().length),y(x,()=>t().segments,T),y(x,()=>t().size,E),y(x,()=>t().expires,null),y(x,n(l,{get when(){return t().note},get children(){return[` · `,r(()=>t().note)]}}),null),y(D,n(l,{get when(){return d()>0},get children(){return[n(l,{get when(){return d()>1},get children(){var e=Dw();return e.addEventListener(`change`,e=>a(Number(e.currentTarget.value)||1)),y(e,n(m,{get each(){return Array.from({length:d()},(e,t)=>t+1)},children:e=>(()=>{var t=Aw(),n=t.firstChild;return y(t,e,n),y(t,d,null),s(()=>t.value=String(e)),t})()})),s(()=>e.value=String(i())),e}}),(()=>{var e=Ow();return e.$$click=()=>void f(),s(t=>{var n=o(),r=`Play segment ${i()}`;return n!==t.e&&(e.disabled=t.e=n),r!==t.t&&b(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e})()]}}),null),y(D,n(l,{get when(){return Z()},get fallback(){return[(()=>{var e=jw();return s(()=>b(e,`href`,p())),e})(),(()=>{var t=Mw();return t.$$click=()=>e.onDelete(),t})()]},get children(){return n(O,{label:`Recording actions`,class:`btn small recording-menu`,text:`⋯`,items:()=>[{label:`Export (zip)`,run:h},{label:`Delete…`,danger:!0,run:()=>e.onDelete()}]})}}),null),s(n=>{var r=`recording-row${d()>0?` has-play`:``}`,i=e.recording.id,a=`${t().kind} · ${t().title}\nSession ${e.recording.sessionID} · recording ${e.recording.id}`,o=!!t().active;return r!==n.e&&k(c,n.e=r),i!==n.t&&b(c,`data-recording-row`,n.t=i),a!==n.a&&b(_,`title`,n.a=a),o!==n.o&&w.classList.toggle(`recording-live`,n.o=o),n},{e:void 0,t:void 0,a:void 0,o:void 0}),c})()}z([`click`]);var zw={entries:100,chars:253},Bw=new Set([...[`co`,`org`,`ac`,`gov`,`net`,`me`,`ltd`,`plc`,`sch`,`nhs`].map(e=>`${e}.uk`),...[`com`,`net`,`org`,`edu`,`gov`,`id`,`asn`].map(e=>`${e}.au`),...[`co`,`ne`,`or`,`ac`,`go`,`gr`,`ed`,`ad`,`lg`].map(e=>`${e}.jp`),...[`co`,`org`,`net`,`ac`,`govt`,`school`,`geek`,`gen`,`kiwi`,`maori`].map(e=>`${e}.nz`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.br`),...[`com`,`net`,`org`,`gov`,`edu`,`ac`].map(e=>`${e}.cn`),...[`com`,`net`,`org`,`gob`,`edu`].map(e=>`${e}.mx`),...[`co`,`net`,`org`,`firm`,`gen`,`ind`,`ac`,`edu`,`gov`,`res`].map(e=>`${e}.in`),...[`co`,`org`,`net`,`ac`,`gov`,`web`].map(e=>`${e}.za`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.tr`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.sg`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.hk`),...[`co`,`or`,`ne`,`go`,`ac`,`re`].map(e=>`${e}.kr`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.tw`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.ar`),...[`co`,`or`,`ac`,`go`].map(e=>`${e}.id`),...[`co`,`or`,`ac`,`go`].map(e=>`${e}.th`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.my`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.ph`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.pk`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.ua`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.pl`),...[`co`,`or`,`ac`].map(e=>`${e}.at`),...[`co`,`org`,`ac`].map(e=>`${e}.il`),`com.es`,`org.es`,`co.it`,`com.ru`,`co.ca`,`eu.org`,`github.io`,`githubpreview.dev`,`gitlab.io`,`pages.dev`,`workers.dev`,`netlify.app`,`vercel.app`,`herokuapp.com`,`appspot.com`,`blogspot.com`,`cloudfront.net`,`azurewebsites.net`,`web.app`,`firebaseapp.com`,`s3.amazonaws.com`,`ngrok.io`,`ngrok-free.app`,`glitch.me`,`repl.co`,`fly.dev`,`onrender.com`]),Vw=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function Hw(e){if(typeof e!=`string`)return{ok:!1,reason:`Expected a hostname`};let t=e.trim();if(!t)return{ok:!1,reason:`Expected a hostname`};if(t.length>zw.chars)return{ok:!1,reason:`${Uw(t)}: at most ${zw.chars} characters`};if(/[\s/\\:@?#[\]%]/.test(t))return{ok:!1,reason:`${Uw(t)}: a hostname only (no scheme, port, path or address)`};let n=t.startsWith(`*.`),r=n?t.slice(2):t;if(r.includes(`*`))return{ok:!1,reason:`${Uw(t)}: a wildcard only as a leading "*."`};let i=Ww(r.replace(/\.$/,``));if(i===void 0)return{ok:!1,reason:`${Uw(t)}: not a hostname`};let a=i.split(`.`);if(a.some(e=>!Vw.test(e)))return{ok:!1,reason:`${Uw(t)}: not a hostname`};if(/^\d+$/.test(a[a.length-1]))return{ok:!1,reason:`${Uw(t)}: an IP address or numeric domain is not allowed`};if(a.length<2)return{ok:!1,reason:n?`${Uw(t)}: too broad (name at least two labels after "*.")`:`${Uw(t)}: name a full hostname (like github.com)`};if(Bw.has(i))return{ok:!1,reason:`${Uw(t)}: too broad (a public suffix: name the site itself)`};let o=n?`*.${i}`:i;return o.length>zw.chars?{ok:!1,reason:`${Uw(t)}: at most ${zw.chars} characters`}:{ok:!0,entry:o}}var Uw=e=>e.length>60?`${e.slice(0,57)}…`:e;function Ww(e){if(e)try{let t=new URL(`http://${e}/`);return t.hostname&&t.hostname===t.host?t.hostname:void 0}catch{return}}function Gw(e){let t;try{t=new URL(e)}catch{return}if((t.protocol===`http:`||t.protocol===`https:`)&&!(t.port&&t.port!==`80`&&t.port!==`443`))return t.hostname.replace(/\.$/,``)||void 0}function Kw(e,t){let n=t.toLowerCase().replace(/\.$/,``);return n?e.some(e=>e.startsWith(`*.`)?n.endsWith(e.slice(1))&&n.length>e.length-1:n===e):!1}function qw(e){return e.split(`.`).map(e=>e.toLowerCase().startsWith(`xn--`)?Jw(e.slice(4))??e:e).join(`.`)}function Jw(e){let t=128,n=0,r=72,i=e.lastIndexOf(`-`),a=[];for(let t=0;t<Math.max(i,0);t++){let n=e.charCodeAt(t);if(n>=128)return;a.push(n)}let o=(e,t,n)=>{e=n?Math.floor(e/700):e>>1,e+=Math.floor(e/t);let r=0;for(;e>455;)e=Math.floor(e/35),r+=36;return r+Math.floor(36*e/(e+38))},s=e=>e>=48&&e<=57?e-22:e>=65&&e<=90?e-65:e>=97&&e<=122?e-97:36;for(let c=i>0?i+1:0;c<e.length;){let i=n;for(let t=1,i=36;;i+=36){if(c>=e.length)return;let a=s(e.charCodeAt(c++));if(a>=36)return;n+=a*t;let o=i<=r?1:i>=r+26?26:i-r;if(a<o)break;t*=36-o}if(r=o(n-i,a.length+1,i===0),t+=Math.floor(n/(a.length+1)),n%=a.length+1,t>1114111)return;a.splice(n++,0,t)}try{return String.fromCodePoint(...a)}catch{return}}var Yw=`/api/settings/media`,[Xw,Zw]=u(),Qw;function $w(){let e=Xw();return!e&&!Qw&&eT(),e}function eT(e=!1){if(Qw&&!e)return Qw;let t=V(Yw).then(e=>e.json()).then(e=>(Zw(e),e),()=>{Qw===t&&(Qw=void 0)});return Qw=t,t}async function tT(e){let t=await(await V(Yw,{method:`PUT`,json:{allowlist:e}})).json();return Zw(t),t}async function nT(e){let t=Xw()??await eT(),n=t?.allowlist??[];return t&&n.includes(e)?t:tT([...n,e])}var[rT,iT]=u(new Map),aT=e=>rT().get(e)??[];function oT(e,t){let n=rT().get(e)??[];if(n.includes(t))return;let r=new Map(rT());r.set(e,[...n,t]),iT(r)}var sT=I(`<p class="small media-off"role=status>Web images are turned off on this hub (HUB_REMOTE_FETCH=off): images from other sites are not loaded, allowed or not.`),cT=I(`<p class="small media-allowlist-error">`),lT=I(`<ul class=media-allowlist aria-label="Allowed sites">`),uT=I(`<p class="small media-allowlist-error"role=alert>`),dT=I(`<div class=media-settings><p class="small muted">Images in replies from these sites load at once, through this hub. Images from other sites show their address and wait for you to load them. Add a site (github.com) or every subdomain of one (*.githubusercontent.com).</p><p class="small media-warning">An allowed site that hosts other people's content (for example a file host) can still receive data an agent puts in an image URL.</p><form class=media-allowlist-add><input type=text aria-label=Site placeholder="github.com or *.githubusercontent.com"autocomplete=off autocapitalize=none><button type=submit class="btn small">Add`),fT=I(`<p class="small muted">No sites allowed yet.`),pT=I(`<span class=muted> (<!>)`),mT=I(`<li><span class=grow></span><button type=button class="btn small">Remove`);function hT(){let[e,t]=u(``),[r,i]=u(``),[a,o]=u(!1),[c,d]=u(``);fe(async()=>{await eT(!0)||d(`Could not load the media settings.`)});let f=()=>$w()?.allowlist??[],p=async(e,t)=>{o(!0);try{return await tT(e),q(t),!0}catch(e){return i(U(e)),!1}finally{o(!1)}},h=async n=>{n?.preventDefault(),i(``);let r=Hw(e());if(!r.ok)return void i(r.reason);if(f().includes(r.entry))return void(t(``),i(`${r.entry} is already allowed`));if(f().length>=zw.entries)return void i(`At most ${zw.entries} allowed sites`);await p([...f(),r.entry],`Images from ${r.entry} now load at once`)&&t(``)},g=e=>{i(``),p(f().filter(t=>t!==e),`${e} removed`)};return(()=>{var o=dT(),u=o.firstChild.nextSibling.nextSibling,d=u.firstChild,p=d.nextSibling;return y(o,n(l,{get when(){return $w()?.remoteFetch===!1},get children(){return sT()}}),u),y(o,n(l,{get when(){return c()},get children(){var e=cT();return y(e,c),e}}),u),y(o,n(l,{get when(){return f().length},get fallback(){return fT()},get children(){var e=lT();return y(e,n(m,{get each(){return f()},children:e=>(()=>{var t=mT(),r=t.firstChild,i=r.nextSibling;return y(r,e,null),y(r,n(l,{get when(){return qw(e)!==e},get children(){var t=pT(),n=t.firstChild.nextSibling;return n.nextSibling,y(t,()=>qw(e),n),t}}),null),i.$$click=()=>g(e),b(i,`aria-label`,`Remove ${e}`),s(()=>i.disabled=a()),t})()})),e}}),u),u.addEventListener(`submit`,e=>void h(e)),d.$$input=e=>(t(e.currentTarget.value),i(``)),b(d,`spellcheck`,!1),y(o,n(l,{get when(){return r()},get children(){var e=uT();return y(e,r),e}}),null),s(()=>p.disabled=a()||!e().trim()),s(()=>d.value=e()),o})()}z([`input`,`click`]);var gT=[`queued`,`placing`,`provisioning`,`running`],_T=e=>typeof e==`object`&&!!e&&!Array.isArray(e),vT=e=>typeof e==`string`,yT=e=>typeof e==`number`&&Number.isFinite(e);function bT(e){if(!_T(e)||!vT(e.id)||!vT(e.state)||!_T(e.spec)||!_T(e.spec.workspace)||!vT(e.spec.workspace.repo))return;let t=e.spec.workspace,n=e.waiting;return{id:e.id,state:e.state,reason:vT(e.reason)?e.reason:``,repo:t.repo,...vT(t.branch)?{branch:t.branch}:{},...vT(e.by)?{by:e.by}:{},...vT(e.byLabel)?{byLabel:e.byLabel}:{},launcherRevoked:e.launcherRevoked===!0,..._T(n)&&vT(n.wait)&&vT(n.reason)&&yT(n.since)?{waiting:{wait:n.wait,reason:n.reason,since:n.since}}:{},...vT(e.name)?{name:e.name}:{},...vT(e.sessionID)?{sessionID:e.sessionID}:{},...vT(e.machineID)?{machineID:e.machineID}:{},concierge:e.by===`app:concierge`&&_T(e.spec.labels)&&e.spec.labels[`hub/system`]===`concierge`,created:yT(e.created)?e.created:0}}function xT(e){return!_T(e)||!Array.isArray(e.launches)?[]:e.launches.map(bT).filter(e=>e!==void 0)}function ST(e,t){if(!_T(t)||t.type!==`launch`)return e;let n=bT(t.launch);return n?gT.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 CT(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 wT={queued:`Queued`,placing:`Placing`,provisioning:`Starting`,running:`Running`,ended:`Ended`},TT=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 ET(e,t){let n=e.name?`@${e.name.replace(/^@+/,``)}`:`${e.repo}${e.branch?` (${e.branch})`:``}`;return{title:n,status:`${wT[e.state]??e.state} · by ${CT(e)}`,detail:e.state===`queued`&&e.waiting?`${e.waiting.reason} · ${TT(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 DT(e,t){if(e.state!==`ready`&&e.state!==`refreshing`)return;let n=e.latest();return n?ST(n,t):void 0}var OT=e=>e.normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase(),kT=e=>!!e&&/[a-z0-9]/.test(e),AT=(e,t)=>t===0||!kT(e[t-1]);function jT(e,t){let n;for(let r=t.indexOf(e);r>=0;r=t.indexOf(e,r+1)){let i=100+e.length*2+(r===0?40:AT(t,r)?20:0)-r*.01;(n===void 0||i>n)&&(n=i)}if(n!==void 0)return n;let r=10,i=-1;for(let n of e){let e=t.indexOf(n,i+1);if(e<0)return;r+=1+(e===i+1?4:0)+(AT(t,e)?6:0)-(i>=0?(e-i-1)*.2:0),i=e}return Math.min(99,r)}function MT(e,t){let n=OT(e).split(/\s+/).filter(Boolean);if(!n.length)return 0;let r=OT(t),i=0;for(let e of n){let t=jT(e,r);if(t===void 0)return;i+=t}return i}var NT=e=>[e.value,e.label,e.detail,e.keywords].filter(Boolean).join(` `);function PT(e,t,{exclude:n=[],limit:r=100}={}){let i=new Set(n),a=new Map,o=[];if(e.forEach((e,n)=>{let r=e.group??``;if(a.has(r)||a.set(r,a.size),i.has(e.value))return;let s=MT(t,NT(e));s!==void 0&&o.push({option:e,score:s,index:n,group:a.get(r)})}),t.trim()){let e=new Map;for(let t of o)e.set(t.group,Math.max(e.get(t.group)??-1/0,t.score));let t=[...e].sort((e,t)=>t[1]-e[1]||e[0]-t[0]).map(([e])=>e);for(let e of o)e.group=t.indexOf(e.group)}return o.sort((e,t)=>e.group-t.group||t.score-e.score||e.index-t.index),o.slice(0,r).map(e=>e.option)}function FT(e,t,n,r=[]){let i=e.trim();if(!i||r.includes(i)||t.some(e=>e.value===i))return;let a=n?.(i);return a?{value:i,problem:a}:{value:i}}function IT(e,t){let n=OT(t).split(/\s+/).filter(Boolean);return n.length?e.some(e=>{let t=OT(NT(e));return n.every(e=>t.includes(e))}):!1}var LT=8,RT=120;function zT({below:e,above:t,want:n}){if(n+LT<=e)return{up:!1,maxHeight:n};let r=t>e,i=Math.max(0,Math.min(n,(r?t:e)-LT));return i<Math.min(n,RT)?{up:r,maxHeight:i,cramped:!0}:{up:r,maxHeight:i}}function BT(e){let t=[];return e.forEach((e,n)=>{let r=t.at(-1);r&&r.group===e.group?r.items.push({option:e,index:n}):t.push({group:e.group,items:[{option:e,index:n}]})}),t}var VT=I(`<div role=option>`),HT=I(`<span role=img>`),UT=I(`<span class="po-id muted combo-detail">`),WT=I(`<span class=combo-text><span class="po-name combo-label">`),GT=I(`<span class=combo-text><span class="po-name combo-label">Use “<!>”</span><span class="po-id muted combo-detail">as typed`),KT=I(`<p class="combo-empty muted small">`),qT=I(`<div><div class="combo-list picker-list"role=listbox>`),JT=I(`<div class=combo><input type=text role=combobox class=combo-input aria-autocomplete=list autocomplete=off autocapitalize=off><p class="combo-problem small"aria-live=polite>`),YT=I(`<div role=group class=combo-section><div class="picker-group combo-group muted small">`),XT=I(`<span class=pick-chip-kind>`),ZT=I(`<span class="pick-chip-detail muted">`),QT=I(`<button type=button class=pick-chip-x>×`),$T=I(`<li class=pick-chip><span class=pick-chip-text><span class=pick-chip-label>`),eE=I(`<ul class=pick-chips>`),tE=I(`<div>`);function nE(e){for(let t=e.parentElement;t;t=t.parentElement){let e=getComputedStyle(t).overflowY;if(e===`auto`||e===`scroll`)return t}}var rE=264;function iE(e){let i=T(),o=`combo-${i}`,c=`combo-problem-${i}`,d,f,[p,h]=u(!1),[g,_]=u(0),[v,S]=u({up:!1,maxHeight:rE}),w=C(()=>PT(e.options,e.query,{exclude:e.exclude,limit:e.limit??60})),E=C(()=>BT(w())),D=C(()=>e.noCustom?void 0:FT(e.query,e.options,e.problem,e.exclude)),O=()=>D()?.problem,A=()=>D()&&!D().problem?D().value:void 0,j=C(()=>!!A()&&!IT(w(),e.query)),M=()=>{let e=A(),t=w().map(e=>e.value);return e===void 0?t:j()?[e,...t]:[...t,e]},N=e=>j()?e+1:e,ee=()=>j()?0:w().length,P=e=>`${o}-${e}`,F=()=>p()&&g()>=0&&g()<M().length?P(g()):void 0,te=t=>{e.onPick(t),e.onQuery(``),_(0),h(!1)},I=(e=!0)=>{if(!d||!f)return;let t=Math.min(rE,f.scrollHeight+2),n=nE(d)?.getBoundingClientRect(),r=Math.max(n?.top??0,0),i=Math.min(n?.bottom??window.innerHeight,window.innerHeight),a=d.getBoundingClientRect(),o=zT({below:i-a.bottom,above:a.top-r,want:t});if(o.cramped&&e)return d.scrollIntoView({block:`start`}),I(!1);S({up:o.up,maxHeight:o.maxHeight})};x(()=>{p()&&(w(),D(),I(),requestAnimationFrame(()=>p()&&I()))}),x(()=>{let e=F();e&&queueMicrotask(()=>document.getElementById(e)?.scrollIntoView({block:`nearest`}))});let ne=t=>{let n=M().length;if(t.key===`ArrowDown`||t.key===`ArrowUp`){if(t.preventDefault(),!p())return void(h(!0),_(t.key===`ArrowDown`?0:Math.max(0,n-1)));_(DC(g(),t.key===`ArrowDown`?1:-1,n))}else t.key===`Home`&&p()&&!e.query?(t.preventDefault(),_(0)):t.key===`End`&&p()&&!e.query?(t.preventDefault(),_(Math.max(0,n-1))):t.key===`Enter`?p()&&n&&g()>=0&&g()<n?(t.preventDefault(),te(M()[g()])):e.query.trim()&&t.preventDefault():t.key===`Escape`&&p()?(t.preventDefault(),t.stopPropagation(),h(!1)):t.key===`Tab`&&h(!1)},re=e=>(()=>{var t=VT();return t.$$click=()=>te(e.value),t.addEventListener(`pointerenter`,()=>_(e.index)),t.$$mousedown=e=>e.preventDefault(),y(t,()=>e.children),s(n=>{var r=P(e.index),i=`picker-opt combo-opt${e.class?` ${e.class}`:``}${g()===e.index?` active`:``}`,a=g()===e.index,o=e.value;return r!==n.e&&b(t,`id`,n.e=r),i!==n.t&&k(t,n.t=i),a!==n.a&&b(t,`aria-selected`,n.a=a),o!==n.o&&b(t,`data-value`,n.o=o),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t})(),ie=e=>n(re,{get index(){return N(e.index)},get value(){return e.row.value},get children(){return[n(l,{get when(){return e.row.online!==void 0},get children(){var t=HT();return s(n=>{var r=`combo-dot${e.row.online?` on`:``}`,i=e.row.online?`online`:`offline`;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),t}}),(()=>{var t=WT(),r=t.firstChild;return y(r,()=>e.row.label??e.row.value),y(t,n(l,{get when(){return e.row.detail},get children(){var t=UT();return y(t,()=>e.row.detail),t}}),null),t})()]}}),ae=()=>n(l,{get when(){return A()},children:e=>n(re,{get index(){return ee()},get value(){return e()},class:`combo-custom`,get children(){var t=GT(),n=t.firstChild,r=n.firstChild.nextSibling;return r.nextSibling,y(n,e,r),t}})}),oe=()=>[e.describedBy,O()?c:``].filter(Boolean).join(` `)||void 0;return(()=>{var i=JT(),u=i.firstChild,g=u.nextSibling,x=d;return typeof x==`function`?t(x,i):d=i,u.$$keydown=ne,u.addEventListener(`blur`,()=>h(!1)),u.$$click=()=>h(!0),u.addEventListener(`focus`,()=>h(!0)),u.$$input=t=>{e.onQuery(t.currentTarget.value),h(!0),_(0)},b(u,`aria-controls`,o),b(u,`spellcheck`,!1),b(g,`id`,c),y(g,()=>O()??``),y(i,n(l,{get when(){return p()},get children(){var i=qT(),c=i.firstChild,u=f;return typeof u==`function`?t(u,c):f=c,b(c,`id`,o),y(c,n(l,{get when(){return j()},get children(){return ae()}}),null),y(c,n(m,{get each(){return E()},children:e=>n(l,{get when(){return e.group},get fallback(){return n(m,{get each(){return e.items},children:e=>n(ie,{get row(){return e.option},get index(){return e.index}})})},children:t=>{let r=`${o}-g-${e.items[0].index}`;return(()=>{var i=YT(),a=i.firstChild;return b(i,`aria-labelledby`,r),b(a,`id`,r),y(a,t),y(i,n(m,{get each(){return e.items},children:e=>n(ie,{get row(){return e.option},get index(){return e.index}})}),null),i})()}})}),null),y(c,n(l,{get when(){return!j()},get children(){return ae()}}),null),y(i,n(l,{get when(){return r(()=>!w().length)()&&!A()},get children(){var t=KT();return y(t,()=>e.query.trim()?`No matches`:`Nothing to suggest: type a value`),t}}),null),s(t=>{var n=`combo-pop${v().up?` up`:``}`,r=e.label,o=`${v().maxHeight}px`;return n!==t.e&&k(i,t.e=n),r!==t.t&&b(c,`aria-label`,t.t=r),o!==t.a&&a(c,`max-height`,t.a=o),t},{e:void 0,t:void 0,a:void 0}),i}}),null),s(t=>{var n=e.label,r=p(),i=F(),a=oe(),o=e.invalid||!!O()||void 0,s=e.placeholder??``,c=e.autofocus;return n!==t.e&&b(u,`aria-label`,t.e=n),r!==t.t&&b(u,`aria-expanded`,t.t=r),i!==t.a&&b(u,`aria-activedescendant`,t.a=i),a!==t.o&&b(u,`aria-describedby`,t.o=a),o!==t.i&&b(u,`aria-invalid`,t.i=o),s!==t.n&&b(u,`placeholder`,t.n=s),c!==t.s&&(u.autofocus=t.s=c),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),s(()=>u.value=e.query),i})()}function aE(e){return(()=>{var t=$T(),r=t.firstChild,i=r.firstChild;return y(t,n(l,{get when(){return e.kind},get children(){var t=XT();return y(t,()=>e.kind),t}}),r),y(i,()=>e.label),y(r,n(l,{get when(){return e.detail},get children(){var t=ZT();return y(t,()=>e.detail),t}}),null),y(t,n(l,{get when(){return e.onRemove},get children(){var t=QT();return t.$$click=()=>e.onRemove(),s(()=>b(t,`aria-label`,e.removeLabel??`Remove ${e.label}`)),t}}),null),s(()=>b(t,`title`,e.title)),t})()}function oE(e){let t=C(()=>new Map(e.options.map(e=>[e.value,e]))),r=n=>{if(e.chip)return e.chip(n);let r=t().get(n);return{label:r?.label??n,detail:r?.detail&&r.detail!==r.label?r.detail:void 0}};return(()=>{var t=tE();return y(t,n(l,{get when(){return e.values.length},get children(){var t=eE();return y(t,n(m,{get each(){return e.values},children:t=>n(aE,_(()=>r(t),{title:t,removeLabel:`Remove ${t}`,onRemove:()=>e.onRemove(t)}))})),s(()=>b(t,`aria-label`,`${e.label}: chosen`)),t}}),null),y(t,n(iE,_(e,{get exclude(){return e.values},onPick:t=>e.onAdd(t)})),null),s(()=>k(t,`chip-picker${e.mono?` mono-chips`:``}`)),t})()}z([`mousedown`,`click`,`input`,`keydown`]);var sE=/^[a-z0-9-]{2,40}$/,cE=e=>sE.test(e),lE=/^([a-z0-9-]{2,40})(?:\.([^./\s#]+))?$/i;function uE(e){if(e.startsWith(`ses_`))return/^ses_[A-Za-z0-9]+$/.test(e)?{kind:`id`,id:e}:void 0;let t=e.startsWith(`@@`);if(!t&&!e.startsWith(`@`))return;let n=lE.exec(e.slice(t?2:1));if(!n||!cE(n[1]))return;let r=n[2]?.toLowerCase(),i=r?{project:r}:{};return t?{kind:`role`,role:n[1],...i}:{kind:`name`,name:n[1],...i}}var dE=e=>!!e&&typeof e==`object`&&!Array.isArray(e),fE=e=>typeof e==`string`&&e?e:void 0;function pE(e){return(dE(e)&&Array.isArray(e.sessions)?e.sessions:[]).flatMap(e=>{if(!dE(e)||typeof e.sessionID!=`string`||!e.sessionID)return[];let t=Array.isArray(e.roles)?e.roles.flatMap(e=>dE(e)&&typeof e.role==`string`?[e.role]:[]):[];return[{sessionID:e.sessionID,...fE(e.name)?{name:fE(e.name)}:{},...fE(e.title)?{title:fE(e.title)}:{},...fE(e.project)?{project:fE(e.project)}:{},online:e.online===!0,...e.archived===!0?{archived:!0}:{},...e.concierge===!0?{concierge:!0}:{},roles:t}]})}var mE=/^orchestrator/,hE=e=>mE.test(e)||e.startsWith(`concierge`),gE=`holder is @@role, @name, ses_… or app:<token id>`,_E=/^app:[0-9a-f]{16}$/,vE={role:`Reserved roles`,session:`Sessions`,app:`Apps`},yE={role:`Reserved role`,session:`Session`,app:`App`},bE=e=>e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()||e,xE=e=>typeof e.project==`string`&&e.project||e.directory||``;function SE({who:e,sessions:t,tokens:n,hidden:r=new Set}){let i=new Map(t.map(e=>[e.id,e])),a=e=>r.has(e),o=new Map([[`orchestrator`,[]]]);for(let t of e)if(!(t.concierge||t.archived||a(t.sessionID)))for(let e of t.roles){if(!mE.test(e))continue;let n=o.get(e)??[];n.push(t.name?`@${t.name}`:t.sessionID),o.set(e,n)}let s=[...o].map(([e,t])=>({value:`@@${e}`,label:`@@${e}`,kind:`role`,group:vE.role,detail:t.length?`Held by ${t.join(`, `)} · follows whoever holds it`:`Follows whoever holds it when the grant is used`})),c=[],l=new Set,u=(e,t)=>{let n=i.get(e);return n&&(n.projectName||xE(n)&&bE(xE(n)))||t||``};for(let t of e){if(t.concierge||t.archived||a(t.sessionID))continue;l.add(t.sessionID);let e=t.title||i.get(t.sessionID)?.title||``,n=u(t.sessionID,t.project);c.push({value:t.name?`@${t.name}`:t.sessionID,label:t.name?`@${t.name}`:e||t.sessionID,kind:`session`,group:vE.session,online:t.online,detail:[t.name?e:t.sessionID,n,t.name?t.sessionID:``].filter(Boolean).join(` · `)})}for(let e of t){if(l.has(e.id)||e.archived||a(e.id))continue;l.add(e.id);let t=u(e.id);c.push({value:e.id,label:e.title||e.id,kind:`session`,group:vE.session,online:!!e.machineOnline,detail:[e.id,t,e.machineName].filter(Boolean).join(` · `)})}let d=c.filter(e=>e.online),f=c.filter(e=>!e.online),p=n.map(e=>({value:`app:${e.id}`,label:e.label||`Unnamed app`,kind:`app`,group:vE.app,detail:`app:${e.id}${e.scopes.length?` · ${e.scopes.join(`, `)}`:``}`}));return[...s,...d,...f,...p]}function CE(e,t){let n=t.find(t=>t.value===e);if(n)return{kind:n.kind,kindLabel:yE[n.kind],label:n.label,detail:n.detail??``};let r=e.startsWith(`@@`)?`role`:e.startsWith(`app:`)?`app`:`session`,i=r===`role`?`Follows whoever holds it when the grant is used`:r===`app`?`One of your app tokens`:`Pinned to that session when the grant is created`;return{kind:r,kindLabel:yE[r],label:e,detail:i}}function wE(e){if(_E.test(e))return;let t=uE(e);if(!t||t.kind===`name`&&t.name===`me`)return gE;if(t.kind===`role`&&!hE(t.role))return`A role holder must be a reserved role (such as @@orchestrator)`}var TE=e=>/^([A-Za-z]:)?[\\/]/.test(e),EE=e=>e.length>1?e.replace(/[\\/]+$/,``):e;function DE(e){let t=e.trim();return t?TE(t)?void 0:`${t} is not an absolute directory`:`A project directory`}function OE({sessions:e,grants:t}){let n=new Map,r=e=>{let t=EE(e.trim());t&&TE(t)&&n.set(t,(n.get(t)??0)+1)};for(let t of e)r(xE(t));for(let e of t)for(let t of e.scope.projects)n.has(EE(t))||r(t);return[...n.keys()].map(e=>({value:e,label:bE(e),detail:e}))}var kE=/^[A-Za-z0-9_.*?-]{1,80}$/,AE=1e3;function jE(e){let t=`${e} is not an action[:glob] pattern (e.g. shell:bun test *)`;if(!e||e!==e.trim())return t;let n=e.indexOf(`:`),r=n<0?e:e.slice(0,n),i=n<0?`*`:e.slice(n+1);return kE.test(r)&&i!==``&&i.length<=AE?void 0:t}var ME=[[`edit`,`Edit any file`],[`write`,`Write any file`],[`read`,`Read any file`],[`glob`,`Find files`],[`grep`,`Search files`],[`list`,`List folders`],[`webfetch`,`Fetch web pages`],[`websearch`,`Search the web`],[`task`,`Start subagents`],[`external_directory`,`Work outside the project folder`],[`shell`,`Run any shell command`]],NE=[[`shell:bun test *`,`Run the tests (bun)`],[`shell:npm test *`,`Run the tests (npm)`],[`shell:npm run *`,`Run package scripts`],[`shell:git status *`,`git status`],[`shell:git diff *`,`git diff`],[`shell:git log *`,`git log`],[`shell:ls *`,`List files`],[`edit:src/*`,`Edit files under src/`]],PE=[[`shell:rm *`,`Delete files`],[`shell:git push *`,`Push commits`],[`shell:git reset --hard *`,`Discard work`],[`shell:sudo *`,`Run as root`],[`shell:curl *`,`Download or upload`],[`edit:.env*`,`Edit secrets files`],[`external_directory`,`Work outside the project folder`]];function FE(e,t){let n=new Map,r=(e,t,r)=>{!n.has(e)&&!jE(e)&&n.set(e,{value:e,label:e,detail:t,group:r})};for(let n of t)for(let t of e===`permit`?n.permissions.allow:n.permissions.never)r(t,`From your grants`,`Used before`);for(let[t,n]of e===`permit`?NE:PE)r(t,n,`Common`);if(e===`permit`)for(let[e,t]of ME)r(e,t,`Every resource of an action`);return[...n.values()]}var IE=e=>e.split(`
10
+ `).map(e=>e.trim()).filter(Boolean);function LE(e,t){let n=IE(e),r=t.trim();return(r&&!n.includes(r)?[...n,r]:n).join(`
11
+ `)}var RE=(e,t)=>IE(e).filter(e=>e!==t).join(`
12
+ `),zE={approve:`Approve permission requests that pass the patterns below`,deny:`Deny permission requests`,answer:`Answer questions and forms (also lets an app with decisions:answer answer its sessions' confirm-tier Decisions)`,prompt:`Send a prompt to a session (also lets an app follow and talk in its conversation)`,stop:`Stop a session's turn`,roles:`Claim and release roles of sessions (apps)`,launch:`Start new sessions in these projects`},BE=[`30m`,`8h`,`1d`,`7d`,`30d`],VE=60,HE=1,UE=1e3;function WE(e,t){let n=e.trim();return/^\d+$/.test(n)?String(Math.min(UE,Math.max(HE,Number(n)+t))):String(VE)}var GE=(e,t)=>e.allow.includes(`approve`)||!!e.permit.trim()||!!e.never.trim()||e.allowAlways||!!t?.permit.trim()||!!t?.never.trim(),KE={projects:DE,permit:jE,never:jE};function qE(e,t){let n={},r=[],i=e,a=t.holder.trim();!i.holder.trim()&&a&&(i={...i,holder:a},r.push(`holder`));for(let e of[`projects`,`permit`,`never`]){let a=t[e].trim();if(!a)continue;let o=KE[e](a);o?n[e]=o:(i={...i,[e]:LE(i[e],a)},r.push(e))}let o=i.holder.trim(),s=o?wE(o):void 0;s&&(n.holder=s);let c=xt(i);return Object.keys(n).length?{draft:e,cleared:[],result:{ok:!1,errors:{...c.ok?{}:c.errors,...n}}}:{draft:i,cleared:r,result:c}}var JE=I(`<div id=agent-activity>`),YE=I(`<section class=settings-section id=agents aria-label=Agents><p class="small muted">What sessions and apps may do for you: approve, deny, answer, prompt or stop in your sessions, only within a grant. Anything outside a grant comes to you as a Decision.</p><div class=chips role=group aria-label="Agents sections"id=grants><button type=button class=chip>Grants</button><button type=button class=chip>Activity`),XE=I(`<ul class=list>`),ZE=I(`<div class="stack connected-apps"id=connected-apps><div class=row><div class=grow><h3>Connected apps</h3><p class="small muted">Apps you let use this hub as you, through their consent page. Each keeps only the scopes you approved; acting still needs a grant.</p></div><button type=button class="btn small">Refresh`),QE=I(`<p class="small muted">`),$E=I(`<p class="small muted">No connected apps.`),eD=I(`<li class=row><div class=grow><div class=name></div><div class="small muted mono"></div><div class=small data-connection-scopes></div><div class="small muted"></div></div><button type=button class="btn small danger">Revoke`),tD=I(`<div class="stack app-clients"id=app-clients><div class=row><div class=grow><h3>App clients</h3><p class="small muted">Apps that may ask you (and <!>) to connect. Register the app's exact redirect URIs and the most it may ask for; its server keeps the secret.</p></div><button type=button class="btn small primary">Register app`),nD=I(`<p class="small muted">No app clients registered.`),rD=I(`<span class="badge-pill off">`),iD=I(`<button type=button class="btn small">Edit`),aD=I(`<button type=button class="btn small">Rotate secret`),oD=I(`<button type=button class="btn small">`),sD=I(`<button type=button class="btn small danger">Delete`),cD=I(`<li class=row><div class=grow><div class=name><span class=badge-pill></span></div><div class="small muted mono"></div><div class="small muted">Returns to </div><div class=small>At most: `),lD=I(`<p role=alert>`),uD=I(`<div class=text-field><span class=field-title id=app-client-audience>Who may connect</span><div class=chips role=group aria-labelledby=app-client-audience><button type=button class=chip>Everyone on this hub</button><button type=button class=chip>Only me`),dD=I(`<form class=grant-form novalidate><label class=text-field><span class=field-title>Name</span><span class="field-desc muted small">Shown on the consent page.</span><input type=text maxlength=100></label><label class=text-field><span class=field-title>Redirect URIs</span><span class="field-desc muted small">One per line, matched exactly: https, or http on 127.0.0.1, [::1] or localhost.</span><textarea rows=3 placeholder=https://app.example.com/hub/callback></textarea></label><fieldset class=grant-verbs><legend class=field-title>Scopes it may ask for</legend></fieldset><div class=dialog-actions><button type=button class=btn>Cancel</button><button type=submit class="btn primary">`),fD=I(`<label class=check><input type=checkbox><span>`),pD=I(`<div class=stack><p class=warn><strong>Copy the secret now.</strong> It will not be shown again. Keep it on the app's server only.</p><div class=dialog-actions><button type=button class="btn primary">Done`),mD=I(`<div class="stack app-tokens"id=app-tokens><div class=row><div class=grow><h3>App tokens</h3><p class="small muted">For MCP gateways, CLIs and other apps. The secret is shown once; grants use the non-secret token ID.</p></div><button type=button class="btn small primary">New token`),hD=I(`<p class="small muted">No app tokens yet.`),gD=I(`<li class=row><div class=grow><div class=name></div><div class="small muted mono">app:</div><div class="small muted"></div></div><button type=button class="btn small danger">Revoke`),_D=I(`<div class="stack launches"id=launches><div class=row><div class=grow><h3>Launches</h3><p class="small muted">Sessions started on your machines by you, apps and sessions. A queued one says why it waits.</p></div><button type=button class="btn small">Refresh`),vD=I(`<p class="small muted">No live launches.`),yD=I(`<div class="small warn"data-launcher-revoked>`),bD=I(`<div class="small muted"data-launch-managed>`),xD=I(`<button type=button class="btn small danger">Stop`),SD=I(`<li class=row><div class=grow><div class=name></div><div class="small muted"></div><div class=small data-launch-reason>`),CD=I(`<span class="field-desc muted small">`),wD=I(`<div class=copy-field><span class=field-title></span><div class=copy-row><div class="copy-value mono"role=textbox aria-readonly=true tabindex=0></div><button type=button class="btn small">Copy`),TD=I(`<div class=stack><p class=warn><strong>Copy this token now.</strong> It will not be shown again.</p><div class=dialog-actions><button type=button class="btn primary">Done`),ED=I(`<p class=error role=alert>`),DD=I(`<form class=grant-form novalidate><label class=text-field><span class=field-title>Label</span><span class="field-desc muted small">Where this token will be used.</span><input type=text maxlength=100></label><fieldset class=grant-verbs><legend class=field-title>Scopes</legend></fieldset><p class="small muted">Act and launch scopes still require grants. Start with read and message scopes unless the app needs more.</p><div class=dialog-actions><button type=button class=btn>Cancel</button><button type=submit class="btn primary">Create token`),OD=I(`<li><label class=switch><span class=notify-kind><span>Agent actions on this hub</span><span class="small muted">Admin: the switch for every user of this hub.</span></span><input type=checkbox data-hub-acting>`),kD=I(`<ul class=switches><li><label class=switch><span class=notify-kind><span>Agent actions</span><span class="small muted">Let agents act for you within their grants. Off: every agent action is refused (paused).</span></span><input type=checkbox data-acting>`),AD=I(`<p class="small warn"role=status data-acting-note>`),jD=I(`<ul class="list grants">`),MD=I(`<div class=stack><div class=row><p class="small muted grow">Each grant lets one holder (a session, a reserved role like @@orchestrator, or an app) act in some projects, for a while.</p><button type=button class="btn small primary">New grant`),ND=I(`<p class="small muted">No grants. Agents can still ask you (Decisions).`),PD=I(`<dt>Permissions`),FD=I(`<dd class=mono>`),ID=I(`<dt>Never`),LD=I(`<button type=button class="btn small danger">Revoke`),RD=I(`<li><div class=grow><div class=name><span></span></div><dl class="grant-facts small"><dt>Projects</dt><dd></dd><dt>May</dt><dd></dd><dt>Limits</dt><dd></dd></dl><div class="small muted"data-expiry>`),zD=I(`<p class="field-error small"role=alert>`),BD=I(`<div class="text-field grant-field"><span class=field-title></span><span class="field-desc muted small">`),VD=I(`<ul class="pick-chips holder-chip"aria-label="Holder: chosen">`),HD=I(`<p class="small warn"data-approve-note>These only apply to approve: tick approve, or remove them.`),UD=I(`<fieldset aria-label=Approving><label class=check><input type=checkbox aria-label="May allow always"><span>May answer “Always allow” (still only for patterns it may approve)`),WD=I(`<p class=error role=alert data-error=form>`),GD=I(`<form class=grant-form novalidate><div class="text-field grant-field"data-field=holder><span class=field-title>Holder</span><span class="field-desc muted small"id=grant-hint-holder></span></div><fieldset class=grant-verbs aria-label=Actions><legend class=field-title>May</legend><div class=verb-grid></div></fieldset><div class=grant-limits><div class="text-field grant-field"data-field=expires><span class=field-title id=grant-expires-title>Expires after</span><span class="field-desc muted small"></span><div class=expiry-row><div class=chips role=group aria-labelledby=grant-expires-title></div><input type=text class=expiry-input aria-label="Expires after"placeholder="e.g. 12h"></div></div><div class="text-field grant-field"data-field=maxActionsPerHour><span class=field-title>Actions per hour</span><span class="field-desc muted small">1–1000</span><div class=stepper><button type=button class="btn small"aria-label="Fewer actions per hour">−</button><input type=number inputmode=numeric min=1 max=1000 step=1 aria-label="Actions per hour"><button type=button class="btn small"aria-label="More actions per hour">+</button></div></div></div><div class=dialog-actions><button type=button class=btn>Cancel</button><button type=submit class="btn primary">`),KD=I(`<label><input type=checkbox><span class=verb-text><span class=verb-name></span><span class="verb-help muted small">`),qD=I(`<button type=button class=chip>`),JD=I(`<ol class="list audit agent-audit">`),YD=I(`<p class="small muted">Loading…`),XD=I(`<button type=button class="btn small">Load older`),ZD=I(`<div class=stack>`),QD=I(`<p class="small err">Could not load: `),$D=I(`<p class="small muted">No agent actions yet.`),eO=I(`<span>`),tO=I(`<li class=audit-row><div class=grow><div class=name><span></span> <span class=muted></span></div><div class="small muted"><span></span></div></div><time class="small muted">`),nO=50,rO=`/api/agent/grants`,iO=`/api/agent/app-tokens`,aO=`/api/agent/launches`,oO=`/api/agent/connections`,sO=`/api/agent/app-clients`,[cO,lO]=u(0);function uO(){let e=d(()=>G(iO).then(Je)),t=d(()=>G(oO).then(Wt)),r=C(()=>[...e[0]()??[],...(t[0]()??[]).map(e=>({id:e.id,label:`${e.clientName} (connected app)`,scopes:e.scopes,created:e.created}))]),[i,a]=u(`grants`);return x(()=>{let e=Pt().hash;e===`#agent-activity`?a(`activity`):e===`#grants`&&a(`grants`)}),(()=>{var o=YE(),c=o.firstChild.nextSibling,u=c.firstChild,d=u.nextSibling;return y(o,n(yO,{}),c),y(o,n(dO,{connections:t}),c),y(o,n(fO,{onChanged:()=>void t[1].refetch()}),c),y(o,n(hO,{tokens:e}),c),y(o,n(gO,{}),c),u.$$click=()=>a(`grants`),d.$$click=()=>a(`activity`),y(o,n(l,{get when(){return i()===`grants`},get children(){return n(bO,{tokens:r})}}),null),y(o,n(l,{get when(){return i()===`activity`},get children(){var e=JE();return y(e,n(SO,{})),e}}),null),s(e=>{var t=i()===`grants`,n=i()===`activity`;return t!==e.e&&b(u,`aria-pressed`,e.e=t),n!==e.t&&b(d,`aria-pressed`,e.t=n),e},{e:void 0,t:void 0}),o})()}function dO(e){let[t,{mutate:i,refetch:a}]=e.connections,o=async e=>{if(await P(`Revoke ${e.clientName}? Its tokens stop working at once and its grants and webhooks are deleted. Sessions it launched keep running until you stop them under Launches.`,`Revoke`,{danger:!0}))try{await V(`${oO}/${K(e.id)}`,{method:`DELETE`}),i(t=>(t??[]).filter(t=>t.id!==e.id)),lO(e=>e+1),q(`${e.clientName} revoked`)}catch(e){q(U(e),`err`),a()}};return(()=>{var e=ZE(),i=e.firstChild.firstChild.nextSibling;return i.$$click=()=>void a(),y(e,n(l,{get when(){return t()},get fallback(){return(()=>{var e=QE();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${U(t.error)}`:`Loading…`})()),e})()},get children(){return n(l,{get when(){return t().length},get fallback(){return $E()},get children(){var e=XE();return y(e,n(m,{get each(){return t()},children:e=>{let t=()=>rt(e,N());return(()=>{var n=eD(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,c=a.nextSibling,l=c.nextSibling,u=r.nextSibling;return y(i,()=>t().title),y(a,()=>t().holder),y(c,()=>t().scopes),y(l,()=>t().detail),u.$$click=()=>void o(e),s(t=>{var r=e.id,i=`Revoke ${e.clientName}`;return r!==t.e&&b(n,`data-connection`,t.e=r),i!==t.t&&b(u,`aria-label`,t.t=i),t},{e:void 0,t:void 0}),n})()}})),e}})}}),null),e})()}function fO(e){let[t,{mutate:i,refetch:a}]=d(()=>G(sO).then(ge)),[o,c]=u(),[f,p]=u(),h=e=>e.audience===`user`||qn(X()),g=e=>i(t=>[e,...(t??[]).filter(t=>t.id!==e.id)].sort((e,t)=>t.created-e.created)),_=async t=>{let n=!t.disabled;if(!n||await P(`Disable ${t.name}? Every account connected to it is disconnected at once.`,`Disable`,{danger:!0}))try{let r=Ge((await(await V(`${sO}/${K(t.id)}`,{method:`PATCH`,json:{disabled:n}})).json())?.client);r?g(r):a(),q(n?`${t.name} disabled`:`${t.name} enabled`),e.onChanged()}catch(e){q(U(e),`err`)}},v=async e=>{if(await P(`Rotate the secret of ${e.name}? The old secret stops working at once: update the app's server first.`,`Rotate`,{danger:!0}))try{let t=await(await V(`${sO}/${K(e.id)}/secret`,{method:`POST`,json:{}})).json(),n=Ge(t?.client);if(!n||typeof t?.secret!=`string`)throw Error(`The hub did not return the new secret`);g(n),p({client:n,secret:t.secret})}catch(e){q(U(e),`err`)}},x=async t=>{if(await P(`Delete ${t.name}? Every account connected to it is disconnected and the app can no longer connect.`,`Delete`,{danger:!0}))try{await V(`${sO}/${K(t.id)}`,{method:`DELETE`}),i(e=>(e??[]).filter(e=>e.id!==t.id)),q(`${t.name} deleted`),e.onChanged()}catch(e){q(U(e),`err`),a()}};return(()=>{var i=tD(),a=i.firstChild.firstChild,u=a.firstChild.nextSibling,d=u.firstChild.nextSibling;d.nextSibling;var S=a.nextSibling;return y(u,()=>qn(X())?`everyone on this hub, for hub-wide ones`:`only you`,d),S.$$click=()=>c(`new`),y(i,n(l,{get when(){return o()},keyed:!0,children:t=>n(pO,{client:t===`new`?void 0:t,onClose:()=>c(void 0),onSaved:(t,n)=>{g(t),c(void 0),n&&p(n),e.onChanged()}})}),null),y(i,n(l,{get when(){return f()},keyed:!0,children:e=>n(mO,{get client(){return e.client},get secret(){return e.secret},onClose:()=>p(void 0)})}),null),y(i,n(l,{get when(){return t()},get fallback(){return(()=>{var e=QE();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${U(t.error)}`:`Loading…`})()),e})()},get children(){return n(l,{get when(){return t().length},get fallback(){return nD()},get children(){var e=XE();return y(e,n(m,{get each(){return t()},children:e=>{let t=()=>je(e);return(()=>{var r=cD(),i=r.firstChild.firstChild,a=i.firstChild,o=i.nextSibling,u=o.nextSibling;u.firstChild;var d=u.nextSibling;return d.firstChild,y(i,()=>e.name,a),y(a,()=>t().badge),y(i,n(l,{get when(){return t().state},get children(){var e=rD();return y(e,()=>t().state),e}}),null),y(o,()=>e.id),y(u,()=>t().redirects,null),y(d,()=>t().scopes,null),y(r,n(l,{get when(){return h(e)},get children(){return[(()=>{var t=iD();return t.$$click=()=>c(e),s(()=>b(t,`aria-label`,`Edit ${e.name}`)),t})(),(()=>{var t=aD();return t.$$click=()=>void v(e),s(()=>b(t,`aria-label`,`Rotate the secret of ${e.name}`)),t})(),(()=>{var t=oD();return t.$$click=()=>void _(e),y(t,()=>e.disabled?`Enable`:`Disable`),s(()=>b(t,`aria-label`,`${e.disabled?`Enable`:`Disable`} ${e.name}`)),t})(),(()=>{var t=sD();return t.$$click=()=>void x(e),s(()=>b(t,`aria-label`,`Delete ${e.name}`)),t})()]}}),null),s(()=>b(r,`data-app-client`,e.id)),r})()}})),e}})}}),null),i})()}function pO(e){let[t,i]=u(e.client?.name??``),[a,o]=u((e.client?.redirectURIs??[]).join(`
13
+ `)),[c,d]=u([...e.client?.scopes??[`sessions:read`]]),[f,p]=u(e.client?.audience??(qn(X())?`hub`:`user`)),[h,g]=u({}),[_,v]=u(!1),x=async n=>{n.preventDefault();let r=Rt({name:t(),redirects:a(),scopes:c(),...e.client?{}:{audience:f()}});if(!r.ok)return g({[r.field]:r.error});g({}),v(!0);try{let t=await(await V(e.client?`${sO}/${K(e.client.id)}`:sO,{method:e.client?`PATCH`:`POST`,json:r.body})).json(),n=Ge(t?.client);if(!n)throw Error(`The hub did not return the client`);q(e.client?`${n.name} updated`:`${n.name} registered`),e.onSaved(n,!e.client&&typeof t?.secret==`string`?{client:n,secret:t.secret}:void 0)}catch(e){g({form:U(e)})}finally{v(!1)}},S=e=>n(l,{get when(){return h()[e.field]},get children(){var t=lD();return y(t,()=>h()[e.field]),s(n=>{var r=e.field===`form`?`error`:`field-error small`,i=e.field;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`data-error`,n.t=i),n},{e:void 0,t:void 0}),t}});return n(de,{open:!0,get title(){return r(()=>!!e.client)()?`Edit ${e.client.name}`:`Register an app`},get onClose(){return e.onClose},class:`app-client-dialog`,get children(){var u=dD(),h=u.firstChild,g=h.firstChild.nextSibling.nextSibling,v=h.nextSibling,C=v.firstChild.nextSibling.nextSibling,w=v.nextSibling;w.firstChild;var T=w.nextSibling,E=T.firstChild,D=E.nextSibling;return u.addEventListener(`submit`,e=>void x(e)),g.$$input=e=>i(e.currentTarget.value),y(u,n(S,{field:`name`}),v),C.$$input=e=>o(e.currentTarget.value),y(u,n(S,{field:`redirects`}),w),y(w,n(m,{each:Nt,children:e=>(()=>{var t=fD(),n=t.firstChild,r=n.nextSibling;return n.addEventListener(`change`,t=>d(t.currentTarget.checked?[...c(),e]:c().filter(t=>t!==e))),y(r,e),s(()=>n.checked=c().includes(e)),t})()}),null),y(u,n(S,{field:`scopes`}),T),y(u,n(l,{get when(){return r(()=>!e.client)()&&qn(X())},get children(){var e=uD(),t=e.firstChild.nextSibling.firstChild,n=t.nextSibling;return t.$$click=()=>p(`hub`),n.$$click=()=>p(`user`),s(e=>{var r=f()===`hub`,i=f()===`user`;return r!==e.e&&b(t,`aria-pressed`,e.e=r),i!==e.t&&b(n,`aria-pressed`,e.t=i),e},{e:void 0,t:void 0}),e}}),T),y(u,n(S,{field:`form`}),T),B(E,`click`,e.onClose,!0),y(D,()=>e.client?`Save`:`Register`),s(()=>D.disabled=_()),s(()=>g.value=t()),s(()=>C.value=a()),u}})}function mO(e){let t=async(e,t)=>{try{await navigator.clipboard.writeText(e),q(`${t} copied`)}catch{q(`Could not copy ${t.toLowerCase()}`,`err`)}};return n(de,{open:!0,get title(){return`Save the secret of ${e.client.name}`},get onClose(){return e.onClose},class:`app-token-dialog`,get children(){var r=pD(),i=r.firstChild.nextSibling,a=i.firstChild;return y(r,n(_O,{field:`client-id`,title:`Client ID`,get value(){return e.client.id},onCopy:()=>void t(e.client.id,`Client ID`)}),i),y(r,n(_O,{field:`client-secret`,title:`Client secret`,get value(){return e.secret},onCopy:()=>void t(e.secret,`Secret`)}),i),y(r,n(_O,{field:`issuer`,title:`Hub (issuer)`,desc:`The app reads the endpoints from /.well-known/oauth-authorization-server.`,get value(){return X()?.publicURL??location.origin},onCopy:()=>void t(X()?.publicURL??location.origin,`Issuer`)}),i),B(a,`click`,e.onClose,!0),r}})}function hO(e){let[t,{mutate:i,refetch:a}]=e.tokens,[o,c]=u(!1),d=async e=>{if(await P(`Revoke ${e.label||e.id}? Apps using it will stop working immediately. Sessions it launched keep running until you stop them under Launches.`,`Revoke`,{danger:!0}))try{await V(`${iO}/${K(e.id)}`,{method:`DELETE`}),i(t=>(t??[]).filter(t=>t.id!==e.id)),lO(e=>e+1),q(`App token revoked`)}catch(e){q(U(e),`err`),a()}};return(()=>{var e=mD(),a=e.firstChild.firstChild.nextSibling;return a.$$click=()=>c(!0),y(e,n(l,{get when(){return o()},get children(){return n(vO,{onClose:()=>c(!1),onCreated:e=>i(t=>[e,...(t??[]).filter(t=>t.id!==e.id)])})}}),null),y(e,n(l,{get when(){return t()},get fallback(){return(()=>{var e=QE();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${U(t.error)}`:`Loading…`})()),e})()},get children(){return n(l,{get when(){return t().length},get fallback(){return hD()},get children(){var e=XE();return y(e,n(m,{get each(){return t()},children:e=>(()=>{var t=gD(),n=t.firstChild,i=n.firstChild,a=i.nextSibling;a.firstChild;var o=a.nextSibling,c=n.nextSibling;return y(i,()=>e.label||`Unnamed app`),y(a,()=>e.id,null),y(o,()=>e.scopes.join(`, `)||`No scopes`,null),y(o,(()=>{var t=r(()=>!!e.created);return()=>t()?` · created ${R(e.created,N())}`:``})(),null),c.$$click=()=>void d(e),s(()=>b(t,`data-app-token`,e.id)),t})()})),e}})}}),null),e})()}function gO(){let[e,{refetch:t,mutate:i}]=d(cO,()=>G(`${aO}?state=${gT.join(`,`)}`).then(e=>xT(e)));M(Nu(t=>{let n=DT({state:e.state,latest:()=>e.latest},t);n&&i(n)}));let[a,o]=u(),c=async e=>{if(await P(`Stop ${ET(e,N()).title}? Its session is stopped and its workspace cleaned up by its policy.`,`Stop`,{danger:!0})){o(e.id);try{await V(`${aO}/${K(e.id)}`,{method:`DELETE`}),q(`Launch stopped`)}catch(e){q(U(e),`err`)}finally{o(void 0),t()}}};return(()=>{var i=_D(),o=i.firstChild.firstChild.nextSibling;return o.$$click=()=>void t(),y(i,n(l,{get when(){return e()},get fallback(){return(()=>{var t=QE();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?`Could not load: ${U(e.error)}`:`Loading…`})()),t})()},get children(){return n(l,{get when(){return e().length},get fallback(){return vD()},get children(){var t=XE();return y(t,n(m,{get each(){return e()},children:e=>{let t=()=>ET(e,N());return(()=>{var r=SD(),i=r.firstChild,o=i.firstChild,u=o.nextSibling,d=u.nextSibling;return y(o,()=>t().title),y(u,()=>t().status),y(d,()=>t().detail),y(i,n(l,{get when(){return t().flag},get children(){var e=yD();return y(e,()=>t().flag),e}}),null),y(i,n(l,{get when(){return t().managed},get children(){var e=bD();return y(e,()=>t().managed),e}}),null),y(r,n(l,{get when(){return t().stopLabel},get children(){var n=xD();return n.$$click=()=>void c(e),s(r=>{var i=t().stopLabel,o=a()===e.id;return i!==r.e&&b(n,`aria-label`,r.e=i),o!==r.t&&(n.disabled=r.t=o),r},{e:void 0,t:void 0}),n}}),null),s(()=>b(r,`data-launch`,e.id)),r})()}})),t}})}}),null),i})()}function _O(e){let t=`copy-field-${e.field}`;return(()=>{var r=wD(),i=r.firstChild,a=i.nextSibling,o=a.firstChild,c=o.nextSibling;return b(i,`id`,t),y(i,()=>e.title),y(r,n(l,{get when(){return e.desc},get children(){var t=CD();return y(t,()=>e.desc),t}}),a),b(o,`aria-labelledby`,t),y(o,()=>e.value),c.$$click=()=>e.onCopy(),s(t=>{var n=e.field,i=`Copy ${e.title.toLowerCase()}`;return n!==t.e&&b(r,`data-copy-field`,t.e=n),i!==t.t&&b(c,`aria-label`,t.t=i),t},{e:void 0,t:void 0}),r})()}function vO(e){let[t,r]=u(`MCP Gateway`),[i,a]=u([`sessions:read`,`messages:send`,`messages:read`]),[o,c]=u(``),[d,f]=u(``),[p,h]=u(``),[g,_]=u(!1),v=async n=>{n.preventDefault();let r=Ft(t(),i());if(!r.ok)return h(r.error);_(!0),h(``);try{let t=await(await V(iO,{method:`POST`,json:r.body})).json(),n=Qt(t);if(!n||typeof t?.token!=`string`)throw Error(`The hub did not return the new token`);e.onCreated(n),c(t.token),f(`app:${n.id}`)}catch(e){h(U(e))}finally{_(!1)}},b=async(e,t)=>{try{await navigator.clipboard.writeText(e),q(`${t} copied`)}catch{q(`Could not copy ${t.toLowerCase()}`,`err`)}};return n(de,{open:!0,get title(){return o()?`Save your app token`:`New app token`},get onClose(){return e.onClose},class:`app-token-dialog`,get children(){return n(l,{get when(){return o()},get fallback(){return(()=>{var o=DD(),c=o.firstChild,u=c.firstChild.nextSibling.nextSibling,d=c.nextSibling;d.firstChild;var f=d.nextSibling.nextSibling,h=f.firstChild,_=h.nextSibling;return o.addEventListener(`submit`,e=>void v(e)),u.$$input=e=>r(e.currentTarget.value),y(d,n(m,{each:Nt,children:e=>(()=>{var t=fD(),n=t.firstChild,r=n.nextSibling;return n.addEventListener(`change`,t=>a(t.currentTarget.checked?[...i(),e]:i().filter(t=>t!==e))),y(r,e),s(()=>n.checked=i().includes(e)),t})()}),null),y(o,n(l,{get when(){return p()},get children(){var e=ED();return y(e,p),e}}),f),B(h,`click`,e.onClose,!0),s(()=>_.disabled=g()),s(()=>u.value=t()),o})()},get children(){var t=TD(),r=t.firstChild.nextSibling,i=r.firstChild;return y(t,n(_O,{field:`token`,title:`Bearer token`,get value(){return o()},onCopy:()=>void b(o(),`Token`)}),r),y(t,n(_O,{field:`holder`,title:`Grant holder`,desc:`Use this non-secret value if you later create an acting or launch grant.`,get value(){return d()},onCopy:()=>void b(d(),`Holder`)}),r),B(i,`click`,e.onClose,!0),t}})}})}function yO(){let[e,{mutate:t}]=d(()=>G(`/api/agent/acting`).then(Ct)),[i,a]=d(()=>qn(X())||void 0,()=>G(`/api/admin/agents/acting`).then(e=>e?.enabled!==!1)),[o,c]=u(!1),f=async e=>{let n=e.checked;c(!0);try{t(Ct(await(await V(`/api/agent/acting`,{method:`PUT`,json:{enabled:n}})).json())),q(n?`Agent actions are on for you`:`Agent actions are off for you`)}catch(t){e.checked=!n,q(U(t),`err`)}finally{c(!1)}},p=async e=>{let n=e.checked;if(!n&&!await P(`Turn agent actions off for everyone on this hub? No agent can act until an admin turns them on again.`,`Turn off`,{danger:!0}))e.checked=!0;else{c(!0);try{let e=await(await V(`/api/admin/agents/acting`,{method:`PUT`,json:{enabled:n}})).json();a.mutate(e?.enabled!==!1),q(n?`Agent actions are on for this hub`:`Agent actions are off for this hub`);let r=await G(`/api/agent/acting`).catch(()=>void 0);r&&t(Ct(r))}catch(t){e.checked=!n,q(U(t),`err`)}finally{c(!1)}}};return n(l,{get when(){return e()},get fallback(){return(()=>{var t=QE();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?`Could not load: ${U(e.error)}`:`Loading…`})()),t})()},children:e=>[(()=>{var t=kD(),a=t.firstChild.firstChild.firstChild.nextSibling;return a.addEventListener(`change`,e=>void f(e.currentTarget)),y(t,n(l,{get when(){return r(()=>!!qn(X()))()&&i()!==void 0},get children(){var e=OD(),t=e.firstChild.firstChild.nextSibling;return t.addEventListener(`change`,e=>void p(e.currentTarget)),s(()=>t.disabled=o()),s(()=>t.checked=i()),e}}),null),s(()=>a.disabled=o()),s(()=>a.checked=e().on),t})(),n(l,{get when(){return e().note},get children(){var t=AD();return y(t,()=>e().note),t}})]})}function bO(e){let[t,{refetch:i,mutate:a}]=d(()=>G(rO).then(Ce)),[o,c]=u(),[f,p]=u(Date.now()),h=setInterval(()=>p(Date.now()),1e3);M(()=>clearInterval(h));let g=async e=>{if(await P(`Revoke the grant of ${e.holder}? It stops at once.`,`Revoke`,{danger:!0}))try{let t=await(await V(`${rO}/${K(e.id)}`,{method:`DELETE`})).json(),n=Te(t?.grant);n?a(e=>(e??[]).map(e=>e.id===n.id?n:e)):i(),q(`Grant of ${e.holder} revoked`)}catch(e){q(U(e),`err`),i()}},_=e=>{a(t=>[e,...(t??[]).filter(t=>t.id!==e.id)].sort((e,t)=>t.created-e.created)),c(void 0)};return(()=>{var i=MD(),a=i.firstChild.firstChild.nextSibling;return a.$$click=()=>c(`new`),y(i,n(l,{get when(){return o()},keyed:!0,children:r=>n(xO,{grant:r===`new`?void 0:r,get grants(){return t()??[]},get tokens(){return e.tokens()??[]},onSaved:_,onClose:()=>c(void 0)})}),null),y(i,n(l,{get when(){return t()},get fallback(){return(()=>{var e=QE();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${U(t.error)}`:`Loading…`})()),e})()},get children(){return n(l,{get when(){return t().length},get fallback(){return ND()},get children(){var e=jD();return y(e,n(m,{get each(){return t()},children:e=>{let t=()=>yt(e,f());return(()=>{var r=RD(),i=r.firstChild.firstChild,a=i.firstChild,o=i.nextSibling,u=o.firstChild.nextSibling,d=u.nextSibling.nextSibling,f=d.nextSibling,p=f.nextSibling,m=o.nextSibling;return y(i,()=>t().holder,a),y(a,()=>t().stateLabel),y(u,()=>t().projects),y(d,()=>t().verbs),y(o,n(l,{get when(){return t().permit},get children(){return[PD(),(()=>{var e=FD();return y(e,()=>t().permit),e})()]}}),f),y(o,n(l,{get when(){return t().never},get children(){return[ID(),(()=>{var e=FD();return y(e,()=>t().never),e})()]}}),f),y(p,()=>t().limits),y(m,()=>t().expiry),y(r,n(l,{get when(){return t().editable},get children(){return[(()=>{var t=iD();return t.$$click=()=>c(e),s(()=>b(t,`aria-label`,`Edit grant of ${e.holder}`)),t})(),(()=>{var t=LD();return t.$$click=()=>void g(e),s(()=>b(t,`aria-label`,`Revoke grant of ${e.holder}`)),t})()]}}),null),s(n=>{var i=`grant-row${t().editable?``:` ended`}`,o=e.id,s=`badge-pill ${t().state}`;return i!==n.e&&k(r,n.e=i),o!==n.t&&b(r,`data-grant`,n.t=o),s!==n.a&&k(a,n.a=s),n},{e:void 0,t:void 0,a:void 0}),r})()}})),e}})}}),null),i})()}function xO(e){let[t,i]=u(Lt(e.grant)),[a,o]=u({}),[c,f]=u(``),[p,h]=u(!1),[g,_]=u({holder:``,projects:``,permit:``,never:``}),v=(e,t)=>{_(n=>({...n,[e]:t})),a()[e]&&o(t=>({...t,[e]:void 0}))},[x]=d(()=>G(`/api/agent/who`).then(pE,()=>[])),S=C(()=>SE({who:x()??[],sessions:Pu(),tokens:e.tokens,hidden:wu()})),w=C(()=>OE({sessions:Pu(),grants:e.grants})),T=C(()=>FE(`permit`,e.grants)),E=C(()=>FE(`never`,e.grants)),D=(e,t)=>{i(n=>({...n,[e]:t})),a()[e]&&o(t=>({...t,[e]:void 0}))},O=async n=>{n.preventDefault(),f(``);let r=qE(t(),g());i(r.draft);for(let e of r.cleared)_(t=>({...t,[e]:``}));let a=r.result;if(!a.ok)o(a.errors);else{o({}),h(!0);try{let t=e.grant?`${rO}/${K(e.grant.id)}`:rO,n=await(await V(t,{method:e.grant?`PUT`:`POST`,json:a.body})).json(),r=Te(n?.grant);q(e.grant?`Grant updated`:`Grant created`),r?e.onSaved(r):e.onClose()}catch(e){let t=U(e),n=e instanceof W&&(e.status===400||e.status===404)?Jt(t):void 0;n?o({[n]:t}):f(e instanceof W&&e.hint?`${t} (${e.hint})`:t)}finally{h(!1)}}},A=e=>n(l,{get when(){return a()[e.field]},get children(){var t=zD();return y(t,()=>a()[e.field]),s(n=>{var r=e.field,i=`grant-error-${e.field}`;return r!==n.e&&b(t,`data-error`,n.e=r),i!==n.t&&b(t,`id`,n.t=i),n},{e:void 0,t:void 0}),t}}),j=e=>(()=>{var r=BD(),i=r.firstChild,o=i.nextSibling;return y(i,()=>e.label),y(o,()=>e.hint),y(r,n(oE,{get label(){return e.label},get placeholder(){return e.placeholder},get options(){return e.options},get values(){return IE(t()[e.field])},onAdd:n=>D(e.field,LE(t()[e.field],n)),onRemove:n=>D(e.field,RE(t()[e.field],n)),get query(){return g()[e.field]},onQuery:t=>v(e.field,t),get problem(){return e.check},get mono(){return e.mono},get chip(){return e.chip},get invalid(){return!!a()[e.field]},get describedBy(){return`grant-hint-${e.field}${a()[e.field]?` grant-error-${e.field}`:``}`}}),null),y(r,n(A,{get field(){return e.field}}),null),s(t=>{var n=e.field,i=`grant-hint-${e.field}`;return n!==t.e&&b(r,`data-field`,t.e=n),i!==t.t&&b(o,`id`,t.t=i),t},{e:void 0,t:void 0}),r})(),M=e=>({label:e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()||e,detail:e}),N=()=>CE(t().holder,S()),ee=()=>t().allow.includes(`approve`);return n(de,{open:!0,get title(){return r(()=>!!e.grant)()?`Edit grant of ${e.grant.holder}`:`New grant`},get onClose(){return e.onClose},wide:!0,class:`grant-dialog`,get children(){var i=GD(),o=i.firstChild,u=o.firstChild.nextSibling,d=o.nextSibling,f=d.firstChild.nextSibling,h=d.nextSibling,_=h.firstChild,x=_.firstChild.nextSibling,C=x.nextSibling.firstChild,P=C.nextSibling,F=_.nextSibling,te=F.firstChild.nextSibling.nextSibling.firstChild,I=te.nextSibling,ne=I.nextSibling,re=h.nextSibling,ie=re.firstChild,ae=ie.nextSibling;return i.addEventListener(`submit`,e=>void O(e)),y(u,()=>e.grant?`A grant's holder cannot change: revoke it and create another.`:`Search, or type @@role, @name, ses_… or app:<token id>. A role follows whoever holds it; a session is pinned to that session.`),y(o,n(l,{get when(){return t().holder},get fallback(){return n(iE,{label:`Holder`,placeholder:`Search roles, sessions and apps…`,get options(){return S()},get query(){return g().holder},onQuery:e=>v(`holder`,e),onPick:e=>D(`holder`,e),problem:wE,get invalid(){return!!a().holder},get describedBy(){return`grant-hint-holder${a().holder?` grant-error-holder`:``}`}})},get children(){var i=VD();return y(i,n(aE,{get kind(){return N().kindLabel},get label(){return N().label},get detail(){return r(()=>N().label===t().holder)()?N().detail:`${t().holder} · ${N().detail}`},get title(){return t().holder},removeLabel:`Change holder`,get onRemove(){return e.grant?void 0:()=>D(`holder`,``)}})),s(()=>b(i,`data-holder`,t().holder)),i}}),null),y(o,n(A,{field:`holder`}),null),y(i,n(j,{field:`projects`,label:`Projects`,hint:`Where it may act: project directories (subdirectories and worktrees included).`,placeholder:`Search projects or type an absolute path…`,get options(){return w()},check:DE,chip:M}),d),y(f,n(m,{each:Bt,children:e=>(()=>{var n=KD(),r=n.firstChild,i=r.nextSibling.firstChild,a=i.nextSibling;return r.addEventListener(`change`,n=>D(`allow`,n.currentTarget.checked?[...t().allow,e]:t().allow.filter(t=>t!==e))),b(r,`aria-label`,e),y(i,e),y(a,()=>zE[e]),s(()=>k(n,`verb-option${t().allow.includes(e)?` on`:``}`)),s(()=>r.checked=t().allow.includes(e)),n})()})),y(d,n(A,{field:`allow`}),null),y(i,n(l,{get when(){return GE(t(),g())},get children(){var e=UD(),r=e.firstChild,i=r.firstChild;return y(e,n(l,{get when(){return!ee()},get children(){return HD()}}),r),y(e,n(j,{field:`permit`,label:`Permissions it may approve`,hint:`Patterns action[:glob]: the action alone covers every resource (e.g. shell:bun test *).`,placeholder:`Search patterns or type one`,get options(){return T()},check:jE,mono:!0}),r),y(e,n(j,{field:`never`,label:`Never`,hint:`Patterns it may never approve; never wins over every allow.`,placeholder:`Search patterns or type one, e.g. shell:rm *`,get options(){return E()},check:jE,mono:!0}),r),i.addEventListener(`change`,e=>D(`allowAlways`,e.currentTarget.checked)),y(e,n(A,{field:`allowAlways`}),null),s(()=>k(e,`grant-approve${ee()?``:` idle`}`)),s(()=>i.checked=t().allowAlways),e}}),h),y(x,()=>e.grant?`From now: saving restarts the countdown.`:`At most 30 days.`),y(C,n(m,{each:BE,children:e=>(()=>{var n=qD();return n.$$click=()=>D(`expires`,e),y(n,e),s(()=>b(n,`aria-pressed`,t().expires.trim()===e)),n})()})),P.$$input=e=>D(`expires`,e.currentTarget.value),y(_,n(A,{field:`expires`}),null),te.$$click=()=>D(`maxActionsPerHour`,WE(t().maxActionsPerHour,-1)),I.$$input=e=>D(`maxActionsPerHour`,e.currentTarget.value),ne.$$click=()=>D(`maxActionsPerHour`,WE(t().maxActionsPerHour,1)),y(F,n(A,{field:`maxActionsPerHour`}),null),y(i,n(l,{get when(){return c()},get children(){var e=WD();return y(e,c),e}}),re),B(ie,`click`,e.onClose,!0),y(ae,()=>e.grant?`Save`:`Create grant`),s(()=>ae.disabled=p()),s(()=>P.value=t().expires),s(()=>I.value=t().maxActionsPerHour),i}})}function SO(){let[e,t]=u([]),[i,a]=u(),[o,c]=u(`loading`),[f,p]=u(``),h=async e=>{c(`loading`);try{let n=Xt(await G(`/api/agent/audit?limit=${nO}${e===void 0?``:`&before=${e}`}`));t(t=>{if(e===void 0)return n.entries;let r=new Set(t.map(e=>e.seq));return[...t,...n.entries.filter(e=>!r.has(e.seq))]}),a(n.next),c(`ready`)}catch(e){p(U(e)),c(`failed`)}};h();let[g]=d(async()=>{try{let{decisions:e}=await G(`/api/decisions`);return(e??[]).map(Pe).filter(e=>!!e)}catch{return[]}}),_=()=>{let e=new Map((g()??[]).map(e=>[e.id,e]));for(let t of du().values())e.set(t.id,t);return[...e.values()]},v=()=>{let t=e()[0]?.seq??0;return[...Tu().filter(e=>e.seq>t),...e()]};return(()=>{var e=ZD();return y(e,n(l,{get when(){return o()!==`failed`},get fallback(){return(()=>{var e=QD();return e.firstChild,y(e,f,null),e})()},get children(){return[n(l,{get when(){return v().length||o()!==`ready`},get fallback(){return $D()},get children(){var e=JD();return y(e,n(m,{get each(){return v()},children:e=>{let t=()=>kt(e,ft(e,_()),Bu);return(()=>{var i=tO(),a=i.firstChild,o=a.firstChild,c=o.firstChild,u=c.nextSibling.nextSibling,d=o.nextSibling,f=d.firstChild,p=a.nextSibling;return y(c,()=>t().who),y(u,()=>t().what),y(f,()=>t().result),y(d,n(l,{get when(){return t().grant},get children(){return[` · `,(()=>{var e=eO();return y(e,()=>t().grant),s(()=>b(e,`title`,t().grantTitle)),e})()]}}),null),y(d,(()=>{var e=r(()=>!!t().reason);return()=>e()?` · ${t().reason}`:``})(),null),y(p,()=>R(e.at,N())),s(n=>{var r=e.seq,a=e.actor.kind===`session`?e.actor.sessionID:void 0,o=t().whatTitle,s=`audit-result ${t().tone}`,l=new Date(e.at).toISOString(),d=new Date(e.at).toLocaleString();return r!==n.e&&b(i,`data-seq`,n.e=r),a!==n.t&&b(c,`title`,n.t=a),o!==n.a&&b(u,`title`,n.a=o),s!==n.o&&k(f,n.o=s),l!==n.i&&b(p,`datetime`,n.i=l),d!==n.n&&b(p,`title`,n.n=d),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),i})()}})),e}}),n(l,{get when(){return o()===`loading`},get children(){return YD()}}),n(l,{get when(){return r(()=>o()===`ready`)()&&i()!==void 0},get children(){var e=XD();return e.$$click=()=>void h(i()),e}})]}})),e})()}z([`click`,`input`]);var CO=I(`<fieldset class=stack id=concierge-watchlist><legend class=field-title>Watchlist`),wO=I(`<p class="small muted">`),TO=I(`<span class="field-desc muted small"data-watchlist-count>Watching <!> session<!> now.`),EO=I(`<label class=check><input type=checkbox><span>Sessions that are working, blocked or failed, have a Decision open, or were active in the last <!> h<span class=muted data-watch-active-count> (<!> now)`),DO=I(`<label class=text-field><span class=small>Watch sessions active in the last (hours)</span><input type=number min=1 max=24 aria-label="Watch sessions active in the last (hours)">`),OO=I(`<label class=check><input type=checkbox><span>Pinned sessions and workspaces<span class=muted> (<!> now)`),kO=I(`<div class=stack><span class=small>Also watch</span><ul class=list></ul><form class=row><input class="mono grow"aria-label="Session to watch"placeholder="@name or ses_… (pick from the list)"list=concierge-sessions><button type=submit class="btn small">Watch`),AO=I(`<div class=stack><span class=small>Muted for the Concierge (beats everything above; your notifications are not affected)</span><ul class=list></ul><form class=row><input class="mono grow"aria-label="Session to mute"placeholder="@name or ses_… (pick from the list)"list=concierge-sessions><button type=submit class="btn small">Mute`),jO=I(`<label class=text-field><span class=small>Projects to watch (one directory per line)</span><textarea class=mono rows=2 aria-label="Projects to watch">`),MO=I(`<datalist id=concierge-sessions>`),NO=I(`<label class=text-field><span class=small>Projects to mute (one directory per line)</span><textarea class=mono rows=2 aria-label="Projects to mute">`),PO=I(`<li class="small muted">No sessions added.`),FO=I(`<li class=row><span class="small grow"></span><button type=button class="btn small">Remove`),IO=I(`<li class="small muted">Nothing muted.`),LO=I(`<li class=row><span class="small grow"></span><button type=button class="btn small">Unmute`),RO=I(`<option>`),zO=`/api/agent/concierge/watchlist`,BO=e=>Bu(e),VO=(e,t)=>e.filter(e=>e.reasons.includes(t)).length,HO=e=>[...new Set(e.split(`
14
+ `).map(e=>e.trim()).filter(Boolean))];function UO(){let[e,{refetch:t,mutate:i}]=d(()=>G(zO)),[a,o]=u(!1),[c,f]=u(``),[p,h]=u(``),g=async(n,r)=>{o(!0);try{let t=await(await n()).json(),a=e();return a&&t.config&&i({...a,config:t.config}),q(r),!0}catch(e){return q(e instanceof W&&e.status===409?`The watchlist changed elsewhere: reloaded`:`Could not save the watchlist: ${U(e)}`,`err`),!1}finally{o(!1),t()}},_=t=>g(()=>V(zO,{method:`PUT`,json:{...t,expectedRevision:e().config.revision}}),`Watchlist saved`),v=(e,t)=>g(()=>V(`${zO}/${e}`,{method:`POST`,json:{session:t}}),e===`watch`?`Watching ${BO(t)}`:e===`mute`?`Muted ${BO(t)} for the Concierge`:`Watchlist saved`);return(()=>{var t=CO();return t.firstChild,y(t,n(l,{get when(){return e()},get fallback(){return(()=>{var t=wO();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?`Could not load the watchlist: ${U(e.error)}`:`Loading…`})()),t})()},children:e=>{let t=()=>e().config;return[(()=>{var t=TO(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(t,()=>e().entries.length,n),y(t,()=>e().truncated?`+`:``,n),y(t,()=>e().entries.length===1?``:`s`,r),t})(),(()=>{var n=EO(),r=n.firstChild,i=r.nextSibling,o=i.firstChild.nextSibling,c=o.nextSibling.nextSibling,l=c.firstChild.nextSibling;return l.nextSibling,r.addEventListener(`change`,e=>void _({autoActive:e.currentTarget.checked})),y(i,()=>t().activeWithinHours,o),y(c,()=>VO(e().entries,`active`),l),s(()=>r.disabled=a()),s(()=>r.checked=t().autoActive),n})(),(()=>{var e=DO(),n=e.firstChild.nextSibling;return n.addEventListener(`change`,e=>{let n=Math.round(Number(e.currentTarget.value));n>=1&&n<=24&&n!==t().activeWithinHours?_({activeWithinHours:n}):e.currentTarget.value=String(t().activeWithinHours)}),s(()=>n.disabled=a()||!t().autoActive),s(()=>n.value=t().activeWithinHours),e})(),(()=>{var n=OO(),r=n.firstChild,i=r.nextSibling.firstChild.nextSibling,o=i.firstChild.nextSibling;return o.nextSibling,r.addEventListener(`change`,e=>void _({usePins:e.currentTarget.checked})),y(i,()=>VO(e().entries,`pinned`)+VO(e().entries,`pinned_project`),o),s(()=>r.disabled=a()),s(()=>r.checked=t().usePins),n})(),(()=>{var e=kO(),r=e.firstChild.nextSibling,i=r.nextSibling,o=i.firstChild,l=o.nextSibling;return y(r,n(m,{get each(){return t().sessions},get fallback(){return PO()},children:e=>(()=>{var t=FO(),n=t.firstChild,r=n.nextSibling;return b(t,`data-watch-session`,e),b(n,`title`,e),b(n,`data-session-id`,e),y(n,()=>BO(e)),r.$$click=()=>void v(`unwatch`,e),s(t=>{var n=a(),i=`Stop watching ${BO(e)}`;return n!==t.e&&(r.disabled=t.e=n),i!==t.t&&b(r,`aria-label`,t.t=i),t},{e:void 0,t:void 0}),t})()})),i.addEventListener(`submit`,e=>(e.preventDefault(),c().trim()&&void v(`watch`,c().trim()).then(e=>e&&f(``)))),o.$$input=e=>f(e.currentTarget.value),s(()=>l.disabled=a()||!c().trim()),s(()=>o.value=c()),e})(),(()=>{var e=AO(),r=e.firstChild.nextSibling,i=r.nextSibling,o=i.firstChild,c=o.nextSibling;return y(r,n(m,{get each(){return t().muted},get fallback(){return IO()},children:e=>(()=>{var t=LO(),n=t.firstChild,r=n.nextSibling;return b(t,`data-muted-session`,e),b(n,`title`,e),b(n,`data-session-id`,e),y(n,()=>BO(e)),r.$$click=()=>void v(`unmute`,e),s(t=>{var n=a(),i=`Unmute ${BO(e)}`;return n!==t.e&&(r.disabled=t.e=n),i!==t.t&&b(r,`aria-label`,t.t=i),t},{e:void 0,t:void 0}),t})()})),i.addEventListener(`submit`,e=>(e.preventDefault(),p().trim()&&void v(`mute`,p().trim()).then(e=>e&&h(``)))),o.$$input=e=>h(e.currentTarget.value),s(()=>c.disabled=a()||!p().trim()),s(()=>o.value=p()),e})(),(()=>{var e=jO(),n=e.firstChild.nextSibling;return n.addEventListener(`change`,e=>void _({projects:HO(e.currentTarget.value)})),s(()=>n.disabled=a()),s(()=>n.value=t().projects.join(`
15
+ `)),e})(),(()=>{var e=MO();return y(e,n(m,{get each(){return Pu().filter(e=>!e.hidden).slice(0,200)},children:e=>(()=>{var t=RO();return s(()=>b(t,`label`,e.title)),s(()=>t.value=e.id),t})()})),e})(),(()=>{var e=NO(),n=e.firstChild.nextSibling;return n.addEventListener(`change`,e=>void _({mutedProjects:HO(e.currentTarget.value)})),s(()=>n.disabled=a()),s(()=>n.value=t().mutedProjects.join(`
16
+ `)),e})()]}}),null),t})()}z([`input`,`click`]);var WO=I(`<section class=settings-section id=concierge aria-label=Concierge><p class="small muted">A hub-managed assistant that watches your sessions, tells you what needs you and answers status questions. It runs as a hidden session on one of your machines and acts only inside the grant you give it; everything else comes to you as a Decision.`),GO=I(`<button type=button class="btn small">Retry`),KO=I(`<p class="small muted"data-concierge-load>`),qO=I(`<button type=button class="btn small">Restart`),JO=I(`<button type=button class="btn small danger">Turn off`),YO=I(`<button type=button class="btn small primary">Turn on`),XO=I(`<p class="small muted"data-concierge-problem>`),ZO=I(`<p class="small muted"data-concierge-hint>After turning it on, open it from <strong>✨ Concierge</strong> at the top of the sidebar (on a phone, the ✨ in the top bar).`),QO=I(`<div class="row concierge-notice err"role=alert data-concierge-suspended><span class=grow>Stopped: </span><button type=button class="btn small">Restart`),$O=I(`<div class=stack><div class=row><div class=grow><div class=name>Status</div><div class="small muted"data-concierge-status></div></div></div><fieldset class=stack id=concierge-machine><legend class=field-title>Machine</legend><span class="field-desc muted small">It needs \`hub node\` with a workspace root and the hub plugin's OpenCode service.</span><ul class=list></ul></fieldset><div class=row id=concierge-brain data-unsupported=brain><div class=grow><div class=field-title>Brain</div><div class="small muted">Not available yet: the Concierge's tools are an exact allow-list (hub, read, glob, grep, question), and Brain's MCP tools cannot be pinned by name.</div></div></div><label class=text-field id=concierge-time-zone><span class=field-title>Time zone</span><input></label><div class=stack id=concierge-grant><div class=field-title>Grant`),ek=I(`<li class="small muted">No machines yet.`),tk=I(`<li class=row><label class="check grow"><input type=radio name=concierge-machine><span><span class="small muted"> · `),nk=I(`<div class=row><p class="small muted grow">No grant: the Concierge reads and notifies; an approve it tries becomes a Decision for you, other actions are proposals you answer.</p><button type=button class="btn small">Use the safe preset</button><button type=button class="btn small">Write a grant…`),rk=I(`<button type=button class="btn small">Renew`),ik=I(`<div class=row data-concierge-grant><div class=grow><div class=small></div><div class=small data-concierge-grant-permissions></div><div class="small muted"> actions/hour</div></div><button type=button class="btn small">Edit</button><button type=button class="btn small danger">Remove`),ak=I(`<optgroup label=Projects>`),ok=I(`<optgroup label="Workspace roots">`),sk=I(`<input class=mono aria-describedby=concierge-directory-hint>`),ck=I(`<div class=stack id=concierge-directory><label class=text-field><span class=field-title>Directory</span><select class=mono aria-describedby=concierge-directory-hint><option value>Choose a directory</option><option>Other folder…</option></select></label><span class="field-desc muted small"id=concierge-directory-hint data-concierge-directory-hint>`),lk=I(`<option>`),uk=I(`<input class=mono aria-label="Other model (provider/model)"aria-describedby=concierge-model-hint placeholder=provider/model>`),dk=I(`<div class=stack id=concierge-model><label class=text-field><span class=field-title>Model</span><select class=mono aria-describedby="concierge-model-hint concierge-model-state"><option value>Machine default</option><option>Other model…</option></select></label><span class="field-desc muted small"id=concierge-model-hint>The machine default, or one of its OpenCode models (provider/model).</span><p class="small muted"id=concierge-model-state role=status data-concierge-models-state>`),fk=I(`<optgroup>`),pk=I(`<p class="field-error small"role=alert>`),mk=I(`<label class=text-field><span class=field-title></span><span class="field-desc muted small"></span><textarea rows=2>`),hk=I(`<p class="small warn"role=note data-shell-warning>`),gk=I(`<p class=error role=alert data-error=form>`),_k=I(`<form class="grant-form card"data-concierge-grant-editor novalidate><fieldset class=stack aria-label=Projects><span class=field-title>Projects</span><span class="field-desc muted small">Where it may act (subdirectories and worktrees included).</span><div class=row><input class="mono grow"aria-label="Another project directory"placeholder=/path/to/project><button type=button class="btn small">Add</button></div></fieldset><fieldset class=grant-verbs aria-label=Actions><span class=field-title>May</span></fieldset><div class=row><label class="text-field grow"><span class=field-title>Expires after</span><span class="field-desc muted small">1h to 30d; saving restarts it</span><input type=text aria-label="Expires after"></label><label class="text-field grow"><span class=field-title>Actions per hour</span><span class="field-desc muted small">1–1000</span><input type=text aria-label="Actions per hour"></label></div><div class=row><button type=submit class="btn small primary">Save grant</button><button type=button class="btn small">Cancel`),vk=I(`<label class=check><input type=checkbox><span class="mono small">`),yk=I(`<label class=check><input type=checkbox><span>`),bk=I(`<button type=button class="btn small">Turn off quiet hours`),xk=I(`<fieldset class=stack id=concierge-quiet><legend class=field-title>Quiet hours</legend><span class="field-desc muted small"> Held news arrives as one update when they end.</span><div class=row><label class=text-field><span class=small>Quiet from</span><input type=time aria-label="Quiet from"></label><label class=text-field><span class=small>Quiet until</span><input type=time aria-label="Quiet until"></label><button type=button class="btn small"></button></div><label class=check><input type=checkbox><span>Urgent news (a blocked or failed session, a Decision) still wakes it`),Sk=I(`<fieldset class=stack id=concierge-digests><legend class=field-title>Digests</legend><span class="field-desc muted small">At these times (<!>) the Concierge sums up what changed and tells you if it matters.</span><ul class=list></ul><div><button type=button class="btn small">Add a digest`),Ck=I(`<li class="small muted">No digests.`),wk=I(`<li class=row><input type=time><span class=digest-days></span><button type=button class="btn small danger">Remove`),Tk=I(`<label class="check small"><input type=checkbox><span>`),Ek=`/api/agent/concierge`;async function Dk(){let e=Qo(await G(Ek));if(!e)throw Error(`The hub answered an unexpected Concierge view`);return e}async function Ok(e){if(!e)return;let{grants:t}=await G(`/api/agent/grants`);return t?.find(t=>t.id===e)}function kk(){let[t,{refetch:i,mutate:a}]=d(Dk),o=()=>t.error?void 0:t(),[c,{refetch:f}]=d(()=>o()?.settings.grantID,Ok),[p,h]=u(!1),[g,_]=u(!1),[v,S]=u({}),[C,w]=u(),T=()=>mu()??o()?.status,E=0,D;x(e(()=>t.error,e=>{if(clearTimeout(D),!e)return void(E=0);E>=4||(D=setTimeout(()=>void i(),1e3*2**E++))})),x(e(()=>mu()?.state,()=>t.error&&void i(),{defer:!0})),M(()=>clearTimeout(D));let O=async(e,t)=>{h(!0);try{let n=await(await t()).json(),r=o();r&&n.settings&&a({...r,settings:n.settings}),q(e)}catch(e){q(U(e),`err`)}finally{h(!1),i(),f()}},k=(e,t=`Saved`,n={})=>{let r=o().settings;return O(t,()=>V(`${Ek}/settings`,{method:`PUT`,json:{...ws(r,e),...n}}))},A=()=>O(`Concierge on`,()=>V(`${Ek}/enable`,{method:`POST`,json:{expectedRevision:o().settings.revision,timeZone:Zt()}})),j=async()=>{if(await P(`Turn the Concierge off? Its session stops and its grant is revoked; notes and watchlist are kept.`,`Turn off`,{danger:!0}))return O(`Concierge off`,()=>V(`${Ek}/disable`,{method:`POST`,json:{expectedRevision:o().settings.revision}}))},ee=()=>O(`Restarting the Concierge`,()=>V(`${Ek}/restart`,{method:`POST`,json:{}}));return(()=>{var e=WO();return e.firstChild,y(e,n(l,{get when(){return o()},get fallback(){return(()=>{var e=KO();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${U(t.error)} `:`Loading…`})(),null),y(e,n(l,{get when(){return t.error},get children(){var e=GO();return e.$$click=()=>(E=0,void i()),e}}),null),e})()},children:e=>{let t=()=>e().settings,u=()=>ls(e().machines),d=()=>ds(t(),e().machines),h=()=>e().machines.find(e=>e.id===t().machineID);return(()=>{var x=$O(),E=x.firstChild,D=E.firstChild.firstChild.nextSibling,O=E.nextSibling,M=O.firstChild.nextSibling.nextSibling,P=O.nextSibling,F=P.nextSibling,te=F.firstChild.nextSibling,I=F.nextSibling;return I.firstChild,y(D,()=>cs(T(),e().machines,N())),y(E,n(l,{get when(){return t().enabled},get children(){return[(()=>{var e=qO();return e.$$click=()=>void ee(),s(()=>e.disabled=p()),e})(),(()=>{var e=JO();return e.$$click=()=>void j(),s(()=>e.disabled=p()),e})()]}}),null),y(E,n(l,{get when(){return!t().enabled},get children(){var e=YO();return e.$$click=()=>void A(),s(t=>{var n=p()||d()!==void 0,r=d()??``;return n!==t.e&&(e.disabled=t.e=n),r!==t.t&&b(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e}}),null),y(x,n(l,{get when(){return r(()=>!t().enabled)()&&d()},get children(){var e=XO();return y(e,d),e}}),O),y(x,n(l,{get when(){return!t().enabled},get children(){return ZO()}}),O),y(x,n(l,{get when(){return r(()=>!!(t().enabled&&T()?.state===`failed`))()&&T()?.reason},get children(){var e=QO(),t=e.firstChild;t.firstChild;var n=t.nextSibling;return y(t,()=>T().reason,null),n.$$click=()=>void ee(),s(()=>n.disabled=p()),e}}),O),y(M,n(m,{get each(){return u()},get fallback(){return ek()},children:e=>(()=>{var n=tk(),r=n.firstChild.firstChild,i=r.nextSibling,a=i.firstChild;return a.firstChild,r.addEventListener(`change`,()=>{let n=v()[e.id];w(n===void 0&&t().model!==void 0?e.id:void 0),k(As(t(),e,Y.machines,n))}),y(i,()=>e.name,a),y(a,()=>e.note,null),s(t=>{var i=e.id,a=e.eligible?`yes`:`no`,o=!e.selectable||p();return i!==t.e&&b(n,`data-concierge-machine`,t.e=i),a!==t.t&&b(n,`data-eligible`,t.t=a),o!==t.a&&(r.disabled=t.a=o),t},{e:void 0,t:void 0,a:void 0}),s(()=>r.checked=t().machineID===e.id),n})()})),y(x,n(Ak,{get settings(){return t()},get machine(){return h()},get busy(){return p()},save:k}),P),y(x,n(jk,{get settings(){return t()},get machine(){return h()},get busy(){return p()},save:k,onModels:(e,n)=>{if(S({...v(),[e]:n}),C()!==e||t().machineID!==e)return;w(void 0);let r=js(t(),n);r!==t()&&k(r,`Model back to ${h()?.name??`the machine`}'s default`)}}),P),te.addEventListener(`change`,e=>{let n=e.currentTarget.value.trim()||Zt(),r=t().quietHours;k({...t(),timeZone:n,...r?{quietHours:{...r,timeZone:n}}:{}})}),y(x,n(Nk,{get settings(){return t()},get busy(){return p()},save:k}),I),y(x,n(Pk,{get settings(){return t()},get busy(){return p()},save:k}),I),y(x,n(UO,{}),I),y(I,n(l,{get when(){return t().grant},get fallback(){return(()=>{var e=nk(),n=e.firstChild.nextSibling,r=n.nextSibling;return n.$$click=()=>void k({...t(),grant:fs([t().directory])},`Grant set`),r.$$click=()=>_(!0),s(e=>{var i=p()||!t().directory,a=p()||g();return i!==e.e&&(n.disabled=e.e=i),a!==e.t&&(r.disabled=e.t=a),e},{e:void 0,t:void 0}),e})()},children:e=>(()=>{var i=ik(),a=i.firstChild,o=a.firstChild,u=o.nextSibling,d=u.nextSibling,f=d.firstChild,m=a.nextSibling,h=m.nextSibling;return y(o,()=>xs(e()).head),y(u,()=>xs(e()).permissions),y(d,()=>e().maxActionsPerHour,f),y(d,(()=>{var e=r(()=>!!c());return()=>e()?` · ${c().state===`active`?Ss(c().expiresAt,N()):c().state}`:t().enabled?``:` · created when you turn it on`})(),null),m.$$click=()=>_(!0),y(i,n(l,{get when(){return t().enabled},get children(){var n=rk();return n.$$click=()=>void k(t(),`Grant renewed`,{grant:e()}),s(()=>n.disabled=p()),n}}),h),h.$$click=()=>void k({...t(),grant:void 0},`Grant removed`),s(e=>{var t=p()||g(),n=p();return t!==e.e&&(m.disabled=e.e=t),n!==e.t&&(h.disabled=e.t=n),e},{e:void 0,t:void 0}),i})()}),null),y(I,n(l,{get when(){return g()},get children(){return n(Mk,{get spec(){return t().grant},get directory(){return t().directory},get machineID(){return t().machineID},get revision(){return t().revision},onClose:()=>_(!1),onSaved:e=>{let t=o();t&&a({...t,settings:e}),_(!1),q(`Grant saved`),i(),f()}})}}),null),s(()=>b(x,`data-concierge-state`,T()?.state??`disabled`)),s(()=>te.value=t().timeZone),x})()}}),null),e})()}function Ak(t){let r=()=>Ds(t.machine,Y.machines),i=()=>[...r().projects,...r().roots],[a,o]=u(!1);x(e(()=>t.machine?.id,()=>o(!1),{defer:!0}));let c=()=>a()?Ts:ks(t.settings.directory,i()),d=e=>{e!==t.settings.directory&&t.save({...t.settings,directory:e})},f=()=>r().roots,p=()=>Os(t.machine,r());return(()=>{var e=ck(),i=e.firstChild,a=i.firstChild.nextSibling,u=a.firstChild.nextSibling,h=i.nextSibling;return a.addEventListener(`change`,e=>{let t=e.currentTarget.value;if(t===`__other__`)return o(!0);o(!1),d(t||void 0)}),y(a,n(l,{get when(){return r().projects.length},get children(){var e=ak();return y(e,n(m,{get each(){return r().projects},children:e=>(()=>{var t=lk();return t.value=e,y(t,e),t})()})),e}}),u),y(a,n(l,{get when(){return f().length},get children(){var e=ok();return y(e,n(m,{get each(){return f()},children:e=>(()=>{var t=lk();return t.value=e,y(t,e),t})()})),e}}),u),u.value=Ts,y(h,p),y(e,n(l,{get when(){return c()===Ts},get children(){var e=sk();return e.addEventListener(`change`,e=>d(e.currentTarget.value.trim()||void 0)),s(n=>{var r=`Other folder on ${t.machine?.name??`the machine`}`,i=t.machine?.roots[0]?`${t.machine.roots[0].replace(/\/+$/,``)}/…`:`/path/to/repo`,a=t.busy;return r!==n.e&&b(e,`aria-label`,n.e=r),i!==n.t&&b(e,`placeholder`,n.t=i),a!==n.a&&(e.disabled=n.a=a),n},{e:void 0,t:void 0,a:void 0}),s(()=>e.value=t.settings.directory??``),e}}),null),s(()=>a.disabled=!t.machine||t.busy),s(()=>a.value=c()),e})()}function jk(t){let r=()=>Ps(t.machine),[i,{refetch:a}]=d(()=>t.machine&&!r()?t.machine.id:void 0,async e=>({id:e,options:Ns(await G(`${Ek}/machines/${encodeURIComponent(e)}/models`))})),o=()=>i.error||i.loading?void 0:i()?.id===t.machine?.id?i():void 0;x(e(o,e=>e&&t.onModels(e.id,e.options.map(e=>e.value))));let c=()=>o()?.options??[],f=()=>[...new Set(c().map(e=>e.provider))],[p,h]=u(!1);x(e(()=>t.machine?.id,()=>h(!1),{defer:!0}));let g=()=>!o()&&!i.error&&t.settings.model?t.settings.model:void 0,_=()=>p()?Ts:g()??ks(t.settings.model,c().map(e=>e.value)),v=e=>{e!==t.settings.model&&t.save({...t.settings,model:e})},S=()=>r()?r():i.loading?`Loading ${t.machine?.name??`the machine`}'s models…`:i.error?`Could not load the models: ${U(i.error)}`:!o()||c().length?``:`Its OpenCode reports no models: type one, or keep the machine default.`;return(()=>{var e=dk(),r=e.firstChild,o=r.firstChild.nextSibling,u=o.firstChild.nextSibling,d=r.nextSibling.nextSibling;return o.addEventListener(`change`,e=>{let t=e.currentTarget.value;if(t===`__other__`)return h(!0);h(!1),v(t||void 0)}),y(o,n(l,{get when(){return g()},children:e=>(()=>{var t=lk();return y(t,e),s(()=>t.value=e()),t})()}),u),y(o,n(m,{get each(){return f()},children:e=>(()=>{var t=fk();return b(t,`label`,e),y(t,n(m,{get each(){return c().filter(t=>t.provider===e)},children:e=>(()=>{var t=lk();return y(t,()=>e.label),s(()=>t.value=e.value),t})()})),t})()}),u),u.value=Ts,y(d,S,null),y(d,n(l,{get when(){return i.error},get children(){return[` `,(()=>{var e=GO();return e.$$click=()=>void a(),e})()]}}),null),y(e,n(l,{get when(){return _()===Ts},get children(){var e=uk();return e.addEventListener(`change`,e=>v(e.currentTarget.value.trim()||void 0)),s(()=>e.disabled=t.busy),s(()=>e.value=t.settings.model??``),e}}),null),s(e=>{var n=t.busy,r=i.loading?`true`:`false`;return n!==e.e&&(o.disabled=e.e=n),r!==e.t&&b(o,`aria-busy`,e.t=r),e},{e:void 0,t:void 0}),s(()=>o.value=_()),e})()}function Mk(e){let[t,r]=u(ms(e.spec,e.directory)),[i,a]=u({}),[o,c]=u(``),[d,f]=u(!1),[p,h]=u(``),g=(e,n)=>r({...t(),[e]:n}),_=()=>(Y.machines??[]).find(t=>t.id===e.machineID),v=()=>bs(_(),e.directory,t().projects),x=async n=>{n.preventDefault(),c(``);let r=_s(t());if(!r.ok)return a(r.errors);a({}),f(!0);try{let t=await(await V(`${Ek}/settings`,{method:`PUT`,json:{grant:r.body,expectedRevision:e.revision}})).json();e.onSaved(t.settings)}catch(e){let t=U(e),n=e instanceof W&&e.status===400?ys(t):void 0;n?a({[n]:t}):c(t)}finally{f(!1)}},S=e=>n(l,{get when(){return i()[e.field]},get children(){var t=pk();return y(t,()=>i()[e.field]),s(()=>b(t,`data-error`,e.field)),t}}),C=e=>(()=>{var r=mk(),i=r.firstChild,a=i.nextSibling,o=a.nextSibling;return y(i,()=>e.label),y(a,()=>e.hint),o.$$input=t=>g(e.field,t.currentTarget.value),y(r,n(S,{get field(){return e.field}}),null),s(t=>{var n=e.label,r=e.placeholder??``;return n!==t.e&&b(o,`aria-label`,t.e=n),r!==t.t&&b(o,`placeholder`,t.t=r),t},{e:void 0,t:void 0}),s(()=>o.value=t()[e.field]),r})();return(()=>{var r=_k(),i=r.firstChild,a=i.firstChild.nextSibling.nextSibling,c=a.firstChild,u=c.nextSibling,f=i.nextSibling;f.firstChild;var _=f.nextSibling,w=_.firstChild,T=w.firstChild.nextSibling.nextSibling,E=w.nextSibling,D=E.firstChild.nextSibling.nextSibling,O=_.nextSibling,k=O.firstChild,A=k.nextSibling;return r.addEventListener(`submit`,e=>void x(e)),y(i,n(m,{get each(){return v()},children:e=>(()=>{var n=vk(),r=n.firstChild,i=r.nextSibling;return r.addEventListener(`change`,n=>g(`projects`,n.currentTarget.checked?[...t().projects,e]:t().projects.filter(t=>t!==e))),b(r,`aria-label`,e),y(i,e),s(()=>r.checked=t().projects.includes(e)),n})()}),a),c.$$input=e=>h(e.currentTarget.value),u.$$click=()=>(g(`projects`,[...t().projects,p().trim()]),h(``)),y(i,n(S,{field:`projects`}),null),y(f,n(m,{each:ps,children:e=>(()=>{var n=yk(),r=n.firstChild,i=r.nextSibling;return r.addEventListener(`change`,n=>g(`allow`,n.currentTarget.checked?[...t().allow,e]:t().allow.filter(t=>t!==e))),b(r,`aria-label`,e),y(i,e),s(()=>r.checked=t().allow.includes(e)),n})()}),null),y(r,n(S,{field:`allow`}),_),y(r,n(C,{field:`permit`,label:`Permissions it may approve`,hint:`Patterns action[:glob], one per line, for example read or edit. Shell, outside folders and tools always need your tap.`,placeholder:`read`}),_),y(r,n(l,{get when(){return vs(t().permit)},get children(){var e=hk();return y(e,()=>vs(t().permit)),e}}),_),y(r,n(C,{field:`never`,label:`Never`,hint:`Patterns it may never approve, one per line; never wins.`,placeholder:`shell:rm *`}),_),T.$$input=e=>g(`expires`,e.currentTarget.value),y(w,n(S,{field:`expires`}),null),D.$$input=e=>g(`maxActionsPerHour`,e.currentTarget.value),y(E,n(S,{field:`maxActionsPerHour`}),null),y(r,n(l,{get when(){return o()},get children(){var e=gk();return y(e,o),e}}),O),B(A,`click`,e.onClose,!0),s(e=>{var t=!p().trim(),n=d();return t!==e.e&&(u.disabled=e.e=t),n!==e.t&&(k.disabled=e.t=n),e},{e:void 0,t:void 0}),s(()=>c.value=p()),s(()=>T.value=t().expires),s(()=>D.value=t().maxActionsPerHour),r})()}function Nk(e){let[t,i]=u(e.settings.quietHours?.start??``),[a,o]=u(e.settings.quietHours?.end??``);return(()=>{var c=xk(),u=c.firstChild.nextSibling,d=u.firstChild,f=u.nextSibling,p=f.firstChild,m=p.firstChild.nextSibling,h=p.nextSibling,g=h.firstChild.nextSibling,_=h.nextSibling,v=f.nextSibling.firstChild;return y(u,(()=>{var t=r(()=>!!e.settings.quietHours);return()=>t()?`Quiet ${e.settings.quietHours.start}–${e.settings.quietHours.end} (${e.settings.quietHours.timeZone}).`:`Off: news wakes the Concierge any time.`})(),d),m.$$input=e=>i(e.currentTarget.value),g.$$input=e=>o(e.currentTarget.value),_.$$click=()=>void e.save({...e.settings,quietHours:{start:t(),end:a(),timeZone:e.settings.timeZone}},`Quiet hours saved`),y(_,()=>e.settings.quietHours?`Save quiet hours`:`Turn on quiet hours`),y(f,n(l,{get when(){return e.settings.quietHours},get children(){var t=bk();return t.$$click=()=>void e.save({...e.settings,quietHours:void 0},`Quiet hours off`),s(()=>t.disabled=e.busy),t}}),null),v.addEventListener(`change`,t=>void e.save({...e.settings,quietAllowsUrgent:t.currentTarget.checked})),s(n=>{var r=e.busy||!t()||!a(),i=e.busy;return r!==n.e&&(_.disabled=n.e=r),i!==n.t&&(v.disabled=n.t=i),n},{e:void 0,t:void 0}),s(()=>m.value=t()),s(()=>g.value=a()),s(()=>v.checked=e.settings.quietAllowsUrgent),c})()}function Pk(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=Sk(),o=a.firstChild.nextSibling,c=o.firstChild.nextSibling;c.nextSibling;var l=o.nextSibling,u=l.nextSibling.firstChild;return y(o,()=>e.settings.timeZone,c),y(l,n(m,{get each(){return t()},get fallback(){return Ck()},children:(a,o)=>(()=>{var c=wk(),l=c.firstChild,u=l.nextSibling,d=u.nextSibling;return l.addEventListener(`change`,e=>e.currentTarget.value&&i(o(),{at:e.currentTarget.value})),y(u,n(m,{each:tc,children:(t,n)=>(()=>{var r=Tk(),c=r.firstChild,l=c.nextSibling;return c.addEventListener(`change`,e=>{let t=nc(a.days,n(),e.currentTarget.checked);JSON.stringify(t)===JSON.stringify(a.days)?e.currentTarget.checked=!0:i(o(),{days:t})}),y(l,t),s(n=>{var r=`Digest ${o()+1} on ${t}`,i=e.busy;return r!==n.e&&b(c,`aria-label`,n.e=r),i!==n.t&&(c.disabled=n.t=i),n},{e:void 0,t:void 0}),s(()=>c.checked=!a.days||a.days.includes(n())),r})()})),d.$$click=()=>r(t().filter((e,t)=>t!==o()),`Digest removed`),s(t=>{var n=o(),r=`Digest ${o()+1} time`,i=e.busy,a=e.busy,s=`Remove digest ${o()+1}`;return n!==t.e&&b(c,`data-digest`,t.e=n),r!==t.t&&b(l,`aria-label`,t.t=r),i!==t.a&&(l.disabled=t.a=i),a!==t.o&&(d.disabled=t.o=a),s!==t.i&&b(d,`aria-label`,t.i=s),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),s(()=>l.value=a.at),c})()})),u.$$click=()=>r([...t(),{at:`08:00`}],`Digest added`),s(()=>u.disabled=e.busy||t().length>=4),a})()}z([`click`,`input`]);var Fk=e=>`/api/sessions/${encodeURIComponent(e)}/context-cards`,Ik=(e,t)=>`${Fk(e)}/${encodeURIComponent(t)}/refresh`,Lk=e=>`/api/context-cards/primary?sessions=${encodeURIComponent(e.join(`,`))}`,Rk=`/api/settings/context-cards`,zk=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:void 0,Bk=e=>typeof e==`string`,Vk=e=>typeof e==`number`&&Number.isFinite(e);function Hk(e){if(!Array.isArray(e))return;let t=e.map(zk).filter(e=>!!e&&Bk(e.label)&&Bk(e.value)).map(e=>({label:e.label,value:e.value}));return t.length===e.length&&t.length?t:void 0}function Uk(e){let t=zk(e);if(!t||!Bk(t.provider)||!Bk(t.sessionID)||!Bk(t.title)||!Bk(t.headline)||!Vk(t.generatedAt))return;let n=Hk(t.fields);return{provider:t.provider,sessionID:t.sessionID,title:t.title,headline:t.headline,body:Bk(t.body)?t.body:``,...n?{fields:n}:{},generatedAt:t.generatedAt,...Bk(t.model)?{model:t.model}:{},inputsHash:Bk(t.inputsHash)?t.inputsHash:``,version:Vk(t.version)?t.version:0,trigger:Bk(t.trigger)?t.trigger:`manual`,...t.primary===!0?{primary:!0}:{}}}function Wk(e){let t=zk(e)??{};return{cards:(Array.isArray(t.cards)?t.cards:[]).map(Uk).filter(e=>!!e),providers:(Array.isArray(t.providers)?t.providers:[]).map(zk).filter(e=>!!e&&Bk(e.id)&&Bk(e.label)).map(e=>({id:e.id,label:e.label,primary:e.primary===!0,usesModel:e.usesModel===!0})),enabled:t.enabled===!0,configured:t.configured===!0}}function Gk(e){return e<6e4?`just now`:e<36e5?`${Math.floor(e/6e4)}m ago`:e<864e5?`${Math.floor(e/36e5)}h ago`:`${Math.floor(e/864e5)}d ago`}var Kk=(e,t)=>`updated ${Gk(Math.max(0,t-e.generatedAt))}${e.model?` · ${e.model}`:``}`,qk={disabled:`Context cards are off. Turn them on in Settings › Concierge.`,unchanged:`Up to date: nothing changed since this card.`,rate_limited:`Refreshed a moment ago. Try again shortly.`,backoff:`The model failed several times. Cards pause for a while.`,circuit:`The model is failing for this hub. Cards pause for a few minutes.`,weaker:`The session is unreachable now. The last card stays.`,"no-model":`No model is configured for context cards.`,budget:`Today's context card budget is used up.`,empty:`Nothing to summarise yet.`,unknown:`This card is not available.`,gone:`The session is gone.`};function Jk(e){let t=zk(e)??{};if(t.outcome!==`generated`)return t.outcome===`skipped`?qk[String(t.reason)]??`No new card this time.`:`The card could not be made. Try again later.`}var Yk=(e,t)=>e.type===`contextCard`&&e.sessionID===t;function Xk(e){let t=zk(e)??{},n=zk(t.model),r=zk(t.usage),i=zk(r?.limits);return{enabled:t.enabled===!0,available:t.available===!0,configured:t.configured===!0,...n&&Bk(n.provider)&&Bk(n.model)?{model:{provider:n.provider,model:n.model,keySource:Bk(n.keySource)?n.keySource:``}}:{},...r&&Vk(r.calls)&&Vk(r.tokens)&&i&&Vk(i.calls)&&Vk(i.tokens)?{usage:{calls:r.calls,tokens:r.tokens,limits:{calls:i.calls,tokens:i.tokens}}}:{}}}var Zk=class{options;cards=new Map;requested=new Set;queue=[];scheduled=!1;listeners=new Set;constructor(e){this.options=e}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}line(e){return this.requested.has(e)||this.enqueue(e),this.cards.get(e)?.headline}card(e){return this.cards.get(e)??void 0}message(e){e.type===`contextCard`&&e.primary===!0&&typeof e.sessionID==`string`&&(this.requested.delete(e.sessionID),this.enqueue(e.sessionID))}clear(){let e=[...this.cards].filter(([,e])=>e).map(([e])=>e);this.cards.clear(),this.requested.clear();for(let t of e)for(let e of this.listeners)e(t)}put(e){e.primary&&this.set(e.sessionID,e)}set(e,t){let n=this.cards.get(e)?.headline;if(this.cards.set(e,t),this.requested.add(e),n!==(t?.headline??void 0))for(let t of this.listeners)t(e)}enqueue(e){this.requested.add(e),this.queue.push(e),!this.scheduled&&(this.scheduled=!0,this.options.schedule(()=>void this.flush()))}async flush(){this.scheduled=!1;let e=[...new Set(this.queue)];this.queue=[];let t=[];for(let n=0;n<e.length;n+=200)t.push(e.slice(n,n+200));await Promise.all(t.map(async e=>{try{let t=await this.options.fetch(e);for(let n of e)this.set(n,Uk(t[n])??null)}catch{for(let t of e)this.requested.delete(t)}}))}},[Qk,$k]=u(0),eA=new Zk({fetch:async e=>(await G(Lk(e))).cards??{},schedule:e=>void setTimeout(e,30)});eA.subscribe(()=>$k(e=>e+1)),Nu(e=>eA.message(e));function tA(e){return Qk(),eA.line(e)}La(tA);var nA=e=>eA.put(e),rA=()=>eA.clear(),iA=I(`<div class=context-cards-settings data-context-cards-settings><p class="muted small">A short, automatically updated card per session (Details rail, session list, Concierge board) that helps you pick its work back up. Off until you turn it on: nothing is sent to a model before.</p><p class="muted small"data-context-cards-sent>When on, for sessions you used in the last day, the hub sends the model (after a turn ends, when a session gets blocked, when you come back, every 30 minutes, and on Refresh): the title, intent, state, what it waits on, and the newest messages (yours, the agent's and error messages, each cut to 1,200 characters; tools by name only). Known key, token and password formats are redacted first (private keys, API keys and tokens, AWS keys, passwords in URLs, password=/secret=/token= values, Authorization headers); other secrets written in the text may still be sent.`),aA=I(`<p class="muted small">`),oA=I(`<ul class=switches><li><label class=switch><span class=notify-kind><span>Context cards</span><span class="small muted"data-context-cards-delete-note>Pick-up summaries of your sessions (off until you turn it on). Turning this off deletes saved cards.</span></span><input type=checkbox data-context-cards-toggle>`),sA=I(`<p class="muted small">Turned off for this hub (HUB_CONTEXT_CARDS=off or contextCards.enabled false).`),cA=I(`<p class="muted small">No model configured: set an OpenRouter key in Speech, or contextCards.model in hub.json.`),lA=I(`<p class="muted small">Model: <span class=mono></span> (<!>)`),uA=I(`<p class="muted small">Daily budget: <!> / <!> calls · <!> / <!> tokens used today`),dA=I(`<p class=field-error>`);function fA(){let[e,{mutate:t}]=d(async()=>Xk(await G(Rk))),[i,a]=u(``),[o,c]=u(!1),f=async e=>{c(!0),a(``);try{t(Xk(await(await V(Rk,{method:`PUT`,json:{enabled:e}})).json())),e||rA()}catch(e){a(U(e))}finally{c(!1)}};return(()=>{var t=iA();return t.firstChild.nextSibling,y(t,n(l,{get when(){return e()},get fallback(){return(()=>{var t=aA();return y(t,()=>e.error?`Could not load the context card settings.`:`Loading…`),t})()},children:e=>[(()=>{var t=oA(),n=t.firstChild.firstChild.firstChild.nextSibling;return n.addEventListener(`change`,e=>void f(e.currentTarget.checked)),s(()=>n.disabled=o()||!e().available),s(()=>n.checked=e().enabled),t})(),n(l,{get when(){return!e().available},get children(){return sA()}}),n(l,{get when(){return r(()=>!!e().available)()&&!e().configured},get children(){return cA()}}),n(l,{get when(){return e().model},children:e=>(()=>{var t=lA(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(n,()=>e().model),y(t,()=>e().provider,r),y(t,()=>e().keySource===`speech`?`, the speech key`:``,r),t})()}),n(l,{get when(){return e().usage},children:e=>(()=>{var t=uA(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling,i=r.nextSibling.nextSibling,a=i.nextSibling.nextSibling;return a.nextSibling,y(t,()=>e().calls,n),y(t,()=>e().limits.calls,r),y(t,()=>e().tokens.toLocaleString(),i),y(t,()=>e().limits.tokens.toLocaleString(),a),t})()})]}),null),y(t,n(l,{get when(){return i()},children:e=>(()=>{var t=dA();return y(t,e),t})()}),null),t})()}function pA(e,t){let n=Math.max(0,Math.ceil((e-t)/1e3));return`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}`}function mA(e,t){return t.find(t=>!e.has(t.id))}function hA(e,t,n){let r=t?Date.parse(t):NaN;return Number.isFinite(r)?n+Math.max(0,e-r-1e3):e}var gA={L:0,M:1,Q:2,H:3},_A={L:1,M:0,Q:3,H:2},vA=[[-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]],yA=[[-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]],bA=(e,t)=>!!(e>>>t&1);function xA(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 SA(e,t){let n=gA[t];return Math.floor(xA(e)/8)-vA[n][e]*yA[n][e]}function CA(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 wA(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]=CA(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=CA(n,2)}return t}function TA(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]^=CA(t,e))}return n}function EA(e,t,n){let r=gA[n],i=yA[r][t],a=vA[r][t],o=Math.floor(xA(t)/8),s=i-o%i,c=Math.floor(o/i),l=wA(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=TA(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 DA(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=SA(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 OA=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=_A[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,bA(r,e));this.set(8,7,bA(r,6)),this.set(8,8,bA(r,7)),this.set(7,8,bA(r,8));for(let e=9;e<15;e++)this.set(14-e,8,bA(r,e));for(let e=0;e<8;e++)this.set(i-1-e,8,bA(r,e));for(let e=8;e<15;e++)this.set(8,i-15+e,bA(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,bA(t,e)),this.set(r,n,bA(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]=bA(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 kA(e,t={}){let n=t.ecc??`M`,r=new TextEncoder().encode(e),i=1;for(;4+(i<=9?8:16)+r.length*8>SA(i,n)*8;)if(++i>40)throw Error(`Text too long for a QR code`);let a=new OA(i,n);a.codewords(EA(DA(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 AA(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 jA=.8,MA=1.8,NA=.05,PA=`hub.fontScale`,FA=e=>Math.min(MA,Math.max(jA,e)),IA=(e,t)=>Number((Math.round(e/t)*t).toFixed(2));function LA(e){return Number.isFinite(e)?IA(FA(e),NA):1}function RA(e){return e?LA(Number(e)):1}function zA(e,t,n){return LA(!(t>0)||!(n>0)?e:n/t*e)}function BA(e,t){let n=FA((Number.isFinite(e)?e:1)*Math.exp(-t*.01));return Number(n.toFixed(3))}var VA=e=>`${Math.round(e*100)}%`;function HA(e){try{return RA(e.getItem(PA))}catch{return 1}}function UA(e,t){let n=LA(t);try{n===1?e.removeItem(PA):e.setItem(PA,String(n))}catch{}return n}var WA=()=>typeof localStorage>`u`?void 0:localStorage,[GA,KA]=u(WA()?HA(WA()):1),qA=GA;function JA(e){document.documentElement.style.setProperty(`--font-scale`,String(e))}var YA;function XA(e,t={}){let n=t.settle===!1?e:LA(e);KA(n),JA(n),clearTimeout(YA);let r=()=>{let e=WA();if(!e)return;let t=UA(e,n);t!==GA()&&(KA(t),JA(t))};t.settle===!1?YA=setTimeout(r,250):r()}var ZA=`.scroller, .home-scroll`,QA=e=>e instanceof Element&&e.closest(ZA)!==null;function $A(e=document){JA(GA());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`&&QA(e.target)&&(t.set(e.pointerId,{x:e.clientX,y:e.clientY}),t.size===2&&(n={scale:GA(),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=zA(n.scale,n.distance,r());e!==GA()&&XA(e,{settle:!1})}},o=e=>{t.delete(e.pointerId)&&t.size<2&&n&&(n=void 0,XA(GA()))},s=e=>{e.touches.length>=2&&QA(e.target)&&e.preventDefault()},c=e=>{e.ctrlKey&&QA(e.target)&&(e.preventDefault(),XA(BA(GA(),e.deltaMode===1?e.deltaY*16:e.deltaY),{settle:!1}))},l,u=e=>{QA(e.target)&&(e.preventDefault(),e.type===`gesturestart`?l=GA():e.type===`gesturechange`&&l!==void 0&&e.scale?XA(zA(l,1,e.scale),{settle:!1}):e.type===`gestureend`&&(l=void 0,XA(GA())))},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 ej=[`light`,`system`,`dark`],tj=`hub.theme`;function nj(e){return e===`light`||e===`dark`||e===`system`?e:`system`}function rj(e){return e===`system`?void 0:e}function ij(){try{return nj(localStorage.getItem(tj))}catch{return`system`}}var[aj,oj]=u(ij());function sj(e){let t=rj(e);t?document.documentElement.dataset.theme=t:delete document.documentElement.dataset.theme;try{e===`system`?localStorage.removeItem(tj):localStorage.setItem(tj,e)}catch{}oj(e)}var cj=[`macos`,`linux`,`windows`],lj={macos:`macOS`,linux:`Linux`,windows:`Windows`},uj=`~/projects`,dj=200,fj=[{id:`session-only`,label:`OpenCode only`,description:`Connects OpenCode on the machine to this hub; its sessions show up here.`},{id:`launch-node`,label:`+ launch node`,description:`Also runs a launch node, so you can start sessions on the machine from here, in a workspace folder.`},{id:`full-harness`,label:`All harnesses`,description:`OpenCode, Claude Code and Codex with their spokes, and the launch node.`}],pj=new Set([`session-only`,`launch-node`]),mj=e=>cj.includes(e);function hj(e,t){let n=mj(t)?t:`linux`,r=(e.userAgentData?.platform??``).toLowerCase(),i=e.userAgent??``;return r===`android`||r===`ios`||/Android|iPhone|iPad|iPod/.test(i)||/Macintosh/.test(i)&&(e.maxTouchPoints??0)>1?n:r===`windows`?`windows`:r===`macos`?`macos`:r===`linux`||r===`chrome os`||r===`chromeos`?`linux`:/Windows/.test(i)?`windows`:/Macintosh|Mac OS X/.test(i)?`macos`:/Linux|X11|CrOS/.test(i)?`linux`:n}var gj=(e,t)=>e!==`windows`||pj.has(t),_j=e=>fj.map(t=>({...t,comingSoon:!gj(e,t.id)}));function vj(e){let t=e.replace(/\\/g,`/`);return/^[a-z]:\//.test(t)?t[0].toUpperCase()+t.slice(1):t}function yj(e,t=`linux`){let n=t===`windows`;if(!e)return`Give a folder, e.g. ~/projects.`;if(n){if(/^[\\/]{2}/.test(e))return`Network (UNC) folders are not supported: use a folder on a drive, e.g. C:\\Users\\you\\projects.`;e=vj(e)}if(e.length>dj)return`At most ${dj} characters.`;let r=n&&/^[A-Z]:\//.test(e),i=r?e.slice(2):e;if(!/^[A-Za-z0-9._/~-]+$/.test(i))return`Use only letters, digits and . _ - ~ / (no spaces or shell characters).`;if(n){if(!r&&!e.startsWith(`~/`))return`Start with a drive (C:\\) or ~\\.`}else if(!e.startsWith(`/`)&&!e.startsWith(`~/`))return`Start with / or ~/.`;if(e.includes(`//`))return`No empty folder names (//).`;if(e.split(`/`).includes(`..`))return`No .. in the path.`}function bj(e){try{let t=new URL(e);return t.protocol===`https:`||t.protocol===`http:`?t.origin:void 0}catch{return}}function xj(e){let t=bj(e.origin);if(!t)return{ok:!1,error:`This hub has no usable public URL (http or https).`};if(!gj(e.os,e.profile))return{ok:!1,error:`${fj.find(t=>t.id===e.profile)?.label??e.profile} is coming soon on ${lj[e.os]}.`};let n=new URLSearchParams;if(e.profile!==`session-only`&&n.set(`profile`,e.profile),e.profile===`launch-node`){let t=e.root||`~/projects`,r=yj(t,e.os);if(r)return{ok:!1,error:`Workspace folder: ${r}`};let i=e.os===`windows`?vj(t):t;i!==`~/projects`&&n.set(`root`,i)}e.profile!==`session-only`&&e.activate&&n.set(`activate`,`1`);let r=n.toString(),i=`${t}/${e.os===`windows`?`install.ps1`:`install.sh`}${r?`?${r}`:``}`;return i.includes(`'`)?{ok:!1,error:`The command would contain a quote.`}:{ok:!0,command:e.os===`windows`?`irm '${i}' | iex`:`curl -fsSL '${i}' | sh`}}var Sj=/^(\s{0,3})(`{3,}|~{3,})\s*([^\s`]*)/,Cj=/^\s{0,3}(#{1,6})(?:\s+(.*))?$/,wj=/^\s{0,3}(={2,}|-{3,})\s*$/,Tj=/^\s{0,3}>\s?(.*)$/,Ej=/^(\s*)([-*+]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/,Dj=/^\[([ xX])\](?:\s+(.*))?$/,Oj=/^:?-+:?$/,kj=e=>e.length-e.trimStart().length,Aj=(e,t)=>e.slice(Math.min(t,kj(e))),jj=e=>Sj.test(e);function Mj(e){let t=0;for(;t<e.length&&/\s/.test(e[t]);)t++;let n=e[t];if(t>3||n!==`-`&&n!==`*`&&n!==`_`)return!1;let r=0;for(;t<e.length;t++)if(e[t]===n)r++;else if(!/\s/.test(e[t]))return!1;return r>=3}var Nj=e=>jj(e)||Cj.test(e)||Mj(e)||Tj.test(e)||Ej.test(e),Pj=32,Fj=20;function Ij(e,t={}){let n=String(e??``).replace(/\r\n?/g,`
17
+ `).split(`
18
+ `).map(e=>e.replace(/^[ \t]+/,e=>e.replace(/\t/g,` `))),r=!!t.streaming,i=Lj(n,{streaming:r},!0,0).blocks;return qj(i,r?Kj(i):void 0)}function Lj(e,t,n,r){if(r>Pj)return Rj(e);let i=[],a=[],o=!1,s=!1,c=!1,l=()=>{o&&s&&(c=!0),o=!1,s=!0},u=()=>{a.length&&i.push({type:`paragraph`,text:a.join(`
19
+ `)}),a=[]};for(let s=0;s<e.length;s++){let c=e[s];if(!c.trim()){u(),o=!0;continue}let d=Sj.exec(c);if(d){u(),l();let[,t,n]=d,r=[];for(s++;s<e.length;s++){let i=/^\s*(`{3,}|~{3,})\s*$/.exec(e[s]);if(i&&i[1][0]===n[0]&&i[1].length>=n.length)break;r.push(Aj(e[s],t.length))}i.push({type:`code`,lang:d[3]??``,text:r.join(`
20
+ `)});continue}if(a.length){let e=wj.exec(c);if(e){i.push({type:`heading`,level:e[1][0]===`=`?1:2,text:a.join(`
21
+ `)}),a=[];continue}}let f=Cj.exec(c);if(f){u(),l(),i.push({type:`heading`,level:f[1].length,text:Bj(f[2]??``).trim()});continue}if(Mj(c)){u(),l(),i.push({type:`rule`});continue}let p=Gj(e,s,t.streaming&&n);if(p){u(),l(),i.push(p.block),s=p.end-1;continue}if(Tj.test(c)){u(),l();let a=[],o=s;for(;o<e.length;o++){let t=Tj.exec(e[o]);if(t)a.push(t[1]);else if(e[o].trim()&&a.at(-1)?.trim()&&!Nj(e[o]))a.push(e[o]);else break}i.push({type:`quote`,blocks:Lj(a,t,n&&o===e.length,r+1).blocks}),s=o-1;continue}let m=Ej.exec(c);if(m&&(!a.length||Vj(m[2]))){u(),l();let a=Hj(e,s,t,n,r);i.push(a.block),s=a.end-1,a.trailingBlank&&(o=!0)}else a.length||l(),a.push(c.trim())}return u(),{blocks:i,loose:c,trailingBlank:o}}function Rj(e){let t=[],n=[];for(let r of e)r.trim()?n.push(r.trim()):n.length&&(t.push({type:`paragraph`,text:n.join(`
22
+ `)}),n=[]);return n.length&&t.push({type:`paragraph`,text:n.join(`
23
+ `)}),{blocks:t,loose:!1,trailingBlank:!e.at(-1)?.trim()}}var zj=e=>e!==void 0&&Xj.test(e);function Bj(e){let t=e.length;for(;zj(e[t-1]);)t--;let n=t;for(;e[n-1]===`#`;)n--;if(n===t||n>0&&!zj(e[n-1]))return e;for(;zj(e[n-1]);)n--;return e.slice(0,n)}var Vj=e=>!/\d/.test(e)||/^0*1[.)]$/.test(e);function Hj(e,t,n,r,i){let a=Ej.exec(e[t]),o=/\d/.test(a[2]),s=a[2].slice(-1),c=[],l=!1,u=!1,d=t;for(;d<e.length;){let t=Ej.exec(e[d]);if(!t||/\d/.test(t[2])!==o||t[2].slice(-1)!==s)break;c.length&&u&&(l=!0);let a=t[1].length,f=t[3]?.replace(/\t/g,` `).length??0,p=a+t[2].length+(f>=1&&f<=4?f:1),m=[f>4?`${` `.repeat(f-1)}${t[4]??``}`.trim():t[4]??``],h,g=e=>{if(h){let t=/^\s*(`{3,}|~{3,})\s*$/.exec(e);t&&t[1][0]===h[0]&&t[1].length>=h.length&&(h=void 0)}else{let t=Sj.exec(e);t&&(h=t[2])}};g(m[0]);let _=d+1,v=0;for(;_<e.length;_++){let t=e[_];if(!t.trim()){v++;continue}let n=kj(t),r;if(r=h?!0:v?n>=Math.min(p,a+2):n>=p?!0:Ej.test(t)?n>=a+2:n>a||!Nj(t)&&!jj(m.at(-1)),!r)break;for(;v;v--)m.push(``);let i=Aj(t,p);m.push(i),g(i)}u=v>0;let y=Dj.exec(m[0]),b=Lj(y?[y[2]??``,...m.slice(1)]:m,n,r&&_===e.length,i+1);b.loose&&(l=!0),c.push({...y?{checked:y[1]!==` `}:{},blocks:b.blocks}),d=_}let f=o?Number(a[2].slice(0,-1)):void 0;return{block:{type:`list`,ordered:o,...o?{start:f}:{},loose:l,items:c},end:d,trailingBlank:u}}function Uj(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 Wj=e=>{let t=e.trim(),n=t.startsWith(`:`),r=t.length>1&&t.endsWith(`:`);return n&&r?`center`:r?`right`:n?`left`:null};function Gj(e,t,n){let r=e[t];if(!r.includes(`|`))return;let i=Uj(r),a=e[t+1],o;if(a!==void 0){let r=Uj(a),s=t+1===e.length-1;r.length===i.length&&r.every(e=>Oj.test(e))?o=r.map(Wj):s&&/^[\s|:-]*$/.test(a)&&(a.includes(`-`)||n)&&a.includes(`|`)&&r.length<=i.length&&(o=i.map((e,t)=>r[t]&&Oj.test(r[t])?Wj(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(`|`)||jj(t)||Tj.test(t)||Cj.test(t))break;s.push(Uj(t).slice(0,i.length))}return{block:{type:`table`,align:o,head:i,rows:s},end:Math.min(c,e.length)}}function Kj(e){let t=e.at(-1);if(t){if(t.type===`paragraph`||t.type===`heading`)return{node:t};if(t.type===`quote`)return Kj(t.blocks);if(t.type===`list`)return Kj(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 qj(e,t){let n=e=>t?.node===e;return e.map(e=>{switch(e.type){case`paragraph`:return{type:`paragraph`,children:pM(e.text,{streaming:n(e)})};case`heading`:return{type:`heading`,level:e.level,children:pM(e.text,{streaming:n(e)})};case`quote`:return{type:`quote`,blocks:qj(e.blocks,t)};case`list`:return{...e,items:e.items.map(e=>({...e.checked===void 0?{}:{checked:e.checked},blocks:qj(e.blocks,t)}))};case`table`:{let r=(r,i,a)=>pM(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 Jj(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 Yj=/[!-/:-@[-`{-~]/,Xj=/\s/,Zj=/[\p{L}\p{N}_]/u,Qj={"**":`strong`,__:`strong`,"~~":`del`,"==":`mark`},$j=(e,t,n)=>{let r=0;for(;e[t+r]===n;)r++;return r},eM=0,tM=e=>({s:e,closers:new Map}),nM=e=>new Int32Array(e.s.length+2);function rM(e,t,n){if(!e.runs){e.runs=new Map;let t=e.s;for(let n=t.indexOf("`");n>=0;n=t.indexOf("`",n)){let r=$j(t,n,"`"),i=e.runs.get(r);i?i.push(n):e.runs.set(r,[n]),n+=r}}let r=e.runs.get(n);if(!r)return-1;let i=0,a=r.length;for(;i<a;){let e=i+a>>1;r[e]<t?i=e+1:a=e}return i<r.length?r[i]:-1}function iM(e,t){let n=e.s[t];if(n===`\\`)return t+2;if(n==="`"){let n=$j(e.s,t,"`"),r=rM(e,t+n,n);return(r>=0?r:t)+n}return t+1}function aM(e,t,n,r,i){let a=e.s,o=e.closers.get(t);o||e.closers.set(t,o=nM(e));let s=a.length-r.length,c=[],l=-1;for(let t=n;t<=s;){if(o[t]!==eM){l=o[t]-2;break}c.push(t);let n=a[t];if(n!==`\\`&&n!=="`"&&a.startsWith(r,t)&&i(t)){l=t;break}t=iM(e,t)}for(let e of c)o[e]=l+2;return l}function oM(e,t,n,r){let i=n=>n>=t?-1:e[n]===eM?void 0:e[n]-2,a=[n];for(;a.length;){let t=a[a.length-1];if(i(t)!==void 0){a.pop();continue}let n=r(t),o;if(typeof n==`number`)o=n;else if(n===`open`){let e=i(t+1);e===void 0?a.push(t+1):e<0?o=-1:(o=i(e+1))===void 0&&a.push(e+1)}else(o=i(n.next))===void 0&&a.push(n.next);o!==void 0&&(e[t]=o+2,a.pop())}return i(n)}function sM(e,t){let n=e.s;return oM(e.brackets??=nM(e),n.length,t+1,t=>{let r=n[t];return r===`]`?t:r===`[`?`open`:{next:iM(e,t)}})}function cM(e,t){let n=e.s;return oM(e.parens??=nM(e),n.length,t,e=>{let t=n[e];return t===`)`?e:t===`
24
+ `?-1:t===`(`?`open`:{next:e+1}})}function lM(e,t){let n=e.newline;return(!n||t<n.from||n.at>=0&&t>n.at)&&(e.newline={from:t,at:e.s.indexOf(`
25
+ `,t)}),e.newline.at>=0}function uM(e){let t=e.trim();return t.startsWith(`<`)?t.slice(1,t.indexOf(`>`)>0?t.indexOf(`>`):void 0):t.split(/\s+/)[0]??``}var dM=e=>e.map(e=>e.type===`text`||e.type===`code`?e.text:e.type===`image`?e.alt:e.type===`br`?` `:dM(e.children)).join(``);function fM(e,t){let n=/^https?:\/\/[^\s<>]+/i.exec(e.slice(t,t+2048));if(!n)return;let r=n[0],i=e=>r.split(e).length-1,a=i(`(`),o=i(`)`),s=i(`[`),c=i(`]`),l=r.length;for(;;){let e=r[l-1];if(/[.,:;!?'"*_~]/.test(e))l--;else if(e===`)`&&a<o)o--,l--;else if(e===`]`&&s<c)c--,l--;else break}return/^https?:\/\/[^/]/i.test(r.slice(0,l))?r.slice(0,l):void 0}function pM(e,t={}){let n=String(e??``),r=!!t.streaming,i=t.depth??0;if(i>Fj)return n?[{type:`text`,text:n}]:[];let a=tM(n),o=(e,n,r=t.inLink)=>pM(e,{inLink:r,streaming:n,depth:i+1}),s=[],c=``,l=(...e)=>{c&&s.push({type:`text`,text:c}),c=``,s.push(...e)},u=0;for(;u<n.length;){let e=n[u],i=n[u+1];if(e===`\\`){if(i===`
26
+ `){l({type:`br`}),u+=2;continue}if(i!==void 0&&Yj.test(i)){c+=i,u+=2;continue}}if(e===`
27
+ `){let e=c.length;for(;c[e-1]===` `;)e--;c=c.slice(0,e),l({type:`br`}),u++;continue}if(e==="`"){let e=$j(n,u,"`"),t=rM(a,u+e,e);if(t>=0||r){let r=n.slice(u+e,t>=0?t:void 0);r.length>2&&r.startsWith(` `)&&r.endsWith(` `)&&r.trim()&&(r=r.slice(1,-1)),l({type:`code`,text:r}),u=t>=0?t+e:n.length;continue}c+=n.slice(u,u+e),u+=e;continue}let s=n.slice(u,u+2),d=Qj[s];if(d&&i!==void 0&&n[u+2]!==void 0&&!Xj.test(n[u+2])&&n[u+2]!==e&&(e!==`_`||u===0||!Zj.test(n[u-1]))){let t=aM(a,s,u+3,s,t=>!Xj.test(n[t-1])&&(e!==`_`||!Zj.test(n[t+2]??``)));if(t>0||r){l({type:d,children:o(n.slice(u+2,t>0?t:void 0),t<0)}),u=t>0?t+2:n.length;continue}}if((e===`*`||e===`_`)&&i!==void 0&&i!==e&&!Xj.test(i)&&(e===`*`||u===0||!Zj.test(n[u-1]))){let t=aM(a,e,u+1,e,t=>n[t+1]===e||n[t-1]===e?!1:!Xj.test(n[t-1])&&(e!==`_`||!Zj.test(n[t+1]??``)));if(t>u+1||r){l({type:`em`,children:o(n.slice(u+1,t>u?t:void 0),t<0)}),u=t>u?t+1:n.length;continue}}let f=e===`!`&&i===`[`;if(e===`[`||f){let e=f?u+1:u,i=sM(a,e);if(i>0&&n[i+1]===`(`){let s=cM(a,i+2),c=()=>o(n.slice(e+1,i),!1,!0);if(s>0){let e=uM(n.slice(i+2,s)),r=Jj(e);f?l({type:`image`,alt:dM(c()),...r?{href:r}:{},src:e}):r&&!t.inLink?l({type:`link`,href:r,children:c()}):!r&&!t.inLink&&e?l({type:`label`,target:e,children:c()}):l(...c()),u=s+1;continue}if(r&&!lM(a,i)){l(...f?[{type:`text`,text:dM(c())}]:c()),u=n.length;continue}}}if(e===`<`&&!t.inLink){let e=/^<([a-zA-Z][a-zA-Z0-9+.-]{1,31}:[^\s<>]*)>/.exec(n.slice(u,u+2048)),t=/^<([^\s<>@\\]+@[^\s<>@\\]+\.[^\s<>@\\]+)>/.exec(n.slice(u,u+512)),r=e??t;if(r){let t=Jj(e?r[1]:`mailto:${r[1]}`);t?l({type:`link`,href:t,children:[{type:`text`,text:r[1]}]}):c+=r[0],u+=r[0].length;continue}}if((e===`h`||e===`H`)&&!t.inLink&&(u===0||!/[\p{L}\p{N}_/]/u.test(n[u-1]))&&n.slice(u-2,u)!==`](`){let e=fM(n,u),t=e&&Jj(e);if(e&&t){l({type:`link`,href:t,children:[{type:`text`,text:e}]}),u+=e.length;continue}}c+=e,u++}return c&&s.push({type:`text`,text:c}),s}var mM={files:200,fileBytes:5242880,totalBytes:20971520,chunkBytes:524288,inlineBytes:393216,bundlePathMax:200,pathMax:4096,refMax:300,skipped:200};new Set(Object.values({html:`text/html`,htm:`text/html`,css:`text/css`,js:`text/javascript`,mjs:`text/javascript`,json:`application/json`,txt:`text/plain`,csv:`text/csv`,md:`text/markdown`,pdf:`application/pdf`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,svg:`image/svg+xml`}));var hM=e=>typeof e==`string`&&e.length>0&&e.length<=mM.pathMax&&!/[\u0000\r\n]/.test(e);function gM(e){return!hM(e)||e.startsWith(`~`)||/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e)&&!/^file:/i.test(e)?!1:/\.html?$/i.test(e)}var _M=new Set([`html`,`htm`]),vM=e=>_M.has(e.toLowerCase());function yM(e){let t=[],n=e=>{for(let r of e)if(r.type===`code`&&vM(r.lang))t.push(r);else if(r.type===`quote`)n(r.blocks);else if(r.type===`list`)for(let e of r.items)n(e.blocks)};return n(e),t}var bM=new Map,xM=256;function SM(e){let t=bM.get(e);if(t!==void 0)return t;let n=e.includes("```")||e.includes(`~~~`)?yM(Ij(e)).length:0;return bM.size>=xM&&bM.delete(bM.keys().next().value),bM.set(e,n),n}function CM(e,t){let n=new Set(t?[t]:[]);for(let t of e)t.type===`assistant`&&t.messageID&&t.live&&t.key===`${t.messageID}:text`&&n.add(t.messageID);let r=new Map,i=new Map;for(let t of e){if(t.type!==`assistant`||!t.messageID||n.has(t.messageID))continue;let e=r.get(t.messageID)??0;i.set(t.key,{messageID:t.messageID,base:e}),r.set(t.messageID,e+SM(t.text))}return i}function wM(e){let t=e?.status,n=e?.code,r=e instanceof Error?e.message:String(e);return e instanceof Error&&e.name===`NetworkError`?r:typeof t==`number`?t===404?n===`too_old`?`Can't preview this message (it's too far back or no longer available)`:`This HTML block isn't available to preview yet — try again in a moment.`:t===409?`The session's machine is offline. Try again when it's back.`:t===413?`This HTML block is too large to preview (over 2 MiB).`:t===422?`This hub can't store previews.`:t===400?`This block can't be previewed.`:t===429?`Too many previews right now. Try again in a moment.`:`Couldn't open the preview: ${r}`:`Couldn't open the preview: ${r}`}function TM(e){let t=e.type===`code`?e.text:e.type===`link`?e.href:e.type===`label`?e.target:void 0;return t!==void 0&&gM(t)?t:void 0}var EM=Math.round(mM.fileBytes/1048576);function DM(e){let t=e?.status,n=e?.code,r=e instanceof Error?e.message:String(e);return e instanceof Error&&e.name===`NetworkError`?r:t===404?n===`refused`?`This page isn't one of this session's files, so it can't be previewed.`:`This message isn't available to preview anymore.`:t===409?n===`changed`?`The page kept changing while it was read. Try again.`:`The session's machine is offline. Try again when it's back.`:t===413?`This page is too large to preview (over ${EM} MiB).`:t===422?/previewBundle/.test(r)?`The session's machine can't preview local pages yet (update Hub there).`:`This hub can't store previews.`:t===502?`The session's machine sent a broken preview.`:t===429?`Too many previews right now. Try again in a moment.`:t===400?`This page can't be previewed.`:`Couldn't open the preview: ${r}`}var OM={missing:`not found`,refused:`not one of this session's files`,too_large:`over ${EM} MiB`,limit:`over the preview's size or file limit`,name:`a file name previews can't hold`,type:`a type previews can't hold`};function kM(e,t=0){let n=e??[],r=n.length+t;if(r!==0)return{title:`${r} ${r===1?`file`:`files`} not included`,items:n.map(e=>`${e.path} — ${OM[e.reason]??e.reason}`),...t>0?{more:`and ${t} more`}:{}}}var[AM,jM]=u(new Map),MM=e=>AM().get(e);function NM(e,t){let n=Array.isArray(t.skipped)?t.skipped.filter(e=>e&&typeof e.path==`string`&&typeof e.reason==`string`):[],r=typeof t.skippedMore==`number`&&t.skippedMore>0?t.skippedMore:0;jM(t=>new Map(t).set(e,{skipped:n,more:r}))}var PM=I(`<span role=alert>`),FM=I(`<button type=button>`);async function IM(e){let{sessionID:t,messageID:n}=e,r=`path`in e?{messageID:n,path:e.path}:{messageID:n,block:e.block},i=await $e(`${H(t)}/previews`,r),a=i?.artifact?.id;if(typeof a!=`string`||!a)throw Error(`The hub's answer wasn't a preview.`);return`path`in e&&NM(a,i),a}function LM(e){let[t,r]=u(!1),[i,a]=u(),o=()=>`path`in e.target,c=async()=>{if(!(t()||e.waiting)){r(!0),a(void 0);try{let t=await IM(e.target);Sn(t)||a(vn)}catch(e){a(e instanceof Error&&e.message===`The hub's answer wasn't a preview.`?e.message:o()?DM(e):wM(e))}finally{r(!1)}}},d=()=>e.waiting?`Load earlier messages to preview`:o()?`Preview this page and its files in an isolated frame beside the session`:`Preview this HTML in an isolated frame beside the session`;return[n(l,{get when(){return i()},get children(){var t=PM();return y(t,i),s(()=>k(t,e.inline?`md-preview-err`:`code-preview-err`)),t}}),(()=>{var n=FM();return n.$$click=()=>void c(),y(n,()=>t()?`Opening…`:`Preview`),s(r=>{var i=e.inline?`md-preview`:`code-btn code-preview`,a=t(),s=t()||e.waiting,c=d(),l=o()?`Preview ${e.target.path}`:void 0;return i!==r.e&&k(n,r.e=i),a!==r.t&&b(n,`aria-busy`,r.t=a),s!==r.a&&(n.disabled=r.a=s),c!==r.o&&b(n,`title`,r.o=c),l!==r.i&&b(n,`aria-label`,r.i=l),r},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),n})()]}z([`click`]);var RM=`/api/agent/artifacts`,zM={textBytes:2097152,imageBytes:10485760,editBytes:1048576,revisionsPage:20},BM=encodeURIComponent,VM=e=>`${RM}/${BM(e)}`,HM=(e,t)=>`${VM(e)}/revisions?limit=${zM.revisionsPage}${t?`&cursor=${BM(t)}`:``}`,UM=(e,t)=>`${VM(e)}/revisions/${BM(t)}`,WM=(e,t,n)=>`${UM(e,t)}/blobs/${BM(n)}`,GM=e=>typeof e==`object`&&!!e&&!Array.isArray(e),KM=e=>typeof e==`string`&&e.length>0,qM=e=>typeof e==`number`&&Number.isFinite(e),JM=e=>typeof e==`string`&&Tn.includes(e),YM=(e,t)=>GM(e)&&GM(e[t])?e[t]:e;function XM(e){let t=YM(e,`artifact`);if(!GM(t)||!KM(t.id)||typeof t.title!=`string`||!JM(t.kind)||!KM(t.latestRevisionID)||!qM(t.revision))return;let n=Array.isArray(t.tags)?t.tags.filter(e=>typeof e==`string`):void 0;return{v:1,id:t.id,title:t.title,kind:t.kind,state:t.state===`archived`?`archived`:`active`,visibility:t.visibility===`workspace`?`workspace`:`private`,latestRevisionID:t.latestRevisionID,revision:t.revision,createdAt:qM(t.createdAt)?t.createdAt:0,updatedAt:qM(t.updatedAt)?t.updatedAt:0,...KM(t.description)?{description:t.description}:{},...KM(t.workspaceID)?{workspaceID:t.workspaceID}:{},...KM(t.createdBySessionID)?{createdBySessionID:t.createdBySessionID}:{},...n?.length?{tags:n}:{},...t.origin===`preview`?{origin:`preview`}:{},...ZM(t.provenance)??{}}}function ZM(e){if(GM(e)&&KM(e.sessionID)&&KM(e.messageID)){if(KM(e.path))return{provenance:{sessionID:e.sessionID,messageID:e.messageID,path:e.path}};if(qM(e.block))return{provenance:{sessionID:e.sessionID,messageID:e.messageID,block:e.block}}}}function QM(e){if(GM(e)){if(e.kind===`user`)return{kind:`user`};if(e.kind===`session`&&KM(e.sessionID))return{kind:`session`,sessionID:e.sessionID};if(e.kind===`ai_job`&&KM(e.jobID))return{kind:`ai_job`,jobID:e.jobID}}}function $M(e){let t=YM(e,`revision`);if(!GM(t)||!KM(t.id)||!KM(t.artifactID)||!qM(t.number)||!Array.isArray(t.blobs))return;let n=QM(t.author);if(!n)return;let r=t.blobs.filter(e=>bn(e)===void 0);return{v:1,id:t.id,artifactID:t.artifactID,number:t.number,blobs:r.map(e=>({hash:e.hash,bytes:e.bytes,mediaType:e.mediaType,...e.path===void 0?{}:{path:e.path}})),author:n,createdAt:qM(t.createdAt)?t.createdAt:0,...KM(t.baseRevisionID)?{baseRevisionID:t.baseRevisionID}:{},...KM(t.entry)?{entry:t.entry}:{}}}function eN(e){let t=GM(e)?e:{};return{items:Array.isArray(t.items)?t.items.flatMap(e=>$M(e)??[]):[],...KM(t.cursor)?{cursor:t.cursor}:{}}}function tN(e){return e.kind===`user`?`You`:e.kind===`session`?`Session ${e.sessionID.slice(0,12)}…`:`AI job`}var nN=[`text/markdown`,`text/plain`,`text/csv`,`text/html`,`text/css`,`text/javascript`,`application/json`],rN=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`],iN={markdown:{"text/markdown":`markdown`,"text/plain":`markdown`},code:Object.fromEntries(nN.map(e=>[e,`code`])),image:Object.fromEntries(rN.map(e=>[e,`image`])),table:{"text/csv":`table`,"application/json":`table`},chart:{"application/json":`chart`},dashboard:{"application/json":`dashboard`},file:{...Object.fromEntries(rN.map(e=>[e,`image`])),"text/plain":`text`,"text/markdown":`text`}},aN={ts:`ts`,tsx:`tsx`,js:`js`,jsx:`jsx`,mjs:`js`,cjs:`js`,py:`python`,go:`go`,rs:`rust`,sh:`bash`,bash:`bash`,json:`json`,css:`css`,html:`html`,htm:`html`,md:`markdown`,yaml:`yaml`,yml:`yaml`,toml:`toml`,sql:`sql`,java:`java`,c:`c`,h:`c`,cpp:`cpp`,rb:`ruby`,swift:`swift`,kt:`kotlin`,diff:`diff`,csv:`csv`,txt:``},oN={"text/javascript":`js`,"text/css":`css`,"application/json":`json`,"text/html":`html`,"text/markdown":`markdown`,"text/csv":`csv`};function sN(e){let t=e.path?.split(`/`).pop()?.split(`.`).slice(1).pop()?.toLowerCase();return t!==void 0&&t in aN?aN[t]:oN[e.mediaType]??``}function cN(e,t){let n=t.blobs;if(Cn.includes(e))return{mode:`isolated`,files:n,...n[0]?{file:lN(t)??n[0]}:{}};if(!n.length)return{mode:`empty`,files:n};let r=iN[e],i=lN(t)??n.find(e=>r[e.mediaType])??n[0],a=r[i.mediaType];if(!a)return{mode:`download`,file:i,files:n,note:`A ${i.mediaType} file can't be shown as ${e===`image`?`an`:`a`} ${e} here.`};let o=a===`image`?zM.imageBytes:zM.textBytes;return i.bytes>o?{mode:`download`,file:i,files:n,note:`This file is too large to preview (${Math.ceil(i.bytes/1024)} KiB).`}:{mode:a,file:i,files:n,...a===`code`?{lang:sN(i)}:{}}}function lN(e){return e.entry===void 0?void 0:e.blobs.find(t=>t.path===e.entry)}var uN=class extends Error{limit;name=`TooLargeError`;code=`too_large`;constructor(e){super(`A file here is at most ${Math.round(e/1024)} KiB`),this.limit=e}};async function dN(e,t){let n=Number(e.headers.get(`content-length`)??``);if(Number.isFinite(n)&&n>t)throw await e.body?.cancel().catch(()=>{}),new uN(t);if(!e.body)return new Uint8Array;let r=e.body.getReader(),i=[],a=0;for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw await r.cancel().catch(()=>{}),new uN(t);i.push(n)}let o=new Uint8Array(a),s=0;for(let e of i)o.set(e,s),s+=e.byteLength;return o}function fN(e){let t=e&&typeof e==`object`?e:{},n=typeof t.status==`number`?t.status:0,r=typeof t.message==`string`?t.message:``;return t.name===`NetworkError`||n===503?{kind:`offline`,text:`Can't reach the hub right now. Nothing was lost; try again when it's back.`}:t.name===`TooLargeError`||t.code===`too_large`?{kind:`too_large`,text:r||`The file is too large.`}:n===404||n===403?{kind:`not_found`,text:`This artifact doesn't exist or you can't see it.`}:n===401?{kind:`forbidden`,text:`This device isn't signed in to the hub.`}:n===422||t.code===`unsupported`?{kind:`unsupported`,text:`Artifacts aren't supported on this hub yet.`}:n===409||t.code===`conflict`?{kind:`conflict`,text:`The artifact changed since you opened it.`}:n===429||t.code===`rate_limited`?{kind:`rate_limited`,text:r?`Limit reached: ${r}`:`A limit was reached; try again later.`}:n===400?{kind:`invalid`,text:r||`The hub refused the change.`}:{kind:`error`,text:r?`Something went wrong: ${r}`:`Something went wrong (HTTP ${n}).`}}var pN=e=>new TextEncoder().encode(e).byteLength;function mN(e,t){if(e.state!==`active`||t.id!==e.latestRevisionID||Cn.includes(e.kind)||t.blobs.length!==1)return!1;let n=t.blobs[0];return nN.includes(n.mediaType)&&n.bytes<=zM.editBytes}function hN(e,t,n){if(pN(n)>zM.editBytes)throw new uN(zM.editBytes);return{baseRevisionID:e,upload:[{mediaType:t.mediaType,data:n,encoding:`utf8`,...t.path===void 0?{}:{path:t.path}}]}}var gN=e=>`hub.artifactDraft.v1.${e}`;function _N(e,t){try{let n=e?.getItem(gN(t)),r=n?JSON.parse(n):void 0;return GM(r)&&r.v===1&&KM(r.base)&&typeof r.text==`string`?{v:1,base:r.base,text:r.text}:void 0}catch{return}}function vN(e,t){let n=_N(t.storage,e.artifactID),r=n?n.base===e.baseRevisionID?{status:`editing`,draft:n.text,baseRevisionID:n.base,restored:!0}:{status:`conflict`,draft:n.text,baseRevisionID:n.base,latestRevisionID:e.baseRevisionID,restored:!0}:{status:`editing`,draft:e.original,baseRevisionID:e.baseRevisionID},i=e.original,a,o=e=>{r=e,t.onChange()},s=()=>{try{r.draft===i&&r.baseRevisionID===e.baseRevisionID?t.storage?.removeItem(gN(e.artifactID)):pN(r.draft)<=zM.editBytes&&t.storage?.setItem(gN(e.artifactID),JSON.stringify({v:1,base:r.baseRevisionID,text:r.draft}))}catch{}};return{state:()=>r,setDraft(e){o({...r,draft:e,status:r.status===`conflict`?`conflict`:`editing`}),s()},async save(){if(r.status===`saving`||r.status===`conflict`||r.draft===i&&r.baseRevisionID===e.baseRevisionID)return;let n;try{n=hN(r.baseRevisionID,e.file,r.draft)}catch(e){o({...r,status:`error`,error:{kind:`too_large`,text:`${e.message}; shorten the draft to save it.`}});return}let c=`${r.baseRevisionID}\n${r.draft}`,l=a?.sig===c?a.key:t.newKey();a={sig:c,key:l};let u=r;o({...r,status:`saving`});try{let r=await t.revise(e.artifactID,n,l);return i=u.draft,t.storage?.removeItem(gN(e.artifactID)),o({status:`saved`,draft:u.draft,baseRevisionID:r.id}),r}catch(e){let t=fN(e),n=e.details;t.kind===`conflict`?o({...u,status:`conflict`,error:t,...KM(n?.latestRevisionID)?{latestRevisionID:n.latestRevisionID}:{}}):o({...u,status:`error`,error:t}),s();return}},rebase(e){let{latestRevisionID:t,error:n,...i}=r;o({...i,status:`editing`,baseRevisionID:e}),s()},discard(){t.storage?.removeItem(gN(e.artifactID)),a=void 0,o({status:`editing`,draft:i,baseRevisionID:e.baseRevisionID})}}}var yN=/^\/artifacts\/([^/?#]+)(?:\/revisions\/([^/?#]+))?$/;function bN(e){let t=yN.exec(e);if(!t)return;let[,n,r]=t;if(_e(`artifact`,n)&&(r===void 0||_e(`revision`,r)))return r===void 0?{id:n}:{id:n,rev:r}}var xN=e=>({ok:!1,reason:e});function SN(e){let t=e?.status;return xN(t===404||t===403?`not_found`:`error`)}async function CN(e,t){let n;try{n=await t.artifact(e.id)}catch(e){return SN(e)}if(n.id!==e.id)return xN(`not_found`);if(n.kind!==`image`&&n.kind!==`file`)return xN(`not_image`);let r=e.rev??n.latestRevisionID,i;try{i=await t.revision(n.id,r)}catch(e){return SN(e)}if(i.id!==r||i.artifactID!==n.id)return xN(`not_found`);let a=wN(n,i);return a?a.bytes>Nn.maxBytes?xN(`too_large`):{ok:!0,artifactID:n.id,revisionID:r,title:n.title,file:a,src:WM(n.id,r,a.hash),page:`/artifacts/${encodeURIComponent(n.id)}`}:xN(`not_image`)}function wN(e,t){let n=cN(e.kind,t),r=n.file;if(r&&Mn.includes(r.mediaType))return n.mode===`image`||n.mode===`download`?r:void 0}function TN(e){let t=e.now??Date.now,n=e.ttlMs??3e4,r=jn(e.limit??3),i=new Map;return{resolve(a){let o=`${a.id}/${a.rev??``}`,s=i.get(o);if(s&&t()-s.at<=n)return s.answer;let c=r.acquire().then(async t=>{try{return await CN(a,e.reader)}finally{t()}});return i.set(o,{at:t(),answer:c}),c}}}var EN={text:`No longer available from this artifact`,retry:!1},DN={text:`Artifacts aren't available on this hub`,retry:!1};function ON(e,t){return t===`not_found`||t===void 0&&e===404?{...EN}:t===`unsupported`||t===void 0&&e===422?{...DN}:Ln(e,t)}var kN=I(`<a class=md-image target=_blank rel="noopener noreferrer">`),AN=I(`<span class=md-artifact><a class=md-artifact-link title="Open the artifact">`),jN=()=>new W(404,`No such artifact`),MN=TN({reader:{async artifact(e){let t=XM(await G(VM(e)));if(!t)throw jN();return t},async revision(e,t){let n=$M(await G(UM(e,t)));if(!n)throw jN();return n}}}),NN={not_found:`Image (artifact not found)`,not_image:`Artifact (not an image)`,too_large:`Image (too large to show inline)`,error:`Image (couldn't load the artifact)`};function PN(e){let[t]=d(()=>bN(e.href),e=>MN.resolve(e)),r=()=>{let e=t.state===`ready`?t():void 0;return e?.ok?e:void 0},i=t=>({key:`artifact:${t.artifactID}:${t.revisionID}:${t.file.hash}`,name:e.alt||t.title||`image`,mime:t.file.mediaType,src:t.src,bytes:t.file.bytes,download:t.src}),a=t=>(()=>{var n=kN();return b(n,`title`,t),y(n,()=>e.alt||`image`),s(()=>b(n,`href`,e.href)),n})();return n(v,{get fallback(){return a(t.state===`ready`&&!t().ok?NN[t().reason]:`Image (opens in a new tab)`)},get children(){return n(o,{get when(){return r()},children:e=>{let t=C(()=>i(e()));return(()=>{var r=AN(),i=r.firstChild;return y(r,n(zn,{get images(){return[t()]},children:e=>n(Fn,{get image(){return t()},class:`md-media`,explain:ON,onOpen:()=>e(t().key)})}),i),y(i,()=>e().title||`Artifact`),s(t=>{var n=e().artifactID,a=e().page;return n!==t.e&&b(r,`data-artifact`,t.e=n),a!==t.t&&b(i,`href`,t.t=a),t},{e:void 0,t:void 0}),r})()}})}})}var FN=e=>`/api/media/remote?url=${encodeURIComponent(e)}`;function IN(e,t){let n;try{n=new URL(e,t.origin)}catch{return{kind:`invalid`}}if(n.origin===new URL(t.origin).origin)return{kind:`same-origin`};if(n.protocol!==`http:`&&n.protocol!==`https:`)return{kind:`invalid`};let r=Gw(n.href),i=r??n.host.replace(/\.(?=:|$)/,``),a=qw(i);if(!t.enabled)return{kind:`off`,host:i,unicode:a,url:e};let o=n.username!==``||n.password!==``;return r&&!o&&(Kw(t.allowlist,r)||t.sessionHosts.includes(r))?{kind:`auto`,host:r,src:FN(e)}:{kind:`card`,host:i,unicode:a,src:FN(e),url:e}}var LN=I(`<span class=remote-image>`),RN=I(`<span class=remote-card-unicode>(<!>)`),zN=I(`<span class=remote-card-alt>`),BN=I(`<button type=button class="btn small">Always allow `),VN=I(`<span class=remote-card-actions><button type=button class="btn small">Load image`),HN=I(`<button type=button class=remote-card-session>Load all from this domain in this session`),UN=I(`<span class=remote-card><span class=remote-card-head><span class=remote-card-domain></span></span><button type=button class=remote-card-url>`),WN=I(`<span class=remote-card-off>Web images are turned off on this hub`),GN=c(``),KN=e=>IN(e,{origin:location.origin,allowlist:[],sessionHosts:[],enabled:!0}).kind!==`same-origin`,qN=(e,t=64)=>{let n=e.replace(/^https?:\/\//i,``);return n.length>t?`${n.slice(0,t-21)}…${n.slice(-20)}`:n};function JN(e){let t=le(GN),[i,a]=u(!1),[c,d]=u(!1),[f,p]=u(!1),m=C(()=>{let n=$w();return IN(e.href,{origin:location.origin,allowlist:n?.allowlist??[],sessionHosts:aT(t),enabled:n?.remoteFetch!==!1})}),h=()=>{let e=m();return e.kind===`card`||e.kind===`off`?e:void 0},g=()=>{let e=m();return e.kind===`auto`||e.kind===`card`&&i()?e.src:void 0},_=()=>e.alt||h()?.host||`image`,x=async e=>{p(!0);try{await nT(e),q(`Images from ${e} now load at once`)}catch(t){q(`Could not allow ${e}: ${U(t)}`,`err`)}finally{p(!1)}};return(()=>{var i=LN();return y(i,n(v,{get children(){return[n(o,{get when(){return g()},children:e=>{let t={key:e(),name:_(),mime:`image/*`,src:e()};return n(zn,{images:[t],children:e=>n(Fn,{image:t,class:`md-media`,onOpen:()=>e(t.key)})})}}),n(o,{get when(){return h()},children:i=>(()=>{var o=UN(),u=o.firstChild,p=u.firstChild,m=u.nextSibling;return y(u,n(L,{name:`image`}),p),y(p,()=>i().host),y(u,n(l,{get when(){return i().unicode!==i().host},get children(){var e=RN(),t=e.firstChild.nextSibling;return t.nextSibling,y(e,()=>i().unicode,t),e}}),null),m.$$click=()=>d(!c()),y(m,(()=>{var e=r(()=>!!c());return()=>e()?i().url:qN(i().url)})()),y(o,n(l,{get when(){return e.alt},get children(){var t=zN();return y(t,()=>e.alt),t}}),null),y(o,n(l,{get when(){return i().kind===`card`},get fallback(){return WN()},get children(){return[(()=>{var e=VN(),t=e.firstChild;return t.$$click=()=>a(!0),y(e,n(l,{get when(){return!i().host.includes(`:`)},get children(){var e=BN();return e.firstChild,e.$$click=()=>void x(i().host),y(e,()=>i().host,null),s(()=>e.disabled=f()),e}}),null),e})(),n(l,{get when(){return!i().host.includes(`:`)},get children(){var e=HN();return e.$$click=()=>oT(t,i().host),e}})]}}),null),s(e=>{var t=i().url,n=i().kind,r=c(),a=`Web address: ${i().url}`;return t!==e.e&&b(o,`title`,e.e=t),n!==e.t&&b(o,`data-state`,e.t=n),r!==e.a&&b(m,`aria-expanded`,e.a=r),a!==e.o&&b(m,`aria-label`,e.o=a),e},{e:void 0,t:void 0,a:void 0,o:void 0}),o})()})]}})),s(t=>{var n=e.alt,r=m().host;return n!==t.e&&b(i,`data-alt`,t.e=n),r!==t.t&&b(i,`data-host`,t.t=r),t},{e:void 0,t:void 0}),i})()}z([`click`]);var YN=e=>`/api/media/unfurl?url=${encodeURIComponent(e)}`;function XN(e,t){if(!t.enabled)return{kind:`none`};let n;try{n=new URL(e,t.origin)}catch{return{kind:`none`}}if(n.protocol!==`http:`&&n.protocol!==`https:`||n.origin===new URL(t.origin).origin||n.username!==``||n.password!==``)return{kind:`none`};let r=Gw(n.href);return r?{kind:Kw(t.allowlist,r)?`auto`:`tap`,host:r,url:n.href}:{kind:`none`}}function ZN(e,t){for(let n of e)n.type===`link`?t.push(n.href):(n.type===`strong`||n.type===`em`||n.type===`del`||n.type===`mark`)&&ZN(n.children,t)}function QN(e,t,n={}){let r=new Set,i=new Set,a=new Map;if(n.streaming||!t.enabled)return{auto:r,tap:i,cards:a};let o=(e,n)=>{for(let o of n){let n=XN(o,t);if(n.kind===`none`||r.has(n.url)||i.has(n.url))continue;n.kind===`auto`&&r.size<3?r.add(n.url):i.add(n.url);let s=a.get(e)??[];s.push(n.url),a.set(e,s)}},s=e=>{for(let t of e){let e=[];if(t.type===`paragraph`||t.type===`heading`)ZN(t.children,e);else if(t.type===`table`)for(let n of[t.head,...t.rows])for(let t of n)ZN(t,e);else if(t.type===`list`)for(let e of t.items)s(e.blocks);else t.type===`quote`&&s(t.blocks);e.length&&o(t,e)}};return s(e),{auto:r,tap:i,cards:a}}function $N(e,t){if(typeof e!=`string`||!e)return;let n=IN(e,{origin:t.origin,allowlist:t.allowlist,sessionHosts:[],enabled:t.enabled});return n.kind===`auto`?n.src:void 0}function eP(e,t){return t===`not_html`||e===415?{text:`No preview: not a web page`,retry:!1}:t===`disabled`?{text:`Link previews are turned off on this hub`,retry:!1}:t===`bad_url`||e===400?{text:`This link can't be previewed`,retry:!1}:t===`refused`||e===403?{text:`No preview: that address is not allowed`,retry:!1}:t===`rate_limited`||e===429?{text:`Too many previews right now: try again`,retry:!0}:t===`timeout`||e===504?{text:`No preview: the site didn't answer in time`,retry:!0}:t===`upstream`||e===502?{text:`No preview: couldn't reach the site`,retry:!0}:e===0?{text:`Couldn't load the preview (offline?)`,retry:!0}:{text:`Couldn't load the preview`,retry:!0}}var tP=class extends Error{reason;status;code;constructor(e,t=0,n){super(e.text),this.reason=e,this.status=t,this.code=n}},nP=256,rP={title:200,description:300,siteName:100},iP=(e,t)=>new tP(eP(e,t),e,t),aP=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;function oP(e,t){if(typeof e!=`string`)return;let n=e.replace(aP,``).trim();return n?n.length>t?`${n.slice(0,t-1)}…`:n:void 0}function sP(e,t){let n=e&&typeof e==`object`?e:{},r=typeof n.url==`string`&&/^https?:\/\//i.test(n.url)?n.url:t,i=oP(n.title,rP.title),a=oP(n.description,rP.description),o=oP(n.siteName,rP.siteName),s=typeof n.image==`string`&&/^https?:\/\//i.test(n.image)?n.image:void 0;return{url:r,...i?{title:i}:{},...a?{description:a}:{},...o?{siteName:o}:{},...s?{image:s}:{}}}function cP(e={}){let t=e.fetch??((...e)=>fetch(...e)),n=e.slots??jn(3),r=e.timeoutMs??2e4,i=new Map,a=new Map,o=new Map;async function s(e){let i=await n.acquire(),a=new AbortController,o=!1,s=setTimeout(()=>(o=!0,a.abort()),r);try{let n;try{n=await t(YN(e),{credentials:`same-origin`,referrerPolicy:`no-referrer`,signal:a.signal})}catch{throw o?iP(504,`timeout`):iP(0)}let r=await n.json().catch(()=>void 0);if(!n.ok)throw iP(n.status,typeof r?.code==`string`?r.code:void 0);if(!r||typeof r!=`object`)throw iP(500);return sP(r,e)}finally{clearTimeout(s),i()}}return{load(e){let t=i.get(e);if(t)return Promise.resolve(t);let n=a.get(e);if(n)return Promise.reject(n);let r=o.get(e);if(r)return r;let c=s(e).then(t=>(o.delete(e),i.set(e,t),i.size>nP&&i.delete(i.keys().next().value),t),t=>{o.delete(e);let n=t instanceof tP?t:iP(0);throw a.set(e,n),n});return o.set(e,c),c},forget(e){a.delete(e)}}}var lP=I(`<button type=button class=link-preview-btn>`),uP=I(`<div class=link-cards>`),dP=I(`<div class=link-card>`),fP=I(`<span class=link-card-loading>Loading a preview of <!>…`),pP=I(`<span class=link-card-title>`),mP=I(`<span class=link-card-desc>`),hP=I(`<a class=link-card-link target=_blank rel="noopener noreferrer"><span class=link-card-site>`),gP=I(`<button type=button class="btn small">Retry`),_P=I(`<span class=link-card-failed><span class=link-card-note>`),vP=cP({slots:On}),yP=c(()=>void 0);function bP(e){let t=le(yP),r=C(()=>{let n=t();if(!n)return;let r=XN(e.href,n.context);return r.kind!==`none`&&n.plan.tap.has(r.url)&&!n.tapped.has(r.url)?r:void 0});return n(l,{get when(){return r()},children:e=>(()=>{var r=lP();return r.$$click=()=>t()?.tap(e().url),y(r,n(L,{name:`search`})),s(t=>{var n=`Preview ${e().host}`,i=`Preview ${e().host}`;return n!==t.e&&b(r,`aria-label`,t.e=n),i!==t.t&&b(r,`title`,t.t=i),t},{e:void 0,t:void 0}),r})()})}function xP(e){let t=le(yP),r=C(()=>{let n=t();return(n?.plan.cards.get(e.block)??[]).filter(e=>n.plan.auto.has(e)||n.tapped.has(e))});return n(l,{get when(){return r().length},get children(){var e=uP();return y(e,n(m,{get each(){return r()},children:e=>n(SP,{url:e,get auto(){return t()?.plan.auto.has(e)===!0},context:()=>t()?.context})})),e}})}function SP(e){let[r,i]=u({at:`waiting`}),[a,c]=u(!e.auto),d,f=!0;M(()=>f=!1);let p=()=>{try{return new URL(e.url).hostname}catch{return e.url}};fe(()=>{if(a())return;if(typeof IntersectionObserver>`u`)return void c(!0);let e=new IntersectionObserver(e=>e.some(e=>e.isIntersecting)&&c(!0),{rootMargin:`300px 0px`});e.observe(d),M(()=>e.disconnect())});let m=()=>{i({at:`loading`}),vP.load(e.url).then(e=>f&&i({at:`shown`,preview:e}),e=>{if(!f)return;let t=e instanceof tP?e.reason:{text:`Couldn't load the preview`,retry:!0};i({at:`failed`,...t})})};x(()=>{a()&&r().at===`waiting`&&m()});let h=()=>{vP.forget(e.url),m()},g=()=>{let e=r();return e.at===`shown`?e.preview:void 0},_=()=>{let e=r();return e.at===`failed`?e:void 0},S=C(()=>{let t=g(),n=e.context();return t&&n?$N(t.image,n):void 0});return(()=>{var i=dP(),a=d;return typeof a==`function`?t(a,i):d=i,y(i,n(v,{get fallback(){return(()=>{var e=fP(),t=e.firstChild.nextSibling;return t.nextSibling,y(e,p,t),e})()},get children(){return[n(o,{get when(){return g()},children:t=>[(()=>{var r=hP(),i=r.firstChild;return y(i,()=>t().siteName??p()),y(r,n(l,{get when(){return t().title},get children(){var e=pP();return y(e,()=>t().title),e}}),null),y(r,n(l,{get when(){return t().description},get children(){var e=mP();return y(e,()=>t().description),e}}),null),s(t=>{var n=e.url,i=e.url;return n!==t.e&&b(r,`href`,t.e=n),i!==t.t&&b(r,`title`,t.t=i),t},{e:void 0,t:void 0}),r})(),n(l,{get when(){return S()},children:e=>n(Fn,{get image(){return{key:e(),name:t().title??p(),mime:`image/*`,src:e()}},class:`link-card-image`})})]}),n(o,{get when(){return _()},children:e=>(()=>{var t=_P(),r=t.firstChild;return y(r,()=>e().text),y(t,n(l,{get when(){return e().retry},get children(){var e=gP();return e.$$click=h,e}}),null),t})()})]}})),s(t=>{var n=e.url,a=r().at;return n!==t.e&&b(i,`data-url`,t.e=n),a!==t.t&&b(i,`data-state`,t.t=a),t},{e:void 0,t:void 0}),i})()}z([`click`]);var CP=I(`<span class=md-image>`),wP=I(`<a class=md-image target=_blank rel="noopener noreferrer"title="Image (opens in a new tab)">`),TP=I(`<br>`),EP=I(`<code class=inline-code>`),DP=I(`<a rel="noopener noreferrer">`),OP=I(`<div><div class=code-head><span class=code-lang></span><button type=button class=code-btn></button><button type=button class=code-btn></button></div><pre class=code><code>`),kP=I(`<span>`),AP=I(`<hr>`),jP=I(`<p>`),MP=I(`<input type=checkbox disabled>`),NP=I(`<li>`),PP=I(`<blockquote>`),FP=I(`<div class=table-wrap><table><thead><tr></tr></thead><tbody>`),IP=I(`<th>`),LP=I(`<tr>`),RP=I(`<td>`),zP=I(`<div class=md>`),[BP,VP]=u(),HP=!1;function UP(){HP||(HP=!0,Hn(()=>import(`./highlight-y4rJE6Tt.js`).then(e=>VP({run:e.highlight,languageOf:e.languageOf}),()=>HP=!1),[]))}var WP=65536;function GP(e,t){UP();let n=BP();return!n||!e||t.length>WP||!n.languageOf(e)?[{text:t}]:n.run(t,e)}function KP(e){let t=le(eF),r=C(()=>{let n=t(),r=n&&!n.streaming&&!e.inLink?TM(e.node):void 0;return n&&r!==void 0?{sessionID:n.sessionID,messageID:n.messageID,path:r,waiting:n.waiting}:void 0});return n(l,{get when(){return r()},children:e=>n(LM,{get target(){return e()},get waiting(){return e().waiting},inline:!0})})}var qP=c(()=>void 0);function JP(e){let t=le(qP),i=C(()=>An(e.node,t()?.images)),a=()=>e.node.alt||`image`;return n(v,{get fallback(){return(()=>{var e=CP();return y(e,a),e})()},get children(){return[n(o,{get when(){return r(()=>!!(i().kind===`remote`&&KN(i().href)))()&&i()},children:t=>n(JN,{get href(){return t().href},get alt(){return e.node.alt}})}),n(o,{get when(){return r(()=>i().kind===`local`)()&&i()},children:r=>n(Fn,{get image(){return{...r().image,name:e.node.alt||r().image.name}},class:`md-media`,onOpen:()=>t()?.open(r().image.key)})}),n(o,{get when(){return r(()=>i().kind===`artifact`)()&&i()},children:t=>n(PN,{get href(){return t().href},get alt(){return e.node.alt}})}),n(o,{get when(){return r(()=>i().kind===`artifact`||i().kind===`remote`)()&&i()},children:e=>(()=>{var t=wP();return y(t,a),s(()=>b(t,`href`,e().href)),t})()})]}})}function YP(e){return n(g,{get each(){return e.nodes},children:t=>n(v,{get children(){return[n(o,{get when(){return r(()=>t().type===`text`)()&&t()},children:e=>r(()=>e().text)}),n(o,{get when(){return t().type===`br`},get children(){return TP()}}),n(o,{get when(){return r(()=>t().type===`code`)()&&t()},children:r=>[(()=>{var e=EP();return y(e,()=>r().text),e})(),n(KP,{get node(){return t()},get inLink(){return e.inLink}})]}),n(o,{get when(){return r(()=>t().type===`link`)()&&t()},children:r=>[(()=>{var e=DP();return y(e,n(YP,{get nodes(){return r().children},inLink:!0})),s(t=>{var n=r().href,i=r().href.startsWith(`/`)?void 0:`_blank`;return n!==t.e&&b(e,`href`,t.e=n),i!==t.t&&b(e,`target`,t.t=i),t},{e:void 0,t:void 0}),e})(),n(bP,{get href(){return r().href}}),n(KP,{get node(){return t()},get inLink(){return e.inLink}})]}),n(o,{get when(){return r(()=>t().type===`image`)()&&t()},children:e=>n(JP,{get node(){return e()}})}),n(o,{get when(){return r(()=>`children`in t())()&&t()},children:r=>[n(D,{get component(){return{strong:`strong`,em:`em`,del:`del`,mark:`mark`}[r().type]??`span`},get children(){return n(YP,{get nodes(){return r().children},get inLink(){return e.inLink}})}}),n(l,{get when(){return r().type===`label`},get children(){return n(KP,{get node(){return t()},get inLink(){return e.inLink}})}})]})]}})})}async function XP(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 ZP(e){let[t,r]=u(!1),[i,a]=u(!1),o;M(()=>clearTimeout(o)),UP();let c=C(()=>{let t=BP();return!t||!e.lang||e.text.length>WP||!t.languageOf(e.lang)?[{text:e.text}]:t.run(e.text,e.lang)}),d=()=>e.lang||`text`;return(()=>{var u=OP(),f=u.firstChild,p=f.firstChild,m=p.nextSibling,h=m.nextSibling,_=f.nextSibling,v=_.firstChild;return y(p,d),y(f,()=>e.actions,m),m.$$click=()=>a(!i()),y(m,()=>i()?`No wrap`:`Wrap`),h.$$click=async()=>{await XP(e.text)&&(r(!0),clearTimeout(o),o=setTimeout(()=>r(!1),1500))},y(h,()=>t()?`Copied`:`Copy`),y(v,n(g,{get each(){return c()},children:e=>n(l,{get when(){return e().kind},get fallback(){return e().text},get children(){var t=kP();return y(t,()=>e().text),s(()=>k(t,`tok-${e().kind}`)),t}})})),s(n=>{var r=`code-block${i()?` wrap`:``}`,a=i(),o=i()?`Scroll long lines`:`Wrap long lines`,s=t()?`Copied`:`Copy ${d()} code`,c=e.lang||void 0;return r!==n.e&&k(u,n.e=r),a!==n.t&&b(m,`aria-pressed`,n.t=a),o!==n.a&&b(m,`title`,n.a=o),s!==n.o&&b(h,`aria-label`,n.o=s),c!==n.i&&b(_,`data-lang`,n.i=c),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),u})()}var QP=E(()=>Hn(()=>import(`./Diagram-BGmyRb-R.js`),__vite__mapDeps([0,1,2,3,4,5,6]))),$P=c(()=>void 0),eF=c(()=>void 0);function tF(e){let t=e.at(-1);if(t){if(t.type===`code`)return t;if(t.type===`quote`)return tF(t.blocks);if(t.type===`list`)return tF(t.items.at(-1)?.blocks??[])}}function nF(e){let t=le($P),i=le(eF),a=C(()=>{let n=i(),r=t()===e.block?void 0:n?.number(e.block);return n&&r!==void 0?{sessionID:n.sessionID,messageID:n.messageID,block:r,waiting:n.waiting}:void 0}),o=()=>n(ZP,{get lang(){return e.block.lang},get text(){return e.block.text},get actions(){return n(l,{get when(){return a()},children:e=>n(LM,{get target(){return e()},get waiting(){return e().waiting}})})}});return n(l,{get when(){return r(()=>!!Vn(e.block.lang))()&&t()!==e.block},get fallback(){return o()},get children(){return n(f,{get fallback(){return o()},get children(){return n(QP,{get lang(){return e.block.lang},get text(){return e.block.text}})}})}})}var rF={left:`left`,center:`center`,right:`right`};function iF(e){return n(g,{get each(){return e.blocks},children:e=>n(v,{get children(){return[n(o,{get when(){return r(()=>e().type===`paragraph`)()&&e()},children:e=>[(()=>{var t=jP();return y(t,n(YP,{get nodes(){return e().children}})),t})(),n(xP,{get block(){return e()}})]}),n(o,{get when(){return r(()=>e().type===`heading`)()&&e()},children:e=>[n(D,{get component(){return`h${Math.min(6,e().level+2)}`},get children(){return n(YP,{get nodes(){return e().children}})}}),n(xP,{get block(){return e()}})]}),n(o,{get when(){return r(()=>e().type===`list`)()&&e()},children:e=>n(D,{get component(){return e().ordered?`ol`:`ul`},get start(){return r(()=>!!(e().ordered&&e().start!==1))()?e().start:void 0},get class(){return e().loose?`loose`:void 0},get children(){return n(g,{get each(){return e().items},children:e=>(()=>{var t=NP();return y(t,n(l,{get when(){return e().checked!==void 0},get children(){var t=MP();return s(()=>b(t,`aria-label`,e().checked?`Done`:`Not done`)),s(()=>t.checked=e().checked),t}}),null),y(t,n(iF,{get blocks(){return e().blocks}}),null),s(()=>k(t,e().checked===void 0?void 0:`task`)),t})()})}})}),n(o,{get when(){return r(()=>e().type===`code`)()&&e()},children:e=>n(nF,{get block(){return e()}})}),n(o,{get when(){return r(()=>e().type===`quote`)()&&e()},children:e=>(()=>{var t=PP();return y(t,n(iF,{get blocks(){return e().blocks}})),t})()}),n(o,{get when(){return r(()=>e().type===`table`)()&&e()},children:e=>[(()=>{var t=FP(),r=t.firstChild.firstChild,i=r.firstChild,a=r.nextSibling;return y(i,n(g,{get each(){return e().head},children:(t,r)=>(()=>{var i=IP();return y(i,n(YP,{get nodes(){return t()}})),s(t=>h(i,e().align[r]?{"text-align":rF[e().align[r]]}:void 0,t)),i})()})),y(a,n(g,{get each(){return e().rows},children:t=>(()=>{var r=LP();return y(r,n(g,{get each(){return t()},children:(t,r)=>(()=>{var i=RP();return y(i,n(YP,{get nodes(){return t()}})),s(t=>h(i,e().align[r]?{"text-align":rF[e().align[r]]}:void 0,t)),i})()})),r})()})),t})(),n(xP,{get block(){return e()}})]}),n(o,{get when(){return e().type===`rule`},get children(){return AP()}})]}})})}function aF(e){let t=C(()=>Ij(e.text,{streaming:e.streaming})),r=C(()=>e.streaming&&kn(e.text)?tF(t()):void 0),i=C(()=>e.preview?new Map(yM(t()).map((e,t)=>[e,t])):void 0),a=C(()=>{let t=e.preview,n=i();if(t&&n)return{sessionID:t.sessionID,messageID:t.messageID,waiting:t.waiting===!0,streaming:e.streaming===!0,number:e=>n.has(e)?t.base+n.get(e):void 0}}),[o,s]=u(new Set),c=C(()=>{if(!e.links)return;let n=$w();if(!n)return;let r={origin:location.origin,allowlist:n.allowlist,enabled:n.remoteFetch!==!1};return{context:r,plan:QN(t(),r,{streaming:e.streaming}),tapped:o(),tap:e=>s(new Set([...o(),e]))}}),d=i=>n(yP.Provider,{value:c,get children(){return n(qP.Provider,{value:()=>i&&e.images?.length?{images:e.images,open:i}:void 0,get children(){return n($P.Provider,{value:r,get children(){return n(eF.Provider,{value:a,get children(){return n(iF,{get blocks(){return t()}})}})}})}})}}),f=C(()=>Pn(t(),e.images));return(()=>{var t=zP();return y(t,n(l,{get when(){return e.images?.length},get fallback(){return d()},get children(){return n(zn,{get images(){return f()},children:e=>d(e)})}})),t})()}z([`click`]);var oF=I(`<div class=dialog-head><h2 id=setup-machine-title>Set up Hub on a machine`),sF=I(`<label class="sm-field sm-root"><span class=sm-label>Workspace folder</span><input type=text class=mono autocapitalize=off autocomplete=off aria-describedby=setup-machine-root-hint><span id=setup-machine-root-hint class="small muted">Where sessions started from here run on the machine<!>. Empty: <!>.`),cF=I(`<label class="check sm-activate"><input type=checkbox><span>Start services now<span class="small muted block">Loads the machine's Hub services right away. Off: they are installed, and the installer prints how to start them.`),lF=I(`<div class="dialog-body setup-machine"><p id=setup-machine-intro class="small muted">Run this on the machine. It installs hubctl, then waits for you to approve the machine here (Settings → Machines &amp; devices → Approvals).</p><fieldset class=sm-field><legend>Operating system</legend><div class=sm-seg></div></fieldset><fieldset class=sm-field><legend>What to install</legend><div class=sm-profiles></div></fieldset><div class=sm-command-box><button type=button class="btn primary sm-copy"aria-label="Copy command"> </button></div><p class="small muted"aria-live=polite>`),uF=I(`<dialog class="dialog setup-machine-dialog"aria-labelledby=setup-machine-title aria-describedby=setup-machine-intro data-setup-machine>`),dF=I(`<label class=sm-seg-item><input type=radio name=setup-os>`),fF=I(`<label class=sm-profile><input type=radio name=setup-profile><span class=grow><span class=name></span><span class="small muted">`),pF=I(`<p class="error small"role=alert>`),mF=I(`<code class=sm-command data-setup-command>`),hF=`hub.setupMachine.os`,gF=`button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`,[_F,vF]=u();function yF(e={}){_F()||vF(e)}var bF=()=>{try{return localStorage.getItem(hF)??void 0}catch{return}};function xF(){let e,i,[a,o]=u(`linux`),[c,d]=u(`session-only`),[f,p]=u(``),[h,g]=u(!1),[_,v]=u(!1),S,w=()=>vF(void 0);x(()=>{let t=_F();e&&(t&&!e.open?(i=t.returnTo?.()??document.activeElement,o(hj(navigator,bF())),d(`session-only`),p(``),g(!1),v(!1),e.showModal(),queueMicrotask(()=>e?.querySelector(`input[name=setup-os]:checked`)?.focus())):!t&&e.open&&(e.close(),i?.isConnected&&i.focus(),i=void 0))});let T=e=>{o(e),gj(e,c())||d(`session-only`);try{localStorage.setItem(hF,e)}catch{}},E=()=>X()?.publicURL??location.origin,D=C(()=>xj({origin:E(),os:a(),profile:c(),root:f().trim(),activate:h()})),O=()=>a()===`windows`,k=()=>c()===`launch-node`,A=()=>c()!==`session-only`,j=()=>k()&&!D().ok,M=async()=>{let e=D();e.ok&&(await XP(e.command)?(q(`Command copied`),v(!0),clearTimeout(S),S=setTimeout(()=>v(!1),2e3)):q(`Couldn't copy: select the command and copy it`,`err`))};return(()=>{var i=uF();i.$$keydown=t=>{if(t.key!==`Tab`||!e)return;let n=[...e.querySelectorAll(gF)].filter(e=>!(e instanceof HTMLInputElement&&e.type===`radio`&&!e.checked));if(!n.length)return;let r=n[0],i=n[n.length-1];t.shiftKey&&document.activeElement===r?(t.preventDefault(),i.focus()):!t.shiftKey&&document.activeElement===i&&(t.preventDefault(),r.focus())},i.$$click=t=>t.target===e&&w(),i.addEventListener(`cancel`,e=>{e.preventDefault(),w()});var o=e;return typeof o==`function`?t(o,i):e=i,y(i,n(l,{get when(){return _F()},get children(){return[(()=>{var e=oF();return e.firstChild,y(e,n(F,{icon:`close`,label:`Close`,onClick:w}),null),e})(),(()=>{var e=lF(),t=e.firstChild.nextSibling,i=t.firstChild.nextSibling,o=t.nextSibling,u=o.firstChild.nextSibling,v=o.nextSibling,x=v.firstChild,S=x.firstChild,C=v.nextSibling;return y(i,n(m,{each:cj,children:e=>(()=>{var t=dF(),n=t.firstChild;return n.addEventListener(`change`,()=>T(e)),n.value=e,y(t,()=>lj[e],null),s(()=>t.classList.toggle(`on`,a()===e)),s(()=>n.checked=a()===e),t})()})),y(u,n(m,{get each(){return _j(a())},children:e=>(()=>{var t=fF(),n=t.firstChild,i=n.nextSibling.firstChild,o=i.nextSibling;return n.addEventListener(`change`,()=>d(e.id)),y(i,()=>e.label),y(o,(()=>{var t=r(()=>!!e.comingSoon);return()=>t()?`Coming soon on ${lj[a()]}`:e.description})()),s(r=>{var i=c()===e.id,a=!!e.comingSoon,o=e.comingSoon;return i!==r.e&&t.classList.toggle(`on`,r.e=i),a!==r.t&&t.classList.toggle(`disabled`,r.t=a),o!==r.a&&(n.disabled=r.a=o),r},{e:void 0,t:void 0,a:void 0}),s(()=>n.value=e.id),s(()=>n.checked=c()===e.id),t})()})),y(e,n(l,{get when(){return k()},get children(){var e=sF(),t=e.firstChild.nextSibling,n=t.nextSibling,r=n.firstChild.nextSibling,i=r.nextSibling.nextSibling;return i.nextSibling,t.$$input=e=>p(e.currentTarget.value),b(t,`placeholder`,uj),b(t,`spellcheck`,!1),y(n,()=>O()?` (C:\\Users\\you\\projects, C:/… or ~/…)`:``,r),y(n,uj,i),s(()=>b(t,`aria-invalid`,j()?`true`:void 0)),s(()=>t.value=f()),e}}),v),y(e,n(l,{get when(){return A()},get children(){var e=cF(),t=e.firstChild;return t.addEventListener(`change`,e=>g(e.currentTarget.checked)),s(()=>t.checked=h()),e}}),v),y(v,n(l,{get when(){return r(()=>!!D().ok)()&&D().command},get fallback(){return(()=>{var e=pF();return y(e,()=>D().error),e})()},children:e=>(()=>{var t=mF();return y(t,e),t})()}),x),x.$$click=()=>void M(),y(x,n(L,{get name(){return _()?`check`:`copy`}}),S),y(x,()=>_()?`Copied`:`Copy`,null),y(C,n(l,{get when(){return _()},get children(){return[`Copied. Paste it into a terminal on the machine`,r(()=>O()?` (PowerShell)`:``),`.`]}})),s(()=>x.disabled=!D().ok),e})()]}})),i})()}z([`click`,`keydown`,`input`]);var SF=I(`<h3 class=section-title>`),CF=I(`<section class=settings-section>`),wF=I(`<div class=settings-search role=search><input type=search placeholder="Search settings"aria-label="Search settings">`),TF=I(`<nav class=settings-nav aria-label="Settings sections">`),EF=I(`<div class=settings><header class=topbar><h1 class=title></h1></header><div class=settings-body><div class=settings-content><p class="small muted settings-footer">Server <!> · v`),DF=I(`<a>`),OF=I(`<ul class=settings-results aria-label="Search results">`),kF=I(`<p class="muted settings-empty">No settings match.`),AF=I(`<li><a><span class=name></span><span class="small muted"> · `),jF=I(`<ul class=settings-list aria-label="Settings sections">`),MF=I(`<li><a><span class=grow><span class=name></span><span class="small muted">`),NF=I(`<div class=settings-page><p class=muted>No such settings section.</p><a class="btn small"href=/settings>All settings`),PF=I(`<div class=settings-page><h2 class=settings-page-title>`),FF=I(`<span class=badge-pill>`),IF=I(`<div class="small muted">`),LF=I(`<div class=account-card><span aria-hidden=true></span><div class=grow><div><strong></strong></div><div class="small muted">This device: </div></div><button type=button class="btn danger">Sign out`),RF=I(`<h3>Notify me when`),zF=I(`<p class="small notify-summary"data-notify-summary>`),BF=I(`<p class="small warn">These apply once this device is subscribed.`),VF=I(`<p class=activity-hint data-activity-hint><strong>Know what happens with the screen off:</strong> turn on <em>All done</em> for one notification when a session and its subagents finish, or the <em>Activity digest</em> for one quiet, self-replacing summary per session.`),HF=I(`<h4>When`),UF=I(`<ul class=switches><li id=quiet-hours><label class=switch><span>Quiet hours</span><input type=checkbox>`),WF=I(`<p class="small muted"> muted (⋯ menu of a session → Unmute notifications).`),GF=I(`<p class="small muted">Checking this device…`),KF=I(`<div class=notify-status-row><p role=status></p><details class=notify-details><summary class=small>Details</summary><dl class="notify-facts small muted"><dt>Permission</dt><dd></dd><dt>Service worker</dt><dd></dd><dt>Subscribed on this hub</dt><dd>`),qF=I(`<button type=button class="btn small primary">Enable notifications on this device`),JF=I(`<button type=button class="btn small">Turn off on this device`),YF=I(`<span class=notify-test id=notify-test><select aria-label="Test notification kind"data-test-kind><option value>Basic test</option></select><button type=button class="btn small">Send test notification`),XF=I(`<div class=row-actions>`),ZF=I(`<option>`),QF=I(`<p data-test-result>`),$F=I(`<details class=notify-group><summary><h4></h4><span class="small muted notify-group-summary"data-group-summary></span></summary><ul class=switches>`),eI=I(`<div class=quiet-hours><label>At most one per session every <select data-activity-minutes></select></label><span class="small muted">Collapses into one notification per session; respects quiet hours and muted sessions.`),tI=I(`<li><label class=switch><span class=notify-kind><span></span><span class="small muted"></span></span><input type=checkbox>`),nI=I(`<div class=quiet-hours><label>From <input type=time></label><label>to <input type=time></label><span class="small muted">. Hand-offs still come through.`),rI=I(`<ul class=switches><li class=appearance-theme id=set-theme><span id=color-theme>Color theme</span><div class=theme-toggle role=radiogroup aria-labelledby=color-theme></div></li><li class=speed id=set-text-size><label for=text-size>Text size</label><input id=text-size type=range><output for=text-size></output><button type=button class="btn small"aria-label="Reset text size">Reset`),iI=I(`<p class="small muted">On this device. Pinch the conversation or the session list to change it too (a trackpad pinch works on desktop).`),aI=I(`<button type=button role=radio class=theme-choice><span>`),oI=I(`<details class=turn-advanced><summary class=small>Advanced</summary><div class=turn-knobs></div><p class="small muted">Empty: the default. Values outside a field's range are clamped. Slow cap: a score slower than this hands the turn to the timers (it rises to twice the usual score time on a slow device, at most 5 s). A URL query parameter (e.g. ?voiceTurn.threshold=0.6) overrides these until the page reloads without it; “in use” shows what applies.`),sI=I(`<ul class=switches><li class=speed id=set-voice-speed><label for=voice-speed>Voice speed</label><input id=voice-speed type=range><output for=voice-speed></output></li><li id=set-sensitivity><div class=switch><span id=voice-sensitivity>Mic sensitivity</span><div class=chips role=radiogroup aria-labelledby=voice-sensitivity></div></div><p class="small muted">How sure Voice mode must be that you are speaking to it. Low: noisy places (only clear, sustained speech counts). High: quiet rooms and soft voices. On this device; applies at once, also while Voice mode is on.</p></li><li id=set-turn-detection><div class=switch><span id=voice-turn-detection>Turn detection</span><div class=chips role=radiogroup aria-labelledby=voice-turn-detection></div></div><p class="small muted">When Voice mode decides you finished speaking. Timers: a fixed wait after you stop (1 s, 1.6 s when the words sound unfinished). Smart Turn: an on-device audio model (Pipecat Smart Turn v3, 8.7 MB, loaded on first use) scores your intonation at each pause; a confident “finished” sends at once, otherwise it waits (at most 3 s). The Voice bar shows its score. On this device; applies at once.</p></li><li id=set-voice-front><label class=switch><span>Voice front</span><input type=checkbox></label><p class="small muted">On (the default): in Voice mode a fast voice agent answers in front of the session. It says what it understood, then passes your request to the session, which keeps its own agent and model. No spoken “On it.” phrases (the tones stay). Off: Voice mode talks to the session directly, with short spoken replies. If the front is not available, Voice mode talks to the session directly too. The front runs on the session's Voice model (else the machine's <code>voiceModel</code>): pick a fast paid model. On this device; applies the next time Voice mode starts.</p></li><li id=set-cues><label class=switch><span>Progress cues</span><input type=checkbox></label><p class="small muted">In Voice mode: a soft tone when the agent hears you, then short, varied acknowledgements while it works (“On it.”, “One moment.”, “I’ll hand that off.”, “Still on it.” …).</p></li><li id=set-background><label class=switch><span>Keep listening when the screen is off</span><input type=checkbox></label><p class="small muted">Off: the screen stays on while listening. On: lock-screen controls and listening with the screen off. Best effort. Android Chrome usually stops the microphone when the screen turns off; Hub shows when listening is paused and resumes when you unlock. Applies the next time Voice mode starts.`),cI=I(`<button type=button class=chip role=radio>`),lI=I(`<label class=small> <input type=number inputmode=decimal> <output class=muted data-turn-effective>in use: `),uI=I(`<h3>Waiting for approval`),dI=I(`<ul class=list>`),fI=I(`<li><div class=grow><div class=name></div><div class="small muted">Code <!> · requested </div></div><button type=button class="btn small primary">Approve</button><button type=button class="btn small danger">Deny`),pI=I(`<div class=row><p class="small muted grow">Computers connected to this hub. Set one up with a one-line installer (macOS, Linux, Windows).</p><button type=button id=setup-machine class="btn small">Set up a machine`),mI=I(`<p class="small muted">None yet.`),hI=I(`<li><div class=grow><div class=name><span aria-hidden=true></span> </div><div class="small muted"></div></div><button type=button class="btn small danger">Revoke`),gI=I(`<div class=row><p class="small muted grow">Browsers and the Hub app signed in to your account. Add the app on a phone or tablet by scanning a code.</p><button type=button class="btn small">Add app`),_I=I(`<p class="small muted">`),vI=I(`<span class=muted> · this device`),yI=I(`<li><div class=grow><div class=name></div><div class="small muted">last seen </div></div><button type=button class="btn small danger">`),bI=I(`<svg class=qr role=img aria-label="QR code for the app link"shape-rendering=crispEdges><rect width=100% height=100% fill=#fff></rect><path fill=#000>`),xI=I(`<p class="small muted">Expires in <span class=add-app-countdown></span> · single use`),SI=I(`<div class=row><code class="add-app-link grow"></code><button type=button class="btn small">Copy</button><a class="btn small">Open`),CI=I(`<div class=add-app-body><p class=small>In the Hub app, choose <b>Add hub</b> and scan this code, or open the link on the phone with the app. It links the app to your account on <b></b>.</p><p class="small muted">Anyone with this code can sign in as you until it is used or expires; show it only to your own device.`),wI=I(`<div class=add-app-expired><p class="small warn">This code expired.</p><button type=button class="btn small primary">New code`),TI=I(`<div class=row><p class="small muted grow">Use Hub from a phone or tablet: scan a code in the Hub app to link it to your account.</p><button type=button class="btn small">Add app`),EI=I(`<p class="small muted">How your <a href=/teams>teams</a> work with the rest of your sessions.`),DI=I(`<ul class=switches><li id=team-isolation><label class=switch><span class=notify-kind><span>Team isolation</span><span class="small muted">On: sessions seated in a team see only their teams' sessions; your other sessions are hidden from them. Off: they also see your sessions in no team. Your own view is unchanged either way.</span></span><input type=checkbox data-team-isolation>`),OI=I(`<div class=chips role=group aria-label="Admin sections">`),kI=I(`<p class=error role=alert>`),AI=I(`<div id=admin-machines>`),jI=I(`<p class="small muted">Approving a machine makes it yours. Someone else's machine: let them approve it from their phone with the code OpenCode shows (/approve?code=…).`),MI=I(`<div id=admin-audit>`),NI=I(`<span class=count>`),PI=I(`<button type=button class=chip>`),FI=I(`<p class=muted>No machines are waiting for approval.`),II=I(`<div class=stack><div class=row><input type=search class=grow placeholder="Search by email or name"aria-label="Search users"><select aria-label=Show></select><select aria-label="Sort by">`),LI=I(`<p class=muted>`),RI=I(`<li class=muted>No users match.`),zI=I(`<span class=badge-pill>Admin`),BI=I(`<span class="badge-pill off">Disabled`),VI=I(`<span class=badge-pill>You`),HI=I(`<li><div class=grow><div class=name></div><div class="small muted"> · <!> · seen `),UI=I(`<button type=button>`),WI=I(`<p class=muted>No machines are connected to this hub yet.`),GI=I(`<li><div class=grow><div class=name><span aria-hidden=true></span> </div><div class="small muted"> · </div></div><button type=button class="btn small danger">Revoke`),KI=I(`<ol class="list audit">`),qI=I(`<p class=muted>Nothing recorded yet.`),JI=I(`<li><div class=grow><div class=name></div><div class="small muted"></div></div><time class="small muted">`);function YI(e){return(()=>{var t=CF();return i(t,_({get id(){return e.id}},()=>e.title?{"aria-labelledby":`h-${e.id}`}:{"aria-label":e.label??e.id}),!1,!0),y(t,n(l,{get when(){return e.title},get children(){var t=SF();return y(t,()=>e.title),s(()=>b(t,`id`,`h-${e.id}`)),t}}),null),y(t,()=>e.children,null),t})()}var XI=2400,ZI=3e3;function QI(e){if(!e)return;let t=Date.now()+ZI,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`),XI)}};requestAnimationFrame(n)}var $I=e=>vt(!0).find(t=>t.id===e)?.label,eL=!1;function tL(){let t=()=>qn(X()),i=()=>{let e=xC();return e.name===`settings`?e.section:void 0},a=()=>gt(i(),{admin:t(),phone:Z()}),[c,d]=u(``),f=()=>It(c(),bt(t()));x(e(Pt,e=>QI(At(decodeURIComponent(e.hash.slice(1))))));let p=()=>{eL?(eL=!1,history.back()):Vt(`/settings`)},h=()=>(()=>{var e=wF(),t=e.firstChild;return t.$$keydown=e=>{e.key===`Escape`&&d(``);let t=f()[0];e.key===`Enter`&&t&&(d(``),Vt(`/settings/${t.section}#${t.id}`))},t.$$input=e=>d(e.currentTarget.value),s(()=>t.value=c()),e})();return(()=>{var e=EF(),i=e.firstChild,u=i.firstChild,g=i.nextSibling,_=g.firstChild,x=_.firstChild,S=x.firstChild.nextSibling;return S.nextSibling,y(i,n(l,{get when(){return Z()},get children(){return n(l,{get when(){return a()!==`list`},get fallback(){return n(F,{icon:`menu`,label:`Open sidebar`,onClick:Gp})},get children(){return n(F,{icon:`back`,label:`All settings`,onClick:p})}})}}),u),y(u,(()=>{var e=r(()=>!!(Z()&&a()!==`list`));return()=>e()?$I(a())??`Settings`:`Settings`})()),y(g,n(l,{get when(){return!Z()},get children(){var e=TF();return y(e,h,null),y(e,n(m,{get each(){return vt(t())},children:e=>(()=>{var t=DF();return t.$$click=()=>d(``),y(t,()=>e.label),s(n=>{var r=`/settings/${e.id}`,i=a()===e.id&&!c()?`page`:void 0;return r!==n.e&&b(t,`href`,n.e=r),i!==n.t&&b(t,`aria-current`,n.t=i),n},{e:void 0,t:void 0}),t})()}),null),e}}),_),y(_,n(l,{get when(){return r(()=>!!Z())()&&a()===`list`},get children(){return h()}}),x),y(_,n(l,{get when(){return!c()},get fallback(){return n(nL,{get results(){return f()},onPick:()=>d(``)})},get children(){return n(v,{get fallback(){return n(iL,{})},get children(){return[n(o,{get when(){return a()===`list`},get children(){return n(rL,{onPick:()=>eL=!0})}}),n(o,{get when(){return r(()=>a()!==`list`)()&&a()},keyed:!0,children:e=>n(aL,{id:e})})]}})}}),x),y(x,()=>X()?.publicURL??location.origin,S),y(x,()=>X()?.version??`?`,null),e})()}function nL(e){return n(l,{get when(){return e.results.length},get fallback(){return kF()},get children(){var t=OF();return y(t,n(m,{get each(){return e.results},children:t=>(()=>{var n=AF(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild;return B(r,`click`,e.onPick,!0),y(i,()=>t.label),y(a,()=>$I(t.section),o),y(a,()=>t.description,null),s(()=>b(r,`href`,`/settings/${t.section}#${t.id}`)),n})()})),t}})}function rL(e){return(()=>{var t=jF();return y(t,n(m,{get each(){return vt(qn(X()))},children:t=>(()=>{var r=MF(),i=r.firstChild,a=i.firstChild.firstChild,o=a.nextSibling;return B(i,`click`,e.onPick,!0),y(a,()=>t.label),y(o,()=>t.description),y(i,n(L,{name:`chevron`}),null),s(()=>b(i,`href`,`/settings/${t.id}`)),r})()})),t})()}function iL(){return NF()}function aL(e){return(()=>{var t=PF(),i=t.firstChild;return y(i,()=>$I(e.id)),y(t,n(v,{get children(){return[n(o,{get when(){return e.id===`general`},get children(){return[n(sL,{}),n(lL,{}),n(xL,{})]}}),n(o,{get when(){return e.id===`notifications`},get children(){return n(cL,{})}}),n(o,{get when(){return e.id===`voice`},get children(){return[n(mL,{}),n(Lw,{}),n(YI,{id:`speech`,title:`Speech`,get children(){return n(mw,{})}})]}}),n(o,{get when(){return e.id===`media`},get children(){return n(YI,{id:`media-allowlist`,title:`Web images`,get children(){return n(hT,{})}})}}),n(o,{get when(){return e.id===`machines`},get children(){return[n(_L,{}),n(vL,{})]}}),n(o,{get when(){return e.id===`agents`},get children(){return n(uO,{})}}),n(o,{get when(){return e.id===`concierge`},get children(){return[n(kk,{}),n(YI,{id:`context-cards`,title:`Context cards`,get children(){return n(fA,{})}})]}}),n(o,{get when(){return e.id===`teams`},get children(){return n(CL,{})}}),n(o,{get when(){return r(()=>e.id===`admin`)()&&qn(X())},get children(){return n(EL,{})}})]}}),null),s(()=>b(t,`data-settings-section`,e.id)),t})()}async function oL(){if(Jn(X()).mode!==`pairing`||await P(`Sign out this device? You will need a new pairing code.`,`Sign out`,{danger:!0})){await(await np().catch(()=>void 0))?.unsubscribe().catch(()=>{}),await V(`/api/logout`,{method:`POST`,json:{}}).catch(()=>{});try{as(localStorage)}catch{}ld(),location.href=`/`}}function sL(){let e=()=>Jn(X());return n(YI,{id:`account`,title:`Account`,get children(){var t=LF(),r=t.firstChild,i=r.nextSibling,a=i.firstChild,o=a.firstChild,c=a.nextSibling;c.firstChild;var u=i.nextSibling;return y(r,()=>e().initial),y(o,()=>e().title),y(a,n(l,{get when(){return e().badge},get children(){var t=FF();return y(t,()=>e().badge),t}}),null),y(i,n(l,{get when(){return e().subtitle},get children(){var t=IF();return y(t,()=>e().subtitle),t}}),c),y(c,()=>X()?.device?.name??`paired`,null),u.$$click=()=>void oL(),s(()=>k(r,`avatar large${e().badge?` admin`:``}`)),t}})}function cL(){let[e,{refetch:t}]=d(Xf,()=>ip()),[i,a]=u(!1),[o,c]=u(),[f,p]=u(``),[h,g]=u(),[_,v]=u(null),[x,S]=u(),C=()=>x()??T()?.activityMinutes??5,w=()=>e()?qe(e().env):void 0,T=()=>e()?.view,E=()=>h()??T()?.prefs,D=()=>h()?_():T()?.quietHours??null,O=async(e,n)=>{a(!0);try{await e(),n&&q(n)}catch(e){q(U(e),`err`)}finally{a(!1),g(void 0),t()}},A=async e=>{try{let t=await(await V(`/api/push/prefs`,{method:`PUT`,json:e})).json();g(t.prefs),v(t.quietHours??null),t.activityMinutes!==void 0&&S(t.activityMinutes)}catch(e){q(U(e),`err`)}},j=async()=>{c(void 0);try{c(lt(await cp(f()||void 0)))}catch(e){c({ok:!1,text:U(e)})}};return n(YI,{id:`notifications`,label:`Notifications`,get children(){return[n(l,{get when(){return w()},get fallback(){return GF()},children:t=>[(()=>{var n=KF(),i=n.firstChild,a=i.nextSibling.firstChild.nextSibling.firstChild.nextSibling,o=a.nextSibling.nextSibling,c=o.nextSibling.nextSibling;return y(i,()=>t().message),y(a,(()=>{var t=r(()=>!!e().env.supported);return()=>t()?e().env.permission:`unsupported`})()),y(o,()=>e().env.worker?`registered`:`not registered`),y(c,()=>e().env.hubSubscribed?`yes`:`no`),s(e=>{var n=t().warn?`notify-status warn`:`notify-status ok`,r=t().state;return n!==e.e&&k(i,e.e=n),r!==e.t&&b(i,`data-state`,e.t=r),e},{e:void 0,t:void 0}),n})(),(()=>{var r=XF();return y(r,n(l,{get when(){return t().action===`enable`},get children(){var e=qF();return e.$$click=()=>void O(op,`Notifications are on for this device`),s(()=>e.disabled=i()),e}}),null),y(r,n(l,{get when(){return t().action===`disable`},get children(){var e=JF();return e.$$click=()=>void O(sp,`Notifications are off for this device`),s(()=>e.disabled=i()),e}}),null),y(r,n(l,{get when(){return e().env.hubSubscriptions>0},get children(){var e=YF(),t=e.firstChild;t.firstChild;var r=t.nextSibling;return t.addEventListener(`change`,e=>p(e.currentTarget.value)),y(t,n(m,{each:$t,children:e=>(()=>{var t=ZF();return y(t,()=>e.label),s(()=>t.value=e.key),t})()}),null),r.$$click=()=>void j(),s(()=>t.value=f()),e}}),null),r})(),n(l,{get when(){return o()},children:e=>(()=>{var t=QF();return y(t,()=>e().text),s(()=>k(t,e().ok?`small ok`:`small err`)),t})()})]}),n(l,{get when(){return E()},get children(){return[RF(),(()=>{var e=zF();return y(e,()=>be(E())),e})(),n(l,{get when(){return r(()=>!!w())()&&w().state!==`on`},get children(){return BF()}}),n(l,{get when(){return r(()=>`activity`in E()&&!E().activity)()&&!E().done},get children(){return VF()}}),n(m,{get each(){return qt.filter(e=>e.kinds.some(e=>e.key in E()))},children:e=>(()=>{var t=$F(),i=t.firstChild,a=i.firstChild,o=a.nextSibling,c=i.nextSibling;return y(a,()=>e.title),y(o,()=>pt(e.kinds,E())),y(c,n(m,{get each(){return e.kinds.filter(e=>e.key in E())},children:e=>(()=>{var t=tI(),i=t.firstChild.firstChild,a=i.firstChild,o=a.nextSibling,c=i.nextSibling;return y(a,()=>e.label),y(o,()=>e.description),c.addEventListener(`change`,t=>void A({[e.key]:t.currentTarget.checked})),y(t,n(l,{get when(){return r(()=>e.key===`activity`)()&&E().activity},get children(){var e=eI(),t=e.firstChild.firstChild.nextSibling;return t.addEventListener(`change`,e=>void A({activityMinutes:Number(e.currentTarget.value)})),y(t,n(m,{each:ot,children:e=>(()=>{var t=ZF();return y(t,e===1?`minute`:`${e} minutes`),s(()=>t.value=String(e)),t})()})),s(()=>t.value=String(C())),e}}),null),s(n=>{var r=`pref-${e.key}`,i=e.key;return r!==n.e&&b(t,`id`,n.e=r),i!==n.t&&b(c,`data-pref`,n.t=i),n},{e:void 0,t:void 0}),s(()=>c.checked=!!E()[e.key]),t})()})),s(()=>b(t,`data-notify-group`,e.title)),t})()}),HF(),(()=>{var e=UF(),t=e.firstChild,r=t.firstChild.firstChild.nextSibling;return r.addEventListener(`change`,e=>void A({quietHours:e.currentTarget.checked?{start:`22:00`,end:`07:00`,timeZone:Zt()}:null})),y(t,n(l,{get when(){return D()},children:e=>(()=>{var t=nI(),n=t.firstChild,r=n.firstChild.nextSibling,i=n.nextSibling,a=i.firstChild.nextSibling,o=i.nextSibling,c=o.firstChild;return r.addEventListener(`change`,t=>void A({quietHours:{...e(),start:t.currentTarget.value,timeZone:Zt()}})),a.addEventListener(`change`,t=>void A({quietHours:{...e(),end:t.currentTarget.value,timeZone:Zt()}})),y(o,()=>e().timeZone,c),s(()=>r.value=e().start),s(()=>a.value=e().end),t})()}),null),s(()=>r.checked=!!D()),e})(),n(l,{get when(){return Qf().size},get children(){var e=WF(),t=e.firstChild;return y(e,()=>_n(Qf().size,`session`),t),e}})]}})]}})}function lL(){return n(YI,{id:`appearance`,title:`Appearance`,get children(){return[(()=>{var e=rI(),t=e.firstChild,r=t.firstChild.nextSibling,i=t.nextSibling.firstChild.nextSibling,a=i.nextSibling,o=a.nextSibling;return y(r,n(m,{each:ej,children:e=>(()=>{var t=aI(),n=t.firstChild;return t.$$click=()=>sj(e),y(t,e===`light`?`☀`:e===`dark`?`☾`:`▣`,n),y(n,()=>e[0].toUpperCase()+e.slice(1)),s(()=>b(t,`aria-checked`,aj()===e)),t})()})),i.$$input=e=>XA(Number(e.currentTarget.value)),b(i,`min`,jA),b(i,`max`,MA),b(i,`step`,NA),y(a,()=>VA(qA())),o.$$click=()=>XA(1),s(e=>{var t=VA(qA()),n=qA()===1;return t!==e.e&&b(i,`aria-valuetext`,e.e=t),n!==e.t&&(o.disabled=e.t=n),e},{e:void 0,t:void 0}),s(()=>i.value=qA()),e})(),iI()]}})}var uL={low:`Low`,normal:`Normal`,high:`High`},dL={timers:`Timers (current)`,smart:`Smart Turn (experimental)`},fL={threshold:{label:`Threshold`,step:`0.05`},graceMs:{label:`Grace (ms)`,step:`50`},fallbackMs:{label:`Fallback (ms)`,step:`100`},slowMs:{label:`Slow cap (ms)`,step:`100`}},pL=T_.flatMap(e=>fL[e.field]?[{...e,...fL[e.field],placeholder:String(S_[e.field])}]:[]);function mL(){let[e,t]=u(Jy.speed),[r,i]=u(Jy.sensitivity),[a,o]=u(Jy.turnDetection),[c,d]=u(Jy.smartTurn);return n(YI,{id:`voice`,title:`Voice`,get children(){var u=sI(),f=u.firstChild,p=f.firstChild.nextSibling,h=p.nextSibling,g=f.nextSibling,_=g.firstChild.firstChild.nextSibling,v=g.nextSibling,x=v.firstChild,S=x.firstChild.nextSibling;x.nextSibling;var C=v.nextSibling,w=C.firstChild.firstChild.nextSibling,T=C.nextSibling,E=T.firstChild.firstChild.nextSibling,D=T.nextSibling.firstChild.firstChild.nextSibling;return p.$$input=e=>{Jy.speed=Number(e.currentTarget.value),t(Jy.speed)},b(p,`min`,Ba),b(p,`max`,2),b(p,`step`,Va),y(h,()=>Ua(e())),y(_,n(m,{each:Ay,children:e=>(()=>{var t=cI();return t.$$click=()=>{Jy.sensitivity=e,i(e)},y(t,()=>uL[e]),s(n=>{var i=r()===e,a=r()===e;return i!==n.e&&b(t,`aria-checked`,n.e=i),a!==n.t&&b(t,`aria-pressed`,n.t=a),n},{e:void 0,t:void 0}),t})()})),y(S,n(m,{each:b_,children:e=>(()=>{var t=cI();return t.$$click=()=>{Jy.turnDetection=e,o(e),j_({mode:e,load:p_})},y(t,()=>dL[e]),s(n=>{var r=a()===e,i=a()===e;return r!==n.e&&b(t,`aria-checked`,n.e=r),i!==n.t&&b(t,`aria-pressed`,n.t=i),n},{e:void 0,t:void 0}),t})()})),y(v,n(l,{get when(){return a()===`smart`},get children(){var e=oI(),t=e.firstChild.nextSibling;return y(t,n(m,{each:pL,children:e=>(()=>{var t=lI(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling.nextSibling;return i.firstChild,y(t,()=>e.label,n),r.addEventListener(`change`,t=>{t.currentTarget.value=Jy.setSmartTurnKnob(e.key,t.currentTarget.value),d(Jy.smartTurn)}),y(i,()=>c()[e.field],null),s(n=>{var i=e.key,a=e.min,o=e.max,s=e.step,c=e.placeholder;return i!==n.e&&b(t,`data-turn-knob`,n.e=i),a!==n.t&&b(r,`min`,n.t=a),o!==n.a&&b(r,`max`,n.a=o),s!==n.o&&b(r,`step`,n.o=s),c!==n.i&&b(r,`placeholder`,n.i=c),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),s(()=>r.value=E_(e.key,localStorage.getItem(e.key))??``),t})()})),e}}),null),w.addEventListener(`change`,e=>Jy.front=e.currentTarget.checked),E.addEventListener(`change`,e=>Jy.cues=e.currentTarget.checked),D.addEventListener(`change`,e=>Jy.background=e.currentTarget.checked),s(()=>b(p,`aria-valuetext`,Ua(e()))),s(()=>p.value=e()),s(()=>w.checked=Jy.front),s(()=>E.checked=Jy.cues),s(()=>D.checked=Jy.background),u}})}async function hL(e,t){try{await V(`/api/enrollments/${K(e.userCode)}/${t}`,{method:`POST`,json:{}}),q(t===`approve`?`${e.machineName} approved; it belongs to you`:`Request denied`)}catch(e){q(U(e),`err`)}Ad()}function gL(){return n(l,{get when(){return au().length},get children(){return[uI(),(()=>{var e=dI();return y(e,n(m,{get each(){return au()},children:e=>(()=>{var t=fI(),n=t.firstChild,r=n.firstChild,i=r.nextSibling,a=i.firstChild.nextSibling;a.nextSibling;var o=n.nextSibling,s=o.nextSibling;return y(r,()=>e.machineName),y(i,()=>e.userCode,a),y(i,()=>R(e.created,N()),null),o.$$click=()=>void hL(e,`approve`),s.$$click=()=>void hL(e,`deny`),t})()})),e})()]}})}function _L(){let e=async e=>{if(await P(`Revoke ${e.name}? Its OpenCode processes disconnect and it must be connected again.`,`Revoke`,{danger:!0}))try{await V(`/api/machines/${K(e.id)}`,{method:`DELETE`}),q(`${e.name} revoked`)}catch(e){q(U(e),`err`)}};return n(YI,{id:`machines`,title:`Machines`,get children(){return[(()=>{var e=pI(),t=e.firstChild.nextSibling;return t.$$click=()=>yF(),e})(),n(gL,{}),n(l,{get when(){return(Y.machines??[]).length},get fallback(){return mI()},get children(){var t=dI();return y(t,n(m,{get each(){return Y.machines},children:t=>(()=>{var n=hI(),i=n.firstChild,a=i.firstChild,o=a.firstChild;o.nextSibling;var c=a.nextSibling,l=i.nextSibling;return y(a,()=>t.name,null),y(c,(()=>{var e=r(()=>!!t.online);return()=>e()?`online · ${_n(t.processes.length,`OpenCode process`)}`:`offline · seen ${R(t.lastSeen,N())}`})()),l.$$click=()=>void e(t),s(e=>{var n=`online-dot${t.online?` on`:``}`,r=`Revoke machine ${t.name}`;return n!==e.e&&k(o,e.e=n),r!==e.t&&b(l,`aria-label`,e.t=r),e},{e:void 0,t:void 0}),n})()})),t}})]}})}function vL(){let[e,{refetch:t,mutate:i}]=d(()=>G(`/api/devices`).then(e=>e.devices)),[a,o]=u(!1),s=async e=>{if(e.current)return void oL();if(await P(`Revoke ${e.name}?`,`Revoke`,{danger:!0})){try{await V(`/api/devices/${K(e.id)}`,{method:`DELETE`}),q(`${e.name} revoked`)}catch(e){q(U(e),`err`)}t()}};return n(YI,{id:`devices`,title:`Devices`,get children(){return[(()=>{var e=gI(),t=e.firstChild.nextSibling;return t.$$click=()=>o(!0),e})(),n(l,{get when(){return a()},get children(){return n(bL,{get known(){return new Set((e()??[]).map(e=>e.id))},onLinked:e=>i(e),onClose:()=>{o(!1),t()}})}}),n(l,{get when(){return e()},get fallback(){return(()=>{var t=_I();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?U(e.error):`Loading…`})()),t})()},get children(){var t=dI();return y(t,n(m,{get each(){return e()},children:e=>(()=>{var t=yI(),r=t.firstChild,i=r.firstChild,a=i.nextSibling;a.firstChild;var o=r.nextSibling;return y(i,()=>e.name,null),y(i,n(l,{get when(){return e.current},get children(){return vI()}}),null),y(a,()=>R(e.lastSeen,N()),null),o.$$click=()=>void s(e),y(o,()=>e.current?`Sign out`:`Revoke`),t})()})),t}})]}})}var yL=2e3;function bL(e){let[t,r]=u(),[i,a]=u(``),[o,c]=u(Date.now()),d=async()=>{a(``);try{let e=await V(`/api/devices/link`,{method:`POST`,json:{}}),t=await e.json(),n=Date.now();c(n),r({...t,expiresAt:hA(t.expiresAt,e.headers.get(`date`),n)})}catch(e){a(U(e))}},f=()=>(t()?.expiresAt??0)<=o(),p=()=>{let e=t();return e?kA(e.url,{ecc:`M`}):void 0},m=setInterval(()=>c(Date.now()),1e3),h=!1,g=setInterval(async()=>{if(!(h||!t()||f())){h=!0;try{let t=(await G(`/api/devices`)).devices,n=mA(e.known,t);n&&(e.onLinked(t),q(`${n.name} linked`),e.onClose())}catch{}finally{h=!1}}},yL);return M(()=>{clearInterval(m),clearInterval(g)}),d(),n(de,{open:!0,title:`Add the Hub app`,get onClose(){return e.onClose},class:`add-app`,get children(){return n(l,{get when(){return t()},get fallback(){return(()=>{var e=_I();return y(e,()=>i()||`Creating a link code…`),e})()},children:e=>(()=>{var t=CI(),r=t.firstChild,i=r.firstChild.nextSibling.nextSibling.nextSibling,a=r.nextSibling;return y(i,()=>e().hub),y(t,n(l,{get when(){return!f()},get fallback(){return(()=>{var e=wI(),t=e.firstChild.nextSibling;return t.$$click=()=>void d(),e})()},get children(){return[(()=>{var e=bI(),t=e.firstChild.nextSibling;return s(n=>{var r=`0 0 ${p().size+8} ${p().size+8}`,i=AA(p(),4);return r!==n.e&&b(e,`viewBox`,n.e=r),i!==n.t&&b(t,`d`,n.t=i),n},{e:void 0,t:void 0}),e})(),(()=>{var t=xI(),n=t.firstChild.nextSibling;return y(n,()=>pA(e().expiresAt,o())),t})(),(()=>{var t=SI(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling;return y(n,()=>e().url),r.$$click=()=>void navigator.clipboard?.writeText(e().url).then(()=>q(`Link copied`),()=>q(`Copy failed`,`err`)),s(()=>b(i,`href`,e().url)),t})()]}}),a),t})()})}})}function xL(){let[e,t]=u(),r=async()=>{try{t(new Set((await G(`/api/devices`)).devices.map(e=>e.id)))}catch(e){q(U(e),`err`)}};return n(YI,{id:`add-app`,title:`Add the Hub app`,get children(){return[(()=>{var e=TI(),t=e.firstChild.nextSibling;return t.$$click=()=>void r(),e})(),n(l,{get when(){return e()},children:e=>n(bL,{get known(){return e()},onLinked:()=>{},onClose:()=>t(void 0)})})]}})}var SL=`/api/agent/team-settings`;function CL(){let[e,{mutate:t,refetch:i}]=d(()=>G(SL).then(e=>e.settings)),[a,o]=u(!1),c=async n=>{let r=e();if(!r)return;let a=n.checked;o(!0);try{let e=await(await V(SL,{method:`PUT`,json:{teamIsolation:a,expectedRevision:r.revision}})).json();t(e.settings),q(a?`Team isolation is on`:`Team isolation is off`)}catch(e){n.checked=!a,e instanceof W&&e.status===409?(q(`Team settings changed elsewhere. Showing the current setting; try again.`,`err`),i()):q(U(e),`err`)}finally{o(!1)}};return n(YI,{id:`teams`,label:`Teams`,get children(){return[EI(),n(l,{get when(){return e()},get fallback(){return(()=>{var t=_I();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?`Could not load: ${U(e.error)}`:`Loading…`})()),t})()},children:e=>(()=>{var t=DI(),n=t.firstChild.firstChild.firstChild.nextSibling;return n.addEventListener(`change`,e=>void c(e.currentTarget)),s(()=>n.disabled=a()),s(()=>n.checked=e().teamIsolation),t})()})]}})}var wL=(e,t)=>Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[],TL=e=>e.id===`local`?`Hub owner (pairing)`:e.name||e.email||e.id;function EL(){let e=()=>Xn(X()),[t,r]=u(e()[0]?.[0]??`machines`),[i,a]=u(``);x(()=>{let t=Pt().hash,n=t===`#admin-machines`?`machines`:t===`#admin-audit`?`audit`:void 0;n&&e().some(([e])=>e===n)&&r(n)});let o=async(e,t)=>{try{return await e(),a(``),q(t),!0}catch(e){return a(lr(e)),q(i(),`err`),!1}};return n(YI,{id:`admin`,label:`Admin`,get children(){return[(()=>{var i=OI();return y(i,n(m,{get each(){return e()},children:([e,i])=>(()=>{var o=PI();return o.$$click=()=>(r(e),a(``)),y(o,i,null),y(o,n(l,{get when(){return e===`approvals`&&au().length},get children(){var e=NI();return y(e,()=>au().length),e}}),null),s(()=>b(o,`aria-pressed`,t()===e)),o})()})),i})(),n(l,{get when(){return i()},get children(){var e=kI();return y(e,i),e}}),n(l,{get when(){return t()===`users`},get children(){return n(DL,{change:o})}}),n(l,{get when(){return t()===`machines`},get children(){var e=AI();return y(e,n(OL,{change:o})),e}}),n(l,{get when(){return t()===`approvals`},get children(){return[jI(),n(l,{get when(){return au().length},get fallback(){return FI()},get children(){return n(gL,{})}})]}}),n(l,{get when(){return t()===`audit`},get children(){var e=MI();return y(e,n(kL,{})),e}})]}})}function DL(e){let[t,{refetch:i}]=d(()=>G(`/api/admin/users`).then(e=>wL(e,`users`))),[a,o]=u(``),[c,f]=u(`all`),[p,h]=u(`role`),g=async(t,n)=>{await P(n.confirm,n.label,{danger:!!n.danger})&&(await e.change(()=>V(`/api/admin/users/${K(t.id)}`,{method:`PUT`,json:n.change}),`${TL(t)}: ${n.label.toLowerCase()} done`)&&t.id===X()?.user?.id&&(eu(void 0),await Uu().catch(()=>!1)),i())};return(()=>{var e=II(),i=e.firstChild.firstChild,u=i.nextSibling,d=u.nextSibling;return i.$$input=e=>o(e.currentTarget.value),u.addEventListener(`change`,e=>f(e.currentTarget.value)),y(u,n(m,{each:Gn,children:([e,t])=>(()=>{var n=ZF();return n.value=e,y(n,t),n})()})),d.addEventListener(`change`,e=>h(e.currentTarget.value)),y(d,n(m,{each:Wn,children:([e,t])=>(()=>{var n=ZF();return n.value=e,y(n,t),n})()})),y(e,n(l,{get when(){return t()},get fallback(){return(()=>{var e=LI();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${lr(t.error)}`:`Loading…`})()),e})()},get children(){var e=dI();return y(e,n(m,{get each(){return sr(t(),{query:a(),filter:c(),sort:p()})},get fallback(){return RI()},children:e=>(()=>{var i=HI(),a=i.firstChild,o=a.firstChild,c=o.nextSibling,u=c.firstChild,d=u.nextSibling;return d.nextSibling,y(o,()=>TL(e),null),y(o,n(l,{get when(){return e.role===`admin`},get children(){return zI()}}),null),y(o,n(l,{get when(){return e.disabled},get children(){return BI()}}),null),y(o,n(l,{get when(){return e.id===X()?.user?.id},get children(){return VI()}}),null),y(a,n(l,{get when(){return r(()=>!!e.name)()&&e.email},get children(){var t=IF();return y(t,()=>e.email),t}}),c),y(c,()=>_n(e.machines??0,`machine`),u),y(c,()=>_n(e.devices??0,`device`),d),y(c,()=>R(e.lastSeen,N())||`never`,null),y(i,n(m,{get each(){return cr(e,t(),X()?.user?.id)},children:t=>(()=>{var n=UI();return n.$$click=()=>void g(e,t),y(n,()=>t.label),s(()=>k(n,`btn small${t.danger?` danger`:``}`)),n})()}),null),s(()=>k(i,e.disabled?`disabled`:``)),i})()})),e}}),null),s(()=>i.value=a()),s(()=>u.value=c()),s(()=>d.value=p()),e})()}function OL(e){let[t,{refetch:i}]=d(()=>G(`/api/admin/machines`).then(e=>wL(e,`machines`)));return n(l,{get when(){return t()},get fallback(){return(()=>{var e=LI();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${lr(t.error)}`:`Loading…`})()),e})()},get children(){return n(l,{get when(){return t().length},get fallback(){return WI()},get children(){var a=dI();return y(a,n(m,{get each(){return t()},children:t=>{let n=t.ownerEmail??(t.ownerID===`local`?`hub owner`:t.ownerID)??`unknown`;return(()=>{var a=GI(),o=a.firstChild,c=o.firstChild,l=c.firstChild;l.nextSibling;var u=c.nextSibling,d=u.firstChild,f=o.nextSibling;return y(c,()=>t.name,null),y(u,n,d),y(u,()=>t.ownerID===X()?.user?.id?` (you)`:``,d),y(u,(()=>{var e=r(()=>!!t.online);return()=>e()?`online`:`offline · seen ${R(t.lastSeen,N())}`})(),null),f.$$click=async()=>{await P(`Revoke ${t.name} (${n})? Its OpenCode processes disconnect and it must be connected again.`,`Revoke`,{danger:!0})&&(await e.change(()=>V(`/api/admin/machines/${K(t.id)}`,{method:`DELETE`}),`${t.name} revoked`),i())},s(()=>k(l,`online-dot${t.online?` on`:``}`)),a})()}})),a}})}})}function kL(){let[e]=d(async()=>{let[e,t,n]=await Promise.all([G(`/api/admin/audit`),G(`/api/admin/users`).then(e=>wL(e,`users`),()=>[]),G(`/api/admin/machines`).then(e=>wL(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 ar(wL(e,`audit`).length?wL(e,`audit`):wL(e,`entries`),r)});return n(l,{get when(){return e()},get fallback(){return(()=>{var t=LI();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?`Could not load: ${lr(e.error)}`:`Loading…`})()),t})()},get children(){return n(l,{get when(){return e().length},get fallback(){return qI()},get children(){var t=KI();return y(t,n(m,{get each(){return e()},children:e=>(()=>{var t=JI(),n=t.firstChild,i=n.firstChild,a=i.nextSibling,o=n.nextSibling;return y(i,()=>e.action),y(a,()=>e.actor,null),y(a,(()=>{var t=r(()=>!!e.target);return()=>t()?` → ${e.target}`:``})(),null),y(a,(()=>{var t=r(()=>!!e.detail);return()=>t()?` · ${e.detail}`:``})(),null),y(o,()=>R(e.at,N())),s(t=>{var n=new Date(e.at).toISOString(),r=new Date(e.at).toLocaleString();return n!==t.e&&b(o,`datetime`,t.e=n),r!==t.t&&b(o,`title`,t.t=r),t},{e:void 0,t:void 0}),t})()})),t}})}})}z([`input`,`keydown`,`click`]);var AL=I(`<a href=/settings/voice#recordings title="This conversation is recorded on this hub (Settings → Voice → Recording)"><span class=recording-dot aria-hidden=true>`),jL=I(`<button type=button class="btn small recording-mark"data-recording-mark title="Bookmark this moment in the recording (or say “mark that”)">Mark`),ML=I(`<span class="recording-note small"data-recording-note>`),NL=I(`<span class=sr-only role=status aria-live=polite data-recording-status>`);function PL(){let[e,t]=u(Ml.get());return M(Ml.subscribe(()=>t(Ml.get()))),e}function FL(e){let t=PL(),i=t=>e.sessionID===void 0||t.sessionID===void 0||t.sessionID===e.sessionID,a=()=>t().on&&i(t()),o=a(),[c,d]=u(``);return M(Ml.subscribe(()=>{let e=Ml.get(),t=e.on&&i(e);t!==o&&(o=t,d(t?`Recording on`:`Recording off`))})),[n(l,{get when(){return a()},get children(){var e=AL();return e.firstChild,y(e,()=>Nl(t()),null),s(n=>{var r=`recording-indicator${t().audio?``:` no-audio`}`,i=t().audio?`on`:`no-audio`,a=`${Nl(t())}: this conversation is recorded on the hub. Open the recording settings`;return r!==n.e&&k(e,n.e=r),i!==n.t&&b(e,`data-recording-indicator`,n.t=i),a!==n.a&&b(e,`aria-label`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),e}}),n(l,{get when(){return r(()=>!!(e.mark&&a()))()&&t().marks},get children(){var e=jL();return e.$$click=()=>Wl(),e}}),n(l,{get when(){return r(()=>!(a()||!t().note))()&&i(t())},get children(){var e=ML();return y(e,()=>t().note),e}}),n(l,{get when(){return e.announce},get children(){var e=NL();return y(e,c),e}})]}z([`click`]);var IL=I(`<div role=status><a class=voice-pill-link title="Go to the session in Voice mode">Voice: <strong></strong></a><button type=button class="btn small end"aria-label="End Voice mode">End`);function LL(){let e=()=>Px().sessionID??``;return(()=>{var t=IL(),r=t.firstChild,i=r.firstChild.nextSibling,a=r.nextSibling;return y(t,n(L,{name:`wave`}),r),y(i,Fx),y(t,n(FL,{announce:!0,get sessionID(){return e()}}),a),a.$$click=()=>void wx.end(),s(n=>{var i=`voice-pill ${Px().voice}`,a=`Voice mode is on in ${Fx()}`,o=Ot(e());return i!==n.e&&k(t,n.e=i),a!==n.t&&b(t,`aria-label`,n.t=a),o!==n.a&&b(r,`href`,n.a=o),n},{e:void 0,t:void 0,a:void 0}),t})()}z([`click`]);var RL=`/api/agent/workspaces`,zL=50,BL=4e3,VL=e=>e instanceof W?{status:e.status,...e.code?{code:e.code}:{},message:e.message,...e.details?{details:e.details}:{}}:{status:0,message:e instanceof tn||e instanceof Error?e.message:String(e)},HL=e=>qm(VL(e));function UL(){let[e,t]=u(`loading`),[n,r]=u(),[i,a]=u([]),[o,s]=Or({}),[c,l]=u(),[d,f]=u(new Set),p=new Map,m=new Map,h=!1;async function g(){try{let e=Nm(await G(`${RL}?state=active&limit=${zL}`));a(e.items),r(void 0),t(`ready`)}catch(e){e instanceof W&&(e.status===404||e.code===`unsupported`)?t(`unavailable`):e instanceof W&&e.status===403?t(`forbidden`):(r(HL(e)),t(`error`))}}async function _(e){p.set(e,Date.now()),s(e,e=>({...e??{},loading:!0}));try{let t=Mm(await G(`${RL}/${K(e)}/board`));if(!t)throw Error(`The hub sent a board this console can't read.`);return s(e,e=>({...e,board:t,loading:!1,error:void 0})),t}catch(t){s(e,e=>({...e,loading:!1,error:HL(t)}));return}}async function v(){try{l(Ce(await G(`/api/agent/grants`)))}catch{l(`error`)}}function y(e){if(m.has(e))return;let t=Math.max(0,(p.get(e)??0)+BL-Date.now());m.set(e,setTimeout(()=>{m.delete(e),d().has(e)&&document.visibilityState!==`hidden`&&_(e)},t))}function b(){h||(h=!0,g(),Nu(e=>{if(e.type===`resync`&&g(),e.type===`catalog`||e.type===`resync`)for(let e of d())y(e)}))}function x(e){let t=new Set(d());t.has(e)?t.delete(e):(t.add(e),_(e),c()===void 0&&v()),f(t)}let S=(e,t)=>s(e,e=>({...e??{loading:!1},notice:t}));async function C(e,t){await V(`${RL}/${K(e)}/supervision`,{method:`PUT`,json:t})}async function w(e,t,n){let r=o[e]?.board;if(!r||o[e]?.saving)return;let i=Im(r,t);if(i)i!==`unchanged`&&S(e,{text:Gm(i),kind:`warn`});else{s(e,e=>({...e,saving:!0,notice:{text:`Saving: ${n}…`,kind:``}}));try{await T(e,t,Um(t,r.revision),n)}finally{s(e,e=>({...e,saving:!1}))}}}async function T(e,t,n,r){try{await C(e,n),await _(e),S(e,{text:`Done: ${r}.`,kind:``});return}catch(t){if(!(t instanceof W&&t.status===409&&t.code===`conflict`)){S(e,{text:HL(t),kind:`err`}),_(e);return}}let i=await _(e);if(!i)return S(e,{text:`The workspace changed elsewhere and could not be reloaded. Your change is kept: ${r}.`,kind:`warn`,pending:t});let a=Km(t,i);if(a.kind===`done`)return S(e,{text:`Already done elsewhere: ${r}.`,kind:``});if(a.kind===`dropped`)return S(e,{text:a.reason,kind:`warn`});try{await C(e,a.body),await _(e),S(e,{text:`The workspace changed elsewhere; re-applied your change: ${r}.`,kind:``})}catch(n){_(e),n instanceof W&&n.status===409?S(e,{text:`The workspace keeps changing elsewhere. Your change is kept: ${r}.`,kind:`warn`,pending:t}):S(e,{text:HL(n),kind:`err`})}}return{availability:e,listError:n,workspaces:i,boards:o,grants:c,expanded:d,start:b,loadList:g,loadBoard:_,toggle:x,move:w,notify:S}}var WL=ce(UL),GL=`hub.sidebar.sections.collapsed`;function KL(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 qL(e,t){let n=KL(e);n.has(t)?n.delete(t):n.add(t);try{e.setItem(GL,JSON.stringify([...n]))}catch{}return n}var JL=e=>e!==`results`;function YL(e,t,n){if(t&&JL(e)){if(e===`needs`)return{text:String(t),label:`${_n(t,`session`)} ${t===1?`needs`:`need`} you`};if(n)return{text:String(t),label:_n(t,e===`workspaces`?`workspace`:`session`)}}}var XL=I(`<button type=button class=side-section-toggle><span class=side-section-title>`),ZL=I(`<div class=side-section-head>`),QL=I(`<span class=side-section-title>`),$L=I(`<span aria-hidden=true data-section-count>`),[eR,tR]=u(KL(localStorage)),nR=(e,t)=>JL(t)&&eR().has(e),rR=e=>`side-sec-${e.replace(/[^A-Za-z0-9_-]/g,`-`)}`;function iR(e){let t=()=>nR(e.id,e.kind),r=()=>YL(e.kind,e.count,t());return(()=>{var i=ZL();return y(i,n(l,{get when(){return JL(e.kind)},get fallback(){return(()=>{var t=QL();return y(t,()=>e.title),t})()},get children(){var i=XL(),a=i.firstChild;return i.$$click=()=>tR(qL(localStorage,e.id)),y(i,n(L,{get name(){return t()?`chevron`:`down`},class:`side-section-caret`}),a),y(a,()=>e.title),y(i,n(l,{get when(){return r()},children:t=>(()=>{var n=$L();return y(n,()=>t().text),s(()=>k(n,`side-count${e.kind===`needs`?` needs`:``}`)),n})()}),null),s(n=>{var a=!t(),o=rR(e.id),s=e.id,c=r()?`${e.title}, ${r().label}`:e.title,l=t()?`Show ${e.title}`:`Hide ${e.title}`;return a!==n.e&&b(i,`aria-expanded`,n.e=a),o!==n.t&&b(i,`aria-controls`,n.t=o),s!==n.a&&b(i,`data-section-toggle`,n.a=s),c!==n.o&&b(i,`aria-label`,n.o=c),l!==n.i&&b(i,`title`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),i}}),null),y(i,()=>e.children,null),i})()}z([`click`]);var aR=I(`<p class=side-empty>Workspaces are not available to this device.`),oR=I(`<p class=side-empty role=alert>Could not load workspaces: <!> <button type=button class=link-btn>Retry`),sR=I(`<ul class=ws-list>`),cR=I(`<section aria-label=Workspaces data-section=workspaces>`),lR=I(`<p class=ws-goal><span class=sr-only>Goal: `),uR=I(`<div class=ws-panel>`),dR=I(`<li><button type=button class=ws-head><span class=ws-title>`),fR=I(`<p class=ws-notice role=status aria-live=polite>`),pR=I(`<p class=side-empty role=alert>Could not load the board: <!> <button type=button class=link-btn>Retry`),mR=I(`<button type=button class=link-btn>Retry`),hR=I(`<p class=side-empty>Loading…`),gR=I(`<p class=side-empty>No members yet.`),_R=I(`<ul role=tree>`),vR=I(`<div>Drop here: no supervisor`),yR=I(`<p class=ws-keys>Drag to change supervision, or Alt+arrows. Supervision grants nothing.`),bR=I(`<p class=ws-keys>`),xR=I(`<span class="ws-rel ws-spawned"title="Native parent session (unchanged by supervision)">spawned by <a tabindex=-1>`),SR=I(`<span class="ws-rel ws-supervised"title="Workspace supervision link">supervised by `),CR=I(`<ul class=ws-assignments>`),wR=I(`<li role=treeitem><div class=ws-row><a class=ws-member tabindex=-1></a></div><p class=ws-meta>`),TR=I(`<span>`),ER=I(`<span class=ws-assignment-stale> · stale`),DR=I(`<li><span class=ws-assignment-title></span> <span class=ws-assignment-status>`),OR=I(`<ul>`),kR=I(`<details class=ws-controls><summary>Delegated controls</summary><p class=muted>Read-only. Grants held by roles or apps are not listed here; dragging never creates one.`),AR=I(`<p>Could not load your grants.`),jR=I(`<p>Loading…`),MR=I(`<p> holds no grant from you. Supervising grants nothing: it can message and ask, and actions on this session come to you as Decisions. <a href=/settings/agents#grants>Grants are in Settings → Agents &amp; access.`),NR=I(`<li> · <!> · <!> <span class=muted>(grant <!>)`),PR=new Set([`idle`,`working`,`blocked`,`error`]),FR={open:`open`,in_progress:`in progress`,blocked:`blocked`},IR={ArrowRight:`indent`,ArrowLeft:`outdent`,ArrowUp:`up`,ArrowDown:`down`};function LR(e){let t=WL;fe(()=>t.start());let r=()=>{let e=t.availability();return e===`forbidden`||e===`error`||e===`ready`&&t.workspaces().length>0};return n(l,{get when(){return r()},get children(){var r=cR();return y(r,n(iR,{id:`workspaces`,kind:`workspaces`,title:`Workspaces`,get count(){return t.workspaces().length}}),null),y(r,n(l,{get when(){return t.availability()===`forbidden`},get children(){return aR()}}),null),y(r,n(l,{get when(){return t.availability()===`error`},get children(){var e=oR(),n=e.firstChild.nextSibling,r=n.nextSibling.nextSibling;return y(e,()=>t.listError(),n),r.$$click=()=>void t.loadList(),e}}),null),y(r,n(l,{get when(){return!nR(`workspaces`,`workspaces`)},get children(){var r=sR();return y(r,n(m,{get each(){return t.workspaces()},children:t=>n(RR,{ws:t,get onPick(){return e.onPick}})})),s(()=>b(r,`id`,rR(`workspaces`))),r}}),null),s(()=>k(r,`side-section ws-section${nR(`workspaces`,`workspaces`)?` collapsed`:``}`)),r}})}function RR(e){let t=WL,r=()=>t.expanded().has(e.ws.id),i=`ws-panel-${e.ws.id}`;return(()=>{var a=dR(),o=a.firstChild,c=o.firstChild;return o.$$click=()=>t.toggle(e.ws.id),b(o,`aria-controls`,i),y(o,n(L,{get name(){return r()?`down`:`chevron`}}),c),y(c,()=>e.ws.title),y(a,n(l,{get when(){return e.ws.goal},get children(){var t=lR();return t.firstChild,y(t,()=>e.ws.goal,null),s(()=>b(t,`title`,e.ws.goal)),t}}),null),y(a,n(l,{get when(){return r()},get children(){var t=uR();return b(t,`id`,i),y(t,n(VR,{get ws(){return e.ws},get onPick(){return e.onPick}})),t}}),null),s(t=>{var n=`ws-item${r()?` open`:``}`,i=e.ws.id,s=r();return n!==t.e&&k(a,t.e=n),i!==t.t&&b(a,`data-workspace`,t.t=i),s!==t.a&&b(o,`aria-expanded`,t.a=s),t},{e:void 0,t:void 0,a:void 0}),a})()}var zR=(e,t)=>{let n=e.members.find(e=>e.memberID===t);if(!n)return`a member`;let r=Ym(Y.machines,n.sessionID);return r.found?r.title:n.session?.name??n.sessionID};function BR(e,t,n){let r=zR(e,t.memberID);return t.supervisorMemberID===null?`${r} has no supervisor`:n===`reorder`?`${r} reordered`:`${r} supervised by ${zR(e,t.supervisorMemberID)}`}function VR(e){let i=WL,o=()=>e.ws.id,c=()=>i.boards[o()],d=()=>c()?.board,f=C(()=>d()?Fm(d()):void 0),[p,h]=u(),[g,_]=u(),[v,S]=u(),w,T,E=()=>{let e=f();if(e?.flat.length)return e.flat.some(e=>e.member.memberID===p())?p():e.flat[0].member.memberID},D=e=>{h(e),w?.querySelector(`[data-member="${CSS.escape(e)}"]`)?.focus()};x(()=>{if(f(),T){let e=T;queueMicrotask(()=>{w?.querySelector(`[data-member="${CSS.escape(e)}"]`)&&(T=void 0,D(e))})}});let j=(e,t,n=!1)=>{let r=d();e&&r&&(n&&(T=e.memberID),i.move(o(),e,BR(r,e,t)))},M=(t,n,r)=>{let a=r.flat.indexOf(n);if(t.altKey&&IR[t.key]){t.preventDefault();let e=IR[t.key],a=Hm(r,n.member.memberID,e);return a?j(a,e===`up`||e===`down`?`reorder`:`supervise`,!0):i.notify(o(),{text:`No move that way.`,kind:`warn`})}if(t.altKey||t.ctrlKey||t.metaKey)return;let s=t.key===`ArrowDown`?r.flat[a+1]:t.key===`ArrowUp`?r.flat[a-1]:t.key===`Home`?r.flat[0]:t.key===`End`?r.flat[r.flat.length-1]:void 0;s?(t.preventDefault(),D(s.member.memberID)):t.key===`Enter`&&t.target===t.currentTarget&&(t.preventDefault(),e.onPick?.(),Vt(Ot(n.member.sessionID)))},N=e=>{let t=e.currentTarget.querySelector(`.ws-row`).getBoundingClientRect(),n=e.clientY-t.top;return n<t.height*.25?`before`:n>t.height*.75?`after`:`inside`},ee=(e,t)=>{let n=d(),r=e.member.memberID,i=[];for(let[e,a,o]of[[`indent`,`Supervised by the member above`,`Alt+→`],[`outdent`,`Up one level`,`Alt+←`],[`up`,`Move up`,`Alt+↑`],[`down`,`Move down`,`Alt+↓`],[`detach`,`No supervisor`,``]]){let s=Hm(t,r,e);s&&!Im(n,s)&&i.push({label:a,hint:o,run:()=>j(s,e===`up`||e===`down`?`reorder`:`supervise`,!0)})}let a=t.flat.filter(e=>e.member.memberID!==r&&!Im(n,Vm(t,r,{memberID:e.member.memberID,position:`inside`})));if(a.length){i.push({section:`Supervised by`});for(let e of a)i.push({label:zR(n,e.member.memberID),run:()=>j(Vm(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=fR();return y(e,()=>c()?.notice?.text??``,null),y(e,n(l,{get when(){return c()?.notice?.pending},children:e=>(()=>{var t=mR();return t.$$click=()=>j(e(),`supervise`),t})()}),null),e})(),n(l,{get when(){return c()?.error},get children(){var e=pR(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return y(e,()=>c().error,t),n.$$click=()=>void i.loadBoard(o()),e}}),n(l,{get when(){return f()},get fallback(){return n(l,{get when(){return!c()?.error},get children(){return hR()}})},children:u=>[n(l,{get when(){return!u().flat.length},get children(){return gR()}}),(()=>{var r=_R(),f=w;return typeof f==`function`?t(f,r):w=r,y(r,n(m,{get each(){return u().flat},children:t=>{let r=()=>Ym(Y.machines,t.member.sessionID),c=()=>zR(d(),t.member.memberID),f=()=>t.supervisorMemberID?u().flat.find(e=>e.member.memberID===t.supervisorMemberID)?.children??[]:u().roots,p=()=>Xm(t,d(),Y.machines),x=()=>PR.has(t.member.session?.state??``)?t.member.session.state:`idle`,C=()=>d().workspace.state===`active`&&!i.boards[o()]?.saving;return(()=>{var i=wR(),o=i.firstChild,d=o.firstChild,w=o.nextSibling;return i.addEventListener(`drop`,e=>{let n=g();if(!n)return;e.preventDefault(),e.stopPropagation();let r=N(e);_(void 0),S(void 0),j(Vm(u(),n,{memberID:t.member.memberID,position:r}),r===`inside`?`supervise`:`reorder`)}),i.addEventListener(`dragleave`,e=>{e.currentTarget.contains(e.relatedTarget)||S(void 0)}),i.addEventListener(`dragover`,e=>{let n=g();n&&n!==t.member.memberID&&(e.preventDefault(),e.stopPropagation(),S(`${t.member.memberID}:${N(e)}`))}),i.addEventListener(`dragend`,()=>{pm(),_(void 0),S(void 0)}),i.addEventListener(`dragstart`,e=>{fm(e,{target:{sessionID:t.member.sessionID},label:c()}),e.dataTransfer?.setData(`text/plain`,t.member.memberID),e.dataTransfer&&(e.dataTransfer.effectAllowed=`move`),_(t.member.memberID)}),i.$$keydown=e=>M(e,t,u()),i.addEventListener(`focus`,e=>e.target===e.currentTarget&&h(t.member.memberID)),y(o,n(A,{get state(){return x()}}),d),d.$$click=()=>e.onPick?.(),b(d,`draggable`,!1),y(d,c),y(o,n(O,{get label(){return`Move ${c()}`},class:`icon-btn small row-more`,items:()=>ee(t,u())}),null),y(w,n(m,{get each(){return Qm(t.member,r())},children:e=>(()=>{var t=TR();return y(t,()=>e.label),s(n=>{var r=`ws-badge ${e.kind}`,i=e.title;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),null),y(w,n(l,{get when(){return p().spawnedBy},get children(){var e=xR(),t=e.firstChild.nextSibling;return y(t,()=>p().spawnedBy.title),s(()=>b(t,`href`,Ot(p().spawnedBy.sessionID))),e}}),null),y(w,n(l,{get when(){return p().supervisedBy},get children(){var e=SR();return e.firstChild,y(e,()=>p().supervisedBy.title,null),e}}),null),y(i,n(l,{get when(){return t.assignments.length},get children(){var e=CR();return y(e,n(m,{get each(){return t.assignments},children:e=>(()=>{var t=DR(),r=t.firstChild,i=r.nextSibling.nextSibling;return y(r,()=>e.title),y(i,()=>FR[e.status]??e.status),y(t,n(l,{get when(){return e.stale?.length},get children(){var t=ER();return s(()=>b(t,`title`,e.stale.join(`, `))),t}}),null),s(()=>k(t,`ws-assignment ${e.status}`)),t})()})),s(()=>b(e,`aria-label`,`Assignments of ${c()}`)),e}}),null),y(i,n(l,{get when(){return p().supervisedBy},children:e=>n(HR,{get supervisorSessionID(){return e().sessionID},get supervisorTitle(){return e().title},get memberDirectory(){return r().directory}})}),null),s(e=>{var n=t.depth+1,r=f().length,o=f().indexOf(t)+1,s=E()===t.member.memberID,l=`${c()}${t.member.master?`, master`:``}${p().supervisedBy?`, supervised by ${p().supervisedBy.title}`:``}`,u=E()===t.member.memberID?0:-1,m=t.member.memberID,h=`ws-node${t.member.presence===`online`?``:` away`}${g()===t.member.memberID?` dragged`:``}${v()?.startsWith(`${t.member.memberID}:`)?` drop-${v().split(`:`)[1]}`:``}`,_=String(t.depth),y=C()&&!t.member.master,x=Ot(t.member.sessionID);return n!==e.e&&b(i,`aria-level`,e.e=n),r!==e.t&&b(i,`aria-setsize`,e.t=r),o!==e.a&&b(i,`aria-posinset`,e.a=o),s!==e.o&&b(i,`aria-selected`,e.o=s),l!==e.i&&b(i,`aria-label`,e.i=l),u!==e.n&&b(i,`tabindex`,e.n=u),m!==e.s&&b(i,`data-member`,e.s=m),h!==e.h&&k(i,e.h=h),_!==e.r&&a(i,`--ws-depth`,e.r=_),y!==e.d&&b(i,`draggable`,e.d=y),x!==e.l&&b(d,`href`,e.l=x),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0}),i})()}})),s(t=>{var n=`ws-tree${g()?` dragging`:``}`,i=`Supervision in ${e.ws.title}`,a=`ws-keys-${o()}`,s=c()?.saving?`true`:void 0;return n!==t.e&&k(r,t.e=n),i!==t.t&&b(r,`aria-label`,t.t=i),a!==t.a&&b(r,`aria-describedby`,t.a=a),s!==t.o&&b(r,`aria-busy`,t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),r})(),n(l,{get when(){return g()},get children(){var e=vR();return e.addEventListener(`drop`,e=>{e.preventDefault();let t=g();_(void 0),S(void 0),t&&j(Vm(u(),t,{root:!0}),`supervise`)}),e.addEventListener(`dragleave`,()=>S(void 0)),e.addEventListener(`dragover`,e=>{e.preventDefault(),S(`root`)}),s(()=>k(e,`ws-root-drop${v()===`root`?` over`:``}`)),e}}),(()=>{var e=yR();return s(()=>b(e,`id`,`ws-keys-${o()}`)),e})(),n(l,{get when(){return u().staleLinks||d().membersTruncated||d().linksTruncated},get children(){var e=bR();return y(e,n(l,{get when(){return u().staleLinks},get children(){return[r(()=>u().staleLinks),` link(s) to departed members not shown. `]}}),null),y(e,n(l,{get when(){return d().membersTruncated||d().linksTruncated},children:`Some members are not shown (limit).`}),null),e}})]})]}function HR(e){let t=WL,i=()=>{let n=t.grants();return Array.isArray(n)?th(n,e.supervisorSessionID,e.memberDirectory,Date.now()):n};return(()=>{var t=kR(),a=t.firstChild.nextSibling;return y(t,n(l,{get when(){return i()!==`error`},get fallback(){return AR()},get children(){return n(l,{get when(){return Array.isArray(i())},get fallback(){return jR()},get children(){return n(l,{get when(){return i().length},get fallback(){return(()=>{var t=MR(),n=t.firstChild;return y(t,()=>e.supervisorTitle,n),t})()},get children(){var e=OR();return y(e,n(m,{get each(){return i()},children:e=>(()=>{var t=NR(),n=t.firstChild,i=n.nextSibling,a=i.nextSibling.nextSibling,o=a.nextSibling.nextSibling,s=o.firstChild.nextSibling;return s.nextSibling,y(t,()=>e.verbs.join(`, `),n),y(t,(()=>{var t=r(()=>e.covers===void 0);return()=>t()?`folder unknown`:e.covers?`covers this session's folder`:`not this session's folder`})(),i),y(t,()=>Ss(e.expiresAt,Date.now()),a),y(o,()=>e.grantID,s),t})()})),e}})}})}}),a),t})()}z([`click`,`keydown`]);var UR=I(`<nav aria-label=Primary><ul>`),WR=I(`<a>`),GR=I(`<li>`),KR=I(`<a class="side-link nav-link disabled"aria-disabled=true>`),qR=I(`<div class=nav-rail>`),JR=()=>({signedIn:!!X(),concierge:mu()?.state});function YR(e){let t=()=>we(Pt().pathname);return(()=>{var r=UR(),i=r.firstChild;return y(i,n(m,{get each(){return Se(JR())},children:r=>(()=>{var i=GR();return y(i,n(l,{get when(){return r.enabled},get fallback(){return(()=>{var t=KR();return y(t,n(L,{get name(){return r.dest.icon}}),null),y(t,n(l,{get when(){return!e.compact},get children(){return r.dest.label}}),null),s(n=>{var i=`${r.dest.label} isn't available`,a=e.compact?r.dest.label:void 0;return i!==n.e&&b(t,`title`,n.e=i),a!==n.t&&b(t,`aria-label`,n.t=a),n},{e:void 0,t:void 0}),t})()},get children(){var i=WR();return i.$$click=()=>e.onPick?.(),y(i,n(L,{get name(){return r.dest.icon}}),null),y(i,n(l,{get when(){return!e.compact},get children(){return r.dest.label}}),null),s(n=>{var a=`side-link nav-link${t()===r.dest.id?` active`:``}`,o=r.dest.route,s=t()===r.dest.id?`page`:void 0,c=e.compact?r.dest.label:void 0,l=e.compact?r.dest.label:void 0;return a!==n.e&&k(i,n.e=a),o!==n.t&&b(i,`href`,n.t=o),s!==n.a&&b(i,`aria-current`,n.a=s),c!==n.o&&b(i,`aria-label`,n.o=c),l!==n.i&&b(i,`title`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),i}})),i})()})),s(()=>k(r,e.compact?`nav-rail-links`:`feature-nav`)),r})()}function XR(e){return(()=>{var t=qR();return y(t,n(F,{icon:`sidebar`,label:`Show sidebar (⌘B)`,get onClick(){return e.onExpand}}),null),y(t,n(YR,{compact:!0}),null),t})()}z([`click`]);var ZR=I(`<span class=concierge-btn-text>Concierge`),QR=I(`<span aria-hidden=true>`),$R=I(`<button type=button>`),ez=I(`<a href=/settings/concierge data-concierge-button=disabled data-indicator=off>`),tz;function nz(){let e=tz;return tz=void 0,e}function rz(e){let t=()=>dt().name===`concierge`,i=()=>e.labelled?ZR():null,a=e=>n(l,{get when(){return e.indicator!==`running`},get children(){var t=QR();return y(t,(()=>{var t=r(()=>e.indicator===`attention`);return()=>t()?e.count??`!`:``})()),s(()=>k(t,`concierge-ind ind-${e.indicator}`)),t}});return n(l,{get when(){return mu()},children:r=>{let o=()=>Ys(r(),xu(),t(),Date.now(),Hs(su(),r(),{tiers:`all`}).length,new Set(su().filter(e=>e.state===`open`).map(e=>e.id)));return n(l,{get when(){return qs(r())===!0},get fallback(){return(()=>{var t=ez();return t.$$click=()=>e.onPick?.(),y(t,n(L,{name:`spark`}),null),y(t,i,null),y(t,()=>a(o()),null),s(n=>{var r=`icon-btn concierge-btn off ind-off${e.labelled?` labelled`:``}`,i=o().label,a=o().title;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`aria-label`,n.t=i),a!==n.a&&b(t,`title`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()},get children(){var c=$R();return c.$$click=n=>{if(e.onPick?.(),t())return St(`/`);tz=n.currentTarget,Vt(`/concierge`)},y(c,n(L,{name:`spark`}),null),y(c,i,null),y(c,()=>a(o()),null),s(n=>{var i=`icon-btn concierge-btn state-${r().state} ind-${o().indicator}${t()?` on`:``}${e.labelled?` labelled`:``}`,a=o().label,s=t(),l=o().title,u=r().state,d=o().indicator;return i!==n.e&&k(c,n.e=i),a!==n.t&&b(c,`aria-label`,n.t=a),s!==n.a&&b(c,`aria-expanded`,n.a=s),l!==n.o&&b(c,`title`,n.o=l),u!==n.i&&b(c,`data-concierge-button`,n.i=u),d!==n.n&&b(c,`data-indicator`,n.n=d),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0}),c}})}})}z([`click`]);var iz=I(`<section class="side-section side-decisions"aria-label=Decisions><ul class=side-list><li class=side-row><a class=side-row-link data-side-decisions><span class=decision-mark aria-hidden=true>⚑</span><span class=side-title>`),az=I(`<div class=sidebar><div class=side-top><a class=brand href=/><span class=brand-name>Hub</span></a><div class=side-top-actions></div></div><div class=side-search><input type=search placeholder="Search sessions"aria-label="Search sessions"></div><a class=side-new href=/new> New session</a><nav class=side-sessions aria-label=Sessions><div class=side-head><span>Sessions</span></div><div class=side-scroll></div></nav><div class=side-foot>`),oz=I(`<p class=side-empty>`),sz=I(`<a class="icon-btn small">`),cz=I(`<ul class=side-list>`),lz=I(`<section>`),uz=I(`<span aria-hidden=true>`),dz=I(`<span class=account-name>`),fz=I(`<span class=badge title="Machines waiting for approval">`),pz=I(`<span class="terminal-wait small muted"title="Herdr says this session waits for input; answer it in its terminal"data-waiting-in-terminal>waiting in terminal`),mz=I(`<span class=jobs-badge>`),hz=I(`<span class=unread-dot role=img aria-label=Unread>`),gz=I(`<a class=side-row-link><span class=side-text><span class=side-title>`),_z=I(`<li>`),vz=I(`<span class=side-row-link>`),yz=I(`<span class=side-sub data-row-sub>`),bz=I(`<span class="waiting-since small">`),xz=`hub.sidebar.groupBy`,Sz=`hub.sidebar.sort`;function Cz(e){let[t,i]=u(``),[a,o]=u(localStorage.getItem(xz)===`machine`?`machine`:`project`),[c,d]=u(localStorage.getItem(Sz)===`title`?`title`:`recent`),f=C(()=>ja(Pu(),{query:t(),groupBy:a(),sortBy:c(),now:N()})),p=()=>{let e=xC();return e.name===`session`?e.id:void 0},h=()=>Jn(X()),g=(e,t)=>{e&&(o(e),localStorage.setItem(xz,e)),t&&(d(t),localStorage.setItem(Sz,t))};return(()=>{var o=az(),u=o.firstChild,d=u.firstChild,_=d.firstChild,v=d.nextSibling,x=u.nextSibling,S=x.firstChild,C=x.nextSibling,w=C.firstChild,T=C.nextSibling,E=T.firstChild;E.firstChild;var D=E.nextSibling,A=T.nextSibling;return d.$$click=()=>e.phone&&e.onClose(),y(d,n(Qd,{class:`brand-mark`}),_),y(v,n(rz,{labelled:!0,onPick:()=>e.phone&&e.onClose()}),null),y(v,n(l,{get when(){return e.phone},get fallback(){return n(F,{icon:`sidebar`,label:`Collapse sidebar (⌘B)`,get onClick(){return e.onCollapse}})},get children(){return n(F,{icon:`close`,label:`Close sidebar`,get onClick(){return e.onClose}})}}),null),y(x,n(L,{name:`search`}),S),S.$$keydown=e=>e.key===`Escape`&&i(``),S.$$input=e=>i(e.currentTarget.value),C.$$click=()=>e.phone&&e.onClose(),y(C,n(L,{name:`plus`}),w),y(o,n(YR,{onPick:()=>e.phone&&e.onClose()}),T),y(E,n(O,{label:`Group and sort`,items:()=>[{section:`Group by`},{label:`Project`,checked:a()===`project`,run:()=>g(`project`,void 0)},{label:`Server`,checked:a()===`machine`,run:()=>g(`machine`,void 0)},{section:`Sort by`},{label:`Recent activity`,checked:c()===`recent`,run:()=>g(void 0,`recent`)},{label:`Title`,checked:c()===`title`,run:()=>g(void 0,`title`)}]}),null),y(D,n(l,{get when(){return su().length},get children(){var t=iz(),n=t.firstChild.firstChild.firstChild,i=n.firstChild.nextSibling;return n.$$click=()=>e.phone&&e.onClose(),y(i,(()=>{var e=r(()=>su().length===1);return()=>e()?`A Decision waits for you`:`${su().length} Decisions wait for you`})()),s(()=>b(n,`href`,Hs(su(),mu(),{tiers:`all`}).length===su().length?`/concierge`:`/`)),t}}),null),y(D,n(l,{get when(){return f().length},get fallback(){return(()=>{var e=oz();return y(e,()=>t()?`No sessions match.`:`No sessions yet.`),e})()},get children(){return n(m,{get each(){return f()},children:t=>(()=>{var i=lz();return y(i,n(iR,{get id(){return t.id},get kind(){return t.kind},get title(){return t.title},get count(){return t.rows.length},get children(){return n(l,{get when(){return r(()=>t.kind===`group`)()&&t.machineID},get children(){var e=sz();return y(e,n(L,{name:`plus`})),s(n=>{var r=`New session in ${t.title}`,i=`New session in ${t.title}`,a=`/new?machine=${encodeURIComponent(t.machineID)}${t.directory?`&dir=${encodeURIComponent(t.directory)}`:``}${t.key?`&key=${encodeURIComponent(t.key)}`:``}`;return r!==n.e&&b(e,`aria-label`,n.e=r),i!==n.t&&b(e,`title`,n.t=i),a!==n.a&&b(e,`href`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),e}})}}),null),y(i,n(l,{get when(){return!nR(t.id,t.kind)},get children(){var r=cz();return y(r,n(m,{get each(){return t.rows},children:t=>n(wz,{row:t,get active(){return p()===t.id},onPick:()=>e.phone&&e.onClose()})})),s(()=>b(r,`id`,rR(t.id))),r}}),null),s(e=>{var n=`side-section ${t.kind}${nR(t.id,t.kind)?` collapsed`:``}`,r=t.title,a=t.id;return n!==e.e&&k(i,e.e=n),r!==e.t&&b(i,`aria-label`,e.t=r),a!==e.a&&b(i,`data-section`,e.a=a),e},{e:void 0,t:void 0,a:void 0}),i})()})}}),null),y(D,n(LR,{onPick:()=>e.phone&&e.onClose()}),null),y(A,n(O,{get label(){return`Account and settings (${h().title})`},class:`account`,align:`left`,up:!0,get text(){return[(()=>{var e=uz();return y(e,()=>h().initial),s(()=>k(e,`avatar${h().badge?` admin`:``}`)),e})(),(()=>{var e=dz();return y(e,()=>h().title),e})(),n(l,{get when(){return au().length},get children(){var e=fz();return y(e,()=>au().length),e}}),n(L,{name:`settings`})]},items:()=>[{label:`Settings`,hint:au().length?`${au().length} to approve`:void 0,run:()=>{e.phone&&e.onClose(),Vt(`/settings`)}},{label:`Set up Hub on a machine`,run:()=>{e.phone&&e.onClose(),yF({returnTo:()=>document.querySelector(`.side-foot .account`)})}}]})),s(()=>S.value=t()),o})()}function wz(e){let t=()=>e.row,r=()=>Px().phase!==`off`&&Px().sessionID===t().id;return(()=>{var i=_z();return y(i,n(l,{get when(){return!Vh(t().id,`sidebar`)},get fallback(){return(()=>{var e=vz();return y(e,n(A,{get state(){return t().state}}),null),y(e,n(Zg,{get id(){return t().id},get title(){return t().title},place:`sidebar`,class:`side-title`,children:null}),null),e})()},get children(){var r=gz(),i=r.firstChild,a=i.firstChild;return B(r,`dragend`,pm),r.addEventListener(`dragstart`,e=>fm(e,{target:{sessionID:t().id},label:t().title})),B(r,`click`,e.onPick,!0),y(r,n(A,{get state(){return t().state}}),i),y(r,n(l,{get when(){return Pa(t(),Px())},get children(){return n(ne,{})}}),i),y(a,()=>t().title),y(i,n(l,{get when(){return Ra(t())},children:e=>(()=>{var t=yz();return y(t,e),t})()}),null),y(r,n(Qg,{get id(){return t().id}}),null),y(r,n(l,{get when(){return za(t(),N())},children:e=>(()=>{var t=bz();return y(t,e),s(()=>b(t,`title`,`Waiting for you for ${e()}`)),t})()}),null),y(r,n(l,{get when(){return t().error},children:e=>n(ie,{get text(){return e()}})}),null),y(r,n(l,{get when(){return t().waitingInTerminal},get children(){return pz()}}),null),y(r,n(l,{get when(){return t().jobs},get children(){var e=mz();return y(e,()=>t().jobs),s(n=>{var r=qi(t().jobs),i=qi(t().jobs);return r!==n.e&&b(e,`title`,n.e=r),i!==n.t&&b(e,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),e}}),null),y(r,n(l,{get when(){return t().unread},get children(){return hz()}}),null),s(n=>{var i=Ot(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&&b(r,`href`,n.e=i),a!==n.t&&b(r,`aria-current`,n.t=a),o!==n.a&&b(r,`title`,n.a=o),s!==n.o&&b(r,`draggable`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),r}}),null),y(i,n(O,{get label(){return`More actions for ${t().title}`},class:`icon-btn small row-more`,items:()=>Uh(t(),{open:!1,place:`sidebar`})}),null),s(()=>k(i,`side-row${e.active?` active`:``}${t().unread?` unread`:``}${r()?` voice-here`:``}`)),i})()}z([`click`,`input`,`keydown`]);var Tz={cycle:`F6`,close:`Control+Alt+W`,moveEarlier:`Control+Alt+Shift+ArrowLeft`,moveLater:`Control+Alt+Shift+ArrowRight`,focus:e=>`Control+Alt+${e}`},Ez=new Set([`ArrowLeft`,`ArrowUp`]),Dz=new Set([`ArrowRight`,`ArrowDown`]);function Oz(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 Ez.has(e.key)?{type:`move`,step:-1}:Dz.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<=gn?{type:`focus`,index:n-1}:void 0}var kz=`hub.paneSizes.v1`,Az={cols:280,rows:160},jz=[`vertical`,`horizontal`,`grid`];function Mz(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 Nz(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 Pz(e){return e>0?Array.from({length:e},()=>1/e):[]}function Fz(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 Iz(e,t,n,r,i,a,o){let s=r?64:16,[c,l]=o===`cols`?[`ArrowRight`,`ArrowLeft`]:[`ArrowDown`,`ArrowUp`];if(n===c)return Fz(e,t,s,i,a);if(n===l)return Fz(e,t,-s,i,a);if(n===`Home`)return Fz(e,t,-2*i,i,a);if(n===`End`)return Fz(e,t,2*i,i,a)}var Lz=(e,t,n)=>`${e}:${t}:${n}`;function Rz(e){let[t,n,r,...i]=e.split(`:`),a=Number(n);if(i.length||!jz.includes(t)||!Number.isInteger(a)||a<2||a>gn||r!==`cols`&&r!==`rows`)return;let o=Mz(t,a)[r];return o>1?o:void 0}function zz(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 Bz(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=Rz(e),i=n===void 0?void 0:zz(t,n);i&&(r[e]=i)}return r}function Vz(e,t,n,r,i,a){let o=Lz(n,r,i),s=Rz(o),c=s===void 0?void 0:zz(a,s);if(!c)return t;let l={...t,[o]:c};try{e?.setItem(kz,JSON.stringify({v:1,sizes:l}))}catch{}return l}function Hz(e,t,n){let r=Mz(t,n),i=i=>{let a=e[Lz(t,n,i)];return a&&a.length===r[i]?a:Pz(r[i])};return{cols:i(`cols`),rows:i(`rows`)}}function Uz(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 Wz=200,Gz=10,Kz=e=>e instanceof Error?e.message:String(e),qz=e=>e&&typeof e==`object`&&typeof e.status==`number`?e.status:void 0,Jz=class{timeline;fetch;options;state=`idle`;error;cursor;invalid=!1;generation=0;loading;oldestMessageID;constructor(e,t,n={}){this.timeline=e,this.fetch=t,this.options=n}get hasOlder(){return this.cursor!==void 0}get cutMessageID(){return this.cursor===void 0?void 0:this.oldestMessageID}get limit(){return this.options.limit??80}changed(){this.options.onChange?.()}async first(){let e=this.begin(),t=await this.fetch({limit:this.limit,order:`desc`});e===this.generation&&await this.show(t,e)}async resync(){let e=this.begin(),t=await this.fetch({limit:this.limit,order:`desc`});if(e!==this.generation)return;let n=t.items??[],r=t.older===void 0||n.some(e=>this.timeline.fromHistory(e?.key));t.cursor===void 0&&r?(this.timeline.load(n),this.state===`loading`&&(this.state=this.cursor===void 0?`done`:`idle`),this.changed()):(this.timeline.forgetHistory(),await this.show(t,e))}older(){if(this.loading)return this.loading;if(this.state!==`idle`||this.cursor===void 0)return Promise.resolve();let e=this.generation,t=this.cursor;this.state=`loading`,this.changed();let n=(async()=>{try{let n=await this.fetch({limit:this.limit,before:t});if(e!==this.generation)return;this.timeline.load(n.items,{older:!0}),this.oldestMessageID=Yz(n.items),this.cursor=n.older,this.state=n.older===void 0?`done`:`idle`,this.error=void 0}catch(t){if(e!==this.generation)return;this.state=`error`,this.error=Kz(t),this.invalid=qz(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=Kz(t),this.invalid=!0,this.changed()}}else return this.state=`idle`,this.error=void 0,this.older()}}begin(){return this.loading=void 0,++this.generation}async show(e,t){if(this.timeline.load(e.items),this.oldestMessageID=Yz(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<Gz;e++){let e=await this.fetch({limit:Wz,cursor:n});if(t!==this.generation)return;this.timeline.load(e.items),n=e.cursor}this.cursor=void 0,this.state=`done`}else this.cursor=e.older,this.state=e.older===void 0?`done`:`idle`;this.changed()}};function Yz(e){if(!Array.isArray(e))return;let t=e.find(e=>e&&typeof e==`object`&&(e.depth??0)===0);return typeof t?.messageID==`string`&&t.messageID?t.messageID:void 0}var Xz=[`native`,`hooks`,`rpc`,`screen`],Zz={opencode:`OpenCode`,"claude-code":`Claude Code`,codex:`Codex`},Qz=e=>Zz[e]??e;function $z(e){let t=e?.harness||`opencode`,n=e?.features?.includes(`setModel`)===!0;if(t===`opencode`)return{native:!0,harness:t,harnessName:`OpenCode`,evidence:`native`,turn:!0,steer:!0,interrupt:!0,stop:!0,permission:!0,form:!0,models:!0,timeline:!0,summary:!0,voice:!0,sessionModel:n,queued:!1};let r=Xz.includes(e?.evidence??``)?e.evidence:`unknown`,i=e?.features?new Set(e.features):void 0,a=e=>!i||i.has(e);return{native:!1,harness:t,harnessName:Qz(t),evidence:r,turn:a(`turn`),steer:a(`steer`),interrupt:a(`interrupt`),stop:a(`stop`),permission:a(`permission`),form:a(`form`),models:a(`models`),timeline:a(`timeline`),summary:a(`summary`),voice:a(`conversation`)&&a(`steer`),sessionModel:n,queued:r===`hooks`||r===`screen`||r===`unknown`}}var eB={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 tB(e){if(e.native)return;let t=eB[e.evidence];return{level:e.evidence,label:t.label,detail:t.detail(e.harnessName)}}function nB(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 rB(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 iB={queued:`queued`,retained:`held`,pending:`pending`,dropped:`not delivered`};function aB(e){return typeof e==`string`?iB[e]:void 0}function oB(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 sB=/data:([\w.+-]+\/[\w.+-]+)?((?:;[\w.+-]+=[^;,\s"'<>]*)*);base64,([A-Za-z0-9+/_-]+={0,2})/gi,cB=/^[A-Za-z0-9+/_-]+={0,2}$/,lB=[`mime`,`mimeType`,`media_type`,`mediaType`];function uB(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 dB(e,t){return`[${e||`data`}, ${uB(t)} — not shown]`}function fB(e){return e.includes(`base64,`)?e.replace(sB,(e,t,n,r)=>dB(t?.toLowerCase(),r)):e}function pB(e){if(typeof e.data!=`string`||!cB.test(e.data))return;let t=lB.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 mB(e){return hB(e)}function hB(e){if(typeof e==`string`)return fB(e);if(Array.isArray(e))return e.map(hB);if(!e||typeof e!=`object`)return e;let t=e,n=pB(t),r={};for(let[e,i]of Object.entries(t))r[e]=e===`data`&&n?dB(n,i):hB(i);return r}var gB=(e,t,n)=>`/api/sessions/${encodeURIComponent(e)}/timeline/messages/${encodeURIComponent(t)}/files/${n}`,_B=(e,t,n)=>`/api/sessions/${encodeURIComponent(e)}/timeline/messages/${encodeURIComponent(t)}/media/${encodeURIComponent(n)}`,vB=e=>typeof e==`number`&&Number.isInteger(e)&&e>0,yB=e=>Mn.includes(e),bB=(e,t)=>typeof e==`string`&&Dn(e)?.kind===t;function xB(e,t,n,r){let i=_B(e.sessionID,e.messageID,n.ref);return{key:t,name:r,mime:n.mime,src:i,download:`${i}?download=1`,ref:n.ref,...typeof n.bytes==`number`&&Number.isInteger(n.bytes)&&n.bytes>=0?{bytes:n.bytes}:{},...vB(n.width)&&vB(n.height)?{width:n.width,height:n.height}:{}}}var SB=e=>typeof e.sessionID==`string`&&typeof e.messageID==`string`,CB=(e,t)=>typeof e.name==`string`&&e.name?e.name:t;function wB(e,t,n){let r=n?`tool`:`path`,i=e.media;if(!Array.isArray(i)||!SB(e))return[];let a=[];for(let o of i){if(a.length>=Nn.perRow)break;o&&bB(o.ref,r)&&typeof o.mime==`string`&&yB(o.mime)&&a.push({...xB(e,`${e.key}:${o.ref}`,o,CB(o,t)),...n?{tool:!0}:{}})}return a}function TB(e){let t=[];if(Array.isArray(e.images))e.images.forEach((n,r)=>{n&&typeof n.mime==`string`&&t.push({key:`${e.key}:${r}`,name:String(n.name||`image`),mime:n.mime,...typeof n.preview==`string`?{src:n.preview}:{}})});else if(Array.isArray(e.files))for(let n of e.files){if(!n||typeof n.mime!=`string`||!Number.isInteger(n.index))continue;let r=`${e.key}:${n.index}`,i=CB(n,n.mime.startsWith(`image/`)?`image`:`file`);if(n.ref!==void 0){bB(n.ref,`file`)&&yB(n.mime)&&SB(e)?t.push(xB(e,r,n,i)):t.push({key:r,name:i,mime:n.mime});continue}let a=B_(n.mime)&&SB(e);t.push({key:r,name:i,mime:n.mime,...a?{src:gB(e.sessionID,e.messageID,n.index)}:{}})}return t}function EB(e,t={}){let n=[];for(let r of e)if(!((r.depth??0)>0))switch(r.kind){case`user`:{let e=TB(r),t=typeof r.messageID==`string`&&r.key===`${r.messageID}:text`?{messageID:r.messageID}:{},i=typeof r.note==`string`&&r.note?{note:r.note}:{};(r.text||e.length)&&n.push({type:`user`,key:r.key,text:r.text??``,...e.length?{images:e}:{},...t,...i});break}case`assistant`:{if(!r.text)break;let e=wB(r,`image`,!1);n.push({type:`assistant`,key:r.key,text:r.text,live:r.live===!0,...typeof r.messageID==`string`&&r.messageID?{messageID:r.messageID}:{},...e.length?{media:e}:{}});break}case`reasoning`:{let e=r.state===`running`,t=!e&&typeof r.at==`number`&&typeof r.completed==`number`?Math.max(0,Math.round((r.completed-r.at)/1e3)):void 0;n.push({type:`thought`,key:r.key,text:r.text??``,running:e,...t===void 0?{}:{seconds:t}});break}case`tool`:{let e=n[n.length-1],t=e?.type===`tools`?e:void 0,i=t??{type:`tools`,key:`tools:${r.key}`,items:[],failed:0,running:0};i.items.push(r);let a=wB(r,`screenshot`,!0);a.length&&(i.media=[...i.media??[],...a]),r.state===`failed`&&i.failed++,r.state===`running`&&i.running++,t||n.push(i);break}case`message`:n.push(AB(r));break;case`error`:n.push(r.declined===!0?{type:`error`,key:r.key,label:`${t.denied?.(r)??`Denied`}: the turn stopped`,denied:!0}:OB(r));break;case`retry`:n.push({type:`retry`,key:r.key,...DB(`attempt`,r.attempt),...DB(`next`,r.next),...typeof r.errorType==`string`?{errorType:r.errorType}:{},...DB(`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 DB=(e,t)=>typeof t==`number`&&Number.isFinite(t)?{[e]:t}:{};function OB(e){let t=typeof e.text==`string`&&e.text.trim()?e.text.trim():void 0,n=ki(e.errorType),r=ji(e.errorStatus);return{type:`error`,key:e.key,label:n??t??`Error`,...n&&t?{message:t}:{},...r?{status:r}:{}}}function kB(e,t){return{text:Li(e,t),waiting:Mi(e.next,t)!==void 0}}function AB(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=aB(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 jB=`The provider returned this thought redacted: an encrypted signature, no readable text.`;function MB(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…`:jB,muted:!0}}function NB(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 PB(e,t){return JSON.stringify(mB(e??{summary:t.summary||void 0,error:t.error}),null,2)}var FB=I(`<p class=composer-error role=alert>`),IB=I(`<p class="composer-hint muted small">`),LB=I(`<li class="attachment busy"aria-label="Preparing image"><span class="spinner small">`),RB=I(`<ul class=attachments aria-label="Attached images">`),zB=I(`<div><button type=button class=split-main>`),BB=I(`<button type=button class="btn stop"aria-label="Stop the session and its subagents"> Stop`),VB=I(`<span class=sr-only>`),HB=I(`<button type=button class=model-chip title="Voice model (the voice front you talk to in Voice mode)">Voice: `),UB=I(`<form><div class=composer-box><textarea rows=1 aria-label=Message></textarea><input type=file class=sr-only tabindex=-1 aria-hidden=true data-testid=attach-input multiple><div class=composer-actions><button type=button class=icon-btn aria-label="Attach images"></button><span class=grow></span><button type=button></button><button type=submit></button></div></div><div class=composer-meta><span class="muted small"></span><span class=grow>`),WB=I(`<li class=attachment><img><button type=button class=attachment-remove title=Remove>`),GB=I(`<span class="spinner small">`),KB=I(`<button type=button class="session-model pickable"aria-haspopup=dialog><span class=chip-key>Model: `),qB=I(`<span class=session-model><span class=chip-key>Model: `),JB=I(`<button type=button class=split-chev aria-label="Choose microphone"aria-haspopup=dialog>`),YB=I(`<p class="error small pad">`),XB=I(`<div class="menu mic-picker"role=dialog aria-label=Microphone><div class=menu-section>Microphone</div><div class=level aria-label="Input level"role=meter aria-valuemin=0 aria-valuemax=100><span>`),ZB=I(`<button type=button class=menu-item role=menuitemradio><span class=menu-check></span><span class=menu-label>`),QB=I(`<span class=muted> · “<!>…”`),$B=I(`<span class=voice-ignored title="Heard as background noise, not sent"> · ignored: “<!>”`),eV=I(`<span class="voice-turn muted"title="Smart Turn (experimental): how sure the model is that you finished your turn"> · `),tV=I(`<span class="chip voice-front"title="Voice front: a fast voice agent answers and relays to the session">front`),nV=I(`<p class="voice-hint voice-front-fallback small"role=status>`),rV=I(`<p class="voice-hint small">Allow notifications to keep a “Voice mode on” notification with an End button while the screen is off. <button type=button class=link>Allow notifications`),iV=I(`<div role=region aria-label="Voice mode"><div class=wave aria-hidden=true></div><span class=voice-state role=status aria-live=polite></span><span class=grow></span><button type=button class=model-chip title="Voice model"></button><button type=button></button><button type=button class="btn small end">End`),aV=I(`<span>`);function oV(e){let r,i,[a,o]=u(!1),c=()=>e.images.length>=F_.maxImages,d=()=>{r.style.height=`auto`,r.style.height=`${Math.min(r.scrollHeight,280)}px`};x(()=>{e.draft,queueMicrotask(d)});let f=()=>e.view.primary===`steer`?`Steer`:`Send`;return(()=>{var u=UB(),d=u.firstChild,p=d.firstChild,h=p.nextSibling,g=h.nextSibling,_=g.firstChild,v=_.nextSibling.nextSibling,x=v.nextSibling,S=d.nextSibling,C=S.firstChild;C.nextSibling,u.addEventListener(`drop`,t=>{let n=qS(t.dataTransfer);o(!1),n.length&&(t.preventDefault(),e.onAttach(n))}),u.addEventListener(`dragleave`,e=>{e.currentTarget.contains(e.relatedTarget)||o(!1)}),u.addEventListener(`dragover`,e=>{[...e.dataTransfer?.types??[]].includes(`Files`)&&(e.preventDefault(),o(!0))}),u.addEventListener(`submit`,t=>{t.preventDefault(),e.view.canSubmit&&!e.attaching&&e.onSubmit()}),y(u,n(l,{get when(){return e.error},get children(){var t=FB();return y(t,()=>e.error),t}}),d),y(u,n(l,{get when(){return e.view.hint},get children(){var t=IB();return y(t,()=>e.view.hint),t}}),d),y(d,n(l,{get when(){return e.images.length||e.attaching},get children(){var t=RB();return y(t,n(m,{get each(){return e.images},children:t=>(()=>{var r=WB(),i=r.firstChild,a=i.nextSibling;return a.$$click=()=>e.onDetach(t.id),y(a,n(L,{name:`close`})),s(e=>{var n=t.preview,r=t.name,o=t.name,s=`Remove ${t.name}`;return n!==e.e&&b(i,`src`,e.e=n),r!==e.t&&b(i,`alt`,e.t=r),o!==e.a&&b(i,`title`,e.a=o),s!==e.o&&b(a,`aria-label`,e.o=s),e},{e:void 0,t:void 0,a:void 0,o:void 0}),r})()}),null),y(t,n(l,{get when(){return e.attaching},get children(){return LB()}}),null),t}}),p),p.$$keydown=t=>{t.key===`Enter`&&!t.shiftKey&&!t.isComposing&&!(matchMedia(`(max-width: 760px)`).matches&&`ontouchstart`in window)&&(t.preventDefault(),e.view.canSubmit&&!e.attaching&&e.onSubmit())},p.addEventListener(`paste`,t=>{let n=qS(t.clipboardData);n.length&&(t.preventDefault(),e.onAttach(n))}),p.$$input=t=>e.onInput(t.currentTarget.value);var w=r;typeof w==`function`?t(w,p):r=p,h.addEventListener(`change`,t=>{let n=[...t.currentTarget.files??[]];t.currentTarget.value=``,n.length&&e.onAttach(n)});var T=i;return typeof T==`function`?t(T,h):i=h,_.$$click=()=>i.click(),y(_,n(L,{name:`plus`})),B(v,`click`,e.onDictate,!0),y(v,n(l,{get when(){return!e.transcribing},get fallback(){return GB()},get children(){return n(L,{get name(){return e.dictating===!1?`mic`:`stop`}})}})),y(g,n(l,{get when(){return e.showVoice!==!1},get children(){var t=zB(),r=t.firstChild;return B(r,`click`,e.onVoice,!0),y(r,n(L,{name:`wave`})),y(t,n(sV,{}),null),s(n=>{var i=`split${e.voiceOn?` on`:``}`,a=e.voiceOn,o=e.voiceOn?`End Voice mode`:`Start Voice mode`,s=e.voiceBlocked??(e.voiceOn?`End Voice mode`:`Voice mode: talk hands-free`),c=!!e.voiceBlocked&&!e.voiceOn;return i!==n.e&&k(t,n.e=i),a!==n.t&&b(r,`aria-pressed`,n.t=a),o!==n.a&&b(r,`aria-label`,n.a=o),s!==n.o&&b(r,`title`,n.o=s),c!==n.i&&(r.disabled=n.i=c),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t}}),x),y(g,n(l,{get when(){return e.view.showStop},get children(){var t=BB(),r=t.firstChild;return B(t,`click`,e.onStop,!0),y(t,n(L,{name:`stop`}),r),s(()=>t.disabled=!e.view.canStop),t}}),x),y(x,n(l,{get when(){return e.view.primary===`send`},get fallback(){return f()},get children(){return[n(L,{name:`send`}),(()=>{var e=VB();return y(e,f),e})()]}})),y(C,()=>e.metaLeft),y(S,n(l,{get when(){return e.sessionModel},children:t=>n(l,{get when(){return e.sessionModelPickable},get fallback(){return(()=>{var e=qB();return e.firstChild,y(e,()=>t().label.replace(/^Model: /,``),null),s(n=>{var r=t().title,i=t().title;return r!==n.e&&b(e,`title`,n.e=r),i!==n.t&&b(e,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),e})()},get children(){var n=KB();return n.firstChild,n.$$click=()=>e.onModel(`session`),y(n,()=>t().label.replace(/^Model: /,``),null),s(e=>{var r=t().title,i=t().title;return r!==e.e&&b(n,`title`,e.e=r),i!==e.t&&b(n,`aria-label`,e.t=i),e},{e:void 0,t:void 0}),n}})}),null),y(S,n(l,{get when(){return e.showModels!==!1},get children(){var t=HB();return t.firstChild,t.$$click=()=>e.onModel(`voice`),y(t,()=>e.voiceModel,null),t}}),null),s(t=>{var n=`composer${a()?` dragging`:``}`,r=e.voiceOn?`Voice mode is on — talk, or type here`:e.view.primary===`steer`?`Steer the running session…`:`Reply…`,i=P_.join(`,`),o=c()?`At most ${F_.maxImages} images per message`:`Attach images (or paste / drop them here)`,s=c()||e.attaching,l=`icon-btn${e.dictating===!1?``:` recording`}`,d=e.dictating===!1?`Dictate`:`Stop dictation`,f=e.voiceBlocked??(e.dictating===!1?`Dictate`:`Stop dictation (${e.dictating}s left)`),m=!!e.voiceBlocked||e.transcribing||e.voiceOn,g=`btn primary send ${e.view.primary}`,y=!e.view.canSubmit||e.attaching;return n!==t.e&&k(u,t.e=n),r!==t.t&&b(p,`placeholder`,t.t=r),i!==t.a&&b(h,`accept`,t.a=i),o!==t.o&&b(_,`title`,t.o=o),s!==t.i&&(_.disabled=t.i=s),l!==t.n&&k(v,t.n=l),d!==t.s&&b(v,`aria-label`,t.s=d),f!==t.h&&b(v,`title`,t.h=f),m!==t.r&&(v.disabled=t.r=m),g!==t.d&&k(x,t.d=g),y!==t.l&&(x.disabled=t.l=y),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0,r:void 0,d:void 0,l:void 0}),s(()=>p.value=e.draft),u})()}function sV(){let[e,r]=u(!1),[i,o]=u([]),[c,d]=u(0),[f,p]=u(``),h,g,_,[v,x]=u({right:0,bottom:0}),S=async()=>{_?.(),_=void 0;try{_=await nb(sb(),d),p(``)}catch(e){p(e.name===`NotAllowedError`?`Microphone permission was denied.`:`Microphone: ${e.message}`)}},C=async()=>{let e=h.getBoundingClientRect();if(x({right:window.innerWidth-e.right,bottom:window.innerHeight-e.top+6}),r(!0),!navigator.mediaDevices)return p(`This browser cannot use the microphone here (it needs HTTPS).`);o(await tb().catch(()=>[])),S()},w=()=>{r(!1),_?.(),_=void 0,d(0)},T=t=>e()&&!h.contains(t.target)&&!g?.contains(t.target)&&w(),E=t=>e()&&t.key===`Escape`&&!ee(g)&&w();return document.addEventListener(`mousedown`,T),document.addEventListener(`keydown`,E),M(()=>{document.removeEventListener(`mousedown`,T),document.removeEventListener(`keydown`,E),w()}),[(()=>{var r=JB();r.$$click=()=>e()?w():void C();var i=h;return typeof i==`function`?t(i,r):h=r,y(r,n(L,{name:`down`})),s(()=>b(r,`aria-expanded`,e())),r})(),n(l,{get when(){return e()},get children(){return n(pe,{get children(){var e=XB(),r=e.firstChild.nextSibling,o=r.firstChild,u=g;return typeof u==`function`?t(u,e):g=e,y(e,n(m,{get each(){return[{deviceId:``,label:`System default`},...i().filter(e=>e.deviceId&&e.deviceId!=="default")]},children:(e,t)=>(()=>{var n=ZB(),r=n.firstChild,i=r.nextSibling;return n.$$click=()=>{lb(e.deviceId),S()},y(r,()=>sb()===e.deviceId?`✓`:``),y(i,()=>e.label||`Microphone ${t()}`),s(()=>b(n,`aria-checked`,sb()===e.deviceId)),n})()}),r),y(e,n(l,{get when(){return f()},get children(){var e=YB();return y(e,f),e}}),null),s(t=>{var n=`${v().right}px`,i=`${v().bottom}px`,s=Math.round(c()*100),l=`${Math.round(c()*100)}%`;return n!==t.e&&a(e,`right`,t.e=n),i!==t.t&&a(e,`bottom`,t.t=i),s!==t.a&&b(r,`aria-valuenow`,t.a=s),l!==t.o&&a(o,`width`,t.o=l),t},{e:void 0,t:void 0,a:void 0,o:void 0}),e}})}})]}var cV={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 lV(e,t){let n=e?[e.summary,e.detail]:[];return t&&n.push(t.mode===`silero`?`speech detection: on-device model${t.avgMs?` (${t.avgMs.toFixed(1)} ms per 32 ms of audio)`:``}`:`speech detection: loudness (the on-device model is loading or unavailable)`),n.length?n.join(`
28
+ `):void 0}function uV(e){let t=()=>e.state===`listening`&&e.working?`Thinking`:cV[e.state],r=[.5,.8,1,.7,.45];return(()=>{var i=iV(),o=i.firstChild,c=o.nextSibling,u=c.nextSibling,d=u.nextSibling,f=d.nextSibling,p=f.nextSibling;return y(o,n(m,{each:r,children:t=>(()=>{var n=aV();return s(r=>a(n,`transform`,`scaleY(${Math.max(.15,Math.min(1,(e.state===`speaking`?.6:e.level)*t*1.6))})`)),n})()})),y(c,t,null),y(c,n(l,{get when(){return e.held},get children(){var t=QB(),n=t.firstChild.nextSibling;return n.nextSibling,y(t,()=>e.held,n),t}}),null),y(c,n(l,{get when(){return e.ignored},get children(){var t=$B(),n=t.firstChild.nextSibling;return n.nextSibling,y(t,()=>e.ignored,n),t}}),null),y(c,n(l,{get when(){return e.turn},get children(){var t=eV();return t.firstChild,y(t,()=>e.turn,null),t}}),null),y(i,n(l,{get when(){return e.front?.on},get children(){return tV()}}),u),y(i,n(FL,{announce:!0,mark:!0}),u),B(d,`click`,e.onModel,!0),y(d,()=>e.model),B(f,`click`,e.onMute,!0),y(f,n(L,{get name(){return e.state===`paused`?`muted`:`mic`}})),B(p,`click`,e.onEnd,!0),y(i,n(l,{get when(){return e.front?.fallback},get children(){var e=nV();return y(e,tx),e}}),null),y(i,n(l,{get when(){return e.notifyHint},get children(){var t=rV(),n=t.firstChild.nextSibling;return n.$$click=()=>e.onAllowNotifications?.(),t}}),null),s(t=>{var n=`voice-bar ${e.state}`,r=e.detector?.mode,a=lV(e.timing,e.detector),o=`icon-btn${e.state===`paused`?` on`:``}`,s=e.state===`paused`,l=e.state===`paused`?`Unmute`:`Mute`,u=e.state===`paused`?`Unmute`:`Mute`;return n!==t.e&&k(i,t.e=n),r!==t.t&&b(i,`data-vad`,t.t=r),a!==t.a&&b(c,`title`,t.a=a),o!==t.o&&k(f,t.o=o),s!==t.i&&b(f,`aria-pressed`,t.i=s),l!==t.n&&b(f,`aria-label`,t.n=l),u!==t.s&&b(f,`title`,t.s=u),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),i})()}z([`input`,`keydown`,`click`]);var dV=e=>e===`voice`?`Voice model`:`Session model`,fV=()=>({query:``,active:0}),pV=e=>[void 0,...(e.variants??[]).filter(e=>e!=="default")];function mV(e,t,n=100){if(t.chosen)return{mode:`variants`,model:t.chosen,rows:pV(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 hV=(e,t)=>({...e,query:t,active:0}),gV=(e,t)=>({providerID:e.providerID,modelID:e.modelID,...t?{variant:t}:{}});function _V(e,t,n){let r=mV(e,t);if(r.mode===`variants`)return n<0||n>=r.rows.length?{state:t}:{state:t,pick:gV(r.model,r.rows[n])};let i=r.rows[n];return i?pV(i).length>1?{state:{...t,chosen:i,active:0}}:{state:t,pick:gV(i)}:{state:t}}function vV(e,t,n,{inSearch:r}){let i=mV(e,t).rows.length;if(n===`ArrowDown`||n===`ArrowUp`)return{state:{...t,active:Math.max(0,DC(t.active,n===`ArrowDown`?1:-1,i))},handled:!0};if(n===`Enter`)return{..._V(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}:{..._V(e,t,r),handled:!0}}return{state:t,handled:!1}}var yV=(e,t)=>({[e]:t}),bV={chosen:`chosen for this session`,reply:`the default model (its latest reply ran on it)`,default:`the default model (no reply yet)`},xV=e=>typeof e==`string`&&e.length>0;function SV(e){let t=e;return typeof t==`object`&&!!t&&xV(t.providerID)&&xV(t.modelID)}var CV=`. Click to change the session's model`;function wV(e,t={}){let n=t.pickable?CV:``;if(!SV(e))return{label:`Model: default`,title:`Model: default (not known yet: it shows once the session has run)${n}`};let r=xV(e.variant)?` · ${e.variant}`:``,i=xV(e.name)?e.name:void 0,a=xV(e.source)?bV[e.source]:void 0;return{label:`Model: ${i??e.modelID}${r}`,title:`Model: ${e.providerID}/${e.modelID}${r}${i?` (${i})`:``}${a?`, ${a}`:``}${n}`}}function TV(e){if(SV(e)&&e.source===`chosen`)return{providerID:e.providerID,modelID:e.modelID,...xV(e.variant)?{variant:e.variant}:{}}}var EV=e=>({model:e}),DV=I(`<div>`),OV=I(`<p class="error small"role=alert>Couldn't load models: `),kV=I(`<p class="muted small">Loading models…`),AV=I(`<input type=search class=picker-search placeholder="Search models"aria-label="Search models"autofocus>`),jV=I(`<p class="muted small"role=status>`),MV=I(`<ul class=picker-list role=listbox aria-label=Models>`),NV=I(`<li class="muted small">No models match.`),PV=I(`<div class="picker-group muted small">`),FV=I(`<span class="po-id muted">variants ›`),IV=I(`<span class=po-mark>✓`),LV=I(`<kbd>`),RV=I(`<li><button type=button role=option><span class=po-name></span><span class="po-id muted">`),zV=I(`<div class=stack><div class=row><button type=button class="btn small"aria-label="Back to models">‹ Back</button><p class="muted small">Variant of </p></div><ul class=picker-list role=listbox aria-label=Variants>`),BV=I(`<li><button type=button role=option><span class=po-name></span><kbd>`);function VV(e,t){let n=e?.prefs[t]??e?.defaults[t];return n?`${n.modelID}${n.variant?` · ${n.variant}`:``}`:`default`}function HV(e){let[t,n]=u(),[r,i]=u(``),[a,o]=u();return{prefs:t,error:r,load:async()=>{try{n(await G(`${H(e())}/model-prefs`)),i(``)}catch(e){i(U(e))}},loadCatalog:async()=>{if(a())return a();let{models:t}=await G(`${H(e())}/models`),n=new Me(t);return o(n),n},save:async(t,r)=>{try{n(await(await V(`${H(e())}/model-prefs`,{method:`PUT`,json:yV(t,r)})).json()),q(`Voice model applies the next time Voice mode starts.`)}catch(e){q(`Couldn't set the Voice model: ${U(e)}`,`err`)}},saveSession:async t=>{try{let{model:n}=await(await V(`${H(e())}/model`,{method:`PUT`,json:EV(t)})).json();return q(`The session's next turn runs on ${n.name||n.modelID}${n.variant?` · ${n.variant}`:``}.`),n}catch(e){q(`Couldn't set the session's model: ${U(e)}`,`err`);return}}}}function UV(t){let[i,a]=u(fV()),[o,c]=u(),[d,f]=u(``),p=()=>t.kind!==void 0,h=()=>t.kind===`session`?t.sessionCurrent:t.kind?t.models.prefs()?.prefs[t.kind]??t.models.prefs()?.defaults[t.kind]:void 0,g=e=>h()?.providerID===e.providerID&&h()?.modelID===e.modelID,_=()=>{a(fV()),f(``),t.models.loadCatalog().then(c,e=>f(U(e)))},v=C(()=>o()?mV(o(),i()):void 0),S=e=>{if(a(e.state),!e.pick||!t.kind)return;let n=t.kind,r=e.pick;if(t.onClose(),n===`voice`)return void t.models.save(n,r);t.models.saveSession(r).then(e=>e&&t.onSessionModel?.(e))},w=e=>o()&&S(_V(o(),i(),e)),T=e=>{if(!o()||e.altKey||e.ctrlKey||e.metaKey)return;let t=vV(o(),i(),e.key,{inSearch:e.target instanceof HTMLInputElement});if(!t.handled)return;e.preventDefault(),S(t);let n=e.currentTarget;queueMicrotask(()=>n.querySelector(`.picker-opt.active`)?.scrollIntoView({block:`nearest`}))};return x(e(p,e=>e&&_())),n(de,{get open(){return p()},get title(){return dV(t.kind??`voice`)},get onClose(){return t.onClose},class:`picker`,get children(){var e=DV();return e.$$keydown=T,y(e,n(l,{get when(){return!d()},get fallback(){return(()=>{var e=OV();return e.firstChild,y(e,d,null),e})()},get children(){return n(l,{get when(){return v()},get fallback(){return kV()},children:e=>n(l,{get when(){return r(()=>e().mode===`models`)()&&e()},get fallback(){return n(WV,{get view(){return e()},get active(){return i().active},get current(){return h()},onPick:w,onBack:()=>a(e=>({...e,chosen:void 0,active:0}))})},children:e=>[(()=>{var e=AV();return e.$$input=e=>a(t=>hV(t,e.currentTarget.value)),s(()=>e.value=i().query),e})(),(()=>{var t=jV();return y(t,(()=>{var t=r(()=>e().total===1);return()=>t()?`1 model`:`${e().total} models`})(),null),y(t,(()=>{var t=r(()=>!!e().more);return()=>t()?` · showing ${e().rows.length}, search to narrow`:``})(),null),t})(),(()=>{var t=MV();return y(t,n(m,{get each(){return e().rows},get fallback(){return NV()},children:(t,r)=>(()=>{var a=RV(),o=a.firstChild,c=o.firstChild,u=c.nextSibling;return y(a,n(l,{get when(){return r()===0||e().rows[r()-1].group!==t.group},get children(){var e=PV();return y(e,()=>t.group),e}}),o),o.$$click=()=>w(r()),y(c,()=>t.name||t.modelID),y(u,()=>t.modelID),y(o,n(l,{get when(){return(t.variants??[]).some(e=>e!=="default")},get children(){return FV()}}),null),y(o,n(l,{get when(){return g(t)},get children(){return IV()}}),null),y(o,n(l,{get when(){return r()<9},get children(){var e=LV();return y(e,()=>r()+1),e}}),null),s(e=>{var n=`picker-opt${i().active===r()?` active`:``}`,a=g(t);return n!==e.e&&k(o,e.e=n),a!==e.t&&b(o,`aria-selected`,e.t=a),e},{e:void 0,t:void 0}),a})()})),t})()]})})}})),e}})}function WV(e){let i;fe(()=>i?.focus());let a=()=>e.current?.providerID===e.view.model.providerID&&e.current?.modelID===e.view.model.modelID;return(()=>{var o=zV(),c=o.firstChild,u=c.firstChild,d=u.nextSibling;d.firstChild;var f=c.nextSibling;return B(u,`click`,e.onBack,!0),y(d,()=>e.view.model.name||e.view.model.modelID,null),y(f,n(m,{get each(){return e.view.rows},children:(o,c)=>(()=>{var u=BV(),d=u.firstChild,f=d.firstChild,p=f.nextSibling;return d.$$click=()=>e.onPick(c()),t(e=>c()===0&&(i=e),d),y(f,o??`Default`),y(d,n(l,{get when(){return r(()=>!!a())()&&e.current?.variant===o},get children(){return IV()}}),p),y(p,()=>c()+1),s(t=>{var n=`picker-opt${e.active===c()?` active`:``}`,r=a()&&e.current?.variant===o;return n!==t.e&&k(d,t.e=n),r!==t.t&&b(d,`aria-selected`,t.t=r),t},{e:void 0,t:void 0}),u})()})),o})()}z([`keydown`,`input`,`click`]);var GV=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;function KV(e){let t=[],n=0,r=0,i=!1;for(let a of String(e??``).replace(/\r\n?/g,`
29
+ `).split(`
30
+ `)){let e=GV.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 qV=new Set([`user`,`launch`,`self`,`prompt`,`title`]),JV=e=>`/api/agent/sessions/${encodeURIComponent(e)}/intent`,YV=e=>e.replace(/\s+/g,` `).trim();function XV(e){let t=Array.from(YV(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 ZV=(e,t)=>({text:e===null?null:YV(e),expectedRevision:t});function QV(e){if(e?.source===`user`)return{text:null,expectedRevision:e.revision};if(e?.source===`prompt`)return{source:`prompt`,text:null,expectedRevision:e.revision}}function $V(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 eH(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`||!qV.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 tH(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 nH(e,t,n){return e.type===`intent`&&e.sessionID===t&&e.revision!==n}var rH=I(`<div class=field><label class=field-label>What is this session for?</label><input type=text><div class=row><button type=button class="btn small primary">Save</button><button type=button class="btn small">Cancel`),iH=I(`<div class=intent-field>`),aH=I(`<button type=button class="btn small">Retry`),oH=I(`<button type=button class="btn small">Clear`),sH=I(`<div class=row><button type=button class="btn small">Edit`),cH=I(`<p class="muted small intent-error">Could not load the intent.`),lH=I(`<p class="muted small">Loading…`),uH=I(`<p class="muted small">No intent yet.`),dH=I(`<p class="small intent-text">`),fH=I(`<p class="muted small">`),pH=I(`<p class=field-error>`);function mH(e){let[i,{refetch:a,mutate:o}]=d(()=>e.sessionID,async e=>eH(await G(JV(e)))),[c,f]=u(!1),[p,m]=u(``),[h,g]=u(!1),[_,v]=u(``),x=()=>XV(p()),S=()=>i.error?void 0:i.loading?i.latest:i();M(Nu(t=>{!c()&&nH(t,e.sessionID,S()?.revision)&&a()}));let C=()=>{m(S()?.source===`title`?``:S()?.text??``),v(``),f(!0)},w=async t=>{if(h()||t!==null&&x())return;let n=t===null?QV(S()):ZV(t,S()?.revision??0);if(n){g(!0),v(``);try{let t=eH(await(await V(JV(e.sessionID),{method:`PUT`,json:n})).json());i.error?a():o(t),f(!1)}catch(e){let t=tH(e instanceof W?{status:e.status,...e.code?{code:e.code}:{},message:e.message}:{message:U(e)},{loaded:!i.error});v(t.text),t.reload&&(f(!1),a())}finally{g(!1)}}};return(()=>{var o=iH();return y(o,n(l,{get when(){return c()},get fallback(){return[n(l,{get when(){return!i.error},get fallback(){return cH()},get children(){return n(l,{get when(){return!i.loading||S()},get fallback(){return lH()},get children(){return n(l,{get when(){return S()},get fallback(){return uH()},children:e=>[(()=>{var t=dH();return y(t,()=>e().text),t})(),(()=>{var t=fH();return y(t,()=>$V(e())),t})()]})}})}}),(()=>{var e=sH(),t=e.firstChild;return t.$$click=C,y(e,n(l,{get when(){return i.error},get children(){var e=aH();return e.$$click=()=>void a(),e}}),null),y(e,n(l,{get when(){return QV(S())},get children(){var e=oH();return e.$$click=()=>void w(null),s(t=>{var n=h(),r=S()?.source===`prompt`?`Not what this session is for: clear it (the title shows instead)`:`Clear your intent`;return n!==t.e&&(e.disabled=t.e=n),r!==t.t&&b(e,`title`,t.t=r),t},{e:void 0,t:void 0}),e}}),null),s(()=>t.disabled=i.loading&&!i.error),e})()]},get children(){var i=rH(),a=i.firstChild,o=a.nextSibling,c=o.nextSibling,u=c.firstChild,d=u.nextSibling;return t(e=>queueMicrotask(()=>e.focus()),o),o.$$keydown=e=>{e.key===`Enter`&&w(p()),e.key===`Escape`&&f(!1)},o.$$input=e=>m(e.currentTarget.value),b(o,`maxlength`,560),y(i,n(l,{get when(){return r(()=>!!p())()&&x()},children:e=>(()=>{var t=pH();return y(t,e),t})()}),c),u.$$click=()=>void w(p()),d.$$click=()=>f(!1),s(t=>{var n=`intent-${e.sessionID}`,r=`intent-${e.sessionID}`,i=h()||!!x(),s=h();return n!==t.e&&b(a,`for`,t.e=n),r!==t.t&&b(o,`id`,t.t=r),i!==t.a&&(u.disabled=t.a=i),s!==t.o&&(d.disabled=t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),s(()=>o.value=p()),i}}),null),y(o,n(l,{get when(){return _()},children:e=>(()=>{var t=pH();return y(t,e),t})()}),null),o})()}z([`input`,`keydown`,`click`]);var hH=e=>`/api/agent/subscriptions?session=${encodeURIComponent(e)}`,gH=e=>`/api/agent/subscriptions/${encodeURIComponent(e)}`,_H=e=>typeof e==`string`,vH=e=>typeof e==`number`&&Number.isFinite(e)?e:0;function yH(e){let t=e;if(t&&typeof t==`object`){if(t.kind===`children`)return{kind:`children`};if(t.kind===`session`&&_H(t.sessionID)&&_H(t.addr))return{kind:`session`,sessionID:t.sessionID,addr:t.addr};if((t.kind===`role`||t.kind===`team`)&&_H(t.addr))return{kind:t.kind,addr:t.addr}}}function bH(e){let t=e?.subscriptions;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=e;if(!t||typeof t!=`object`||!_H(t.id)||!_H(t.subscriber)||!Array.isArray(t.targets)||!Array.isArray(t.types))continue;let r=t.stats??{};n.push({id:t.id,subscriber:t.subscriber,targets:t.targets.map(yH).filter(e=>e!==void 0),types:t.types.filter(_H),delivery:_H(t.delivery)?t.delivery:`queue`,batchMs:vH(t.batchMs),expiresAt:vH(t.expiresAt),pending:vH(t.pending),stats:{delivered:vH(r.delivered),dropped:vH(r.dropped),suppressed:vH(r.suppressed)}})}return n}function xH(e,t){return{listensTo:e.filter(e=>e.subscriber===t),listenedBy:e.filter(e=>e.subscriber!==t)}}function SH(e){if(e<=0)return`ending`;let t=Math.round(e/6e4);if(t<60)return`${Math.max(t,1)} min`;let n=Math.round(e/36e5);return n<48?`${n} h`:`${Math.round(e/864e5)} d`}function CH(e,t){let n=e.targets.map(e=>e.kind===`children`?`its subagents`:e.addr).join(`, `)||`—`,r=[e.types.join(`, `),e.delivery,`every ${Math.round(e.batchMs/1e3)} s`,`${e.stats.delivered} sent`];return e.pending&&r.push(`${e.pending} pending`),e.stats.dropped&&r.push(`${e.stats.dropped} dropped`),e.stats.suppressed&&r.push(`${e.stats.suppressed} loop-suppressed`),r.push(`ends in ${SH(e.expiresAt-t)}`),{title:n,detail:r.join(` · `)}}var wH=I(`<ul class=subscription-list>`),TH=I(`<li class=subscription><div class=subscription-text><span class=small></span><span class="muted small"></span></div><button type=button class="btn small">Remove`),EH=I(`<p class="small subscription-head">Listens to`),DH=I(`<p class="small subscription-head">Listened to by`),OH=I(`<div class=subscriptions-field><div class=row><button type=button class="btn small">Refresh`),kH=I(`<p class="muted small">Could not load the subscriptions.`),AH=I(`<p class="muted small">Loading…`),jH=I(`<p class="muted small">None. An agent follows other sessions with hub subscribe.`);function MH(e){let[t,{refetch:r}]=d(()=>e.sessionID,async e=>bH(await G(hH(e)))),[i,a]=u(``),o=()=>xH(t.error?[]:t.latest??[],e.sessionID),c=async e=>{if(!i()){a(e.id);try{await V(gH(e.id),{method:`DELETE`}),q(`Subscription removed`),r()}catch(e){q(`Could not remove the subscription: ${U(e)}`,`err`)}finally{a(``)}}},f=e=>(()=>{var t=wH();return y(t,n(m,{get each(){return e.items},children:t=>{let n=()=>CH(t,Date.now());return(()=>{var r=TH(),a=r.firstChild,o=a.firstChild,l=o.nextSibling,u=a.nextSibling;return y(o,()=>e.who(t)),y(l,()=>n().detail),u.$$click=()=>void c(t),s(e=>{var n=t.id,a=i()===t.id,o=`Remove subscription ${t.id}`;return n!==e.e&&b(r,`data-subscription`,e.e=n),a!==e.t&&(u.disabled=e.t=a),o!==e.a&&b(u,`aria-label`,e.a=o),e},{e:void 0,t:void 0,a:void 0}),r})()}})),t})();return(()=>{var e=OH(),i=e.firstChild,a=i.firstChild;return y(e,n(l,{get when(){return!t.error},get fallback(){return kH()},get children(){return n(l,{get when(){return!t.loading||t.latest},get fallback(){return AH()},get children(){return n(l,{get when(){return o().listensTo.length||o().listenedBy.length},get fallback(){return jH()},get children(){return[n(l,{get when(){return o().listensTo.length},get children(){return[EH(),n(f,{get items(){return o().listensTo},who:e=>CH(e,Date.now()).title})]}}),n(l,{get when(){return o().listenedBy.length},get children(){return[DH(),n(f,{get items(){return o().listenedBy},who:e=>e.subscriber})]}})]}})}})}}),i),a.$$click=()=>void r(),s(()=>a.disabled=t.loading),e})()}z([`click`]);var NH=I(`<div class=context-cards>`),PH=I(`<p class="muted small">Could not load the context cards. <button type=button class="btn small">Retry`),FH=I(`<p class="muted small">Loading…`),IH=I(`<p class="muted small context-cards-off">`),LH=I(`<article><header class=context-card-head><span class=context-card-title></span><button type=button class="btn small">`),RH=I(`<p class="muted small">No card yet.`),zH=I(`<p class=context-card-headline>`),BH=I(`<p class="small context-card-body">`),VH=I(`<dl class="kv context-card-fields">`),HH=I(`<p class="muted small context-card-meta">`),UH=I(`<dt>`),WH=I(`<dd>`),GH=I(`<p class="muted small context-card-note">`);function KH(e){let[t,{refetch:r}]=d(()=>e.sessionID,async e=>{let t=Wk(await G(Fk(e)));for(let e of t.cards)nA(e);return t}),[i,a]=u(),[o,s]=u({});M(Nu(t=>{Yk(t,e.sessionID)&&r()}));let c=()=>t.error?void 0:t.loading?t.latest:t(),f=e=>c()?.cards.find(t=>t.provider===e),p=async t=>{if(!i()){a(t),s(e=>({...e,[t]:``}));try{let n=await V(Ik(e.sessionID,t),{method:`POST`}).catch(e=>{if(!(e instanceof W&&e.status===429))throw e}),i=n?await n.json():{outcome:`skipped`,reason:`rate_limited`},a=Jk(i),o=Uk(i.card);o&&nA(o),s(e=>({...e,[t]:a??``})),await r()}catch(e){s(n=>({...n,[t]:U(e)}))}finally{a(void 0)}}};return(()=>{var e=NH();return y(e,n(l,{get when(){return!t.error},get fallback(){return(()=>{var e=PH(),t=e.firstChild.nextSibling;return t.$$click=()=>void r(),e})()},get children(){return n(l,{get when(){return c()},get fallback(){return FH()},children:e=>[n(l,{get when(){return!e().enabled},get children(){var t=IH();return y(t,()=>e().configured?`Context cards are off. Turn them on in Settings › Concierge (nothing is sent to a model until you do).`:`No model is configured for context cards (see docs/context-cards.md).`),t}}),n(m,{get each(){return e().providers},children:e=>n(qH,{provider:e,get card(){return f(e.id)},get busy(){return i()===e.id},get disabled(){return!!i()},get note(){return o()[e.id]},onRefresh:()=>void p(e.id)})})]})}})),e})()}function qH(e){return(()=>{var t=LH(),r=t.firstChild.firstChild,i=r.nextSibling;return y(r,()=>e.card?.title??e.provider.label),i.$$click=()=>e.onRefresh(),y(i,()=>e.busy?`Refreshing…`:`Refresh`),y(t,n(l,{get when(){return e.card},get fallback(){return RH()},children:e=>[(()=>{var t=zH();return y(t,()=>e().headline),t})(),n(l,{get when(){return e().body},get children(){var t=BH();return y(t,()=>e().body),t}}),n(l,{get when(){return e().fields?.length},get children(){var t=VH();return y(t,n(m,{get each(){return e().fields},children:e=>[(()=>{var t=UH();return y(t,()=>e.label),t})(),(()=>{var t=WH();return y(t,()=>e.value),t})()]})),t}}),(()=>{var t=HH();return y(t,()=>Kk(e(),N())),t})()]}),null),y(t,n(l,{get when(){return e.note},children:e=>(()=>{var t=GH();return y(t,e),t})()}),null),s(n=>{var r=`context-card${e.provider.primary?` primary`:``}`,a=e.provider.id,o=e.busy,s=e.disabled,c=`Refresh ${e.provider.label}`;return r!==n.e&&k(t,n.e=r),a!==n.t&&b(t,`data-context-card`,n.t=a),o!==n.a&&b(t,`aria-busy`,n.a=o),s!==n.o&&(i.disabled=n.o=s),c!==n.i&&b(i,`title`,n.i=c),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),t})()}z([`click`]);var JH=e=>Array.isArray(e)?e.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`string`):[],YH=e=>typeof e==`string`?e:``,XH=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,ZH=new Set([`working`,`blocked`]),QH=e=>Ir[YH(e.state)]??Ir.idle;function $H(e){let t=new Map,n=[];for(let r of e){let e=t.get(r.id);e===void 0?(t.set(r.id,n.length),n.push(r)):QH(r)<QH(n[e])&&(n[e]=r)}return n}function eU(e,t,n){let r=$H(JH(t)),i=e=>{let t=[],n=new Set([e]);for(let e=!0;e;){e=!1;for(let i of r)n.has(YH(i.parentID))&&!n.has(i.id)&&(n.add(i.id),t.push(i),e=!0)}return t},a=new Map;for(let e of JH(n)){let t=XH(e.updated);t!==void 0&&a.set(e.id,Math.max(t,a.get(e.id)??-1/0))}let o=[];for(let t of r){if(t.parentID!==e||t.id===e)continue;let n=i(t.id),r=[t,...n].map(e=>YH(e.state)),a=r.includes(`blocked`)?`blocked`:t.state===`error`?`error`:r.includes(`working`)?`working`:`idle`,s=[t,...n].filter(e=>e.state===`working`).map(e=>XH(e.since)).filter(e=>e!==void 0);o.push({id:t.id,title:YH(t.title)||`Subagent`,state:a,...a===`working`&&s.length?{since:Math.min(...s)}:{},nested:n.length,order:o.length})}let s=new Set(o.map(e=>e.id));for(let t of JH(n)){if(t.parentID!==e||s.has(t.id))continue;s.add(t.id);let n=YH(t.state),r=n===`working`||n===`blocked`||n===`error`?n:`idle`;o.push({id:t.id,title:YH(t.title)||`Subagent`,state:r,nested:0,order:o.length})}let c=({order:e,...t})=>t,l=o.filter(e=>ZH.has(e.state)).sort((e,t)=>(e.state===t.state?0:e.state===`blocked`?-1:+(t.state===`blocked`))||(e.since??1/0)-(t.since??1/0)||e.order-t.order),u=o.filter(e=>!ZH.has(e.state)).sort((e,t)=>Number(t.state===`error`)-Number(e.state===`error`)||(a.get(t.id)??-1/0)-(a.get(e.id)??-1/0)||t.order-e.order);return{running:l.map(c),finished:u.map(c)}}function tU(e){let t=e.finished.filter(e=>e.state===`error`).length;return[`Subagents`,e.running.length?`${e.running.length} running`:e.finished.length?`${e.finished.length} finished`:``,t?`${t} failed`:``].filter(Boolean).join(` · `)}var nU={working:`Running`,blocked:`Needs you`,error:`Error`,idle:`Done`};function rU(e,t){let n=[nU[e.state]];return e.state===`working`&&e.since!==void 0&&n.push(Gi(t-e.since)),e.nested&&n.push(`${e.nested} subagent${e.nested===1?``:`s`}`),n.join(` · `)}var iU=I(`<section><h3><button type=button class=card-toggle><span>`),aU=I(`<li><a><span class=subagent-text><span class=subagent-title></span><span class="muted small">`),oU=I(`<ul class=job-list>`),sU=I(`<ul class=subagent-list>`),cU=I(`<button type=button class="subagents-more small">`),lU=I(`<ul class=mcp-list>`),uU=I(`<aside class=rail aria-label="Session details"><div class=rail-head><span class=rail-title>Details`),dU=I(`<p class="rail-error small"><strong>`),fU=I(`<p class="muted small">`),pU=I(`<dl class=kv><dt>Machine</dt><dd><span aria-hidden=true></span> <span class=muted>· </span></dd><dt>Project</dt><dd class=mono></dd><dt>Directory</dt><dd class=kv-path data-session-directory><span class="mono path-tail"><bdi></bdi></span></dd><dt>Branch</dt><dd class=mono></dd><dt>Open in</dt><dd>`),mU=I(`<span class=muted>`),hU=I(`<p class="small retry-note">`),gU=I(`<li><span aria-hidden=true></span><span class="job-command mono"></span><span class="muted small">`),_U=I(`<div class=meter role=meter aria-valuemin=0 aria-valuemax=100 aria-label="Context used"><span>`),vU=I(`<p class=small><strong></strong><span class=muted> `),yU=I(`<li><span aria-hidden=true></span><span class=mcp-name></span><span class="muted small">`),bU=I(`<span class=diffstat><span class=add>+</span> <span class=del>−`),xU=I(`<ul class=file-list>`),SU=I(`<p class="muted small">No changes.`),CU=I(`<li><button type=button class=file><span></span><span class=file-name><bdi></bdi></span><span class="diffstat small"><span class=add>+</span> <span class=del>−`),wU=I(`<p class="muted small more-files">+<!> more <!> (only the most-changed files are listed)`),TU=I(`<table class=diff><tbody>`),EU=I(`<p class="muted small pad">The diff is too large to show completely (512 KB).`),DU=I(`<section class=diff-panel><header class=diff-head><select aria-label="Changed file"></select><label class="small muted wrap-toggle"><input type=checkbox> Wrap</label></header><div>`),OU=I(`<option>`),kU=I(`<p class="muted small pad">Loading diff…`),AU=I(`<p class="muted small pad">`),jU=I(`<p class="muted small pad">No textual changes (binary file, or a rename).`),MU=I(`<tr><td class=ln></td><td class=ln></td><td class=code-line><span class=sign>`),NU=e=>e.truncated&&e.totalFiles?Math.max(0,e.totalFiles-e.files.length):0,[PU,FU]=u(LS(localStorage));function IU(e){let t=()=>!PU().has(e.id);return(()=>{var r=iU(),i=r.firstChild,a=i.firstChild,o=a.firstChild;return a.$$click=()=>FU(RS(localStorage,e.id)),y(a,n(L,{name:`chevron`,class:`card-chevron`}),o),y(o,()=>e.title),y(i,()=>e.extra,null),y(r,n(l,{get when(){return t()},get children(){return e.children}}),null),s(n=>{var i=`rail-card${t()?``:` collapsed`}`,o=e.label??e.title,s=e.domID,c=e.id,l=t();return i!==n.e&&k(r,n.e=i),o!==n.t&&b(r,`aria-label`,n.t=o),s!==n.a&&b(r,`id`,n.a=s),c!==n.o&&b(r,`data-card`,n.o=c),l!==n.i&&b(a,`aria-expanded`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),r})()}var LU=e=>e>=1e3?`${(e/1e3).toFixed(e>=1e5?0:1)}k`:String(e);function RU(t){let i=()=>t.found?.session,o=()=>i()?.open?i()?.terminal?.source===`herdr`?`herdr`:`tui`:`background`,c=()=>Wi(i()?.status,N()),d=()=>c().filter(e=>e.status===`running`).length,f=()=>i()?.state===`working`||i()?.status?.some(e=>e.state===`working`)?Ji(i()?.status,i()?.id,se()):void 0,p=()=>zi(i()?.status,i()?.id),h=C(()=>{let e=i()?.id;return e?(Y.machines??[]).flatMap(t=>t.processes.flatMap(t=>t.sessions.filter(t=>t.parentID===e))):[]}),g=C(()=>{let e=i()?.id;return e?eU(e,i()?.status,h()):{running:[],finished:[]}}),_=C(()=>new Map([...g().running,...g().finished].map(e=>[e.id,e]))),[v,S]=u(!1);x(e(()=>i()?.id,()=>S(!1),{defer:!0}));let w=C(()=>{let{running:e,finished:t}=g();return[...e,...v()?t:t.slice(0,3)].map(e=>e.id)},[],{equals:(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n])}),T=e=>n(l,{get when(){return _().get(e)},children:r=>(()=>{var i=aU(),a=i.firstChild,o=a.firstChild,c=o.firstChild,l=c.nextSibling;return a.$$click=()=>Z()&&t.onClose(),b(a,`data-session`,e),y(a,n(A,{get state(){return r().state}}),o),y(c,()=>r().title),y(l,()=>rU(r(),N())),y(a,n(L,{name:`chevron`,class:`chev`}),null),s(t=>{var n=`subagent-row ${r().state}`,i=Ot(e),o=r().title,s=`Open subagent ${r().title} (${rU(r(),N())})`;return n!==t.e&&k(a,t.e=n),i!==t.t&&b(a,`href`,t.t=i),o!==t.a&&b(a,`title`,t.a=o),s!==t.o&&b(a,`aria-label`,t.o=s),t},{e:void 0,t:void 0,a:void 0,o:void 0}),i})()}),E=()=>{let e=t.summary?.mcp;return e?.length?`Connectors · ${e.filter(e=>e.status===`connected`).length} connected`:`Connectors`};return(()=>{var e=uU(),u=e.firstChild;return u.firstChild,y(u,n(F,{icon:`close`,label:`Close details`,get onClick(){return t.onClose}}),null),y(e,n(l,{get when(){return p()},children:e=>(()=>{var t=dU(),n=t.firstChild;return y(n,()=>e().label),y(t,(()=>{var t=r(()=>!!e().status);return()=>t()?` · ${e().status}`:``})(),null),y(t,(()=>{var t=r(()=>!!(e().title&&e().sessionID!==i()?.id));return()=>t()?` · ${e().title}`:``})(),null),s(()=>b(t,`title`,e().text)),t})()}),null),y(e,n(IU,{id:`environment`,title:`Environment`,get children(){return n(l,{get when(){return t.found},get fallback(){return(()=>{var e=fU();return y(e,()=>Y.machines?`Not reported by any connected machine.`:`Loading…`),e})()},children:e=>(()=>{var a=pU(),c=a.firstChild.nextSibling,l=c.firstChild,u=l.nextSibling,d=u.nextSibling;d.firstChild;var f=c.nextSibling.nextSibling,p=f.nextSibling.nextSibling,m=p.firstChild,h=m.firstChild,g=p.nextSibling.nextSibling,_=g.nextSibling.nextSibling;return y(c,()=>e().machine.name,u),y(d,(()=>{var t=r(()=>Y.connection!==`live`);return()=>t()?`Connecting`:e().machine.online?`online`:`offline`})(),null),y(f,()=>j(t.summary?.directory??e().session.directory)),y(h,()=>t.summary?.directory??e().session.directory),y(p,n(F,{icon:`copy`,label:`Copy the directory`,onClick:()=>{let n=t.summary?.directory??e().session.directory;navigator.clipboard.writeText(n).then(()=>q(`Directory copied`),()=>q(`Could not copy the directory`,`err`))}}),null),y(g,()=>t.summary?.branch??(()=>{var e=mU();return y(e,()=>t.loading?`…`:`—`),e})()),y(_,()=>oe[o()],null),y(_,(()=>{var e=r(()=>!!i()?.terminal?.workspace);return()=>e()?` · ${i().terminal.workspace}`:``})(),null),s(n=>{var r=`online-dot${e().machine.online&&Y.connection===`live`?` on`:``}`,i=t.summary?.directory??e().session.directory,a=t.summary?.directory??e().session.directory;return r!==n.e&&k(l,n.e=r),i!==n.t&&b(f,`title`,n.t=i),a!==n.a&&b(m,`title`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),a})()})}}),null),y(e,n(l,{get when(){return i()?.id},children:e=>n(IU,{id:`intent`,title:`Intent`,label:`Session intent`,get children(){return n(mH,{get sessionID(){return e()}})}})}),null),y(e,n(l,{get when(){return c().length||f()},get children(){return n(IU,{id:`jobs`,get title(){return`Jobs${d()?` · ${d()} running`:``}`},label:`Background jobs`,get children(){return[n(l,{get when(){return f()},children:e=>(()=>{var t=hU();return y(t,e),t})()}),(()=>{var e=oU();return y(e,n(m,{get each(){return c()},children:e=>(()=>{var t=gU(),n=t.firstChild,a=n.nextSibling,o=a.nextSibling;return y(a,()=>e.command??e.id),y(o,()=>Ki(e,N()),null),y(o,(()=>{var t=r(()=>!!(e.sessionID!==i()?.id&&e.sessionTitle));return()=>t()?` · ${e.sessionTitle}`:``})(),null),s(r=>{var i=`job ${e.status}`,a=e.command??e.id,o=`job-dot ${e.status===`running`?`on`:e.exit?`bad`:``}`;return i!==r.e&&k(t,r.e=i),a!==r.t&&b(t,`title`,r.t=a),o!==r.a&&k(n,r.a=o),r},{e:void 0,t:void 0,a:void 0}),t})()})),e})()]}})}}),null),y(e,n(l,{get when(){return g().running.length||g().finished.length},get children(){return n(IU,{id:`subagents`,get title(){return tU(g())},label:`Subagents`,get children(){return[(()=>{var e=sU();return y(e,n(m,{get each(){return w()},children:T})),e})(),n(l,{get when(){return g().finished.length>3},get children(){var e=cU();return e.$$click=()=>S(!v()),y(e,(()=>{var e=r(()=>!!v());return()=>e()?`Show fewer`:`${g().finished.length-3} more finished`})()),s(()=>b(e,`aria-expanded`,v())),e}})]}})}}),null),y(e,n(l,{get when(){return i()?.id},children:e=>n(IU,{id:`context-cards`,title:`Context cards`,get children(){return n(KH,{get sessionID(){return e()}})}})}),null),y(e,n(l,{get when(){return i()?.id},children:e=>n(IU,{id:`subscriptions`,title:`Subscriptions`,label:`Session subscriptions`,get children(){return n(MH,{get sessionID(){return e()}})}})}),null),y(e,n(IU,{id:`context`,title:`Context`,get children(){return n(l,{get when(){return t.summary?.context},get fallback(){return(()=>{var e=fU();return y(e,()=>t.loading?`Loading…`:`No usage reported yet.`),e})()},children:e=>[(()=>{var t=_U(),n=t.firstChild;return s(r=>{var i=e().percent??0,o=`${e().percent??0}%`,s=(e().percent??0)>80?`hot`:``;return i!==r.e&&b(t,`aria-valuenow`,r.e=i),o!==r.t&&a(n,`width`,r.t=o),s!==r.a&&k(n,r.a=s),r},{e:void 0,t:void 0,a:void 0}),t})(),(()=>{var t=vU(),n=t.firstChild,i=n.nextSibling;return i.firstChild,y(n,(()=>{var t=r(()=>e().percent!==void 0);return()=>t()?`${e().percent}%`:LU(e().used)})()),y(i,(()=>{var t=r(()=>!!e().limit);return()=>t()?`${LU(e().used)} / ${LU(e().limit)} tokens`:`tokens`})(),null),y(i,(()=>{var t=r(()=>!!e().model);return()=>t()?` · ${e().model}`:``})(),null),t})()]})}}),null),y(e,n(IU,{id:`mcp`,get title(){return E()},label:`MCP servers`,get children(){return n(l,{get when(){return t.summary?.mcp?.length},get fallback(){return(()=>{var e=fU();return y(e,()=>t.loading?`Loading…`:`No MCP servers.`),e})()},get children(){var e=lU();return y(e,n(m,{get each(){return t.summary.mcp},children:e=>(()=>{var t=yU(),n=t.firstChild,r=n.nextSibling,i=r.nextSibling;return y(r,()=>e.name),y(i,()=>e.status.replace(`_`,` `)),s(r=>{var i=e.error??e.status,a=`mcp-dot ${e.status}`;return i!==r.e&&b(t,`title`,r.e=i),a!==r.t&&k(n,r.t=a),r},{e:void 0,t:void 0}),t})()})),e}})}}),null),y(e,n(IU,{id:`changes`,title:`Changes`,domID:`rail-changes`,get extra(){return n(l,{get when(){return t.summary?.changes},children:e=>(()=>{var t=bU(),n=t.firstChild;n.firstChild;var r=n.nextSibling.nextSibling;return r.firstChild,y(n,()=>e().additions,null),y(r,()=>e().deletions,null),t})()})},get children(){return n(l,{get when(){return t.summary?.changes},get fallback(){return(()=>{var e=fU();return y(e,(()=>{var e=r(()=>!!t.loading);return()=>e()?`Loading…`:t.summaryError||`No working-tree changes reported (not a git repository, or OpenCode is still warming up).`})()),e})()},children:e=>n(l,{get when(){return e().files.length},get fallback(){return SU()},get children(){return[(()=>{var r=xU();return y(r,n(m,{get each(){return e().files},children:e=>(()=>{var n=CU(),r=n.firstChild,i=r.firstChild,a=i.nextSibling,o=a.firstChild,c=a.nextSibling.firstChild;c.firstChild;var l=c.nextSibling.nextSibling;return l.firstChild,r.$$click=()=>t.onFile(e.file),y(i,()=>e.status[0].toUpperCase()),y(o,()=>e.file),y(c,()=>e.additions,null),y(l,()=>e.deletions,null),s(t=>{var n=e.file,a=`file-status ${e.status}`;return n!==t.e&&b(r,`title`,t.e=n),a!==t.t&&k(i,t.t=a),t},{e:void 0,t:void 0}),n})()})),r})(),n(l,{get when(){return NU(e())},children:e=>(()=>{var t=wU(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(t,e,n),y(t,()=>e()===1?`file`:`files`,r),t})()})]}})})}}),null),e})()}function zU(e){let[t]=d(()=>e.file,async t=>G(`${H(e.sessionID)}/diff?file=${K(t)}`)),[i,a]=u(!1);return(()=>{var o=DU(),c=o.firstChild,u=c.firstChild,d=u.nextSibling,f=d.firstChild,p=c.nextSibling;return y(c,n(L,{name:`diff`}),u),u.addEventListener(`change`,t=>e.onFile(t.currentTarget.value)),y(u,n(m,{get each(){return e.files},children:e=>(()=>{var t=OU();return t.value=e,y(t,e),t})()})),y(c,n(l,{get when(){return t()},children:e=>(()=>{var t=bU(),n=t.firstChild;n.firstChild;var r=n.nextSibling.nextSibling;return r.firstChild,y(n,()=>e().additions,null),y(r,()=>e().deletions,null),t})()}),d),f.addEventListener(`change`,e=>a(e.currentTarget.checked)),y(c,n(F,{icon:`close`,label:`Close diff`,get onClick(){return e.onClose}}),null),y(p,n(l,{get when(){return!t.loading},get fallback(){return kU()},get children(){return n(l,{get when(){return!t.error},get fallback(){return(()=>{var e=AU();return y(e,(()=>{var e=r(()=>t.error?.message===`No changes for that file`);return()=>e()?`This file has no changes any more.`:`Could not load the diff: ${t.error?.message}`})()),e})()},get children(){return n(l,{get when(){return t()?.patch},get fallback(){return jU()},get children(){return[(()=>{var e=TU(),i=e.firstChild;return y(i,n(m,{get each(){return KV(t().patch).filter(e=>e.type!==`meta`)},children:e=>(()=>{var t=MU(),n=t.firstChild,i=n.nextSibling,a=i.nextSibling,o=a.firstChild;return y(n,()=>e.oldNo??``),y(i,()=>e.newNo??``),y(o,(()=>{var t=r(()=>e.type===`add`);return()=>t()?`+`:e.type===`del`?`−`:` `})()),y(a,()=>e.text,null),s(()=>k(t,e.type)),t})()})),e})(),n(l,{get when(){return t().truncated},get children(){return EU()}})]}})}})}})),s(t=>{var n=`Changes in ${e.file}`,r=`diff-body${i()?` wrap`:``}`;return n!==t.e&&b(o,`aria-label`,t.e=n),r!==t.t&&k(p,t.t=r),t},{e:void 0,t:void 0}),s(()=>u.value=e.file),s(()=>f.checked=i()),o})()}z([`click`]);function BU(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 VU(e,t){return e&&(e.type===`number`||e.type===`integer`)&&typeof t==`string`&&t.trim()?Number(t):typeof t==`string`?t.trim():t}function HU(e,t){let n=new Map(e.map(e=>[e.key,e]));return e.filter(e=>(e.when??[]).every(e=>{let r=VU(n.get(e.key),t[e.key])===e.value;return e.op===`eq`?r:!r}))}var UU=e=>typeof e==`string`?e.trim():``;function WU(e,t){let n={};for(let r of HU(e,t)){let e=GU(r,t[r.key]);e&&(n[r.key]=e)}return n}function GU(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=UU(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=UU(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 KU(e,t){let n={};for(let r of HU(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=UU(e);if(!t)continue;n[r.key]=r.type===`number`||r.type===`integer`?Number(t):t}}}return n}var qU=I(`<p class="muted small"data-answer-unavailable> can't take this answer from the hub; answer it in the terminal.`),JU=I(`<p class="blocker-recommendation small"data-recommendation>`),YU=I(`<p class=blocker-text>`),XU=I(`<div role=group><p class=blocker-head><strong>`),ZU=I(`<p class="muted small">This question has nothing to fill in here; answer it in the terminal.`),QU=I(`<p class="answered-by small muted"data-answered-by>`),$U=I(`<div class=row><button type=button class="btn small primary">Allow once</button><button type=button class="btn small">Always allow</button><button type=button class="btn small danger">Deny`),eW=I(`<form class=form-card novalidate><fieldset><div class=row><button type=submit class="btn small primary"></button><button type=button class="btn small">Dismiss`),tW=I(`<p class="field-error small"role=alert>`),nW=I(`<div>`),rW=I(`<span class=field-title>`),iW=I(`<span class="field-desc muted small">`),aW=I(`<a class="btn small"target=_blank rel="noopener noreferrer">Open link`),oW=I(`<label class=check><input type=checkbox>`),sW=I(`<input type=text placeholder="Other (comma separated)">`),cW=I(`<div role=group class=choice-group>`),lW=I(`<input type=text placeholder="Type your own answer">`),uW=I(`<div role=radiogroup class=choice-group>`),dW=I(`<label class=text-field>`),fW=I(`<input type=text>`),pW=I(`<span class="muted small"> — `),mW=I(`<label class=choice><input type=checkbox><span>`),hW=I(`<label class=choice><input type=radio><span>`);function gW(e,t){return!(e instanceof W)||e.status!==409||e.code!==`gone`?!1:(q(`Already answered or expired`),t(),!0)}function _W(e){let[t,i]=u(!1),a=()=>e.blocker,c=()=>a().sessionID&&a().sessionID!==e.rootID?` (${a().sessionTitle||`subagent`})`:``,d=()=>a().kind===`permission`?`Permission request`:`Question`;return n(l,{get when(){return!t()},get children(){var t=XU(),u=t.firstChild,f=u.firstChild;return y(f,(()=>{var e=r(()=>a().kind===`permission`);return()=>e()?`Permission`:a().question?`Question`:`Form`})()),y(u,c,null),y(t,n(v,{get fallback(){return ZU()},get children(){return[n(o,{get when(){return e.canAnswer===!1},get children(){return[n(yg,{get class(){return`blocker-text${a().kind===`permission`?` mono`:``}`},get text(){return a().summary},what:`the request`,get reveal(){return a().kind===`permission`}}),(()=>{var t=qU(),n=t.firstChild;return y(t,()=>e.harnessName??`This harness`,n),t})()]}}),n(o,{get when(){return a().kind===`permission`},get children(){return[n(yg,{class:`blocker-text mono`,get text(){return a().summary},what:`the request`,reveal:!0}),n(l,{get when(){return Dt(a().recommendation,Bu)},get children(){var e=JU();return y(e,()=>Dt(a().recommendation,Bu)),e}}),n(vW,{get sessionID(){return e.sessionID},get blocker(){return a()},onGone:()=>i(!0)})]}}),n(o,{get when(){return r(()=>a().kind===`form`)()&&a().fields?.length},get children(){return[n(l,{get when(){return!a().question||a().summary!==`Questions`},get children(){var e=YU();return y(e,()=>a().summary),e}}),n(yW,{get sessionID(){return e.sessionID},get blocker(){return a()},get fields(){return a().fields},onGone:()=>i(!0)})]}})]}}),null),y(t,n(l,{get when(){return en(Tu(),a().id,Bu,ju)},children:e=>(()=>{var t=QU();return y(t,()=>e().text),s(()=>b(t,`title`,e().title)),t})()}),null),s(e=>{var n=`card blocker ${a().kind}`,r=`${d()}: ${a().summary}`;return n!==e.e&&k(t,e.e=n),r!==e.t&&b(t,`aria-label`,e.t=r),e},{e:void 0,t:void 0}),t}})}function vW(e){let[t,n]=u(!1),r=async t=>{n(!0);try{await V(`${H(e.sessionID)}/permission`,{method:`POST`,json:{requestID:e.blocker.id,decision:t}}),q(t===`reject`?`Denied`:`Allowed`)}catch(t){gW(t,e.onGone)||q(oB(t)??U(t),`err`),n(!1)}};return(()=>{var e=$U(),n=e.firstChild,i=n.nextSibling,a=i.nextSibling;return n.$$click=()=>void r(`once`),i.$$click=()=>void r(`always`),a.$$click=()=>void r(`reject`),s(e=>{var r=t(),o=t(),s=t();return r!==e.e&&(n.disabled=e.e=r),o!==e.t&&(i.disabled=e.t=o),s!==e.a&&(a.disabled=e.a=s),e},{e:void 0,t:void 0,a:void 0}),e})()}function yW(e){let[t,r]=u(BU(e.fields)),[i,a]=u({}),[o,c]=u(!1),[d,f]=u(!1),p=C((n=[])=>{let r=HU(e.fields,t()).map(e=>e.key);return r.length===n.length&&r.every((e,t)=>e===n[t])?n:r}),h=t=>e.fields.find(e=>e.key===t),g=(e,t)=>{r(n=>({...n,[e]:t})),i()[e]&&a(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e)))},_=async(t,n)=>{c(!0);try{await V(`${H(e.sessionID)}/form`,{method:`POST`,json:{formID:e.blocker.id,...t}}),f(!0),q(n)}catch(t){gW(t,e.onGone)||q(oB(t)??U(t),`err`),c(!1)}},v=n=>{n.preventDefault();let r=WU(e.fields,t());if(a(r),Object.keys(r).length)return;let i=KU(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`):_({answer:i},`Answer sent`)},x=()=>o()||d();return(()=>{var r=eW(),a=r.firstChild,o=a.firstChild,c=o.firstChild,u=c.nextSibling;return r.addEventListener(`submit`,v),y(a,n(m,{get each(){return p()},children:r=>n(l,{get when(){return h(r)},children:a=>(()=>{var o=nW();return b(o,`data-key`,r),y(o,n(bW,{get field(){return a()},get value(){return t()[r]},onChange:e=>g(r,e),get formID(){return e.blocker.id}}),null),y(o,n(l,{get when(){return i()[r]},get children(){var e=tW();return y(e,()=>i()[r]),e}}),null),s(()=>k(o,`form-field ${a().type}`)),o})()})}),o),y(c,()=>d()?`Sent`:`Submit`),u.$$click=()=>void _({cancel:!0},`Dismissed`),s(()=>a.disabled=x()),r})()}function bW(e){let t=()=>e.field,i=()=>`f-${e.formID}-${t().key}`,a=()=>t().title||t().key,c=()=>typeof e.value==`string`?e.value:``,u=()=>Array.isArray(e.value)?e.value:[],d=()=>new Set((t().options??[]).map(e=>e.value)),f=()=>[(()=>{var e=rW();return y(e,a,null),y(e,()=>t().required?` *`:``,null),e})(),n(l,{get when(){return t().description},get children(){var e=iW();return y(e,()=>t().description),e}})];return n(v,{get children(){return[n(o,{get when(){return t().type===`external`},get children(){return[n(f,{}),(()=>{var e=aW();return s(()=>b(e,`href`,t().url)),e})()]}}),n(o,{get when(){return t().type===`boolean`},get children(){var t=oW(),r=t.firstChild;return r.addEventListener(`change`,t=>e.onChange(t.currentTarget.checked)),y(t,n(f,{}),null),s(()=>r.checked=e.value===!0),t}}),n(o,{get when(){return t().type===`multiselect`},get children(){var r=cW();return y(r,n(f,{}),null),y(r,n(m,{get each(){return t().options??[]},children:t=>(()=>{var r=mW(),i=r.firstChild,a=i.nextSibling;return i.addEventListener(`change`,n=>e.onChange(n.currentTarget.checked?[...u(),t.value]:u().filter(e=>e!==t.value))),y(a,()=>t.label),y(r,n(l,{get when(){return t.description},get children(){var e=pW();return e.firstChild,y(e,()=>t.description,null),e}}),null),s(()=>i.checked=u().includes(t.value)),r})()}),null),y(r,n(l,{get when(){return t().custom},get children(){var t=sW();return t.addEventListener(`change`,t=>e.onChange([...u().filter(e=>d().has(e)),...t.currentTarget.value.split(`,`).map(e=>e.trim()).filter(Boolean)])),s(()=>b(t,`aria-label`,`${a()}: other`)),s(()=>t.value=u().filter(e=>!d().has(e)).join(`, `)),t}}),null),s(()=>b(r,`aria-label`,a())),r}}),n(o,{get when(){return r(()=>t().type===`string`)()&&t().options?.length},get children(){var r=uW();return y(r,n(f,{}),null),y(r,n(m,{get each(){return t().options??[]},children:t=>(()=>{var r=hW(),a=r.firstChild,o=a.nextSibling;return a.addEventListener(`change`,()=>e.onChange(t.value)),y(o,()=>t.label),y(r,n(l,{get when(){return t.description},get children(){var e=pW();return e.firstChild,y(e,()=>t.description,null),e}}),null),s(()=>b(a,`name`,i())),s(()=>a.checked=c()===t.value),r})()}),null),y(r,n(l,{get when(){return t().custom},get children(){var t=lW();return t.$$input=t=>e.onChange(t.currentTarget.value),s(()=>b(t,`aria-label`,`${a()}: your own answer`)),s(()=>t.value=d().has(c())?``:c()),t}}),null),s(()=>b(r,`aria-label`,a())),r}}),n(o,{when:!0,get children(){return[(()=>{var e=dW();return y(e,n(f,{})),s(()=>b(e,`for`,i())),e})(),(()=>{var n=fW();return n.$$input=t=>e.onChange(t.currentTarget.value),s(e=>{var r=i(),a=t().type===`number`||t().type===`integer`?`decimal`:void 0,o=t().placeholder??``;return r!==e.e&&b(n,`id`,e.e=r),a!==e.t&&b(n,`inputmode`,e.t=a),o!==e.a&&b(n,`placeholder`,e.a=o),e},{e:void 0,t:void 0,a:void 0}),s(()=>n.value=c()),n})()]}})]}})}z([`click`,`input`]);var xW=I(`<span class=file-chip> `),SW=I(`<button type=button class="icon-btn msg-more"aria-label="Copy, fork or revert"title="Copy, fork (here or beside) or revert"aria-haspopup=true>`),CW=I(`<div class=pill>`),wW=I(`<p class="msg-note muted small"data-answered-note>`),TW=I(`<div><div class=user-body>`),EW=I(`<div class=msg-images>`),DW=I(`<div class=msg-tools role=toolbar aria-label="Copy, fork, revert">`),OW=I(`<span>`),kW=I(`<div class=transcript aria-label=Conversation>`),AW=I(`<div>`),jW=I(`<p class="note sys turn-denied">`),MW=I(`<span class=turn-error-status>`),NW=I(`<div class=turn-error-message>`),PW=I(`<div class="msg turn-error"role=group><span class=turn-error-mark aria-hidden=true>✕</span><div class=turn-error-body><div class=turn-error-head><strong class=turn-error-label>`),FW=I(`<p><span class=turn-retry-mark aria-hidden=true>↻</span><span>`),IW=I(`<a><span class=sub-mark aria-hidden=true></span><span class=sub-label>Subagent · <strong></strong></span><span class="sub-state muted">`),LW=I(`<span class=spinner>`),RW=I(`<span class=hub-msg-kind>`),zW=I(`<span class="hub-msg-state muted">`),BW=I(`<span class="hub-msg-delivery muted"title="Not delivered into a turn yet: the recipient's harness takes it at its next step">`),VW=I(`<div role=group><div class=hub-msg-head><span class=hub-msg-mark aria-hidden=true></span><span class=hub-msg-label></span></div><div class=hub-msg-text>`),HW=I(`<div class="fold-body hub-msg-text">`),UW=I(`<div><button type=button class=fold-head><span class=hub-msg-mark aria-hidden=true>⇄</span><span>`),WW=I(`<a>`),GW=I(`<span class="spinner small">`),KW=I(`<div class="fold thought"><button type=button class=fold-head><span>`),qW=I(`<ul class="fold-body tool-list">`),JW=I(`<div><button type=button class=fold-head><span>`),YW=I(`<pre class=code>`),XW=I(`<div class=tool-detail>`),ZW=I(`<li><button type=button class=tool-head><span class=tool-mark></span><span class=tool-name></span><span class="tool-summary muted"></span><span class="tool-time muted">`),QW=I(`<span class="muted small">Loading full details…`),$W=I(`<span class="error small">`),eG=I(`<span class="muted small">No details for this call yet.`),tG={pending:[`…`,`Sending`],sent:[`✓`,`Sent`],queued:[`◷`,`Queued: the harness takes it at its next step`],heard:[`✓✓`,`Heard by the agent`],failed:[`!`,`Not sent`]};function nG(e){return n(l,{get when(){return e.image.src},get fallback(){return(()=>{var t=xW(),r=t.firstChild;return y(t,n(L,{name:`file`}),r),y(t,()=>e.image.name,null),s(()=>b(t,`title`,e.image.mime)),t})()},get children(){return n(Fn,{get image(){return e.image},class:`msg-image`,get onOpen(){return e.onOpen}})}})}var rG=500;function iG(e){let[t,a]=u(!1),o,c=()=>clearTimeout(o),d=t=>{t.pointerType===`touch`&&e.actions&&(c(),o=setTimeout(()=>a(!0),rG))},f=(e,t)=>()=>{a(!1),e.enabled&&t()};return(()=>{var o=TW(),u=o.firstChild;return i(o,_({get class(){return`msg user${t()?` tools-open`:``}`},get"data-key"(){return e.block.key}},()=>e.block.messageID?{"data-message":e.block.messageID}:{},{onPointerDown:d,onPointerUp:c,onPointerCancel:c,onPointerLeave:c,onFocusOut:e=>!e.currentTarget.contains(e.relatedTarget)&&a(!1),onKeyDown:e=>{if(e.key!==`Escape`)return;let n=e.target?.closest?.(`.msg-tools`);(t()||n)&&(a(!1),n&&e.currentTarget.querySelector(`.msg-more`)?.focus(),e.stopPropagation())}}),!1,!0),y(o,n(l,{get when(){return e.actions},get children(){var r=SW();return r.$$click=e=>{let n=!t(),r=e.currentTarget;a(n),n&&e.detail===0&&queueMicrotask(()=>r.closest(`.msg`)?.querySelector(`.msg-tools button`)?.focus())},y(r,n(L,{name:`more`})),s(n=>{var i=t(),a=`msg-tools-${e.block.key}`;return i!==n.e&&b(r,`aria-expanded`,n.e=i),a!==n.t&&b(r,`aria-controls`,n.t=a),n},{e:void 0,t:void 0}),r}}),u),y(u,n(l,{get when(){return e.block.images?.length},get children(){return n(zn,{get images(){return e.block.images??[]},children:t=>(()=>{var r=EW();return y(r,n(m,{get each(){return e.block.images},children:e=>n(nG,{image:e,onOpen:()=>t(e.key)})})),r})()})}}),null),y(u,n(l,{get when(){return e.block.text},get children(){var t=CW();return y(t,()=>e.block.text),t}}),null),y(u,n(l,{get when(){return e.block.note},get children(){var t=wW();return y(t,()=>e.block.note),t}}),null),y(u,n(l,{get when(){return e.actions},children:t=>(()=>{var i=DW();return y(i,n(F,{icon:`copy`,label:`Copy`,"data-action":`copy`,onClick:()=>(a(!1),t().onCopy(e.block.text))}),null),y(i,n(l,{get when(){return e.block.messageID},children:i=>[n(F,{icon:`fork`,get label(){return r(()=>!!t().fork.enabled)()?`Fork: a new session with the conversation up to here`:t().fork.reason??`Fork is not available`},"data-action":`fork`,get"aria-disabled"(){return!t().fork.enabled},get onClick(){return f(t().fork,()=>t().onFork(i(),e.block.text))}}),n(l,{get when(){return t().onForkBeside},children:a=>n(F,{icon:`split`,get label(){return r(()=>!!t().fork.enabled)()?`Fork and open beside: the new session in a pane next to this one`:t().fork.reason??`Fork is not available`},"data-action":`fork-beside`,get"aria-disabled"(){return!t().fork.enabled},get onClick(){return f(t().fork,()=>a()(i(),e.block.text))}})}),n(F,{icon:`undo`,get label(){return r(()=>!!t().revert.enabled)()?`Revert: undo from here on (restores the files)`:t().revert.reason??`Revert is not available`},"data-action":`revert`,get"aria-disabled"(){return!t().revert.enabled},get onClick(){return f(t().revert,()=>t().onRevert(i(),e.block.text))}})]}),null),s(()=>b(i,`id`,`msg-tools-${e.block.key}`)),i})()}),null),y(o,n(l,{get when(){return e.tick},children:e=>(()=>{var t=OW();return y(t,()=>tG[e()][0]),s(n=>{var r=`tick ${e()}`,i=tG[e()][1],a=tG[e()][1];return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`aria-label`,n.t=i),a!==n.a&&b(t,`title`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),o})()}function aG(e){return n(In,{get children(){return n(oG,e)}})}function oG(e){let t=C(()=>e.previews?CM(e.blocks,e.partialMessage):void 0),i=(n,r)=>{let i=t()?.get(n);return i?{sessionID:e.sessionID,messageID:i.messageID,base:i.base}:e.previews&&r&&r===e.partialMessage?{sessionID:e.sessionID,messageID:r,base:0,waiting:!0}:void 0},a=C(()=>new Map(e.blocks.map(e=>[e.key,e]))),c=C(()=>e.blocks.map(e=>e.key),void 0,{equals:(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n])});return(()=>{var t=kW();return y(t,n(m,{get each(){return c()},children:t=>{let c,u=C(()=>c=a().get(t)??c),d=e=>{let t=u();return t.type===e?t:void 0};return n(v,{get children(){return[n(o,{get when(){return d(`user`)},children:t=>n(iG,{get block(){return t()},get tick(){return e.ticks[t().key]},get actions(){return e.actions}})}),n(o,{get when(){return d(`assistant`)},children:t=>(()=>{var a=AW();return y(a,n(GN.Provider,{get value(){return e.sessionID},get children(){return n(aF,{get text(){return t().text},get streaming(){return t().live},get preview(){return i(t().key,t().messageID)},get images(){return r(()=>!!e.previews)()?t().media:void 0},links:!0})}})),s(e=>{var n=`msg assistant${t().live?` live`:``}`,r=t().key;return n!==e.e&&k(a,e.e=n),r!==e.t&&b(a,`data-key`,e.t=r),e},{e:void 0,t:void 0}),a})()}),n(o,{get when(){return d(`thought`)},children:t=>n(cG,{get block(){return t()},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})}),n(o,{get when(){return d(`tools`)},children:t=>n(lG,{get block(){return t()},get sessionID(){return e.sessionID},get onDetail(){return e.onDetail},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})}),n(o,{get when(){return d(`message`)},children:t=>n(sG,{get block(){return t()},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})}),n(o,{get when(){return r(()=>!!d(`error`)?.denied)()&&d(`error`)},children:e=>(()=>{var t=jW();return y(t,()=>e().label),s(()=>b(t,`data-key`,e().key)),t})()}),n(o,{get when(){return d(`error`)},children:e=>(()=>{var t=PW(),r=t.firstChild.nextSibling,i=r.firstChild,a=i.firstChild;return y(a,()=>e().label),y(i,n(l,{get when(){return e().status},get children(){var t=MW();return y(t,()=>e().status),t}}),null),y(r,n(l,{get when(){return e().message},get children(){var t=NW();return y(t,()=>e().message),t}}),null),s(n=>{var r=e().key,i=`Error: ${e().label}`;return r!==n.e&&b(t,`data-key`,n.e=r),i!==n.t&&b(t,`aria-label`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(o,{get when(){return d(`retry`)},children:e=>{let t=()=>kB(e(),se());return(()=>{var n=FW(),r=n.firstChild.nextSibling;return y(r,()=>t().text),s(r=>{var i=`msg turn-retry${t().waiting?` waiting`:``}`,a=e().key;return i!==r.e&&k(n,r.e=i),a!==r.t&&b(n,`data-key`,r.t=a),r},{e:void 0,t:void 0}),n})()}}),n(o,{get when(){return d(`subagent`)},children:e=>(()=>{var t=IW(),i=t.firstChild,a=i.nextSibling,o=a.firstChild.nextSibling,c=a.nextSibling;return y(i,(()=>{var t=r(()=>e().state===`working`);return()=>t()?LW():`◆`})()),y(o,()=>e().label),y(c,()=>e().state),y(t,n(L,{name:`chevron`,class:`chev`}),null),s(n=>{var r=`subagent ${e().state}`,i=Ot(e().sessionID),a=e().key;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`href`,n.t=i),a!==n.a&&b(t,`data-key`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})]}})}})),t})()}function sG(e){let t=()=>!!e.expanded[e.block.key];return n(l,{get when(){return r(()=>!e.block.primer)()&&!e.block.summary},get fallback(){return(()=>{var r=UW(),a=r.firstChild,o=a.firstChild.nextSibling;return i(r,_({get class(){return`fold hub-note${e.block.summary?` hub-update`:``}`},get"data-key"(){return e.block.key}},()=>e.block.summary?{"data-concierge-update":``}:{}),!1,!0),a.$$click=()=>e.onToggle(e.block.key,!t()),y(o,()=>e.block.summary??e.block.label),y(a,n(L,{name:`chevron`,class:`chev`}),null),y(r,n(l,{get when(){return t()},get children(){var t=HW();return y(t,()=>e.block.text),t}}),null),s(n=>{var r=t(),i=e.block.summary?`Sent by the hub, not by you: show the full update`:void 0;return r!==n.e&&b(a,`aria-expanded`,n.e=r),i!==n.t&&b(a,`title`,n.t=i),n},{e:void 0,t:void 0}),r})()},get children(){var t=VW(),r=t.firstChild,i=r.firstChild,a=i.nextSibling,o=r.nextSibling;return y(i,()=>e.block.direction===`out`?`↗`:`↘`),y(r,n(l,{get when(){return e.block.kind!==`msg`},get children(){var t=RW();return y(t,()=>e.block.kind),t}}),a),y(a,()=>Be(e.block.label,Bu)),y(r,n(l,{get when(){return e.block.state===`open`||e.block.state===`answered`||e.block.state===`declined`||e.block.state===`expired`},get children(){var t=zW();return y(t,()=>e.block.state),t}}),null),y(r,n(l,{get when(){return e.block.delivery},get children(){var t=BW();return y(t,()=>e.block.delivery),s(()=>b(t,`data-delivery`,e.block.delivery)),t}}),null),y(o,n(l,{get when(){return e.block.parts},get fallback(){return e.block.text},children:e=>n(m,{get each(){return e()},children:e=>e.href?(()=>{var t=WW();return y(t,()=>e.text),s(()=>b(t,`href`,e.href)),t})():e.text})})),s(n=>{var r=`msg hub-msg ${e.block.direction}`,i=e.block.key,o=`Hub ${e.block.kind} ${Be(e.block.label,Bu)}`,s=e.block.label;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`data-key`,n.t=i),o!==n.a&&b(t,`aria-label`,n.a=o),s!==n.o&&b(a,`title`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t}})}function cG(e){let t=()=>!!e.expanded[e.block.key],r=t=>e.onToggle(e.block.key,t),i=()=>MB(e.block);return(()=>{var a=KW(),o=a.firstChild,c=o.firstChild;return o.$$click=()=>r(!t()),y(o,n(l,{get when(){return e.block.running},get children(){return GW()}}),c),y(c,()=>i().label),y(o,n(L,{name:`chevron`,class:`chev`}),null),y(a,n(l,{get when(){return t()},get children(){var e=AW();return y(e,()=>i().body),s(()=>k(e,`fold-body reasoning${i().muted?` hidden-reasoning`:``}`)),e}}),null),s(n=>{var r=e.block.key,i=t();return r!==n.e&&b(a,`data-key`,n.e=r),i!==n.t&&b(o,`aria-expanded`,n.t=i),n},{e:void 0,t:void 0}),a})()}function lG(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=JW(),o=i.firstChild,c=o.firstChild;return o.$$click=()=>r(!t()),y(o,n(l,{get when(){return e.block.running},get children(){return GW()}}),c),y(c,a),y(o,n(L,{name:`chevron`,class:`chev`}),null),y(i,n(l,{get when(){return e.block.media?.length},get children(){return n(Rn,{get images(){return e.block.media},label:`Tool images`})}}),null),y(i,n(l,{get when(){return t()},get children(){var t=qW();return y(t,n(m,{get each(){return e.block.items},children:t=>n(uG,{row:t,get sessionID(){return e.sessionID},get onDetail(){return e.onDetail},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})})),t}}),null),s(n=>{var r=`fold tools${e.block.failed?` has-failed`:``}`,a=e.block.key,s=t();return r!==n.e&&k(i,n.e=r),a!==n.t&&b(i,`data-key`,n.t=a),s!==n.a&&b(o,`aria-expanded`,n.a=s),n},{e:void 0,t:void 0,a:void 0}),i})()}function uG(e){let t=()=>!!e.expanded[`tool:${e.row.key}`],i=t=>e.onToggle(`tool:${e.row.key}`,t),[a,o]=u(!1),[c,d]=u(``),f=()=>e.row,p=()=>f().completed&&f().at?qa(f().completed-f().at):``,m=async()=>{let n=!t();if(i(n),n&&f().detail===void 0&&f().messageID&&f().partID!==void 0){o(!0),d(``);try{let t=await G(`${H(e.sessionID)}/timeline/messages/${K(f().messageID)}/parts/${K(String(f().partID))}`);e.onDetail(f().key,t.detail)}catch(e){d(U(e))}finally{o(!1)}}},h=()=>typeof f().summary==`string`?f().summary:``;return(()=>{var e=ZW(),i=e.firstChild,o=i.firstChild,u=o.nextSibling,d=u.nextSibling,g=d.nextSibling;return i.$$click=m,y(o,(()=>{var e=r(()=>f().state===`running`);return()=>e()?GW():f().state===`failed`?`✕`:`✓`})()),y(u,()=>f().name??`tool`),y(d,h),y(g,p),y(e,n(l,{get when(){return t()},get children(){var e=XW();return y(e,n(l,{get when(){return!a()},get fallback(){return QW()},get children(){return n(l,{get when(){return!c()},get fallback(){return(()=>{var e=$W();return y(e,c),e})()},get children(){return n(l,{get when(){return f().detail!==void 0||h()||f().error},get fallback(){return eG()},get children(){var e=YW();return y(e,()=>PB(f().detail,{summary:h(),error:f().error})),e}})}})}})),e}}),null),s(n=>{var r=`tool ${f().state??``}`,a=t(),s=f().state??``;return r!==n.e&&k(e,n.e=r),a!==n.t&&b(i,`aria-expanded`,n.t=a),s!==n.a&&b(o,`aria-label`,n.a=s),n},{e:void 0,t:void 0,a:void 0}),e})()}z([`click`]);var dG={profilesPerUser:200,versionsPerProfile:100,skillsPerProfile:32,commandsPerProfile:64,instructionsChars:32e3,skillChars:32e3,commandChars:8e3,versionBytes:524288,projectsPerProfile:16},fG=[`pending`,`applied`,`partial`,`rejected`,`unsupported`,`restart_required`];function pG(e){if(!Fe(e))return`content must be an object`;if(e.instructions!==void 0&&!ze(e.instructions,dG.instructionsChars))return`instructions must be at most ${dG.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,dG.skillsPerProfile,dG.skillChars,`body`,`skills`],[e.commands,dG.commandsPerProfile,dG.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(!Fe(n)||!Le(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),!wt(n.description,300))return`${a}.${n.name}.description must be 1–300 characters`;if(!ze(n[i],r)||n[i].trim()===``)return`${a}.${n.name}.${i} must be 1–${r} characters`}}if(new TextEncoder().encode(JSON.stringify(e)).length>dG.versionBytes)return`profile version is too large`}function mG(e){if(e===void 0)return;let t=dG.projectsPerProfile;if(!Array.isArray(e)||e.length>t||!e.every(e=>wt(e))||new Set(e).size!==e.length)return`projects must be at most ${t} unique project names`}function hG(e){return Fe(e)?Le(e.name)?wt(e.title)?e.description!==void 0&&!ze(e.description,4e3)?`description must be at most ${Et} characters`:Ee(e.tags)??Ue(e.metadata)??mG(e.projects)??pG(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 gG(e){return Array.isArray(e)?`[${e.map(gG).join(`,`)}]`:Fe(e)?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${gG(e[t])}`).join(`,`)}}`:JSON.stringify(e)}var _G=/^[a-z][a-z0-9_]{0,39}$/,vG=/^[A-Z][A-Z0-9_]{0,63}$/,yG=`secret:`;function bG(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(yG)){if(!vG.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(!_G.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`,xG=e=>typeof e==`number`&&Number.isFinite(e),SG=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=1,CG=e=>Array.isArray(e)?e.filter($):[];function wG(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 TG(e){if(Q(e)&&$(e.id)&&$(e.name)&&$(e.title)&&SG(e.latestVersion)&&xG(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:CG(e.tags),metadata:Q(e.metadata)?Object.fromEntries(Object.entries(e.metadata).filter(e=>$(e[1]))):{},projects:CG(e.projects),latestVersion:e.latestVersion,revision:e.revision,updatedAt:xG(e.updatedAt)?e.updatedAt:0}}var EG=e=>wG(e,TG),DG=[`sessions`,`online`,`olderVersion`,`teamRoles`,`staffedSeats`,`launches`,`liveLaunches`];function OG(e){if(!Q(e))return;let t={};for(let n of DG)xG(e[n])&&(t[n]=e[n]);return Array.isArray(e.teams)&&(t.teams=CG(e.teams)),Array.isArray(e.harnesses)&&(t.harnesses=CG(e.harnesses)),t}function kG(e){if(Q(e)&&SG(e.version)&&xG(e.skills)&&xG(e.commands))return{version:e.version,skills:e.skills,commands:e.commands,instructions:e.instructions===!0}}function AG(e){let t=EG(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?OG(n[e.id]):void 0,i=r?kG(r[e.id]):void 0;return{profile:e,...t?{usage:t}:{},...i?{summary:i}:{}}}),...t.cursor?{cursor:t.cursor}:{}}}var jG=e=>!!e&&((e.sessions??0)>0||(e.teamRoles??0)>0||(e.launches??0)>0);function MG(e){if(!e)return[];let t=[];e.sessions&&t.push(_n(e.sessions,`session`)),e.teamRoles&&t.push(_n(e.teamRoles,`team role`)),e.launches&&t.push(_n(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 NG=e=>[...new Set(e)].sort();function PG(e){return{tags:NG(e.flatMap(e=>e.profile.tags)),projects:NG(e.flatMap(e=>e.profile.projects)),teams:NG(e.flatMap(e=>e.usage?.teams??[])),harnesses:NG(e.flatMap(e=>e.usage?.harnesses??[]))}}function FG(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`===jG(e.usage)))}var IG=e=>(e?.sessions??0)+(e?.teamRoles??0)+(e?.launches??0),LG=(e,t)=>e.profile.name<t.profile.name?-1:+(e.profile.name>t.profile.name);function RG(e,t){let n=[...e];return t===`updated`?n.sort((e,t)=>t.profile.updatedAt-e.profile.updatedAt||LG(e,t)):t===`usage`?n.sort((e,t)=>IG(t.usage)-IG(e.usage)||LG(e,t)):n.sort(LG)}var zG=[`sessions`,`teams`,`launches`,`workspaces`];function BG(e){if(!Q(e)||!$(e.sessionID)||!SG(e.version)||!xG(e.revision))return;let t=Q(e.effective)&&SG(e.effective.version)?e.effective.version:void 0,n=Q(e.ack)&&fG.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,...xG(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 VG(e){if(!Q(e)||!$(e.profileID)||!SG(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:{...OG(e.counts),...Q(e.counts)&&xG(e.counts.workspaces)?{workspaces:e.counts.workspaces}:{}},sessions:(n&&Array.isArray(n.items)?n.items:[]).flatMap(e=>BG(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}:{},...SG(e.version)?{version:e.version}:{},...xG(e.staffed)?{staffed:e.staffed}:{}})),launches:t(e.launches).filter(e=>$(e.id)&&$(e.state)&&SG(e.version)).map(e=>({id:e.id,state:e.state,...$(e.outcome)?{outcome:e.outcome}:{},version:e.version,...$(e.sessionID)?{sessionID:e.sessionID}:{},created:xG(e.created)?e.created:0,updated:xG(e.updated)?e.updated:0})),workspaces:t(e.workspaces).filter(e=>$(e.workspaceID)).map(e=>({workspaceID:e.workspaceID,...$(e.title)?{title:e.title}:{},sessions:xG(e.sessions)?e.sessions:0})),projects:CG(e.projects),hidden:CG(e.hidden).filter(e=>zG.includes(e)),truncated:CG(e.truncated)}}var HG=(e,t)=>t?`/teams/${encodeURIComponent(e)}`:`/watchtower?group=team&team=${encodeURIComponent(e)}`;function UG(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=Ue(n)??mG(r);return i?{ok:!1,error:i}:{ok:!0,patch:{metadata:Object.keys(n).length?n:null,projects:r.length?r:null}}}function WG(e){if(!Q(e)||!$(e.profileID)||!SG(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:xG(e.createdAt)?e.createdAt:0,bytes:xG(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:CG(e.params)}]:[]}),secretRefs:CG(e.secretRefs)}}function GG(e){if(Q(e)&&SG(e.version)&&$(e.digest))return{version:e.version,digest:e.digest,bytes:xG(e.bytes)?e.bytes:0,createdAt:xG(e.createdAt)?e.createdAt:0}}var KG=e=>wG(e,GG);function qG(e){let t=Q(e)?e.version:void 0;if(!Q(t)||!$(t.profileID)||!SG(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:xG(t.createdAt)?t.createdAt:0,content:r}}function JG(e){if(Q(e)&&fG.includes(e.status)&&$(e.digest))return{status:e.status,digest:e.digest,notes:CG(e.notes),at:xG(e.at)?e.at:0,offline:e.offline===!0}}function YG(e){if(Q(e)&&$(e.profileID)&&SG(e.version)&&$(e.digest)&&(e.status===`applied`||e.status===`partial`))return{profileID:e.profileID,version:e.version,digest:e.digest,status:e.status,at:xG(e.at)?e.at:0}}function XG(e){if(!Q(e)||!$(e.sessionID)||!$(e.profileID)||!SG(e.version)||!xG(e.revision))return;let t=JG(e.ack),n=YG(e.effective);return{sessionID:e.sessionID,profileID:e.profileID,version:e.version,revision:e.revision,...t?{ack:t}:{},...n?{effective:n}:{}}}function ZG(e){if(!Q(e)||!(`assignment`in e))return;if(e.assignment===null)return{assignment:null};let t=XG(e.assignment);if(!t)return;let n=TG(e.profile),r=WG(e.version);return{assignment:t,...n?{profile:n}:{},...r?{version:r}:{}}}var QG={pending:`Pending`,applied:`Applied`,partial:`Partly applied`,rejected:`Rejected`,unsupported:`Unsupported`,restart_required:`Restart required`},$G={applied:`ok`,partial:`warn`,restart_required:`warn`,pending:`pending`,unsupported:`err`,rejected:`err`};function eK(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:$G[r],detail:`${e.profile?.title??n} v${t.version}: ${QG[r]}${t.ack?.offline?` (machine offline)`:``}${s?` · v${s} available`:``}`,requested:t.version,...a===void 0?{}:{effective:a},...s?{upgrade:s}:{}}}function tK(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 nK=`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.`,rK={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.`},iK=e=>rK[e]??`This harness reports what took effect after you pin; presets can't apply profiles.`,aK=()=>({instructions:``,model:``,skills:[],commands:[]}),oK=e=>({instructions:e.instructions??``,model:e.model??``,skills:e.skills.map(e=>({...e})),commands:e.commands.map(e=>({...e}))});function sK(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=pG(r);if(i)return{ok:!1,error:i};for(let e of r.commands){let t=bG(e.template);if(typeof t==`string`)return{ok:!1,error:`commands.${e.name}: ${t}`}}return{ok:!0,content:r}}function cK(e,t){let n=sK(e);return!n.ok||gG(n.content)!==gG(t)}function lK(e,t){let n=sK(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=hG(a);return o?{ok:!1,error:o}:{ok:!0,body:a}}function uK(e){let t=bG(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 dK=4e3;function fK(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 ${dK} characters`};n[r]=e}return{ok:!0,body:{params:n}}}function pK(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 mK=`Control+Alt+P`,hK=e=>e.ctrlKey&&e.altKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyP`,gK=(e,t)=>e?e.endsWith(`
31
+ `)?e+t:`${e}\n${t}`:t,_K=(e,t,n)=>({profileID:e,version:t,expectedRevision:n.assignment?.revision??0});function vK(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 yK=e=>!!e.assignment&&(e.assignment.ack?.status??`pending`)===`pending`,bK=15e3,xK=16,SK=e=>e>=xK?void 0:Math.min(bK,1e3*2**e);function CK(e){let t=e,n=t?.message??String(e);switch(t?.code){case`conflict`:return`Changed elsewhere meanwhile${xG(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 wK=encodeURIComponent,TK=`/api/agent`,EK={list:(e=`active`,t=!0)=>`${TK}/profiles?state=${e}&limit=200${t?`&include=usage,summary`:``}`,usage:(e,t)=>`${TK}/profiles/${wK(e)}/usage?limit=200${t?`&cursor=${wK(t)}`:``}`,create:()=>`${TK}/profiles`,one:e=>`${TK}/profiles/${wK(e)}`,versions:e=>`${TK}/profiles/${wK(e)}/versions`,version:(e,t)=>`${TK}/profiles/${wK(e)}/versions/${t}`,session:e=>`${TK}/sessions/${wK(e)}/profile`,unpin:(e,t)=>`${TK}/sessions/${wK(e)}/profile?expectedRevision=${t}`,render:(e,t)=>`${TK}/sessions/${wK(e)}/profile/commands/${wK(t)}/render`},DK=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,OK=async e=>e.json().catch(()=>({})),kK=async(e=`active`)=>EG(await G(EK.list(e,!1))),AK=async(e=`active`)=>AG(await G(EK.list(e)));async function jK(e,t){let n=VG(await G(EK.usage(e,t)));if(!n)throw Error(`The hub sent an unreadable usage answer`);return n}async function MK(e,t){let n=TG((await OK(await V(EK.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 NK(e){let t=await G(EK.one(e)),n=TG(t.profile);if(!n)throw Error(`The hub sent an unreadable profile`);return{profile:n,latest:WG(t.latest)}}var PK=async e=>KG(await G(`${EK.versions(e)}?limit=200`));async function FK(e,t){let n=qG(await G(EK.version(e,t)));if(!n)throw Error(`The hub sent an unreadable version`);return n}async function IK(e,t){let n=TG((await OK(await V(EK.create(),{method:`POST`,json:e,headers:{"idempotency-key":t}}))).profile);if(!n)throw Error(`The hub sent an unreadable profile`);return n}async function LK(e,t,n){let r=TG((await OK(await V(EK.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 RK(e,t){let n=TG((await OK(await V(EK.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 zK(e){let t=ZG(await G(EK.session(e)));if(!t)throw Error(`The hub sent an unreadable profile pin`);return t}async function BK(e,t){await V(EK.session(e),{method:`PUT`,json:t})}async function VK(e,t){await V(EK.unpin(e,t),{method:`DELETE`})}async function HK(e,t,n){let r=await OK(await V(EK.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 UK=I(`<p class="error small"role=alert>`),WK=I(`<input type=search role=combobox aria-label="Search commands"aria-controls=prof-commands aria-expanded=true placeholder="Type a command…"autofocus>`),GK=I(`<ul class=prof-commands id=prof-commands role=listbox aria-label=Commands>`),KK=I(`<p class=prof-note>Inserted text goes into this session's composer; review it, then send.`),qK=I(`<p class="muted small">No profile is pinned to this session, so it has no commands. Pin one from the session's profile chip.`),JK=I(`<p class="muted small">Loading commands…`),YK=I(`<p class="muted small">`),XK=I(`<li role=option class=prof-command><strong>/</strong><span class=prof-sub>`),ZK=I(`<p class=prof-secret>Uses secret <!> (name only). The console never asks for or sees its value; the session's machine resolves it only when the harness runs the command itself. Inserted text keeps <code></code> as written.`),QK=I(`<form class=stack><p><strong>/</strong> <span class="muted small"></span></p><div class=row><button type=submit class="btn small primary">Insert into composer</button><button type=button class="btn small">Back`),$K=I(`<label><textarea>`);function eq(e){let t=e.view.assignment,[i]=d(async()=>{if(!t)return[];let n=e.view.version?.commands??[];try{return(await FK(t.profileID,t.version)).content.commands.map(e=>{let t=uK(e.template);return{name:e.name,description:e.description,params:`error`in t?[]:t.params,secrets:`error`in t?[]:t.secrets}})}catch{return n.map(e=>({...e,secrets:[]}))}}),[a,o]=u(``),[c,f]=u(0),[p,h]=u(),[g,_]=u({}),[v,x]=u(``),[S,w]=u(!1),T=C(()=>pK(i()??[],a())),E=e=>{e&&(h(e),_({}),x(``),e.params.length?requestAnimationFrame(()=>document.querySelector(`.prof-palette [data-param]`)?.focus()):D(e))},D=async t=>{let n=fK(t.params,g());if(!n.ok)return x(n.error);w(!0),x(``);try{let{prompt:r}=await HK(e.sessionID,t.name,n.body);Ix.set(e.sessionID,gK(Ix.get(e.sessionID),r)),e.onInserted()}catch(e){x(CK(e))}finally{w(!1)}},O=e=>{let t=T().length;e.key===`ArrowDown`&&t?(e.preventDefault(),f((c()+1)%t)):e.key===`ArrowUp`&&t?(e.preventDefault(),f((c()-1+t)%t)):e.key===`Enter`&&(e.preventDefault(),E(T()[c()]))},k=t=>`prof-cmd-${e.sessionID}-${t}`;return n(de,{open:!0,get title(){return`Commands · ${e.title}`},get onClose(){return e.onClose},class:`prof-dialog prof-palette`,get children(){return[n(l,{get when(){return p()},get fallback(){return n(l,{when:t,get fallback(){return qK()},get children(){return[(()=>{var e=WK();return e.$$keydown=O,e.$$input=e=>(o(e.currentTarget.value),f(0)),s(()=>b(e,`aria-activedescendant`,T().length?k(c()):void 0)),s(()=>e.value=a()),e})(),n(l,{get when(){return i()},get fallback(){return JK()},get children(){return n(l,{get when(){return T().length},get fallback(){return(()=>{var n=YK();return y(n,(()=>{var n=r(()=>!!i().length);return()=>n()?`No command matches.`:`${e.view.profile?.name??`This profile`} v${t.version} has no commands.`})()),n})()},get children(){var e=GK();return y(e,n(m,{get each(){return T()},children:(e,t)=>(()=>{var n=XK(),i=n.firstChild;i.firstChild;var a=i.nextSibling;return n.addEventListener(`pointerenter`,()=>f(t())),n.$$click=()=>E(e),y(i,()=>e.name,null),y(a,()=>e.description,null),y(a,(()=>{var t=r(()=>!!e.params.length);return()=>t()?` · asks for ${e.params.join(`, `)}`:``})(),null),y(a,(()=>{var t=r(()=>!!e.secrets.length);return()=>t()?` · uses secret ${e.secrets.join(`, `)}`:``})(),null),s(e=>{var r=k(t()),i=t()===c();return r!==e.e&&b(n,`id`,e.e=r),i!==e.t&&b(n,`aria-selected`,e.t=i),e},{e:void 0,t:void 0}),n})()})),e}})}}),KK()]}})},children:e=>(()=>{var t=QK(),r=t.firstChild,i=r.firstChild;i.firstChild;var a=i.nextSibling.nextSibling,o=r.nextSibling,c=o.firstChild,u=c.nextSibling;return t.addEventListener(`submit`,t=>(t.preventDefault(),void D(e()))),y(i,()=>e().name,null),y(a,()=>e().description),y(t,n(m,{get each(){return e().params},children:e=>(()=>{var t=$K(),n=t.firstChild;return y(t,e,n),n.$$input=t=>_({...g(),[e]:t.currentTarget.value}),b(n,`data-param`,e),b(n,`rows`,e===`arguments`?3:1),s(()=>n.value=g()[e]??``),t})()}),o),y(t,n(l,{get when(){return e().secrets.length},get children(){var t=ZK(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return y(t,()=>e().secrets.join(`, `),n),y(r,()=>`{{secret:${e().secrets[0]}}}`),t}}),o),y(t,n(l,{get when(){return v()},get children(){var e=UK();return y(e,v),e}}),o),u.$$click=()=>h(void 0),s(()=>c.disabled=S()),t})()}),n(l,{get when(){return r(()=>!p())()&&v()},get children(){var e=UK();return y(e,v),e}})]}})}z([`input`,`keydown`,`click`]);var tq=I(`<span class=prof-up aria-hidden=true>↑v`),nq=I(`<button type=button>`),rq=I(`<section aria-label="Pinned profile"><h3>Pinned`),iq=I(`<label>Profile<select aria-label=Profile>`),aq=I(`<label>Version<select aria-label=Version>`),oq=I(`<div class=row><button type=button class="btn small primary">`),sq=I(`<section aria-label="Pin a profile"><h3></h3><p class=prof-note>`),cq=I(`<p class="error small"role=alert>`),lq=I(`<p class="muted small">No profile is pinned to this session.`),uq=I(`<div class=prof-status><span></span><strong class=small>`),dq=I(`<ul class=prof-guidance aria-label="What took effect">`),fq=I(`<p class=prof-note>`),pq=I(`<div class=row><button type=button class="btn small">Unpin</button><button type=button class="btn small">Commands… (Ctrl+Alt+P)`),mq=I(`<li>`),hq=I(`<div class=prof-upgrade><span>v<!> of <!> is available. This session stays on v<!> until you upgrade it.</span><button type=button class="btn small primary">Upgrade to v`),gq=I(`<p class="muted small">`),_q=I(`<p class="muted small">No active profiles. Create one under Agent profiles (/profiles).`),vq=I(`<option> (<!>)`),yq=I(`<option>v`),bq=e=>{let t=Fu(e)?.session.title;return typeof t==`string`&&t?t:`this session`};function xq(e){let[i,a]=u(),[o,c]=u(!0),[d,f]=u(!1),[p,m]=u(!1),h,g,_=0,v=!0,x=async()=>{try{let t=await zK(e.sessionID);if(!v)return;a(t),c(!0),S()}catch(e){if(!v)return;e instanceof W&&(e.status===404||e.status===403)&&c(!1)}},S=()=>{clearTimeout(g);let e=i();if(!e||!yK(e))return void(_=0);let t=SK(_++);t!==void 0&&(g=setTimeout(()=>void x(),t))},C=async()=>{_=0,await x()};fe(()=>void x()),M(()=>{v=!1,clearTimeout(g)}),fe(()=>{let t=t=>{hK(t)&&e.takesInput()&&o()&&i()&&(t.preventDefault(),m(!0))};document.addEventListener(`keydown`,t),M(()=>document.removeEventListener(`keydown`,t))});let w=()=>eK(i()??{assignment:null}),T=()=>h?.closest(`.session-layout`)?.querySelector(`textarea[aria-label="Message"]`)?.focus();return n(l,{get when(){return r(()=>!!o())()&&i()},get children(){return[(()=>{var e=nq();e.$$click=()=>{f(!0),x()};var a=h;return typeof a==`function`?t(a,e):h=e,b(e,`aria-keyshortcuts`,mK),y(e,(()=>{var e=r(()=>!!i().assignment);return()=>e()?w().label:`Profile`})(),null),y(e,n(l,{get when(){return w().upgrade},get children(){var e=tq();return e.firstChild,y(e,()=>w().upgrade,null),e}}),null),s(t=>{var n=`prof-chip ${w().tone}`,r=i().assignment?.ack?.status??`none`,a=`${w().detail}. Commands: ${mK}`,o=i().assignment?`Agent profile: ${w().label}, ${QG[i().assignment.ack?.status??`pending`]}${w().upgrade?`, v${w().upgrade} available`:``}`:`Agent profile: none`;return n!==t.e&&k(e,t.e=n),r!==t.t&&b(e,`data-profile-status`,t.t=r),a!==t.a&&b(e,`title`,t.a=a),o!==t.o&&b(e,`aria-label`,t.o=o),t},{e:void 0,t:void 0,a:void 0,o:void 0}),e})(),n(l,{get when(){return d()},get children(){return n(Sq,{get sessionID(){return e.sessionID},get harness(){return e.harness},get view(){return i()},onClose:()=>f(!1),onChanged:()=>void C(),onCommands:()=>{f(!1),m(!0)}})}}),n(l,{get when(){return p()},get children(){return n(eq,{get sessionID(){return e.sessionID},get title(){return bq(e.sessionID)},get view(){return i()},onClose:()=>m(!1),onInserted:()=>{m(!1),requestAnimationFrame(T)}})}})]}})}function Sq(t){let[i]=d(()=>kK(`active`).then(e=>e.items)),[a,o]=u(t.view.assignment?.profileID??``),[c,f]=u(0),[p,h]=u(``),[g,_]=u(!1);x(()=>{let e=i.error?void 0:i();e?.length&&!e.some(e=>e.id===a())&&o(e[0].id)});let[v]=d(()=>a()||void 0,e=>PK(e).then(e=>e.items));x(e([()=>v.error?void 0:v(),()=>t.view.assignment?.profileID,()=>t.view.assignment?.version],([e])=>{if(!e?.length)return;let n=t.view.assignment;f(n&&n.profileID===a()&&e.some(e=>e.version===n.version)?n.version:e[0].version)}));let S=()=>eK(t.view),C=()=>tK(t.view),w=()=>vK(t.view,a(),c()),T=async(e,n,r)=>{_(!0),h(``);try{await BK(t.sessionID,_K(e,n,t.view)),q(r),t.onChanged()}catch(e){h(CK(e)),t.onChanged()}finally{_(!1)}},E=async()=>{let e=t.view.assignment;if(e){_(!0),h(``);try{await VK(t.sessionID,e.revision),q(`Unpinned. What the session already applied stays until it restarts.`),t.onChanged()}catch(e){h(CK(e)),t.onChanged()}finally{_(!1)}}};return n(de,{open:!0,get title(){return`Agent profile · ${bq(t.sessionID)}`},get onClose(){return t.onClose},class:`prof-dialog`,get children(){return[(()=>{var e=rq();return e.firstChild,y(e,n(l,{get when(){return t.view.assignment},get fallback(){return lq()},children:e=>[(()=>{var t=uq(),n=t.firstChild,r=n.nextSibling;return y(n,()=>S().label),y(r,()=>QG[e().ack?.status??`pending`],null),y(r,()=>e().ack?.offline?` · machine offline`:``,null),s(t=>{var i=`prof-chip ${S().tone}`,a=e().ack?.status??`pending`;return i!==t.e&&k(n,t.e=i),a!==t.t&&b(r,`data-ack`,t.t=a),t},{e:void 0,t:void 0}),t})(),(()=>{var e=dq();return y(e,n(m,{get each(){return C()},children:e=>(()=>{var t=mq();return y(t,e),t})()})),e})(),n(l,{get when(){return S().upgrade},children:n=>(()=>{var r=hq(),i=r.firstChild,a=i.firstChild.nextSibling,o=a.nextSibling.nextSibling,c=o.nextSibling.nextSibling;c.nextSibling;var l=i.nextSibling;return l.firstChild,y(i,n,a),y(i,()=>t.view.profile?.name??`this profile`,o),y(i,()=>e().version,c),l.$$click=()=>void T(e().profileID,n(),`Upgrading to v${n()}…`),y(l,n,null),s(()=>l.disabled=g()),r})()}),(()=>{var e=fq();return y(e,nK),e})(),(()=>{var e=pq(),n=e.firstChild,r=n.nextSibling;return n.$$click=()=>void E(),B(r,`click`,t.onCommands,!0),b(r,`aria-keyshortcuts`,mK),s(()=>n.disabled=g()),e})()]}),null),e})(),(()=>{var e=sq(),u=e.firstChild,d=u.nextSibling;return y(u,()=>t.view.assignment?`Change the pin`:`Pin a profile`),y(d,()=>iK(t.harness)),y(e,n(l,{get when(){return r(()=>!i.error)()&&i()},get fallback(){return(()=>{var e=gq();return y(e,(()=>{var e=r(()=>!!i.error);return()=>e()?CK(i.error):`Loading profiles…`})()),e})()},get children(){return n(l,{get when(){return i().length},get fallback(){return _q()},get children(){return[(()=>{var e=iq(),t=e.firstChild.nextSibling;return t.addEventListener(`change`,e=>o(e.currentTarget.value)),y(t,n(m,{get each(){return i()},children:e=>(()=>{var t=vq(),n=t.firstChild,r=n.nextSibling;return r.nextSibling,y(t,()=>e.title,n),y(t,()=>e.name,r),s(()=>t.value=e.id),t})()})),s(()=>t.value=a()),e})(),(()=>{var e=aq(),t=e.firstChild.nextSibling;return t.addEventListener(`change`,e=>f(Number(e.currentTarget.value))),y(t,n(m,{get each(){return r(()=>!!v.error)()?[]:v()??[]},children:(e,t)=>(()=>{var n=yq();return n.firstChild,y(n,()=>e.version,null),y(n,()=>t()===0?` (latest)`:``,null),s(()=>n.value=String(e.version)),n})()})),s(()=>t.disabled=!!v.error||!v()),s(()=>t.value=String(c())),e})(),(()=>{var e=oq(),t=e.firstChild;return t.$$click=()=>void T(a(),c(),`${w().label}: sent to the session`),y(t,()=>w().label),s(()=>t.disabled=g()||!a()||!c()),e})()]}})}}),null),s(()=>b(d,`data-harness`,t.harness)),e})(),n(l,{get when(){return p()},get children(){var e=cq();return y(e,p),e}})]}})}z([`click`]);var Cq=10;function wq(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 ${Qz(t)} sessions yet`};return{fork:r(`fork`,`Fork`),revert:r(`revert`,`Revert`)}}var Tq=e=>Number.isSafeInteger(e)&&e>=0?e:0;function Eq(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:Tq(t.hidden),...typeof t.at==`number`&&Number.isFinite(t.at)?{at:t.at}:{},files:n,filesTotal:Math.max(Tq(t.filesTotal),n.length),...Dq(t.stagedAt)?{stagedAt:t.stagedAt}:{}}}var Dq=e=>typeof e==`number`&&Number.isFinite(e);function Oq(e){let t=e?.revertCommitted;if(t&&typeof t==`object`&&typeof t.messageID==`string`&&t.messageID&&Dq(t.until)&&Dq(t.at))return{messageID:t.messageID,...Dq(t.from)?{from:t.from}:{},until:t.until,at:t.at}}function kq(e){let t=Oq(e);return`${Eq(e)?.messageID??``}|${t?`${t.messageID}@${t.at}`:``}`}function Aq(e){let t=Math.max(e.filesTotal,e.files.length);return{text:`${_n(e.hidden,`message`)} reverted`,...t?{files:`${_n(t,`file`)} restored`}:{}}}function jq(e){let t=Math.max(e.filesTotal,e.files.length);if(!t)return;let n=e.files.slice(0,Cq).map(e=>e.file),r=t-n.length;return[`Revert ${_n(e.hidden,`message`)}?`,``,`The session changed ${_n(t,`file`)} since then; ${t===1?`it goes`:`they go`} back to how ${t===1?`it was`:`they were`}:`,n.join(`
32
+ `)+(r>0?`\nand ${r} more`:``),``,`Restore undoes the revert until you send the next message.`].join(`
33
+ `)}function Mq(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 Nq(e,t){return t===void 0?e:e.trim()===t.trim()?``:e}var Pq=new Map;function Fq(e,t){t.length&&Pq.set(e,t)}function Iq(e){let t=Pq.get(e)??[];return Pq.delete(e),t}var Lq=I(`<button type=button class="btn small changes"aria-label="Show changes"><span class=add>+</span> <span class=del>−`),Rq=I(`<div class="banner warn">No connected OpenCode process reports this session. It is read-only until its machine reconnects.`),zq=I(`<p class="muted pad no-timeline"data-unavailable=timeline>The hub can't show this <!> session's transcript; follow it in its terminal. Hub messages and live activity still appear here.`),Bq=I(`<div class=history-sentinel aria-hidden=true>`),Vq=I(`<p class="history-edge loading muted small"role=status><span class="spinner small"></span> Loading earlier messages…`),Hq=I(`<p class="history-edge muted small">Beginning of conversation`),Uq=I(`<p class="history-edge error small"role=alert>Couldn't load earlier messages: <!> <button type=button class="btn small">Retry`),Wq=I(`<p class="muted small pane-unstreamed"role=status>Live text isn't streamed to this pane right now; the reply appears when the turn ends.`),Gq=I(`<p class="working-line muted"role=status><span class="spinner small"></span> `),Kq=I(`<p class="idle-line muted small"> · last activity `),qq=I(`<button type=button class="btn primary tap-to-start">Tap to start Voice mode`),Jq=I(`<p class="note err voice-error"role=alert>Voice mode: `),Yq=I(`<div class=sheet-backdrop>`),Xq=I(`<div><div class=session-main><header class=topbar><div class=topbar-title></div></header><div class=scroller><div class=column></div></div><div class=dock><div class=column>`),Zq=I(`<a class="crumb muted"> <span class=crumb-sep aria-hidden=true>/`),Qq=I(`<h1 class=title>`),$q=I(`<h1 class=title><button type=button class=title-btn>`),eJ=I(`<span class=chip-server><span aria-hidden=true></span><span class=place-sep aria-hidden=true>·</span><span class=place-where>`),tJ=I(`<span> · `),nJ=I(`<span class=place-branch>`),rJ=I(`<div class=session-place><span aria-hidden=true></span><span class=place-machine></span><span class=place-sep aria-hidden=true>·</span><span class=place-where>`),iJ=I(`<span class=session-error-status>`),aJ=I(`<span class="session-error-where muted">in subagent `),oJ=I(`<div class=session-error-message>`),sJ=I(`<div class="banner session-error"role=alert><span class=session-error-mark aria-hidden=true>✕</span><div class=session-error-body><div class=session-error-head><strong>`),cJ=I(`<p class="muted pad">Loading conversation…`),lJ=I(`<p class="muted pad empty-session">No messages yet. Type below, or start Voice mode.`),uJ=I(`<p>`),dJ=I(`<p class="answered-by small muted">`),fJ=I(`<div class=revert-banner role=status><span class=revert-text><span class="muted revert-held"title="Messages from agents and apps are delivered after you restore or send"> · agent messages wait</span></span><button type=button class="btn small"title="Bring the messages and files back">Restore`),pJ=I(`<span class=muted> · `),mJ=I(`<button type=button class="btn stop"aria-label="Stop the session and its subagents"> Stop`),hJ=I(`<div class=composer-unavailable data-no-prompt><p class="muted small">`),gJ=I(`<div class=empty><p class=display>Session not found</p><p class=muted>It may belong to another account, or it no longer exists.</p><a class="btn primary"href=/>Back to sessions`),_J=3e4,vJ=80,yJ=100,bJ=2e3,xJ;function SJ(i){let a=i.id,c=Cc(a,i.visible);M(()=>c.release()),x(()=>i.focused?.()&&c.focus());let d=()=>Vp()&&(i.rail?.()??!0),f,p=()=>{let e=f??d();f=void 0,Wp(!e)},h=()=>document.visibilityState===`visible`&&(i.visible?.()??!0),g=()=>Fu(a),S=()=>Pu().find(e=>e.id===a),w=()=>{let e=g();return e?Ci(e.machine.name,e.session,vt()?.branch):void 0},T=()=>g()?.session.status,E=()=>bo(re()?T()?.filter(e=>ie().has(e.id)):T()),D=()=>!g(),j=C(()=>$z(g()?.process)),ee=()=>tB(j()),te=()=>!!g()&&!j().timeline,I=()=>g()?.session.exposed!==!1,ne=()=>typeof g()?.session.rootID==`string`?g().session.rootID:a,re=()=>ne()!==a;x(()=>{let e=g()?.session;if(!Z()||!e)return;let t=ne()===a?e.parentID:ne();Uz(window.history,location.pathname+location.search+location.hash,typeof t==`string`?t:void 0)});let ie=C(()=>yo(T(),a)),oe=(e,t)=>e===ne()&&(!re()||typeof t==`string`&&ie().has(t)),se=()=>{let e=g()?.session.parentID;if(typeof e==`string`&&e)return{id:e,title:T()?.find(t=>t.id===e)?.title||Fu(e)?.session.title||`Parent session`}},[ce,le]=u(),de=()=>{let e=ce();return e?e.value:Eq(g()?.session)};x(()=>{let e=ce();e&&Eq(g()?.session)?.messageID===e.value?.messageID&&le(void 0)});let pe=C(()=>wq(g()?.process)),me,z=new it,[B,ge]=u(0),_e=()=>ge(e=>e+1),[ve,ye]=u(!1),[be,xe]=u(!1),[Se,Ce]=u([]),[we,Te]=u({}),Ee=0,De=(e,t=``,n)=>Ce(r=>[...r.slice(-20),{key:`n${++Ee}`,text:e,kind:t,...n?{denial:n}:{}}]),[ke,Ae]=u([]),je=!1,Me=()=>{let e=Tu(),t=ke();return t.length?[...e,...t.filter(t=>!e.some(e=>e.seq===t.seq))]:e},Ne=e=>typeof e.sessionID==`string`?_t(Me(),e.sessionID,NB(z.rows(),e),ju):void 0,Pe=C(()=>(B(),new Set(z.rows().flatMap(e=>e.kind===`error`&&e.declined===!0?[Ne(e)?.key??``]:[]).filter(Boolean)))),Fe=new Map,Ie=C(()=>{B(),z.status(T(),a);let e=new Map,t=de(),n=Oq(g()?.session),r=EB(t||n?z.rows().filter(e=>!Mq(e,t,n)):z.rows(),{denied:e=>Ne(e)?.text}).map(t=>{let n=JSON.stringify(t),r=Fe.get(t.key),i=r&&r.json===n?r:{json:n,block:t};return e.set(t.key,i),i.block});return Fe=e,r}),[Le,Re]=Or({}),ze,Be=!0,Ve=()=>requestAnimationFrame(()=>ze&&(ze.scrollTop=ze.scrollHeight));x(e(Ie,()=>Be&&Ve())),x(e(Ie,e=>{!je&&e.some(e=>e.type===`error`&&e.denied&&e.label===`Denied: the turn stopped`)&&(je=!0,G(`/api/agent/audit?limit=${yJ}`).then(e=>Ae(Xt(e).entries)).catch(()=>{}))}));let[Ue,We]=u(0),Ge=e=>new URLSearchParams(Object.entries(e).flatMap(([e,t])=>t===void 0?[]:[[e,String(t)]])).toString(),Ke=new Jz(z,e=>G(`${H(a)}/timeline?${Ge(e)}`),{limit:vJ,onChange:()=>{Ye(()=>he(()=>{We(e=>e+1),_e()})),Ke.state===`idle`&&K()}}),qe=()=>(Ue(),{state:Ke.state,error:Ke.error}),Je=C(()=>(Ue(),Ke.cutMessageID));function Ye(e){let t=ze;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 Xe,Ze;function K(){Ze&&ze&&typeof IntersectionObserver<`u`&&(Xe??=new IntersectionObserver(e=>e.some(e=>e.isIntersecting)&&void Ke.older(),{root:ze,rootMargin:`${Math.round(window.innerHeight*1.5)}px 0px 0px 0px`}),Xe.unobserve(Ze),Xe.observe(Ze))}M(()=>Xe?.disconnect());let Qe=e=>{Ze=e,requestAnimationFrame(()=>requestAnimationFrame(K))},$e=()=>`${de()?.messageID??``}|${kq({revertCommitted:Oq(g()?.session)})}`,et=ae($e),tt=!1;x(e($e,e=>{if(e===et)return;let t=e.split(`|`)[0]===et.split(`|`)[0];et=e,t&&tt?tt=!1:ve()&&rt()}));async function rt(){z.clear(),_e();try{await Ke.first(),await ot(),Be=!0,Ve()}catch(e){De(`Could not refresh the conversation: ${U(e)}`,`err`)}}async function at(){if(te())return ye(!0);try{await Ke.first(),ye(!0),_e(),Ve()}catch(e){e instanceof W&&e.status===404&&!g()?xe(!0):te()||oB(e)||De(e instanceof W&&e.status===409?`No OpenCode process for this session is connected; history is unavailable until it reconnects.`:`Could not load the conversation: ${U(e)}`,`err`),ye(!0)}}async function ot(){try{let{messages:e}=await G(`${H(a)}/messages?limit=200`);for(let t of e??[]){let e=nt(a,t);e&&z.hubMessage(e)}_e()}catch{}}async function st(){try{let e=await G(H(a)),t=Xl.feed(ne());t.load(e.activity??[]),e.status&&t.status(e.status)}catch{}}let lt=ae(()=>T()),dt=Nu(e=>{if(e.type===`resync`){ve()?Ke.resync().catch(e=>De(`Could not refresh the conversation: ${U(e)}`,`err`)).then(ot):at().then(ot),st(),Dt();return}let t=typeof e.rootID==`string`?e.rootID:e.sessionID;if(e.type===`activity`&&oe(t,e.sessionID)&&e.item&&e.item.kind!==`thinking`)z.activity(e.sessionID,e.item),_e();else if(e.type===`reasoning`&&oe(t,e.sessionID)&&typeof e.messageID==`string`&&typeof e.delta==`string`)z.appendReasoning({sessionID:e.sessionID,messageID:e.messageID,delta:e.delta}),_e();else if(e.type===`delta`&&oe(t,e.sessionID)&&typeof e.messageID==`string`&&typeof e.text==`string`)z.appendText({sessionID:e.sessionID,messageID:e.messageID,...Number.isInteger(e.ordinal)?{ordinal:e.ordinal}:{},delta:e.text}),_e();else if(e.type===`message`){let t=nt(a,e.message);t&&(z.hubMessage(t),_e())}else if(e.type===`turn`&&e.sessionID===a&&rn){let{sub:t,sentAt:n}=rn;rn=void 0,sn(e,t,n)}else if(e.type===`status`&&e.sessionID===ne()){for(let t of yy(lt,e.sessions,a))De(t,`sys`);let t=bo(lt);if(lt=e.sessions,!bo(e.sessions)){for(let e of z.rows())e.live&&z.upsert({key:e.key,live:!1});z.endReasoning(void 0),t&&c.streamed()===!1&&ve()&&Ke.resync().catch(()=>{}).then(ot)}_e(),kt()}}),ft;x(e(()=>g()?.session.updated,()=>{clearTimeout(ft),ft=setTimeout(()=>h()&&void gd(a),400)}));let pt=(e,t=!1)=>V(`${H(a)}/presence`,{method:`POST`,json:{visible:e},keepalive:t}).catch(()=>{}),mt=()=>{pt(h(),document.visibilityState!==`visible`),h()&&gd(a,!0)};x(e(()=>i.visible?.()??!0,()=>mt(),{defer:!0}));let ht=ae(c.streamed);x(e(c.streamed,e=>{if(e===void 0)return;let t=ht===!1&&e;ht=e,t&&ve()&&Ke.resync().catch(()=>{}).then(ot)}));let gt,[vt,yt]=u(),[bt,xt]=u(``),[St,Ct]=u(!0),wt=0,Tt,Et=0;async function Dt(){if(wt=Date.now(),g()&&!j().summary)return xt(`Details aren't available for ${j().harnessName} sessions.`),Ct(!1);try{let e=await G(`${H(a)}/summary`);yt(e),xt(``),(!e.branch||!e.changes)&&Et<2&&(Et++,clearTimeout(Tt),Tt=setTimeout(Dt,4e3))}catch(e){xt(e instanceof W&&e.status===409?`The machine is disconnected.`:`Could not load details: ${U(e)}`)}finally{Ct(!1)}}function kt(){clearTimeout(Tt),Tt=setTimeout(Dt,Math.max(0,bJ-(Date.now()-wt)))}let[At,jt]=u(),Mt=HV(()=>a),[Nt,Pt]=u(),Ft=()=>j().sessionModel&&j().models,[It,Lt]=u({...K_(),draft:Ix.get(a)}),Rt=e=>{Lt(t=>q_(t,e)),Ix.set(a,It().draft)};M(Ix.subscribe(e=>{e===a&&Ix.get(a)!==It().draft&&Lt(e=>q_(e,{type:`input`,text:Ix.get(a)}))}));let zt=()=>nB(j(),E()),Bt=()=>{let e=J_(It(),{running:E(),offline:D()}),t=zt();return{...e,canSubmit:e.canSubmit&&t.allowed,showStop:e.showStop&&j().stop,...!e.hint&&t.hint?{hint:t.hint}:{}}},Ht=0,[Ut,Wt]=u(!1),Gt=Promise.resolve();function Kt(e){Gt=Gt.then(async()=>{Wt(!0);try{for(let t of e)try{Rt({type:`attach`,image:await VS(t,It().images)})}catch(e){Rt({type:`attachError`,message:U(e)})}}finally{Wt(!1)}})}async function qt(e,t,n){let r=[];for(let i of n)if(B_(i.mime))try{let n=await(await V(gB(e,t,i.index))).blob();r.push(await VS(new File([n],i.name||`image`,{type:i.mime}),r))}catch{}return r}async function Jt(e){try{await navigator.clipboard.writeText(e),q(`Copied`)}catch{q(`Could not copy: the browser refused`,`err`)}}async function Yt(e,t=!1){try{let n=await(await V(`${H(a)}/fork`,{method:`POST`,json:{messageID:e}})).json();n.text&&Ix.set(n.sessionID,n.text),Fq(n.sessionID,await qt(a,e,n.attachments??[])),q(t?`Forked into a new session beside this one`:`Forked into a new session`),t?wn(n.sessionID):Vt(Ot(n.sessionID))}catch(e){q(oB(e)??`Could not fork: ${U(e)}`,`err`)}}async function Zt(e){if(E())return q(`Wait for the session to finish (or stop it) before reverting`,`warn`);try{let t=jq(await G(`${H(a)}/revert/preview?messageID=${encodeURIComponent(e)}`));if(t&&!await P(t,`Revert`,{danger:!0}))return;let n=await(await V(`${H(a)}/revert`,{method:`POST`,json:{messageID:e,files:!0}})).json();le({value:Eq({revert:n.revert})}),he(()=>{for(let e of It().images)Rt({type:`detach`,id:e.id});Rt({type:`input`,text:n.text??``})}),me=n.text??``;for(let t of await qt(a,e,n.attachments??[]))Rt({type:`attach`,image:t})}catch(e){q(oB(e)??`Could not revert: ${U(e)}`,`err`)}}async function Qt(){try{await V(`${H(a)}/revert/restore`,{method:`POST`,json:{}}),le({value:void 0}),Rt({type:`input`,text:Nq(It().draft,me)}),me=void 0}catch(e){q(`Could not restore: ${U(e)}`,`err`)}}async function $t(){if(!de())return!0;try{return await V(`${H(a)}/revert/commit`,{method:`POST`,json:{}}),tt=!0,le({value:void 0}),me=void 0,!0}catch(e){return q(`Could not send: the revert could not be completed (${U(e)})`,`err`),!1}}let en=()=>{let e=pe();return{fork:e.fork,revert:e.revert.enabled&&E()?{enabled:!1,reason:`Wait for the session to finish (or stop it) before reverting`}:e.revert,onCopy:e=>void Jt(e),onFork:e=>void Yt(e),onForkBeside:e=>void Yt(e,!0),onRevert:e=>void Zt(e)}};async function nn(){let e=It().draft.trim(),t=It().images;if(!e&&!t.length||de()&&!await $t())return;if(fn()&&!t.length){Rt({type:`input`,text:``}),wx.sendTyped(a,e);return}let n=++Ht,r=`local:${n}`,i=E(),o=Date.now();he(()=>{Rt({type:`submit`,id:n}),z.upsert({key:r,kind:`user`,text:e,at:o,...t.length?{images:t.map(({name:e,mime:t,preview:n})=>({name:e,mime:t,preview:n}))}:{}}),Te(e=>({...e,[r]:`pending`})),_e()}),Be=!0,Ve();try{let i={text:e,...t.length?{images:t.map(({mime:e,data:t,name:n})=>({mime:e,data:t,name:n}))}:{}},s=await V(`${H(a)}/turn`,{method:`POST`,json:i,headers:{prefer:`respond-async`}}),c=await s.json().catch(()=>({})),l=Y_(s.status,c);Rt({type:`accepted`,id:n});let u=rB(j(),l);Te(e=>({...e,[r]:u.tick})),u.toast&&q(u.toast),l===`accepted`?rn={sub:n,sentAt:o}:sn(c,n,o)}catch(e){if(e instanceof tn&&!i&&await Z_(E)){Rt({type:`accepted`,id:n}),Te(e=>({...e,[r]:`sent`})),De(`Lost the connection to the hub after sending; the session is working on your message and its reply will appear here.`,`sys`);return}let t=oB(e);t&&q(t,`err`);let a=t??(e instanceof W&&e.status===504?`OpenCode did not answer in time. The session may still be working.`:U(e));he(()=>{Rt({type:`rejected`,id:n,message:a}),z.upsert({key:r,kind:`user`,text:``,images:[]}),_e()})}}let rn,[an,on]=u(new Set);function sn(e,t,n){let r=z.rows().some(e=>e.kind===`assistant`&&(e.at??0)>=n&&e.text);e.reply&&!r&&z.upsert({key:`reply:${t}`,kind:`assistant`,text:e.reply,at:Date.now()});let i=He(Tu(),new Set([a,...ie()]),Date.now(),void 0,ju),o=X_(e,{denied:i?.text});o&&De(o.text,o.kind,i&&o.text.startsWith(i.text)?i.key:void 0),i&&o?.text.startsWith(i.text)&&on(e=>new Set([...e,i.key])),_e()}async function cn(){Rt({type:`stop`});try{let{stopped:e}=await(await V(`${H(a)}/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(oB(e)??`Could not stop: ${U(e)}`,`err`)}finally{Rt({type:`stopped`})}}let ln=()=>Bx(a),un=()=>c.takesInput()?Lx.toggle(a):c.focus(),dn=Px,fn=()=>dn().phase!==`off`&&dn().sessionID===a,pn=()=>dn().phase!==`off`&&dn().sessionID!==void 0&&dn().sessionID!==a,mn=()=>dn().error?.sessionID===a&&!dn().error.gesture?dn().error.message:void 0,hn=()=>dn().error?.sessionID===a&&dn().error.gesture===!0,gn=()=>fo(ru()??void 0,X()?.publicURL)?.micBlocked?`Set up speech in Settings to use the microphone`:void 0;M(wx.attach(a,{user:e=>{let t=`voice:${++Ee}`;return z.upsert({key:t,kind:`user`,text:e,at:Date.now()}),Te(e=>({...e,[t]:`pending`})),_e(),t},tick:(e,t)=>Te(n=>({...n,[e]:t})),agent:e=>{let t=e.messageID?z.liveTextKey(e.messageID):`say:${++Ee}`,{mode:n,text:r}=vy(z.get(t)?.text??``,e.text);n!==`keep`&&(z.upsert({key:t,messageID:e.messageID,kind:`assistant`,text:r,at:z.get(t)?.at??Date.now()}),_e())},note:(e,t)=>De(e,t??`sys`)}));async function _n(){if(!fn()&&!c.takesInput())return c.focus();fn()||(Zy(),Lx.cancel()),await wx.toggle(a),wx.isOn(a)&&wx.state.phase===`on`&&De(`Voice mode on${wx.state.agent?` (${wx.state.agent} agent)`:``}. Speak naturally; say “stop” to interrupt, “pause listening” to end.`,`sys`)}let vn=db(location.href);vn.voice&&(xJ=a,Vt(vn.path,{replace:!0})),x(()=>{xJ===a&&g()&&!gn()&&(xJ=void 0,fn()||_n())}),fe(()=>{for(let e of Iq(a))Rt({type:`attach`,image:e});let e=XS(a);e&&(he(()=>{Rt({type:`input`,text:e.text});for(let t of e.images)Rt({type:`attach`,image:t})}),nn()),st(),gd(a,h()),pt(h()),gt=setInterval(()=>h()&&void pt(!0),_J),document.addEventListener(`visibilitychange`,mt)});let yn=!1;x(()=>{!yn&&Y.machines&&(yn=!0,ae(()=>{at().then(ot),Dt(),(!g()||j().models)&&Mt.load()}))});let bn=()=>void pt(!1,!0);window.addEventListener(`pagehide`,bn),M(()=>{dt(),clearInterval(gt),clearTimeout(Tt),clearTimeout(ft),document.removeEventListener(`visibilitychange`,mt),window.removeEventListener(`pagehide`,bn),bn()});let xn=!1;x(()=>{if(g())xn=!0;else if(xn&&Y.machines){if(i.onGone)return i.onGone();q(`That session is gone (deleted, or its machine was revoked).`,`warn`),Vt(`/`,{replace:!0})}});let Sn=()=>Br(g()?.session).filter(e=>!re()||e.sessionID!==void 0&&ie().has(e.sessionID)),Cn=C(()=>new Map(Sn().map(e=>[`${e.kind}:${e.id}`,e]))),Tn=C((e=[])=>{let t=[...Cn().keys()];return t.length===e.length&&t.every((t,n)=>t===e[n])?e:t}),En=C(()=>{B();let e;for(let t of z.rows())t.kind===`user`&&(t.depth??0)===0&&typeof t.at==`number`&&(e===void 0||t.at>e)&&(e=t.at);return e}),Dn=()=>{let e=new Set(Sn().map(e=>e.id));return ct(Tu(),new Set([a,...ie()]),kn(),En(),new Set([...an(),...Pe()]),Bu,ju).filter(t=>!e.has(t.key))},On=()=>($l(),N(),Xl.has(ne())?Xl.feed(ne()).pulse():void 0),[kn,An]=u(Date.now()),jn=setInterval(()=>An(Date.now()),1e3);M(()=>clearInterval(jn));let Mn=()=>{if(re()){let e=T()?.find(e=>e.id===a);return e?.state===`working`?(kn(),`Working${e.since?` · ${qa(Date.now()-e.since)}`:``}`):void 0}let e=On();if(!E()||!e?.busy)return;kn();let t=Ji(T(),a),n=Ui(T());return`${t??e.label}${e.since?` · ${qa(Date.now()-e.since)}`:``}${n?` · ${qi(n)}`:``}`},Nn=()=>zi(T(),a),Pn=()=>{let e=g()?.session;if(!e)return`Not connected`;let t=Sn().length;return j().voice?`${fn()&&dn().agent?`${dn().agent} agent`:e.conversation?`Voice agent`:`Session agent`} · ${t?`${t} request${t===1?``:`s`} waiting`:I()?`Voice on`:`Voice off`}`:t?`${t} request${t===1?``:`s`} waiting`:`${j().harnessName} session`},Fn=()=>vt()?.changes?.files.map(e=>e.file)??[];return(()=>{var e=Xq(),u=e.firstChild,h=u.firstChild,x=h.firstChild,C=h.nextSibling,T=C.firstChild,M=C.nextSibling.firstChild;e.$$pointerdown=()=>c.focus(),e.$$focusin=()=>c.focus(),y(h,n(l,{get when(){return Z()},get children(){return n(F,{icon:`menu`,label:`Open sidebar`,onClick:Gp})}}),x),y(x,n(l,{get when(){return se()},children:e=>(()=>{var t=Zq(),r=t.firstChild,i=r.nextSibling;return y(t,n(L,{name:`chevron`,class:`crumb-chev`}),r),y(t,()=>e().title,i),s(n=>{var r=Ot(e().id),i=`Back to ${e().title}`,a=`Back to ${e().title}`;return r!==n.e&&b(t,`href`,n.e=r),i!==n.t&&b(t,`title`,n.t=i),a!==n.a&&b(t,`aria-label`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),y(x,n(l,{get when(){return S()},get fallback(){return(()=>{var e=Qq();return y(e,()=>g()?.session.title||(Y.machines?`Session`:`Loading…`)),e})()},children:e=>[n(A,{get state(){return e().state}}),n(Zg,{get id(){return e().id},get title(){return e().title},place:`topbar`,class:`title`,get children(){var t=$q(),n=t.firstChild;return n.$$click=()=>Bh({id:e().id,place:`topbar`}),y(n,()=>e().title),s(()=>b(n,`title`,`${e().title} · click to rename`)),t}}),n(Qg,{get id(){return e().id}}),n(O,{label:`Session actions`,class:`icon-btn small`,items:()=>Uh(e(),{open:!1,place:`topbar`})})]}),null),y(h,n(l,{get when(){return w()},children:e=>(()=>{var t=eJ(),i=t.firstChild,a=i.nextSibling,o=a.nextSibling;return y(t,()=>e().machine,a),y(o,()=>e().where),y(t,n(l,{get when(){return e().branch},get children(){return[n(L,{name:`branch`}),r(()=>e().branch)]}}),null),s(n=>{var r=`${e().text} · ${g().session.directory}`,a=`Runs on ${e().text}`,o=`online-dot${g().machine.online?` on`:``}`;return r!==n.e&&b(t,`title`,n.e=r),a!==n.t&&b(t,`aria-label`,n.t=a),o!==n.a&&k(i,n.a=o),n},{e:void 0,t:void 0,a:void 0}),t})()}),null),y(h,n(l,{get when(){return ee()},children:e=>(()=>{var t=tJ(),n=t.firstChild;return y(t,()=>j().harnessName,n),y(t,()=>e().label,null),s(n=>{var r=`chip-evidence ${e().level}`,i=e().level,a=e().detail,o=`${j().harnessName} · evidence: ${e().label}. ${e().detail}`;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`data-evidence`,n.t=i),a!==n.a&&b(t,`title`,n.a=a),o!==n.o&&b(t,`aria-label`,n.o=o),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),null),y(h,n(xq,{sessionID:a,get harness(){return j().harness},get takesInput(){return c.takesInput}}),null),y(h,n(l,{get when(){return vt()?.changes?.files.length},get children(){var e=Lq(),t=e.firstChild;t.firstChild;var n=t.nextSibling.nextSibling;return n.firstChild,e.$$click=()=>jt(Fn()[0]),y(t,()=>vt().changes.additions,null),y(n,()=>vt().changes.deletions,null),e}}),null),y(h,n(l,{get when(){return pn()},get children(){return n(LL,{})}}),null),y(h,n(l,{get when(){return Z()},get children(){return n(rz,{})}}),null),y(h,n(F,{icon:`rail`,get label(){return d()?`Hide details`:`Show details`},get"aria-pressed"(){return d()},onPointerDown:()=>f=d(),onClick:p}),null),y(h,()=>i.paneTools,null),y(u,n(l,{get when(){return r(()=>!!Z())()&&w()},children:e=>(()=>{var t=rJ(),r=t.firstChild,i=r.nextSibling,a=i.nextSibling.nextSibling;return y(i,()=>e().machine),y(a,()=>e().where),y(t,n(l,{get when(){return e().branch},get children(){return[n(L,{name:`branch`}),(()=>{var t=nJ();return y(t,()=>e().branch),t})()]}}),null),s(n=>{var i=g().session.directory,a=`Runs on ${e().text}`,o=`online-dot${g().machine.online?` on`:``}`;return i!==n.e&&b(t,`title`,n.e=i),a!==n.t&&b(t,`aria-label`,n.t=a),o!==n.a&&k(r,n.a=o),n},{e:void 0,t:void 0,a:void 0}),t})()}),C),y(u,n(l,{get when(){return Nn()},children:e=>(()=>{var t=sJ(),i=t.firstChild.nextSibling,o=i.firstChild,c=o.firstChild;return y(c,()=>e().label),y(o,n(l,{get when(){return e().status},get children(){var t=iJ();return y(t,()=>e().status),t}}),null),y(o,n(l,{get when(){return r(()=>e().sessionID!==a)()&&e().title},get children(){var t=aJ();return t.firstChild,y(t,()=>e().title,null),t}}),null),y(i,n(l,{get when(){return r(()=>!!e().message)()&&e().message!==e().label},get children(){var t=oJ();return y(t,()=>e().message),t}}),null),y(t,n(F,{icon:`close`,label:`Dismiss error`,class:`session-error-dismiss`,onClick:()=>void Yd(e().sessionID)}),null),s(()=>b(t,`data-error-session`,e().sessionID)),t})()}),C),y(u,n(l,{get when(){return r(()=>!!D())()&&Y.machines},get children(){return Rq()}}),C),C.addEventListener(`scroll`,e=>Be=e.currentTarget.scrollHeight-e.currentTarget.scrollTop-e.currentTarget.clientHeight<80);var P=ze;return typeof P==`function`?t(P,C):ze=C,y(T,n(l,{get when(){return!be()},get fallback(){return n(CJ,{})},get children(){return[n(l,{get when(){return ve()},get fallback(){return cJ()},get children(){return[n(l,{get when(){return te()},get children(){var e=zq(),t=e.firstChild.nextSibling;return t.nextSibling,y(e,()=>j().harnessName,t),e}}),n(l,{get when(){return Ie().length||Se().length},get fallback(){return n(l,{get when(){return!te()},get children(){return lJ()}})},get children(){return[(()=>{var e=Bq();return t(Qe,e),e})(),n(v,{get children(){return[n(o,{get when(){return qe().state===`loading`},get children(){return Vq()}}),n(o,{get when(){return r(()=>qe().state===`done`)()&&Ie().length},get children(){return Hq()}}),n(o,{get when(){return qe().state===`error`},get children(){var e=Uq(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return y(e,()=>qe().error,t),n.$$click=()=>void Ke.retry(),e}})]}}),n(aG,{sessionID:a,get blocks(){return Ie()},get ticks(){return we()},get actions(){return en()},previews:!0,get partialMessage(){return Je()},expanded:Le,onToggle:(e,t)=>Re(e,t),onDetail:(e,t)=>{z.detail(e,t),_e()}})]}})]}}),n(m,{get each(){return ut(Se(),Pe())},children:e=>(()=>{var t=uJ();return y(t,()=>e.text),s(n=>{var r=`note ${e.kind}`,i=e.kind===`err`?`alert`:void 0;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`role`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(Kg,{get decisions(){return Oe(su(),a)}}),n(m,{get each(){return Tn()},children:e=>n(l,{get when(){return Cn().get(e)},children:e=>n(_W,{sessionID:a,get blocker(){return e()},rootID:a,get canAnswer(){return r(()=>e().kind===`permission`)()?j().permission:j().form},get harnessName(){return j().harnessName}})})}),n(m,{get each(){return Dn()},children:e=>(()=>{var t=dJ();return y(t,()=>e.text),s(n=>{var r=e.key,i=e.title;return r!==n.e&&b(t,`data-answered-by`,n.e=r),i!==n.t&&b(t,`title`,n.t=i),n},{e:void 0,t:void 0}),t})()}),n(l,{get when(){return r(()=>!!E())()&&c.streamed()===!1},get children(){return Wq()}}),n(l,{get when(){return Mn()},get children(){var e=Gq();return e.firstChild.nextSibling,y(e,Mn,null),e}}),n(l,{get when(){return r(()=>!(E()||!g()))()&&S()},get children(){var e=Kq(),t=e.firstChild;return y(e,()=>ue[S().state],t),y(e,()=>R(S().updated,N()),null),e}})]}})),y(M,n(l,{get when(){return fn()},get children(){return n(uV,{get state(){return dn().voice},get level(){return dn().level},get held(){return dn().held},get ignored(){return dn().ignored},get working(){return E()},get model(){return VV(Mt.prefs(),`voice`)},onMute:()=>wx.mute(),onEnd:()=>void wx.end(),onModel:()=>Pt(`voice`),get notifyHint(){return Mx()},onAllowNotifications:()=>void Nx(),get timing(){return dn().timing},get detector(){return dn().detector},get turn(){return dn().turn},get front(){return dn().front}})}}),null),y(M,n(l,{get when(){return hn()},get children(){var e=qq();return e.$$click=()=>void _n(),e}}),null),y(M,n(l,{get when(){return mn()},get children(){var e=Jq();return e.firstChild,y(e,mn,null),e}}),null),y(M,n(l,{get when(){return de()},children:e=>(()=>{var t=fJ(),r=t.firstChild,i=r.firstChild,a=r.nextSibling;return y(t,n(L,{name:`undo`}),r),y(r,()=>Aq(e()).text,i),y(r,n(l,{get when(){return Aq(e()).files},children:e=>(()=>{var t=pJ();return t.firstChild,y(t,e,null),t})()}),i),a.$$click=()=>void Qt(),s(()=>b(t,`data-revert`,e().messageID)),t})()}),null),y(M,n(l,{get when(){return zt().show},get fallback(){return(()=>{var e=hJ(),t=e.firstChild;return y(t,()=>zt().hint),y(e,n(l,{get when(){return Bt().showStop},get children(){var e=mJ(),t=e.firstChild;return e.$$click=()=>void cn(),y(e,n(L,{name:`stop`}),t),s(()=>e.disabled=!Bt().canStop),e}}),null),e})()},get children(){return n(oV,_({get draft(){return It().draft},get images(){return It().images},get attaching(){return Ut()},get view(){return Bt()},get error(){return It().error},get voiceOn(){return fn()},get voiceBlocked(){return gn()},get dictating(){return ln().recording},get transcribing(){return ln().transcribing},get metaLeft(){return Pn()},get voiceModel(){return r(()=>!!Mt.error())()?`unavailable`:VV(Mt.prefs(),`voice`)}},()=>j().summary?{sessionModel:wV(vt()?.model,{pickable:Ft()}),sessionModelPickable:Ft()}:{},{onInput:e=>Rt({type:`input`,text:e}),onAttach:Kt,onDetach:e=>{let t=It().images.find(t=>t.id===e);t?.preview.startsWith(`blob:`)&&URL.revokeObjectURL(t.preview),Rt({type:`detach`,id:e})},onSubmit:()=>void nn(),onStop:()=>void cn(),onDictate:()=>void un(),onVoice:()=>void _n(),onModel:e=>Pt(e),get showModels(){return j().models},get showVoice(){return j().voice}}))}}),null),y(u,n(l,{get when(){return At()},get children(){return n(zU,{sessionID:a,get file(){return At()},get files(){return r(()=>!!Fn().length)()?Fn():[At()]},onFile:jt,onClose:()=>jt(void 0)})}}),null),y(e,n(l,{get when(){return d()},get children(){return[n(l,{get when(){return Z()},get children(){var e=Yq();return e.$$click=()=>Wp(!1),e}}),n(l,{get when(){return!Z()},get children(){return n(ES,{panel:`rail`,label:`Resize details`})}}),n(RU,{get found(){return g()},get summary(){return vt()},get summaryError(){return bt()},get loading(){return St()},onFile:e=>jt(e),onClose:()=>Wp(!1)})]}}),null),y(e,n(UV,{get kind(){return Nt()},models:Mt,onClose:()=>Pt(void 0),get sessionCurrent(){return TV(vt()?.model)},onSessionModel:e=>yt(t=>t&&{...t,model:e})}),null),s(t=>{var n=`session-layout${d()?` with-rail`:``}`,r=c.paneID,i=c.takesInput()?``:void 0;return n!==t.e&&k(e,t.e=n),r!==t.t&&b(e,`data-pane`,t.t=r),i!==t.a&&b(e,`data-pane-focused`,t.a=i),t},{e:void 0,t:void 0,a:void 0}),e})()}function CJ(){return gJ()}z([`focusin`,`pointerdown`,`click`]);var wJ=I(`<span class=pane-drop-label>`),TJ=I(`<div class=pane-drop-area><span class=pane-drop-hint>`),EJ=I(`<div aria-hidden=true>`),DJ=I(`<div class=pane-dock-map>`),OJ=I(`<div class=pane-dock role=region aria-label="Drop into a pane"><div class=pane-dock-card><p class=pane-dock-title></p><p class="pane-dock-note muted">Edges split, the centre replaces. Up to 4 panes.`),kJ={left:`Split left`,right:`Split right`,top:`Stack above`,bottom:`Stack below`,center:`Replace`};function AJ(e,t){let n=hm(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: ${kJ[t].replace(`Split `,``).replace(`Stack `,``)}`,refused:!1}:n===`added`&&`empty`in e?{text:`Open in a pane`,refused:!1}:{text:kJ[t],refused:!1}}function jJ(e){let[t,r]=u(),i=t=>e.index===void 0?{empty:!0}:{index:e.index,zone:t},a=t=>{if(!mm(t))return;t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getBoundingClientRect(),i=e.index===void 0?`center`:mp(t.clientX-n.left,t.clientY-n.top,n.width,n.height);r(i),t.dataTransfer&&(t.dataTransfer.dropEffect=um()?.move||t.dataTransfer.effectAllowed===`move`?`move`:`copy`)},o=()=>t()?AJ(i(t()),t()):void 0;return(()=>{var c=EJ();return c.addEventListener(`drop`,e=>{if(!mm(e))return;e.preventDefault(),e.stopPropagation();let n=t()??`center`;r(void 0),_m(e,i(n))}),c.addEventListener(`dragleave`,e=>!e.currentTarget.contains(e.relatedTarget)&&r(void 0)),c.addEventListener(`dragover`,a),c.addEventListener(`dragenter`,a),y(c,n(l,{get when(){return e.label},get children(){var t=wJ();return y(t,()=>e.label),t}}),null),y(c,n(l,{get when(){return t()},get children(){var e=TJ(),n=e.firstChild;return y(n,()=>o()?.text),s(()=>b(e,`data-zone`,t())),e}}),null),s(n=>{var r=`pane-drop${e.class?` ${e.class}`:``}`,i=e.style,a=t(),s=o()?.refused?``:void 0;return r!==n.e&&k(c,n.e=r),n.t=h(c,i,n.t),a!==n.a&&b(c,`data-zone`,n.a=a),s!==n.o&&b(c,`data-refused`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),c})()}var MJ=e=>{if(rn(e)!==void 0)return`Artifact`;let t=Fu(e.sessionID)?.session.title,n=typeof t==`string`&&t?t:`Session`;return e.sideChatID?`Side chat: ${n}`:n};function NJ(){let e=xn,t=()=>e().panes.length,i=()=>Mz(e().split,t()),o=n=>{let r=Nz(e().split,t(),n);return{"grid-column":`${r.col+1} / span ${r.colSpan}`,"grid-row":`${r.row+1}`}};return(()=>{var c=OJ(),u=c.firstChild,d=u.firstChild,f=d.nextSibling;return y(d,(()=>{var e=r(()=>!!um()?.label);return()=>e()?`Open “${um().label}” in a pane`:`Open in a pane`})()),y(u,n(l,{get when(){return t()},get fallback(){return n(jJ,{class:`pane-dock-empty`,label:`No panes open: drop here`})},get children(){var t=DJ();return y(t,n(m,{get each(){return e().panes},children:(e,t)=>n(jJ,{get index(){return t()},get label(){return MJ(e)},class:`pane-dock-pane`,get style(){return o(t())}})})),s(e=>{var n=`repeat(${i().cols}, 1fr)`,r=`repeat(${i().rows}, 1fr)`;return n!==e.e&&a(t,`grid-template-columns`,e.e=n),r!==e.t&&a(t,`grid-template-rows`,e.t=r),e},{e:void 0,t:void 0}),t}}),f),c})()}var PJ=I(`<div role=separator tabindex=0>`);function FJ(e){let[t,n]=u(!1),r=[],i=0,a=0,o,c=()=>Az[e.axis],l=t=>e.axis===`cols`?t.clientX:t.clientY,d=e=>Math.round(e*100),f=()=>{let t=e.sizes(),n=(t[e.index]??0)+(t[e.index+1]??0),r=Math.min(c()/Math.max(1,e.total()),n/2);return{min:d(r),max:d(n-r)}},p=()=>{a&&cancelAnimationFrame(a),a=0,n(!1),document.documentElement.classList.remove(`resizing`,`resizing-rows`)},m=(t,n)=>{t.hasPointerCapture(n)&&t.releasePointerCapture(n);let r=o;o=void 0,p(),r&&e.onChange(r,!0)};return M(p),(()=>{var u=PJ();return u.$$keydown=t=>{let n=Iz(e.sizes(),e.index,t.key,t.shiftKey,e.total(),c(),e.axis);n&&(t.preventDefault(),e.onChange(n,!0))},u.$$dblclick=()=>e.onChange(Pz(e.sizes().length),!0),u.addEventListener(`pointercancel`,e=>t()&&m(e.currentTarget,e.pointerId)),u.$$pointerup=e=>t()&&m(e.currentTarget,e.pointerId),u.$$pointermove=n=>{t()&&(o=Fz(r,e.index,l(n)-i,e.total(),c()),a||=requestAnimationFrame(()=>{a=0,o&&e.onChange(o,!1)}))},u.$$pointerdown=t=>{t.button===0&&(t.preventDefault(),t.stopPropagation(),t.currentTarget.setPointerCapture(t.pointerId),r=e.sizes(),i=l(t),n(!0),document.documentElement.classList.add(e.axis===`cols`?`resizing`:`resizing-rows`))},s(n=>{var r=`panel-handle pane-handle${t()?` dragging`:``}`,i=e.axis,a=e.axis===`cols`?`vertical`:`horizontal`,o=`Resize ${e.axis===`cols`?`columns`:`rows`} ${e.index+1} and ${e.index+2}`,s=d(e.sizes()[e.index]??0),c=f().min,l=f().max,p=e.style;return r!==n.e&&k(u,n.e=r),i!==n.t&&b(u,`data-axis`,n.t=i),a!==n.a&&b(u,`aria-orientation`,n.a=a),o!==n.o&&b(u,`aria-label`,n.o=o),s!==n.i&&b(u,`aria-valuenow`,n.i=s),c!==n.n&&b(u,`aria-valuemin`,n.n=c),l!==n.s&&b(u,`aria-valuemax`,n.s=l),n.h=h(u,p,n.h),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0,h:void 0}),u})()}z([`pointerdown`,`pointermove`,`pointerup`,`dblclick`,`keydown`]);var IJ=I(`<span role=status>Send this to the main session? It is queued and arrives after its current turn; nothing is interrupted.`),LJ=I(`<button type=submit class="btn small primary">Send`),RJ=I(`<button type=button class="btn small">Back`),zJ=I(`<form class=sidechat-send><label class=muted>Message for </label><textarea rows=3></textarea><div class=sidechat-row>`),BJ=I(`<div class=sidechat-bar role=group aria-label="Side chat"><div class=sidechat-row><strong>Side chat</strong><span class=muted>from </span><span class=sidechat-tools><button type=button class="btn small">Context</button><button type=button class="btn small">Refresh</button><button type=button class="btn small">Send to main…`),VJ=I(`<p class="muted sidechat-note">`),HJ=I(`<span role=status>`),UJ=I(`<ol class=sidechat-context aria-label="Copied context">`),WJ=I(`<li><span class=muted></span><div class=sidechat-context-text>`),GJ=I(`<p class="muted sidechat-problem"role=alert>`),KJ=I(`<button type=submit class="btn small">Review`),qJ=I(`<button type=button class=btn>Close pane`),JJ=I(`<div class=empty><p class=display>Side chat</p><p class=muted role=status>`),YJ=e=>{let t=Fu(e)?.session.title;return typeof t==`string`&&t?t:`the main session`};function XJ(e){let[t,i]=u(),[a,o]=u(),[c,d]=u(!1),[f,p]=u(!1),[h,g]=u(!1),[_,v]=u(!1),[x,S]=u(``),[C,w]=u(Date.now()),T,E=0,D=!0,O=e=>{i(e),w(Date.now()),clearTimeout(T),ch(e).kind===`launching`?T=setTimeout(k,_h(E++)):E=0};async function k(){try{let t=await G(gh.one(e.sideChatID));if(!D)return;let n=sh(t.sideChat);if(!n)return o(`The hub answered a side chat this console can't read.`);o(void 0),O(n)}catch(e){if(!D)return;o(e instanceof W&&e.status===404?`This side chat is gone, or it isn't yours.`:U(e))}}fe(k),M(()=>{D=!1,clearTimeout(T)});async function A(){let e=t();if(e&&!c()){d(!0);try{let t=await(await V(gh.refresh(e),{method:`POST`,json:{expectedRevision:e.revision}})).json(),n=sh(t.sideChat);n&&O(n),q(dh(t.delivery))}catch(e){e instanceof W&&e.code===`conflict`?(q(`The side chat changed meanwhile. It was reloaded; refresh again.`,`warn`),await k()):q(`Couldn't refresh: ${U(e)}`,`err`)}finally{d(!1)}}}async function j(){let e=t();if(!(!e||c()||ph(x()))){d(!0);try{await V(gh.send(e),{method:`POST`,json:{text:x(),confirmed:!0}}),q(`Sent to the main session. It arrives after its current turn.`),S(``),v(!1),g(!1)}catch(e){q(`Couldn't send: ${U(e)}`,`err`)}finally{d(!1)}}}let N=()=>{let e=t();return e?ch(e):void 0},ee=()=>{let e=N();return e?.kind===`ready`?e.sessionID:void 0},P=()=>{let e=t();return e?uh(e,C()):void 0};return[(()=>{var i=BJ(),a=i.firstChild.firstChild.nextSibling;a.firstChild;var o=a.nextSibling,u=o.firstChild,d=u.nextSibling,C=d.nextSibling;return y(a,()=>YJ(t()?.sourceSessionID??``),null),u.$$click=()=>p(!f()),d.$$click=A,C.$$click=()=>(g(!h()),v(!1)),y(o,()=>e.paneTools,null),y(o,n(l,{get when(){return!e.paneTools},get children(){return n(F,{icon:`close`,class:`small`,label:`Close pane`,title:`Close pane (the side chat keeps running)`,onClick:()=>e.onClose()})}}),null),y(i,n(l,{get when(){return P()},children:e=>(()=>{var t=VJ();return y(t,()=>e().summary,null),y(t,n(l,{get when(){return e().stale},children:e=>[` · `,(()=>{var t=HJ();return y(t,e),t})()]}),null),t})()}),null),y(i,n(l,{get when(){return r(()=>!!f())()&&t()},children:e=>(()=>{var t=UJ();return y(t,n(m,{get each(){return e().snapshot.items},children:e=>(()=>{var t=WJ(),n=t.firstChild,r=n.nextSibling;return y(n,()=>e.role,null),y(n,()=>e.changed?` · changed`:``,null),y(n,()=>e.stale?` · no longer in the main session (earlier copy)`:``,null),y(n,()=>e.clipped?` · shortened`:``,null),y(r,()=>e.text),t})()})),t})()}),null),y(i,n(l,{get when(){return h()},get children(){var i=zJ(),a=i.firstChild;a.firstChild;var o=a.nextSibling,u=o.nextSibling;return i.addEventListener(`submit`,e=>{e.preventDefault(),_()?j():ph(x())||v(!0)}),y(a,()=>YJ(t()?.sourceSessionID??``),null),o.$$input=e=>S(e.currentTarget.value),y(i,n(l,{get when(){return r(()=>!!x())()&&ph(x())},children:e=>(()=>{var t=GJ();return y(t,e),t})()}),u),y(u,n(l,{get when(){return _()},get fallback(){return(()=>{var e=KJ();return s(()=>e.disabled=!!ph(x())),e})()},get children(){return[IJ(),(()=>{var e=LJ();return s(()=>e.disabled=c()),e})(),(()=>{var e=RJ();return e.$$click=()=>v(!1),s(()=>e.disabled=c()),e})()]}})),s(t=>{var n=`sidechat-send-${e.sideChatID}`,r=`sidechat-send-${e.sideChatID}`,i=_()||c();return n!==t.e&&b(a,`for`,t.e=n),r!==t.t&&b(o,`id`,t.t=r),i!==t.a&&(o.disabled=t.a=i),t},{e:void 0,t:void 0,a:void 0}),s(()=>o.value=x()),i}}),null),s(e=>{var n=f(),r=!t(),i=!t()||c(),a=h(),o=!t();return n!==e.e&&b(u,`aria-expanded`,e.e=n),r!==e.t&&(u.disabled=e.t=r),i!==e.a&&(d.disabled=e.a=i),a!==e.o&&b(C,`aria-expanded`,e.o=a),o!==e.i&&(C.disabled=e.i=o),e},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),i})(),n(l,{get when(){return ee()},keyed:!0,get fallback(){return(()=>{var t=JJ(),r=t.firstChild.nextSibling;return y(r,()=>a()??(N()&&N().kind!==`ready`?N().text:`Loading…`)),y(t,n(l,{get when(){return a()},get children(){var t=qJ();return t.$$click=()=>e.onClose(),t}}),null),t})()},children:t=>n(SJ,{id:t,get visible(){return e.visible},get focused(){return e.focused},get onGone(){return e.onGone},get rail(){return e.rail}})})]}z([`click`,`input`]);var ZJ=()=>{try{return globalThis.localStorage}catch{return}},[QJ,$J]=u(Bz(ZJ())),[eY,tY]=u();function nY(e,t){let n=Hz(QJ(),e,t),r=eY();if(!r)return n;let[i,a,o]=r.key.split(`:`);return i===e&&Number(a)===t?{...n,[o]:r.sizes}:n}function rY(e,t,n,r,i=!0){if(!i)return void tY({key:`${e}:${t}:${n}`,sizes:r});tY(void 0),$J(i=>Vz(ZJ(),i,e,t,n,r))}var iY=I(`<span class=pane-tools role=group aria-label=Pane><span class=pane-grip draggable=true title="Drag onto another pane to move this one"aria-hidden=true>`),aY=I(`<div class="cmp-empty pane-empty-drop"><p>No panes are open on this device.</p><p><a href=/>All sessions</a> · <a href=/artifacts>Artifacts</a></p><p class=muted>Drag a session or an artifact here to open it.`),oY=I(`<div class=pane-bar role=toolbar aria-label="Split layout"><span class=seg role=group aria-label=Layout></span><span class="pane-count muted"> of <!> panes · <kbd>F6</kbd> switches`),sY=I(`<div class=pane-tabs role=tablist aria-label="Open sessions">`),cY=I(`<div><div class=pane-grid>`),lY=I(`<button type=button>`),uY=I(`<div role=presentation><button type=button role=tab>`),dY=I(`<section class=pane tabindex=-1>`),fY=I(`<p class="muted cmp-empty">Loading the artifact…`),pY=E(()=>Hn(()=>import(`./ArtifactPane-CXSCmhyJ.js`).then(e=>({default:e.ArtifactPane})),__vite__mapDeps([7,1,8,9,10,11,12,13]))),mY=6,hY=[{split:`vertical`,label:`Side by side`,icon:`split`},{split:`horizontal`,label:`Stacked`,icon:`stack`},{split:`grid`,label:`Grid`,icon:`grid`}],gY=e=>{let t=rn(e);return t===void 0?e.sideChatID?`${e.sessionID}#${e.sideChatID}`:e.sessionID:`!${t}`},_Y=e=>e.startsWith(`!`)?e.slice(1):void 0,vY=e=>e.split(`#`)[0],yY=e=>encodeURIComponent(e).replace(/%/g,`_`),bY=e=>{let t=Fu(e)?.session.title;return typeof t==`string`&&t?t:`Session`},xY=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function SY(r){let[i,a]=u(!1),o=C(()=>({at:Pt(),id:r.routed}),void 0,{equals:(e,t)=>e.at===t.at&&e.id===t.id});S(e(o,({id:e})=>{if(e===void 0)return void a(!1);let t=!0;En(n=>{let r=hn(n,{sessionID:e});return t=r.outcome!==`invalid`,r.layout}),a(!t)})),S(()=>{let e=wu();e.size&&En(t=>ic(t,e))});let c=xn,d=()=>c().panes.length,p=C(()=>c().panes.map(gY),[],{equals:xY}),g=e=>p().indexOf(e),_=()=>p()[c().focused],v=()=>c().split,w=()=>Z()&&d()>1,[T,E]=u({}),D=e=>{let t=_Y(e);return t===void 0?e.includes(`#`)?`Side chat: ${bY(vY(e))}`:bY(vY(e)):`Artifact: ${T()[t]??`…`}`},O=()=>!Z()&&d()>1,A=()=>!!um()&&!Z();x(e(()=>c().panes[c().focused]?.sideChatID?void 0:c().panes[c().focused]?.sessionID,e=>{e&&!i()&&e!==ae(()=>r.routed)&&Vt(Ot(e),{replace:!0})}));let j=()=>requestAnimationFrame(()=>{let e=document.querySelector(`section.pane[data-focused]`);e&&!e.contains(document.activeElement)&&(e.querySelector(`textarea:not([disabled])`)??e).focus()}),N=e=>En(t=>ln(t,e)),ee=e=>{let t=new Map;for(let e of document.querySelectorAll(`section.pane .scroller`))t.set(e,e.scrollTop);e(),requestAnimationFrame(()=>t.forEach((e,t)=>t.scrollTop=e))},P=e=>{let t=c().focused;ee(()=>En(n=>pn(n,t,t+e))),j()},te=e=>{e<0||e>=d()||(En(t=>fn(t,e)),d()||Vt(`/`,{replace:!0}))},I=e=>{q(d()>1?`That session is gone (deleted, or its machine was revoked). Its pane was closed.`:`That session is gone (deleted, or its machine was revoked).`,`warn`),te(g(e))};fe(()=>{let e=e=>{if(i()||e.defaultPrevented||d()<2||e.getModifierState?.(`AltGraph`))return;let t=Oz(e);if(t){if(e.preventDefault(),t.type===`cycle`)En(e=>mn(e,t.step));else if(t.type===`focus`)N(Math.min(t.index,d()-1));else if(t.type===`move`)return P(t.step);else return te(c().focused);w()||j()}};document.addEventListener(`keydown`,e),M(()=>document.removeEventListener(`keydown`,e))});let ne,[re,ie]=u({w:0,h:0});fe(()=>{if(!ne||typeof ResizeObserver>`u`)return;let e=new ResizeObserver(()=>ne&&ie({w:ne.clientWidth,h:ne.clientHeight}));e.observe(ne),M(()=>e.disconnect())});let oe=()=>O()?Mz(v(),d()):{cols:1,rows:1},se=()=>nY(v(),d()),ce=e=>(e===`cols`?re().w:re().h)-(oe()[e]-1)*mY,le=(e,t)=>t>1?e.map(e=>`minmax(0, ${e}fr)`).join(` ${mY}px `):`minmax(0, 1fr)`,ue=()=>({"grid-template-columns":le(se().cols,oe().cols),"grid-template-rows":le(se().rows,oe().rows)}),de=e=>{if(!O())return{"grid-column":`1`,"grid-row":`1`};let t=Nz(v(),d(),e);return{"grid-column":`${2*t.col+1} / span ${2*t.colSpan-1}`,"grid-row":`${2*t.row+1}`}},R=e=>Array.from({length:Math.max(0,e)},(e,t)=>t),pe=e=>(t,n)=>rY(v(),d(),e,t,n),me=e=>{let t=d(),n=c().focused,r=e.key===`ArrowRight`?(n+1)%t:e.key===`ArrowLeft`?(n-1+t)%t:e.key===`Home`?0:e.key===`End`?t-1:-1;r<0||!e.target.matches(`[role="tab"]`)||(e.preventDefault(),N(r),requestAnimationFrame(()=>document.querySelector(`.pane-tabs [role="tab"][aria-selected="true"]`)?.focus()))},z=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 he(e){let t=()=>g(e.key),r=()=>v()===`horizontal`;return n(l,{get when(){return O()},get children(){var i=iY(),a=i.firstChild;return B(a,`dragend`,pm),a.addEventListener(`dragstart`,n=>{let r=c().panes[t()];(!r||!fm(n,{target:r,label:D(e.key),move:!0}))&&n.preventDefault()}),y(a,n(L,{name:`grip`})),y(i,n(F,{icon:`chevron`,class:`small flip`,get label(){return r()?`Move pane up`:`Move pane left`},get"aria-keyshortcuts"(){return Tz.moveEarlier},get disabled(){return t()<=0},onClick:()=>(N(t()),P(-1))}),null),y(i,n(F,{icon:`chevron`,class:`small`,get label(){return r()?`Move pane down`:`Move pane right`},get"aria-keyshortcuts"(){return Tz.moveLater},get disabled(){return t()>=d()-1},onClick:()=>(N(t()),P(1))}),null),y(i,n(F,{icon:`close`,class:`small`,label:`Close pane`,title:`Close pane (the session keeps running)`,get"aria-keyshortcuts"(){return Tz.close},onClick:()=>te(t())}),null),i}})}return n(l,{get when(){return!i()},get fallback(){return n(l,{get when(){return r.routed},keyed:!0,children:e=>n(SJ,{id:e})})},get children(){return[n(l,{get when(){return!d()},get children(){var e=aY();return e.firstChild.nextSibling.nextSibling,y(e,n(l,{get when(){return A()},get children(){return n(jJ,{label:`Open in a pane`})}}),null),e}}),(()=>{var e=cY(),r=e.firstChild;y(e,n(l,{get when(){return O()},get children(){var e=oY(),t=e.firstChild,r=t.nextSibling,i=r.firstChild,a=i.nextSibling;return a.nextSibling,e.$$keydown=z,y(t,n(m,{each:hY,children:e=>(()=>{var t=lY();return t.$$click=()=>En(t=>an(t,e.split)),y(t,n(L,{get name(){return e.icon}})),s(n=>{var r=e.label,i=e.label,a=v()===e.split;return r!==n.e&&b(t,`aria-label`,n.e=r),i!==n.t&&b(t,`title`,n.t=i),a!==n.a&&b(t,`aria-pressed`,n.a=a),n},{e:void 0,t:void 0,a:void 0}),t})()})),y(r,d,i),y(r,gn,a),e}}),r),y(e,n(l,{get when(){return w()},get children(){var e=sY();return e.$$keydown=me,y(e,n(m,{get each(){return p()},children:e=>{let t=()=>_()===e,r=()=>D(e);return(()=>{var i=uY(),a=i.firstChild;return a.$$click=()=>N(g(e)),y(a,r),y(i,n(F,{icon:`close`,class:`small`,get label(){return`Close ${r()}`},get tabindex(){return t()?0:-1},onClick:()=>te(g(e))}),null),s(n=>{var r=`pane-tab${t()?` selected`:``}`,o=`pane-tab-${yY(e)}`,s=`pane-${yY(e)}`,c=t(),l=t()?0:-1;return r!==n.e&&k(i,n.e=r),o!==n.t&&b(a,`id`,n.t=o),s!==n.a&&b(a,`aria-controls`,n.a=s),c!==n.o&&b(a,`aria-selected`,n.o=c),l!==n.i&&b(a,`tabindex`,n.i=l),n},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0}),i})()}})),e}}),r);var i=ne;return typeof i==`function`?t(i,r):ne=r,y(r,n(m,{get each(){return p()},children:e=>{let t=vY(e),r=()=>g(e),i=()=>_()===e,a=()=>!w()||i();return(()=>{var o=dY();return o.$$pointerdown=()=>N(g(e)),o.$$focusin=()=>N(g(e)),y(o,n(l,{get when(){return _Y(e)===void 0},get fallback(){return n(f,{get fallback(){return fY()},get children(){return n(pY,{get artifactID(){return _Y(e)},get paneTools(){return n(he,{key:e})},onTitle:t=>E(n=>({...n,[_Y(e)]:t}))})}})},get children(){return n(l,{get when(){return!e.includes(`#`)},get fallback(){return n(XJ,{get sideChatID(){return e.slice(e.indexOf(`#`)+1)},visible:a,focused:i,onGone:()=>I(e),onClose:()=>te(g(e)),rail:()=>!O()||i(),get paneTools(){return n(he,{key:e})}})},get children(){return n(SJ,{id:t,visible:a,focused:i,onGone:()=>I(e),rail:()=>!O()||i(),get paneTools(){return n(he,{key:e})}})}})}})),s(t=>{var n=`pane-${yY(e)}`,s=w()?`tabpanel`:`region`,c=w()?`pane-tab-${yY(e)}`:void 0,l=w()?void 0:`Pane ${r()+1} of ${d()}: ${D(e)}`,u=i()?``:void 0,f=!a(),p=de(r());return n!==t.e&&b(o,`id`,t.e=n),s!==t.t&&b(o,`role`,t.t=s),c!==t.a&&b(o,`aria-labelledby`,t.a=c),l!==t.o&&b(o,`aria-label`,t.o=l),u!==t.i&&b(o,`data-focused`,t.i=u),f!==t.n&&(o.hidden=t.n=f),t.s=h(o,p,t.s),t},{e:void 0,t:void 0,a:void 0,o:void 0,i:void 0,n:void 0,s:void 0}),o})()}}),null),y(r,n(l,{get when(){return A()},get children(){return n(m,{get each(){return p()},children:e=>n(jJ,{get index(){return g(e)},get style(){return de(g(e))}})})}}),null),y(r,n(m,{get each(){return R(oe().cols-1)},children:e=>n(FJ,{axis:`cols`,index:e,sizes:()=>se().cols,total:()=>ce(`cols`),get onChange(){return pe(`cols`)},get style(){return{"grid-column":`${2*e+2}`,"grid-row":v()===`grid`&&d()%2==1?`1`:`1 / -1`}}})}),null),y(r,n(m,{get each(){return R(oe().rows-1)},children:e=>n(FJ,{axis:`rows`,index:e,sizes:()=>se().rows,total:()=>ce(`rows`),get onChange(){return pe(`rows`)},style:{"grid-row":`${2*e+2}`,"grid-column":`1 / -1`}})}),null),s(t=>{var n=`workspace${O()?` ws-split`:``}${w()?` ws-tabs`:``}`,i=v(),a=ue();return n!==t.e&&k(e,t.e=n),i!==t.t&&b(e,`data-split`,t.t=i),t.a=h(r,a,t.a),t},{e:void 0,t:void 0,a:void 0}),e})()]}})}z([`keydown`,`click`,`focusin`,`pointerdown`]);var CY={artifacts:E(()=>Hn(()=>import(`./Library-CFmMbXEa.js`),__vite__mapDeps([14,1,9,10,11,3,12,15]))),teams:E(()=>Hn(()=>import(`./TeamsPage-C1NGrUR-.js`),__vite__mapDeps([16,1,9,17,18,19]))),watchtower:E(()=>Hn(()=>import(`./Watchtower-DnvlJaU0.js`).then(e=>e.t),__vite__mapDeps([20,1,9,10,11,3,18,17,19,21]))),profiles:E(()=>Hn(()=>import(`./ProfilesDestination-7jpOc2HM.js`),__vite__mapDeps([22,1,9,17])))},wY=I(`<div class=feature-page><header class=topbar><h1 class=title></h1></header><div class=feature-scroll><div class=feature-body>`);function TY(e){return(()=>{var t=wY(),r=t.firstChild,i=r.firstChild,a=r.nextSibling.firstChild;return y(r,n(l,{get when(){return Z()},get children(){return n(F,{icon:`menu`,label:`Open sidebar`,onClick:Gp})}}),i),y(i,()=>e.title),y(r,()=>e.actions,null),y(a,()=>e.children),t})()}var EY=I(`<p class=feature-note> isn't available yet. <a href=/>Back to All sessions`),DY=I(`<p class=muted>Loading…`);function OY(e){let t=C(()=>Ye.find(t=>t.id===e.id)),r=C(()=>{let e=t();return e&&Ve(e,{signedIn:!!X()})===`ok`?CY[e.id]:void 0});return n(l,{get when(){return r()},get fallback(){return n(TY,{get title(){return t()?.label??`Not found`},get children(){var e=EY(),n=e.firstChild;return y(e,()=>t()?.label??`This page`,n),e}})},children:r=>n(f,{get fallback(){return n(TY,{get title(){return t().label},get children(){return DY()}})},get children(){return n(D,{get component(){return r()},get rest(){return e.rest}})}})})}var kY=I(`<span class="badge-pill armed-left"role=timer title="How long this stays armed for a spoken answer">`),AY=I(`<p class="muted small armed-why">Why: `),jY=I(`<div class="card decision armed-decision"role=group aria-label="The Concierge asks you to confirm"><p class="blocker-head decision-head"><strong>Confirm</strong> <span class=muted>from </span></p><p class=armed-question></p><div class="row armed-options"></div><p class="muted small armed-hint">`),MY=I(`<button type=button>`);function NY(e){let t=()=>e.decision,[i,a]=u(!1),[o,c]=u(Date.now()),d=setInterval(()=>c(Date.now()),1e3);M(()=>clearInterval(d));let f=()=>{let e=xu()?.expiresAt;return e===void 0?``:Ze(e,o())},p=async e=>{a(!0);try{await xx(t().id,e)}catch(e){q(U(e),`err`),a(!1)}};return(()=>{var e=jY(),a=e.firstChild,o=a.firstChild.nextSibling.nextSibling;o.firstChild;var c=a.nextSibling,u=c.nextSibling,d=u.nextSibling;return y(o,()=>ve(t(),Bu,wu()),null),y(a,n(l,{get when(){return f()},get children(){var e=kY();return y(e,f),e}}),null),y(c,()=>Re(t(),Bu,wu())),y(e,n(kg,{get decision(){return t()}}),u),y(e,n(l,{get when(){return r(()=>!!t().recommendation?.why)()&&t().recommendation.why!==Ag(t())},get children(){var e=AY();return e.firstChild,y(e,()=>t().recommendation.why,null),e}}),u),y(u,n(m,{get each(){return t().options},children:e=>(()=>{var t=MY();return t.$$click=()=>void p(e.id),y(t,()=>e.label),s(n=>{var r=`btn${e.safe||e.id===`always`?``:` primary`}`,a=i();return r!==n.e&&k(t,n.e=r),a!==n.t&&(t.disabled=n.t=a),n},{e:void 0,t:void 0}),t})()})),y(d,()=>Zs(!!ru()&&!ru().reason)),s(n=>{var r=t().id,i=t().id,a=Tt(t()),s=t().question;return r!==n.e&&b(e,`data-armed-decision`,n.e=r),i!==n.t&&b(e,`data-decision`,n.t=i),a!==n.a&&b(o,`title`,n.a=a),s!==n.o&&b(c,`title`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),e})()}z([`click`]);var PY=I(`<button type=button class="btn small"aria-label="Restart the Concierge"title="Restart the Concierge (a new session)">Restart`),FY=I(`<header class=concierge-head><div class="concierge-title grow"><h2 class=title>Concierge</h2><p class="small muted concierge-status"role=status aria-live=polite></p></div><a class=icon-btn href=/settings/concierge aria-label="Concierge settings"title="Concierge settings">`),IY=I(`<p role=status data-concierge-notice>`),LY=I(`<div class=concierge-asked aria-label="Decisions from the Concierge"role=group>`),RY=I(`<div class="card decision closed-decision"role=group tabindex=-1><p class="blocker-head decision-head"><strong>Decision</strong> <span class=badge-pill></span><span class=grow></span></p><p class="blocker-text decision-question"></p><p class="muted small"data-closed-note>`),zY=I(`<div class=concierge-idle><form class=concierge-composer><textarea rows=1 aria-label="Ask the Concierge"placeholder="The Concierge is not running"disabled>`),BY=I(`<aside class="concierge-panel side"aria-label=Concierge tabindex=-1>`),VY=I(`<section class="concierge-panel page"aria-label=Concierge tabindex=-1>`),HY=I(`<p class="working-line muted small"role=status><span class="spinner small"></span> Working…`),UY=I(`<div class=concierge-scroll>`),WY=I(`<p class="note err"role=alert>Voice: `),GY=I(`<button type=button>`),KY=I(`<div class=concierge-dock><form class=concierge-composer><textarea rows=1 aria-label="Ask the Concierge"></textarea><button type=submit class="btn primary send"aria-label="Send to the Concierge"title="Send (Enter)">`),qY=I(`<p class="muted small pad">Loading…`),JY=I(`<p class="muted small pad">`),YY=I(`<p>`),XY=3e4,ZY=80,QY=/^#decision-(dec_[A-Za-z0-9]{1,64})$/,$Y=new Set([`starting`,`running`,`waiting_machine`,`backoff`,`failed`]),eX=()=>!!ru()&&!ru().reason;function tX(i){let a=mu,o=()=>(Y.machines??[]).map(e=>({id:e.id,name:e.name,online:e.online===!0})),c=()=>o().find(e=>e.id===a()?.machineID),d=()=>$s(a(),c()),f=()=>a()?.state===`running`&&!!a()?.sessionID&&c()?.online!==!1,p=C(()=>yx()),m=C(()=>cc(su(),a(),p())),[h,g]=u(!1),[_,v]=u(),S,w=nz(),T=()=>St(`/`);async function E(){g(!0);try{await V(`/api/agent/concierge/restart`,{method:`POST`,json:{}}),q(`Restarting the Concierge`)}catch(e){q(`Could not restart: ${U(e)}`,`err`)}finally{g(!1)}}fe(()=>{if(i.mode!==`side`)return;let e=e=>{e.key!==`Escape`||e.defaultPrevented||ee(S)||document.querySelector(`.menu-pop, [role='menu']`)||(e.preventDefault(),T())};document.addEventListener(`keydown`,e),M(()=>document.removeEventListener(`keydown`,e)),requestAnimationFrame(()=>S&&!S.contains(document.activeElement)&&S.focus())});function D(e){let t=()=>requestAnimationFrame(()=>{let t=S?.querySelector(`[data-decision="${e}"]`);t?(t.scrollIntoView({block:`nearest`,behavior:`smooth`}),t.classList.add(`flash`),setTimeout(()=>t.classList.remove(`flash`),2500),t.focus({preventScroll:!0})):q(`That Decision is no longer available`)});if(S?.querySelector(`[data-decision="${e}"]`))return t();Dd(e).then(e=>{e&&e.state!==`open`&&v(e),t()})}x(e(Pt,e=>{let t=QY.exec(e.hash)?.[1];t&&(Vt(`/concierge`,{replace:!0}),D(t))})),fe(()=>{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&&QY.exec(new URL(t.getAttribute(`href`)??``,location.origin).hash)?.[1];n&&t.getAttribute(`href`).startsWith(`/concierge#`)&&(e.preventDefault(),D(n))};S?.addEventListener(`click`,e),M(()=>S?.removeEventListener(`click`,e))}),M(()=>{w?.isConnected&&w.focus()});let O=()=>[(()=>{var e=FY(),t=e.firstChild,c=t.firstChild.nextSibling,u=t.nextSibling;return y(e,n(l,{get when(){return i.mode===`page`},get children(){return n(F,{icon:`back`,label:`Back`,onClick:T})}}),t),y(e,n(L,{name:`spark`,class:`concierge-mark`}),t),y(c,()=>cs(a(),o(),N()),null),y(c,n(l,{get when(){return a()?.sessionID},get children(){return n(FL,{get sessionID(){return a().sessionID}})}}),null),y(e,n(l,{get when(){return r(()=>!!a())()&&$Y.has(a().state)},get children(){var e=PY();return e.$$click=()=>void E(),s(()=>e.disabled=h()),e}}),u),y(u,n(L,{name:`settings`})),y(e,n(l,{get when(){return i.mode===`side`},get children(){return n(F,{icon:`close`,label:`Close the Concierge (Esc)`,onClick:T})}}),null),s(()=>b(c,`data-concierge-panel-status`,a()?.state??`none`)),e})(),n(l,{get when(){return d()},get children(){var e=IY();return y(e,d),s(()=>k(e,`concierge-notice${a()?.state===`failed`?` err`:``}`)),e}}),n(l,{get when(){return p()},children:e=>n(NY,{get decision(){return e()}})}),n(l,{get when(){return m().length},get children(){var e=LY();return y(e,n(Kg,{get decisions(){return m()}})),e}}),n(l,{get when(){return _()},keyed:!0,children:e=>(()=>{var t=RY(),r=t.firstChild,i=r.firstChild.nextSibling.nextSibling;i.nextSibling;var a=r.nextSibling,o=a.nextSibling;return y(i,()=>e.state),y(r,n(F,{icon:`close`,label:`Close this Decision`,onClick:()=>v(void 0)}),null),y(a,()=>Re(e,Bu,wu())),y(t,n(kg,{decision:e}),o),y(o,()=>Ho(e)),s(n=>{var r=`Decision (${e.state}): ${e.question}`,i=e.id,o=e.id,s=e.question;return r!==n.e&&b(t,`aria-label`,n.e=r),i!==n.t&&b(t,`data-decision`,n.t=i),o!==n.a&&b(t,`data-closed-decision`,n.a=o),s!==n.o&&b(a,`title`,n.o=s),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t})()}),n(l,{get when(){return r(()=>!!f())()&&a()?.sessionID},keyed:!0,get fallback(){return(()=>{var e=zY();return e.firstChild.addEventListener(`submit`,e=>e.preventDefault()),e})()},children:e=>n(nX,{id:e,get autofocus(){return i.mode===`side`}})})];return n(l,{get when(){return i.mode===`side`},get fallback(){return(()=>{var e=VY(),n=S;return typeof n==`function`?t(n,e):S=e,y(e,O),e})()},get children(){var e=BY(),n=S;return typeof n==`function`?t(n,e):S=e,y(e,O),e}})}function nX(r){let i=r.id,a=()=>Fu(i),o=()=>a()?.session.status,c=()=>bo(o()),d=new it,[f,p]=u(0),h=()=>p(e=>e+1),[g,_]=u(!1),[v,S]=u({}),[w,T]=u([]),E=0,D=(e,t=`sys`)=>T(n=>[...n.slice(-10),{key:`n${++E}`,text:e,kind:t}]),O=C(()=>(f(),d.status(o(),i),EB(d.rows()))),A=C(()=>iX(O())),[j,N]=Or({}),ee,P=!0,F=()=>requestAnimationFrame(()=>ee&&(ee.scrollTop=ee.scrollHeight));x(e(A,()=>P&&F())),x(()=>{for(let e of Ko(O(),du()))Dd(e)});let te=e=>new URLSearchParams(Object.entries(e).flatMap(([e,t])=>t===void 0?[]:[[e,String(t)]])).toString(),I=new Jz(d,e=>G(`${H(i)}/timeline?${te(e)}`),{limit:ZY,onChange:h});async function ne(){try{let{messages:e}=await G(`${H(i)}/messages?limit=200`);for(let t of e??[]){let e=nt(i,t);e&&d.hubMessage(e)}h()}catch{}}async function re(){try{await I.first()}catch(e){D(`Could not load the conversation: ${U(e)}`,`err`)}_(!0),await ne(),F()}let ie,ae=c(),oe=Nu(e=>{let t=typeof e.rootID==`string`?e.rootID:e.sessionID;if(e.type===`resync`)I.resync().catch(()=>{}).then(ne);else if(t!==i)return;else if(e.type===`activity`&&e.item&&e.item.kind!==`thinking`)d.activity(e.sessionID,e.item);else if(e.type===`reasoning`&&typeof e.messageID==`string`&&typeof e.delta==`string`)d.appendReasoning({sessionID:e.sessionID,messageID:e.messageID,delta:e.delta});else if(e.type===`delta`&&typeof e.messageID==`string`&&typeof e.text==`string`)d.appendText({sessionID:e.sessionID,messageID:e.messageID,...Number.isInteger(e.ordinal)?{ordinal:e.ordinal}:{},delta:e.text});else if(e.type===`message`){let t=nt(i,e.message);t&&d.hubMessage(t)}else if(e.type===`turn`&&ie){let{sentAt:t}=ie;ie=void 0,xe(e,t)}else if(e.type===`status`){let t=bo(e.sessions),n=ae&&!t;if(ae=t,t)return;for(let e of d.rows())e.live&&d.upsert({key:e.key,live:!1});d.endReasoning(void 0),n&&I.resync().catch(()=>{}).then(ne)}else return;h()}),se=()=>document.visibilityState===`visible`,ce=(e,t=!1)=>(vx(e),V(`${H(i)}/presence`,{method:`POST`,json:{visible:e},keepalive:t}).catch(()=>{})),le=()=>void ce(se(),!se()),ue=()=>void ce(!1,!0),de,R=Px,pe=()=>R().phase!==`off`&&R().sessionID===i,me=()=>R().error?.sessionID===i?R().error.message:void 0;M(wx.attach(i,{user:e=>{let t=`voice:${++E}`;return d.upsert({key:t,kind:`user`,text:e,at:Date.now()}),S(e=>({...e,[t]:`pending`})),h(),t},tick:(e,t)=>S(n=>({...n,[e]:t})),agent:e=>{let t=e.messageID?d.liveTextKey(e.messageID):`say:${++E}`,{mode:n,text:r}=vy(d.get(t)?.text??``,e.text);n!==`keep`&&(d.upsert({key:t,messageID:e.messageID,kind:`assistant`,text:r,at:d.get(t)?.at??Date.now()}),h())},note:(e,t)=>D(e,t??`sys`)}));async function z(){pe()||(Zy(),Lx.cancel()),await wx.toggle(i),wx.isOn(i)&&wx.state.phase===`on`&&D(`Voice on. Talk to the Concierge; say “yes” or “no” to answer the Decision it is asking about.`)}let[B,ge]=u(``),[_e,ve]=u(!1),ye,be=()=>{ye&&(ye.style.height=`auto`,ye.style.height=`${Math.min(ye.scrollHeight,200)}px`)};function xe(e,t){let n=e.reply?.trim(),r=d.rows().some(e=>e.kind===`assistant`&&(e.at??0)>=t&&e.text?.trim()===n);e.reply&&!r&&d.upsert({key:`reply:${++E}`,kind:`assistant`,text:e.reply,at:Date.now()});let i=X_(e);i&&D(i.text,i.kind),h()}async function Se(){let e=B().trim();if(!e||_e())return;let t=yx(),n=Ws(e,t);if(n.kind===`answer`){ve(!0);try{await xx(n.decisionID,n.option,`text`),ge(``),d.upsert({key:`answered:${++E}`,kind:`user`,text:e,at:Date.now(),note:Ks(t,n.option)}),h(),P=!0,F()}catch(e){q(`Not answered: ${U(e)}${e instanceof W&&e.status===403?`. Tap an option on the card.`:``}`,`err`)}finally{ve(!1)}return}if(ge(``),queueMicrotask(be),pe()){wx.sendTyped(i,e);return}let r=`local:${++E}`,a=Date.now();he(()=>{d.upsert({key:r,kind:`user`,text:e,at:a}),S(e=>({...e,[r]:`pending`})),h()}),P=!0,F();try{let t=await V(`${H(i)}/turn`,{method:`POST`,json:{text:e},headers:{prefer:`respond-async`}}),n=await t.json().catch(()=>({})),o=Y_(t.status,n);S(e=>({...e,[r]:o===`steered`?`queued`:`sent`})),o===`accepted`?ie={sentAt:a}:xe(n,a)}catch(t){S(e=>({...e,[r]:`failed`})),D(`Could not send: ${U(t)}`,`err`),B()||ge(e)}}return fe(()=>{re(),ce(se()),de=setInterval(()=>se()&&void ce(!0),XY),document.addEventListener(`visibilitychange`,le),window.addEventListener(`pagehide`,ue),r.autofocus&&requestAnimationFrame(()=>ye?.focus())}),M(()=>{oe(),clearInterval(de),document.removeEventListener(`visibilitychange`,le),window.removeEventListener(`pagehide`,ue),ue()}),[(()=>{var e=UY();e.addEventListener(`scroll`,e=>P=e.currentTarget.scrollHeight-e.currentTarget.scrollTop-e.currentTarget.clientHeight<80);var r=ee;return typeof r==`function`?t(r,e):ee=e,y(e,n(l,{get when(){return g()},get fallback(){return qY()},get children(){return n(l,{get when(){return A().length},get fallback(){return(()=>{var e=JY();return y(e,()=>Xs(eX())),e})()},get children(){return n(aG,{sessionID:i,get blocks(){return A()},get ticks(){return v()},expanded:j,onToggle:(e,t)=>N(e,t),onDetail:(e,t)=>{d.detail(e,t),h()}})}})}}),null),y(e,n(m,{get each(){return w()},children:e=>(()=>{var t=YY();return y(t,()=>e.text),s(n=>{var r=`note ${e.kind}`,i=e.kind===`err`?`alert`:void 0;return r!==n.e&&k(t,n.e=r),i!==n.t&&b(t,`role`,n.t=i),n},{e:void 0,t:void 0}),t})()}),null),y(e,n(l,{get when(){return c()},get children(){return HY()}}),null),e})(),(()=>{var e=KY(),r=e.firstChild,i=r.firstChild,a=i.nextSibling;y(e,n(l,{get when(){return pe()},get children(){return n(uV,{get state(){return R().voice},get level(){return R().level},get held(){return R().held},get ignored(){return R().ignored},get working(){return c()},model:`Concierge`,onMute:()=>wx.mute(),onEnd:()=>void wx.end(),onModel:()=>q(`The Concierge keeps its own model: change it in Settings → Concierge`),get notifyHint(){return Mx()},onAllowNotifications:()=>void Nx(),get timing(){return R().timing},get detector(){return R().detector},get turn(){return R().turn},get front(){return R().front}})}}),r),y(e,n(l,{get when(){return me()},get children(){var e=WY();return e.firstChild,y(e,me,null),e}}),r),r.addEventListener(`submit`,e=>{e.preventDefault(),Se()}),i.$$keydown=e=>{e.key===`Enter`&&!e.shiftKey&&!e.isComposing&&!(Z()&&`ontouchstart`in window)&&(e.preventDefault(),Se())},i.$$input=e=>{ge(e.currentTarget.value),be()};var o=ye;return typeof o==`function`?t(o,i):ye=i,y(r,n(l,{get when(){return eX()||pe()},get children(){var e=GY();return e.$$click=()=>void z(),y(e,n(L,{name:`wave`})),s(t=>{var n=`icon-btn concierge-voice${pe()?` on`:``}`,r=pe(),i=pe()?`Stop talking to the Concierge`:`Talk to the Concierge`,a=pe()?`End Voice with the Concierge`:`Talk to the Concierge (Voice)`;return n!==t.e&&k(e,t.e=n),r!==t.t&&b(e,`aria-pressed`,t.t=r),i!==t.a&&b(e,`aria-label`,t.a=i),a!==t.o&&b(e,`title`,t.o=a),t},{e:void 0,t:void 0,a:void 0,o:void 0}),e}}),a),y(a,n(L,{name:`send`})),s(e=>{var t=pe()?`Voice is on: talk, or type here`:`Ask the Concierge…`,n=!B().trim()||_e();return t!==e.e&&b(i,`placeholder`,e.e=t),n!==e.t&&(a.disabled=e.t=n),e},{e:void 0,t:void 0}),s(()=>i.value=B()),e})()]}var rX={unknown:`link`};function iX(e){let t=Iu,n=[...du().values()].map(e=>({...e,question:Be(e.question,Bu)})),r=[];for(let i of e)if(!(i.type===`message`&&i.primer)){if(i.type===`message`&&i.direction===`in`&&To(i.from)){let e=Mo(i.text,t);r.push(e?{...i,summary:e}:i)}else i.type===`message`&&i.text.includes(`dec_`)?r.push({...i,parts:Ro(i.text,n,rX)}):i.type===`assistant`&&i.text.includes(`dec_`)?r.push({...i,text:zo(i.text,n,rX)}):i.type===`tools`?r.push({...i,items:i.items.map(e=>typeof e.summary==`string`&&e.summary.includes(`ses_`)?{...e,summary:Vo(e.summary,t)}:e)}):r.push(i)}return r}z([`click`,`input`,`keydown`]);var aX=I(`<main class=entry><p></p><button type=button class=btn>Retry`),oX=I(`<main class=entry><p class=muted>Loading…`),sX=I(`<div class=drawer-backdrop>`),cX=I(`<div class=voice-strip>`),lX=I(`<div class=conn-banner role=status>Reconnecting to the hub…`),uX=I(`<div role=status aria-live=polite>`),dX=I(`<p class="muted cmp-empty"data-concierge-wait>Loading…`),fX=I(`<div><main class=main>`),pX=I(`<button type=button class="btn small">`),mX=I(`<div role=status aria-live=polite><span>`),hX=I(`<header class=topbar><span class="title display grow">Hub`),gX=I(`<div class=home-shell><div class=home-scroll>`),_X=()=>dt().name===`concierge`&&!Z(),vX=()=>{let e=xC();return e.name===`session`?ns(e.id,mu(),bu(),Y.machines,gu(),gu()?[]:Cu()):void 0},yX=()=>{let e=xC();return vX()===`session`?e.id:void 0},bX=()=>pc(Sc(Px().phase===`off`,yX()),dt().name===`concierge`?mu()?.sessionID:void 0);function xX(){td(()=>Px().phase!==`off`),x(()=>nd(bX()));let[t,i]=u(``),[a,c]=u(!1),d=async()=>{i(``);try{if(!await Uu())return;ad(bX()),jd(),up(),c(!0)}catch(e){i(`Cannot reach the hub: ${e.message}`)}};return x(e(()=>dt().name,e=>{e!==`pair`&&!a()&&d(),Z()&&Bp(!1)})),x(()=>{!X()&&a()&&dt().name!==`pair`&&c(!1)}),x(()=>{let e=dt();e.name===`session`&&wu().has(e.id)&&Vt(`/concierge`,{replace:!0})}),x(()=>Lx.viewing(xc()??yX())),fe(()=>M($A())),fe(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`b`&&(e.preventDefault(),Gp())};document.addEventListener(`keydown`,e),M(()=>document.removeEventListener(`keydown`,e))}),x(()=>tm(_X())),x(()=>{let e=nm(),t=document.documentElement.style;t.setProperty(`--side-w`,`${e.side}px`),t.setProperty(`--rail-w`,`${e.rail}px`),e.concierge&&t.setProperty(`--concierge-w`,`${e.concierge}px`)}),x(()=>{a()&&location.hash===`#speech`&&dt().name!==`settings`&&Vt(`/settings/voice#speech`,{replace:!0})}),[n(v,{get children(){return[n(o,{get when(){return r(()=>dt().name===`pair`)()&&dt()},children:e=>n(Nf,{get next(){return e().next},get error(){return e().error}})}),n(o,{get when(){return t()},get children(){var e=aX(),n=e.firstChild,r=n.nextSibling;return y(n,t),r.$$click=()=>void d(),e}}),n(o,{get when(){return!a()},get children(){return oX()}}),n(o,{get when(){return r(()=>dt().name===`approve`)()&&dt()},children:e=>n(Ff,{get code(){return e().code}})}),n(o,{get when(){return r(()=>dt().name===`consent`)()&&dt()},children:e=>n(Lf,{get flow(){return e().flow}})}),n(o,{when:!0,get children(){var e=fX(),t=e.firstChild;return y(e,n(l,{get when(){return!Z()||zp()},get children(){return[n(l,{get when(){return Z()},get children(){var e=sX();return e.$$click=()=>Bp(!1),e}}),n(l,{get when(){return!Lp()||Z()},get children(){return[n(Cz,{get phone(){return Z()},onClose:()=>Bp(!1),onCollapse:Gp}),n(l,{get when(){return!Z()},get children(){return n(ES,{panel:`side`,label:`Resize sidebar`})}})]}})]}}),t),y(e,n(l,{get when(){return r(()=>!!Lp())()&&!Z()},get children(){return n(XR,{onExpand:Gp})}}),t),y(t,n(l,{get when(){return r(()=>Px().phase!==`off`)()&&xC().name!==`session`},get children(){var e=cX();return y(e,n(LL,{})),e}}),null),y(t,n(l,{get when(){return Y.connection===`down`},get children(){return lX()}}),null),y(t,n(l,{get when(){return r(()=>Y.connection!==`down`)()&&Xu()},get children(){var e=uX();return y(e,()=>Xu()===`reconnecting`?`Reconnecting…`:`Updated`),s(()=>k(e,`sync-note ${Xu()}`)),e}}),null),y(t,n(l,{get when(){return r(()=>!(!um()||Z()||yX()))()&&xC().name!==`panes`},get children(){return n(NJ,{})}}),null),y(t,n(v,{get children(){return[n(o,{get when(){return r(()=>!bu())()&&(xC().name===`session`||xC().name===`panes`)||vX()===`wait`},get children(){return dX()}}),n(o,{get when(){return yX()||xC().name===`panes`},get children(){return n(SY,{get routed(){return yX()}})}}),n(o,{get when(){return r(()=>xC().name===`new`)()&&xC()},children:e=>n(vC,_(()=>e()))}),n(o,{get when(){return r(()=>xC().name===`feature`)()&&xC()},children:e=>n(OY,_(()=>e()))}),n(o,{get when(){return xC().name===`settings`},get children(){return n(tL,{})}}),n(o,{get when(){return xC().name===`concierge`},get children(){return n(tX,{mode:`page`})}}),n(o,{when:!0,get children(){return n(SX,{})}})]}}),null),y(e,n(l,{get when(){return _X()},get children(){return n(tX,{mode:`side`})}}),null),s(()=>k(e,`shell${Lp()&&!Z()?` collapsed`:``}${Z()?` phone`:``}${zp()?` drawer`:``}`)),e}})]}}),n(Fh,{}),n(xF,{}),n(re,{}),n(l,{get when(){return Ut()},children:e=>(()=>{var t=mX(),r=t.firstChild;return y(r,()=>e().text),y(t,n(l,{get when(){return e().action},get children(){var t=pX();return t.$$click=()=>{e().action.run(),Mt()},y(t,()=>e().action.label),t}}),null),s(()=>k(t,`toast ${e().kind}`)),t})()})]}function SX(){return(()=>{var e=gX(),t=e.firstChild;return y(e,n(l,{get when(){return Z()},get children(){var e=hX(),t=e.firstChild;return y(e,n(F,{icon:`menu`,label:`Open sidebar`,onClick:Gp}),t),y(e,n(rz,{}),null),e}}),t),y(t,n(bS,{})),e})()}z([`click`]),me(()=>n(xX,{}),document.getElementById(`root`)),dp();export{aj as $,ZP as A,mN as B,CK as C,dG as D,MG as E,VM as F,dN as G,XM as H,tN as I,cN as J,UM as K,WM as L,XP as M,GP as N,Qz as O,zM as P,kM as Q,vN as R,UG as S,HG as T,$M as U,fN as V,eN as W,MM as X,IM as Y,DM as Z,sK as _,NK as a,Y as at,FG as b,BK as c,MK as d,Ph as et,PK as f,cK as g,lK as h,FK as i,Gp as it,aF as j,yF as k,jK as l,uK as m,LK as n,fm as nt,AK as o,Nu as ot,QG as p,HM as q,IK as r,Z as rt,DK as s,Pu as st,TY as t,pm as tt,RK as u,oK as v,RG as w,PG as x,aK as y,gN as z};