@huynle/hub 0.10.1 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/README.md +36 -8
  3. package/package.json +1 -1
  4. package/packages/claude-code/package.json +1 -1
  5. package/packages/claude-code/src/sessions.ts +4 -1
  6. package/packages/cli/dist/hub-cli.js +851 -466
  7. package/packages/cli/package.json +1 -1
  8. package/packages/cli/src/cli.ts +12 -7
  9. package/packages/cli/src/decisions.ts +52 -4
  10. package/packages/cli/src/format.ts +9 -0
  11. package/packages/cli/src/grants-mcp.ts +65 -0
  12. package/packages/cli/src/mcp-operations.ts +49 -0
  13. package/packages/cli/src/mcp.ts +26 -4
  14. package/packages/cli/src/subscriptions-mcp.ts +76 -0
  15. package/packages/cli/src/team-intake-mcp.ts +2 -1
  16. package/packages/cli/src/teams-mcp.ts +9 -3
  17. package/packages/codex/package.json +1 -1
  18. package/packages/codex/src/sessions.ts +14 -3
  19. package/packages/node/package.json +1 -1
  20. package/packages/preset/package.json +1 -1
  21. package/packages/protocol/package.json +1 -1
  22. package/packages/protocol/schema/api/v1/_root.json +119 -0
  23. package/packages/protocol/schema/api/v1/account.json +419 -0
  24. package/packages/protocol/schema/api/v1/decisions.json +635 -0
  25. package/packages/protocol/schema/api/v1/discovery.json +110 -0
  26. package/packages/protocol/schema/api/v1/events.json +679 -0
  27. package/packages/protocol/schema/api/v1/session-actions.json +660 -0
  28. package/packages/protocol/schema/api/v1/sessions.json +2055 -0
  29. package/packages/protocol/schema/api/v1/speech.json +492 -0
  30. package/packages/protocol/schema/api/v1/unspecified.json +282 -0
  31. package/packages/protocol/schema/app-delivery/v1.schema.json +67 -5
  32. package/packages/protocol/schema/app-front/v1.schema.json +7 -3
  33. package/packages/protocol/src/api-v1.ts +8 -0
  34. package/packages/protocol/src/index.ts +2 -0
  35. package/packages/protocol/src/teams.ts +16 -0
  36. package/packages/protocol/src/voice-recording.ts +39 -2
  37. package/packages/runtime-openshell/image/entry.sh +3 -1
  38. package/packages/runtime-openshell/image/start.sh +3 -1
  39. package/packages/runtime-openshell/package.json +1 -1
  40. package/packages/runtime-sdk/package.json +1 -1
  41. package/packages/sdk/package.json +1 -1
  42. package/packages/sdk/src/app-front.ts +2 -2
  43. package/packages/sdk/src/ask-fields.ts +76 -0
  44. package/packages/sdk/src/client.ts +24 -2
  45. package/packages/sdk/src/envelope.ts +3 -2
  46. package/packages/sdk/src/index.ts +1 -0
  47. package/packages/sdk/src/team-intake.ts +6 -0
  48. package/packages/sdk/src/teams.ts +4 -0
  49. package/packages/sdk/src/types.ts +36 -4
  50. package/packages/sdk/src/wake.ts +9 -4
  51. package/packages/spoke-sdk/package.json +1 -1
  52. package/src/central/agent/agent-limits.ts +185 -0
  53. package/src/central/agent/app-decisions.ts +6 -5
  54. package/src/central/agent/decisions.ts +136 -9
  55. package/src/central/agent/delivery.ts +164 -22
  56. package/src/central/agent/errors.ts +2 -1
  57. package/src/central/agent/events.ts +20 -2
  58. package/src/central/agent/grant-routes.ts +14 -1
  59. package/src/central/agent/grants.ts +23 -0
  60. package/src/central/agent/launch-engine.ts +9 -6
  61. package/src/central/agent/message-limits.ts +6 -0
  62. package/src/central/agent/message-routes.ts +33 -6
  63. package/src/central/agent/messages.ts +7 -0
  64. package/src/central/agent/placement.ts +4 -2
  65. package/src/central/agent/read-routes.ts +5 -0
  66. package/src/central/agent/routes.ts +13 -0
  67. package/src/central/agent/subscriptions.ts +15 -4
  68. package/src/central/api-v1.ts +115 -0
  69. package/src/central/artifacts/store.ts +4 -2
  70. package/src/central/concierge/board-results.ts +2 -1
  71. package/src/central/concierge/notifier.ts +4 -2
  72. package/src/central/config.ts +24 -3
  73. package/src/central/health/classify.ts +209 -0
  74. package/src/central/http.ts +380 -36
  75. package/src/central/recording/export.ts +57 -3
  76. package/src/central/recording/index.ts +236 -17
  77. package/src/central/recording/ingest.ts +11 -2
  78. package/src/central/recording/routes.ts +61 -7
  79. package/src/central/recording/schema.ts +68 -3
  80. package/src/central/recording/settings.ts +19 -5
  81. package/src/central/recording/store.ts +19 -0
  82. package/src/central/recording/taps.ts +45 -1
  83. package/src/central/registry.ts +34 -3
  84. package/src/central/speech/openai.ts +4 -4
  85. package/src/central/speech/openrouter.ts +4 -4
  86. package/src/central/speech/provider.ts +32 -1
  87. package/src/central/speech/service.ts +6 -5
  88. package/src/central/teams/budgets.ts +144 -0
  89. package/src/central/teams/hop-stalls.ts +80 -0
  90. package/src/central/teams/intake.ts +38 -6
  91. package/src/central/teams/involvement.ts +95 -0
  92. package/src/central/teams/item-decisions.ts +60 -0
  93. package/src/central/teams/item-eligibility.ts +35 -0
  94. package/src/central/teams/item-stalls.ts +87 -0
  95. package/src/central/teams/loops.ts +40 -0
  96. package/src/central/teams/policy.ts +10 -0
  97. package/src/central/teams/progress.ts +154 -0
  98. package/src/central/teams/routes.ts +2 -0
  99. package/src/central/teams/seats.ts +3 -3
  100. package/src/central/teams/staffing.ts +5 -0
  101. package/src/central/teams/store.ts +20 -1
  102. package/src/central/teams/validation.ts +16 -2
  103. package/src/central/workspaces/coordinator.ts +3 -1
  104. package/src/spoke/hub-tool.ts +26 -11
  105. package/web/dist/assets/{ArtifactPage-CsPjam8D.js → ArtifactPage-TbFJi59n.js} +1 -1
  106. package/web/dist/assets/{ArtifactPane-B9weO8L6.js → ArtifactPane-7D-M-Ich.js} +1 -1
  107. package/web/dist/assets/{ArtifactWorkbench-DzKhMs3l.js → ArtifactWorkbench-DlCLEjut.js} +1 -1
  108. package/web/dist/assets/{Diagram-CuRIffka.js → Diagram-PvOPetOI.js} +1 -1
  109. package/web/dist/assets/{Library-rv5DGtrm.js → Library-Cdi83pOV.js} +2 -2
  110. package/web/dist/assets/{ProfilesDestination-DUuQ9jmd.js → ProfilesDestination-cryC7P6j.js} +1 -1
  111. package/web/dist/assets/TeamsPage-B4xrlGhp.js +1 -0
  112. package/web/dist/assets/Watchtower-60B1JX_J.js +2 -0
  113. package/web/dist/assets/{artifacts-But87Jfo.js → artifacts-DlQEYmDl.js} +1 -1
  114. package/web/dist/assets/index-DA0gKIzv.js +33 -0
  115. package/web/dist/assets/{index-rW6LKQj1.css → index-Dyq-jBeE.css} +1 -1
  116. package/web/dist/assets/live-B2IfKm37.js +5 -0
  117. package/web/dist/assets/{live-BUofsQpz.css → live-De-kd3eW.css} +1 -1
  118. package/web/dist/assets/{pane-layout-BW0RdX5a.js → pane-layout-BAuu_pA3.js} +1 -1
  119. package/web/dist/assets/{renderer2d-DyANQ1WS.js → renderer2d-CsZnF3_o.js} +1 -1
  120. package/web/dist/assets/{renderer3d-vYYKFAJq.js → renderer3d-BIMA0wFn.js} +2 -2
  121. package/web/dist/assets/{safe-area-B2Bk__FK.js → safe-area-dtrnw9NF.js} +1 -1
  122. package/web/dist/assets/{silero-worker-e802lB5T.js → silero-worker-CC2etKS3.js} +1 -1
  123. package/web/dist/assets/{source-C-De8L3s.js → source-GYayxUxS.js} +1 -1
  124. package/web/dist/assets/{toast-CXTwTvDw.js → toast-q818mjUF.js} +1 -1
  125. package/web/dist/index.html +5 -5
  126. package/web/dist/assets/TeamsPage-D_17MkvN.js +0 -1
  127. package/web/dist/assets/Watchtower-DlrNOJ7X.js +0 -2
  128. package/web/dist/assets/index-bX8B6NLo.js +0 -33
  129. package/web/dist/assets/live-BGLA-peO.js +0 -5
@@ -1,33 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Diagram-CuRIffka.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-B9weO8L6.js","assets/ArtifactWorkbench-DzKhMs3l.js","assets/toast-CXTwTvDw.js","assets/artifacts-But87Jfo.js","assets/pane-layout-BW0RdX5a.js","assets/source-C-De8L3s.js","assets/ArtifactWorkbench-9eTj1CeW.css","assets/Library-rv5DGtrm.js","assets/Library-DYsFj_5c.css","assets/TeamsPage-D_17MkvN.js","assets/plural-Bspvoqfq.js","assets/live-BGLA-peO.js","assets/live-BUofsQpz.css","assets/Watchtower-DlrNOJ7X.js","assets/Watchtower-RphjcL0_.css","assets/ProfilesDestination-DUuQ9jmd.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-CXTwTvDw.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-BW0RdX5a.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-But87Jfo.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},J=(e,t=[])=>({required:e,optional:t}),Fc={state:J([`state`]),detector:J([`mode`],[`avgMs`]),"speech.start":J([`bargeIn`]),"speech.end":J([`segment`,`durationMs`,`speechMs`,`forced`]),"segment.closed":J([`segment`,`bytes`,`durationMs`,`speechMs`,`forced`]),"stt.sent":J([`segment`,`bytes`]),"stt.received":J([`segment`,`text`],[`junk`,`empty`,`failed`,`audio`]),"utterance.held":J([`text`]),"utterance.merged":J([`segments`,`pauseMs`]),"utterance.sent":J([`text`,`segments`,`reason`,`holdMs`]),"utterance.accepted":J([`inboxID`]),"utterance.failed":J([`message`],[`status`]),"utterance.command":J([`command`,`text`]),heard:J([`inboxID`]),"say.received":J([`messageID`,`ordinal`,`chars`,`sentences`,`muted`],[`seq`]),"tts.sentence.queued":J([`ref`,`text`]),"tts.request":J([`ref`]),"tts.first.byte":J([`ref`]),"tts.sentence.played":J([`ref`]),"tts.sentence.ended":J([`ref`,`playedMs`,`completed`],[`durationMs`]),"barge.in":J([`cause`,`spoken`,`unplayed`,`mutedMessages`],[`playing`]),"cue.played":J([`cue`],[`name`,`text`]),mic:J([`live`],[`reason`]),control:J([`action`],[`on`]),"turn.timing":J([`firstAudio`],[`speechEnd`,`transcript`,`accepted`,`firstSay`,`firstByte`]),"turn.predict":J([`ms`,`silenceMs`,`decision`],[`p`,`error`]),"decision.voice":J([`decisionID`,`option`,`outcome`]),"clock.sync":J([`t0`,`t1`,`hubAt`]),error:J([`where`,`message`])},Ic=Pc,Lc={"stt.received":{text:Ic.textChars,failed:Ic.messageChars},"utterance.held":{text:Ic.utteranceChars},"utterance.sent":{text:Ic.utteranceChars},"utterance.failed":{message:Ic.messageChars},"utterance.command":{text:Ic.utteranceChars},"tts.sentence.queued":{text:Ic.textChars},"cue.played":{text:Ic.textChars},"turn.predict":{error:Ic.messageChars},error:{message:Ic.messageChars}},Rc={smart:`finished`,"smart-fallback":`hold`};function zc(e,t){if(t?.includes(`turn.predict`))return e;if(e.kind!==`turn.predict`)return e.kind===`utterance.sent`&&typeof e.reason==`string`&&Rc[e.reason]?{...e,reason:Rc[e.reason]}:e}function Bc(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 Vc(e,t){let n=Fc[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=Lc[e]?.[i];r[i]=t!==void 0&&typeof a==`string`?Bc(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:Bc(e.text,Ic.textChars)}),t=r.spoken;r.spoken={text:Bc(t.text,Ic.replyChars),estimated:t.estimated},r.playing&&=e(r.playing),r.unplayed=r.unplayed.slice(0,Wc).map(e),r.mutedMessages=r.mutedMessages.slice(0,Wc)}return r}var Hc=e=>`${e.messageID}:${e.ordinal}:${e.seq??``}:${e.i}`;function Uc(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 Wc=20,Gc=14;function Kc(e,t,n){let r=n&&n>0?n:e.length/Gc*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 qc(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(Kc(r.text,r.playedMs,r.durationMs)),Vc(`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 Jc(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}:{}}}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??Ic.activePerUser} recordings are already running`}:e===429&&t?.code===`limit`?{kind:`failed`,reason:`${t.limit??Ic.recordingsStored} recordings stored; delete some in Settings → Voice`}:{kind:`failed`,reason:typeof t?.error==`string`&&t.error?t.error:`HTTP ${e}`}}var Yc=new TextEncoder,Xc=e=>Yc.encode(e).length,Zc=Xc(`{"events":[]}`),Qc=e=>e.kind===`clock.sync`,$c=e=>Math.max(0,Math.round(e*10)/10);function el(e,t){let n=[],r=Zc;for(let i of e){if(n.length&&i.seq!==n[n.length-1].seq+1)break;let e=Xc(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+Xc(JSON.stringify(o))<=t&&n.push(o),n}var tl=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=$c(this.now()),i={...e,seq:n,t:r},a=Xc(JSON.stringify(i));for(Zc+a>this.limits.batchBytes&&(i={seq:n,t:r,kind:`error`,where:`upload`,message:`event too large: ${e.kind}`},a=Xc(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&&!Qc(i)&&this.scheduled(),n}open(e){this.stopped||this.ready||(this.ready=!0,e&&this.record(Vc(`clock.sync`,e)),this.pending.some(e=>!Qc(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=el(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(!Qc(this.pending[e].e))return this.pending[e].e.seq;let e=this.batch??[];for(let t=e.length-1;t>=0;t--)if(!Qc(e[t]))return e[t].seq;return 0}activePending(){let e=0;for(let t of this.pending)Qc(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=Zc;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=>!Qc(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(Vc(`clock.sync`,{t0:$c(t),t1:$c(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(Vc(`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)}},nl=1048576,rl={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 ${Ic.userBytes/nl} MB in all (${Ic.recordingBytes/nl} MB per recording, ${Ic.recordingsStored} recordings).`,`Secrets in known token formats are scrubbed from the text. Audio is kept even when a secret is scrubbed from the text, and secrets spoken in a way the patterns do not match stay in the text and the audio.`,`Recordings are not encrypted at rest: whoever runs this hub can read them on its disk or database. Delete is immediate.`]};function il(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 al=e=>`${il(e.bytes)} of ${il(e.capBytes)}`;function ol(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 sl={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 cl(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 ll(e,t,n=sl,r=()=>cl(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?`${ol(t-e.startedAt)} · recording now`:ol((e.endedAt??t)-e.startedAt),segments:`${e.segments} segment${e.segments===1?``:`s`}`,size:il(e.bytes),expires:`deleted on ${n.date(e.expiresAt)}`,active:i,...e.audio?{}:{note:`no audio (storage full)`}}}function ul(e,t,n){let r=e?`${e}${t?`+`:``} recording${e===1&&!t?``:`s`}`:`No recordings`;return n?`${r} · ${al(n)}`:r}var dl=e=>{let t=new Date(e);return`${t.getFullYear()}-${t.getMonth()+1}-${t.getDate()}`};function fl(e,t,n=sl.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 pl(e){return e.title.trim().toLowerCase()===e.kind.toLowerCase()?{kind:e.kind}:{kind:e.kind,title:e.title}}function ml(e){let t=e,n=new Set;return{get:()=>t,set(e){t=e;for(let e of[...n])e()},subscribe(e){return n.add(e),()=>n.delete(e)}}}var hl={on:!1,audio:!0},gl=ml(hl),_l=e=>e.audio?`Recording`:`Recording · no audio (storage full)`,vl=e=>e.on?` · recording`:``,yl=ml({}),bl=5e3,xl=new Set([`stored`,`skipped-cap`,`failed`,`off`]),Sl=e=>e&&xl.has(e)?e:void 0,Cl=()=>{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)}`},wl=(e,t=!1)=>({method:`POST`,credentials:`same-origin`,headers:{"content-type":`application/json`},body:JSON.stringify(e),...t?{keepalive:!0}:{}}),Tl;function El(e){e?.type===`recording`&&(e.settings&&typeof e.settings.enabled==`boolean`&&Dl(e.settings),Tl?.onMessage(e))}function Dl(e){yl.set({supported:!0,settings:e}),e.enabled||Tl?.turnedOff()}function Ol(e,t){Tl?.event(e,t)}var kl=class{fetch;now;epoch;limits;take;running=!1;rolled=!1;sessionID=``;client={};retried=new Set;audio=!0;onNote;constructor(e={}){this.fetch=e.fetch??((e,t)=>globalThis.fetch(e,{credentials:`same-origin`,...t})),this.now=e.now??(()=>performance.now()),this.epoch=e.epoch??(()=>Date.now()),this.limits=e.limits}get recordingID(){let e=this.take;return e?.id&&!e.uploader.stopped?e.id:void 0}get active(){return this.recordingID!==void 0}get buffered(){return this.take?.uploader.buffered??0}start(e,t={}){if(this.running)return;this.running=!0,this.rolled=!1,this.sessionID=e;let n=globalThis.navigator;this.client={platform:Uc(n?.userAgent??``),...t},Tl=this,this.indicate(hl),this.begin()}event(e,t){try{let n=this.take,r=n&&zc(Vc(e,t),n.features);r&&n.uploader.record(r)}catch{}}record(e){try{this.take?.uploader.record(e)}catch{}}barge(e){let t=qc(e);t&&this.record(t)}audioResult(e){return Sl(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]:Hc(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,Tl===this&&(Tl=void 0);let n=this.take;this.take=void 0,this.indicate(hl),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,bl))]),n.uploader.close(),await this.end(n.id,t,!1))))}turnedOff(){let e=this.take;e&&(e.uploader.discard(),this.take=void 0,this.indicate(hl))}onMessage(e){if(e?.type!==`recording`)return;e.settings?.enabled===!1&&this.turnedOff();let t=this.take;if(t?.id&&e.recordingID===t.id){if(typeof e.audio==`boolean`&&this.audioChanged(t,e.audio),e.state===`deleted`)t.uploader.discard(),this.take=void 0,this.indicate(hl);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 tl({send:(t,{keepalive:n})=>this.sendEvents(e,t,!!n),now:this.now,onStop:t=>this.ended(e,t),onAudio:t=>this.audioChanged(e,t),...this.limits?{limits:this.limits}:{}}),started:Promise.resolve()},this.take=e,e.started=this.open(e).catch(()=>e.uploader.discard())}async open(e){let t;try{let n=await this.fetch(`/api/settings/recording`);if(n.status===404||n.status===405)return yl.set({supported:!1}),e.uploader.discard();if(n.ok){let{settings:e}=await n.json();e&&yl.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`,wl({sessionID:this.sessionID,clientID:Cl(),anchor:n,client:this.client}));i=e.status,a=await e.json().catch(()=>({}))}catch{}let o=this.now(),s=Jc(i,a);s.kind===`started`?(e.id=s.recording.id,e.features=s.features,this.audio=s.audio,e.uploader.open(s.hubAt===void 0?void 0:{t0:r,t1:o,hubAt:s.hubAt}),this.take===e&&this.running&&this.indicate({on:!0,audio:this.audio,sessionID:this.sessionID,recordingID:e.id})):(e.uploader.discard(),s.kind===`failed`&&t===!0&&this.take===e&&this.running&&this.onNote?.(`Not recording: ${s.reason}`))}async sendEvents(e,t,n){let r=await this.fetch(`/api/recordings/${encodeURIComponent(e.id??``)}/events`,wl({events:t},n));return{status:r.status,body:await r.json().catch(()=>({}))}}end(e,t,n){return this.fetch(`/api/recordings/${encodeURIComponent(e)}/end`,wl({reason:t},n)).then(()=>{},()=>{})}ended(e,t){if(this.take!==e)return;this.take=void 0;let n=t.reason;if(n===`max_duration`&&this.running&&!this.rolled){this.rolled=!0,this.indicate(hl),this.begin();return}let r=t.code===`limit`||n===`limit`?`Recording stopped: limit reached`:void 0;this.indicate(r?{...hl,note:r}:hl),r&&this.onNote?.(r)}audioChanged(e,t){if(this.take!==e||t===this.audio)return;this.audio=t;let n=gl.get();n.on&&n.recordingID===e.id&&this.indicate({...n,audio:t})}indicate(e){gl.set(e)}};async function Al(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,jl]=Or(po()),Ml=new xo,[Nl,Pl]=u(0),Fl=Nl,[X,Il]=u(),[Ll,Rl]=u(),[zl,Bl]=u(),[Vl,Hl]=u([]),[Ul,Wl]=u([]),[Gl,Kl]=u(new Map),ql=Gl,Jl=200;function Yl(e){e.length&&Kl(t=>{let n=new Map(t);for(let t of e)n.delete(t.id),n.set(t.id,t);for(;n.size>Jl;)n.delete(n.keys().next().value);return n})}var[Xl,Zl]=u(),[Ql,$l]=u(!1),[eu,tu]=u(!1),nu=()=>ts(Ql(),eu(),Y.machines!==void 0),[ru,iu]=u();ce(()=>x(()=>{let e=ru(),t=ac(e,Date.now());if(t===void 0)return;let n=setTimeout(()=>iu(t=>t===e?oc(t,Date.now()):t),t+50);M(()=>clearTimeout(n))}));var au=ce(()=>C(()=>{let e=X();if(!e)return[];try{return os(localStorage.getItem(is(e.user?.id)))}catch{return[]}}));ce(()=>x(()=>{let e=Xl(),t=X();if(Ql()&&t)try{localStorage.setItem(is(t.user?.id),JSON.stringify((e?.hiddenSessionIDs??[]).slice(-20)))}catch{}}));var ou=ce(()=>C(()=>$o(Xl(),Y.machines,Ql()?[]:au()),void 0,{equals:(e,t)=>e.size===t.size&&[...e].every(e=>t.has(e))}));Gt(()=>ou());var[su,cu]=u([]),[lu,uu]=u(new Map),du=new Set;async function fu(){try{uu(new Map(Ce(await G(`/api/agent/grants`)).map(e=>[e.id,e])))}catch{}}var pu=e=>lu().get(e),mu=new Set;function hu(e){return mu.add(e),()=>mu.delete(e)}var gu=ce(()=>C(e=>pa(e,fa(Y.machines,Y.prefs,Y.reads,ou(),{activity:Y.activity,intents:Y.intents})))),_u=e=>_o(Y.machines,e),vu=e=>ou().has(e)?`the Concierge`:_u(e)?.session.title||void 0,[yu,bu]=u(new Map);async function xu(){try{let e=await G(`/api/agent/who`),t=Array.isArray(e?.sessions)?e.sessions:[];bu(new Map(t.flatMap(e=>e&&typeof e==`object`&&typeof e.sessionID==`string`&&typeof e.name==`string`&&e.name?[[e.sessionID,e.name]]:[])))}catch{}}function Su(e){if(ou().has(e))return We(e,void 0,!0);let t=_u(e)?.session,n=yu().get(e);if(!n)for(let t of ql().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 Cu=new ii;Ne(()=>{dt().name!==`pair`&&(Gu(),Il(void 0),wu())});function wu(){let e=location.pathname+location.search;Vt(`/pair${e===`/`||e.startsWith(`/pair`)?``:`?next=${K(e)}`}`,{replace:!0})}async function Tu(){if(X())return!0;let e=await fetch(`/api/me`,{credentials:`same-origin`});if(e.status===401)return wu(),!1;if(!e.ok)throw Error(`HTTP ${e.status}`);return Il(await e.json()),!0}async function Eu(){if(Ll()!==void 0)return Ll()??null;try{let e=await fetch(`/api/auth`,{credentials:`same-origin`}),t=e.ok?await e.json():null;return Rl(t),t}catch{return null}}var Du,Ou,ku=1e3,Au=()=>!1,ju={lite:!1},[Mu,Nu]=u(``),Pu,Fu=!1,Iu=new Co({setTimer:(e,t)=>setTimeout(e,t),clearTimer:e=>clearTimeout(e),open:(e,t)=>Uu(e,t),close:()=>Hu(),keepOpen:()=>Au()});function Lu(e){Au=e}function Ru(e){ju=e,Iu.setScope(e)}var zu=!1;function Bu(){zu||(zu=!0,document.addEventListener(`visibilitychange`,()=>document.visibilityState===`hidden`?Iu.hidden():Iu.visible()),window.addEventListener(`pageshow`,e=>{e.persisted&&Iu.state!==`stopped`&&Iu.reopen()}),window.addEventListener(`online`,()=>Iu.state===`open`&&Y.connection===`down`&&Iu.reopen()))}function Vu(e={lite:!1}){Iu.state===`stopped`&&(Bu(),ju=e,Iu.start(e),Ql()||(nd(),setTimeout(()=>!Ql()&&tu(!0),es)),document.visibilityState===`hidden`&&Iu.hidden())}function Hu(){clearTimeout(Ou),Du?.close(),Du=void 0,Iu.state===`paused`&&jl(`connection`,`paused`)}function Uu(e,t){clearTimeout(Ou),Du?.close();let n=wo(Y.connection,t);Fu=n.reconnecting,n.reconnecting&&Wu(`reconnecting`),jl(`connection`,n.connection),Dc(ju);let r=new EventSource(e,{withCredentials:!0});Du=r,r.onopen=()=>{ku=1e3,jl(`connection`,`live`),Fu&&Wu(`updated`,2e3),Fu=!1,_d(),Zu(),qu(),Yu(),fd(),sd(),xu(),fu(),nd()},r.onerror=async()=>{Du===r&&(jl(`connection`,`down`),(await fetch(`/api/me`,{credentials:`same-origin`}).catch(()=>void 0))?.status===401?(Gu(),Il(void 0),wu()):r.readyState===EventSource.CLOSED&&Du===r&&(Du=void 0,Ou=setTimeout(()=>Iu.state===`open`&&Iu.reopen(),ku),ku=Math.min(3e4,ku*2)))},r.addEventListener(`ping`,()=>Iu.received()),r.onmessage=e=>{Iu.received(e.lastEventId||void 0);let t;try{t=JSON.parse(e.data)}catch{return}Ku(t)}}function Wu(e,t){clearTimeout(Pu),Nu(e),t&&(Pu=setTimeout(()=>Nu(``),t))}function Gu(){Iu.stop(),Du?.close(),Du=void 0,clearTimeout(Ou)}function Ku(e){he(()=>{if(Oc(e),e.type===`prefs`?(jl(Fr(t=>go(t,e))),Y.prefsStale&&!Y.prefsPending&&vd()):e.type===`catalog`?jl(Fr(t=>{go(t,e),Cu.apply(t.machines,Date.now())})):jl(Fr(t=>go(t,e))),e.type===`status`){let t=_u(e.sessionID);!Ml.has(e.sessionID)&&t&&Ml.feed(e.sessionID)}if(Ml.apply(e)!==void 0&&Pl(e=>e+1),e.type===`enrollment`&&fd(),e.type===`intent`&&typeof e.sessionID==`string`&&Xu(e.sessionID),e.type===`recording`&&El(e),e.type===`decision`){let t=Pe(e.decision);if(t){od.event(t);let e=Qe(Ul(),t);e&&q(e),Wl(e=>ke(e,t)),Yl([t])}}if(e.type===`concierge`){let t=Zo(e.status);t&&(iu(e=>rc(Xl(),t,e)),Zl(t),$l(!0),$u++);let n=Bs(e.armed);n!==void 0&&(id.event(),iu(n))}if(e.type===`agent`){let t=xe(e.entry);t&&cu(e=>Ht(e,t)),t?.grant&&!lu().has(t.grant)&&!du.has(t.grant)&&(du.add(t.grant),fu())}if(e.type===`resync`&&(Zu(),qu(),Yu(),vd(),fd(),sd(),xu(),fu(),nd()),e.type===`handoff`&&(dt().name!==`session`||dt().id!==e.sessionID)){let t=_u(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 qu(){try{let{activity:e}=await G(`/api/activity/mine`);jl(`activity`,ta(e))}catch{}}var Ju=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 Yu(){try{let{intents:e}=await G(`/api/intents/mine`),t={};for(let[n,r]of Object.entries(e??{})){let e=Ju(r);e&&(t[n]=e)}jl(`intents`,t)}catch{}}async function Xu(e){try{let{intent:t}=await G(`/api/agent/sessions/${K(e)}/intent`),n=Ju(t);jl(`intents`,Fr(t=>{n?t[e]=n:delete t[e]}))}catch{}}async function Zu(){try{let{reads:e}=await G(`/api/reads`);jl(`reads`,e??{})}catch{}}async function Qu(e,t=!1){try{let{reads:n}=await(await V(`${H(e)}/read`,{method:`POST`,json:t?{open:!0}:{}})).json();n&&typeof n==`object`&&jl(`reads`,n)}catch{}}var $u=0,ed,td;function nd(){return ed?(td??=ed.then(()=>(td=void 0,nd())),td):(ed=rd().finally(()=>ed=void 0),ed)}async function rd(){let e=$u;try{let t=Qo(await G(`/api/agent/concierge`));t&&e===$u&&Zl(t.status)}catch(t){t instanceof W&&t.status===404&&e===$u&&Zl(void 0);return}finally{$l(!0)}await ad()}var id=new sc;async function ad(){let e=id.begin();try{let t=Bs((await G(`/api/agent/concierge/arm`)).armed);id.fresh(e)&&t!==void 0&&iu(oc(t,Date.now()))}catch(t){id.fresh(e)&&t instanceof W&&(t.status===404||t.status===403)&&iu(void 0)}}var od=new Ke;async function sd(){let e=od.begin();try{let{decisions:t}=await G(`/api/decisions?state=open`),n=od.settle(e,(t??[]).map(Pe).filter(e=>!!e));if(!n)return;Wl(n),Yl(n)}catch(t){od.fail(e),t instanceof W&&t.status===404&&Wl([])}}var cd=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 ld(e){let t=Gl().get(e);return t?Promise.resolve(t):cd.recall(e).then(t=>(t&&!Gl().has(e)&&Yl([t]),t))}function ud(e){od.event(e),Wl(t=>ke(t,e)),Yl([e])}function dd(e){let t=Ul().find(t=>t.id===e);t&&od.event({...t,state:`closed`}),Wl(t=>t.filter(t=>t.id!==e)),sd()}async function fd(){if(!qn(X()))Hl([]);else try{Hl((await G(`/api/enrollments`)).enrollments??[])}catch{Hl([])}}async function pd(){try{Bl((await G(`/api/settings/speech`)).ready??null)}catch{Bl(null)}}var md=`voice.viewPrefs`,hd=!1,gd=()=>Y.prefsSource===`hub`||Y.prefsSource===`local`;async function _d(){if(!(gd()||hd)){hd=!0;try{jl({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{}jl({prefs:ti(e),prefsSource:`local`})}else jl(`prefsSource`,`error`)}finally{hd=!1}gd()&&await yd()}}async function vd(){jl({prefsStale:!1,prefsSource:`unknown`}),await _d()}async function yd(){let{clear:e,patch:t}=ci(localStorage.getItem(`voice.pins`),localStorage.getItem(`voice.pinnedWorkspaces`),Y.prefs);e&&(t&&(jl(`prefs`,e=>({...e,...t})),!(await bd(t)).ok)||(localStorage.removeItem(`voice.pins`),localStorage.removeItem(`voice.pinnedWorkspaces`)))}async function bd(e){if(Y.prefsSource===`local`)return localStorage.setItem(md,JSON.stringify(Y.prefs)),{ok:!0};jl(`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&&jl(`prefs`,ti(t)),{ok:!0}}catch(e){return{ok:!1,error:e}}finally{jl(`prefsPending`,e=>e-1),!Y.prefsPending&&Y.prefsStale&&vd()}}function xd(e,t,n,r={}){Sd(e,[t],n,r)}function Sd(e,t,n,{message:r,undo:i=!1}={}){if(!gd()){q(`Your view settings are still loading. Try again in a moment.`,`err`),_d();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&&(jl(`prefs`,s),r&&q(r,``,i?{label:`Undo`,run:()=>Sd(e,o,!n)}:void 0),bd(c).then(({ok:t,error:r})=>{t||(jl(`prefs`,oi(Y.prefs,e,o,!n).prefs),q(`Could not save that change: ${U(r)}`,`err`))}))}async function Cd(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 wd(e,t){let n=ni(t);if(`error`in n)return q(n.error,`err`),!1;let{title:r}=n,i=_u(e)?.session.title;if(i===r)return!1;Cu.set(e,r,Date.now()),jl(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&&_u(e)?.session.title===r&&(Cu.drop(e,r),Cu.set(e,n,Date.now()),jl(Fr(t=>void ri(t.machines,e,n)))),!0}catch(t){return Cu.drop(e,r),i!==void 0&&_u(e)?.session.title===r&&jl(Fr(t=>void ri(t.machines,e,i))),q(`Could not rename: ${U(t)}`,`err`),!1}}var[Td,Ed]=u(new Set),Dd=e=>Td().has(e),Od=(e,t)=>Ed(n=>{let r=new Set(n);return t?r.add(e):r.delete(e),r}),kd=6e4;async function Ad(e){if(Dd(e))return;let t=_u(e)?.session.title;Od(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()+kd,i=()=>{let n=_u(e)?.session.title;n!==void 0&&n!==t?(Od(e,!1),q(`Renamed to “${n}”`)):Date.now()>=r?Od(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}Cu.set(e,i,Date.now()),jl(Fr(t=>void ri(t.machines,e,i))),q(`Renamed to “${i}”`)}catch(e){q(`Could not auto-name: ${U(e)}`,`err`)}finally{n||Od(e,!1)}}async function jd(e){try{await V(`${H(e)}/error/dismiss`,{method:`POST`,json:{}})}catch(e){q(`Could not dismiss the error: ${U(e)}`,`err`)}}async function Md(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 Nd=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 Pd(e){let t=()=>e.size??18;return(()=>{var n=Nd();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 Fd=I(`<p class=error role=alert>`),Id=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`),Ld=I(`<p class=muted>Sign in to see and control your own OpenCode sessions.`),Rd=I(`<a class="btn primary signin">Sign in with Google`),zd=I(`<details class=card><summary>Have a pairing code?`),Bd=I(`<main class=entry><h1 class="display brand-big"> Hub`),Vd=I(`<p class=muted>Loading…`),Hd=I(`<p class=muted>Pair this browser with your hub to see and control your OpenCode sessions.`),Ud=I(`<p>A terminal on <strong></strong> asks to act as you through the hub CLI.`),Wd=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.`),Gd=I(`<fieldset class=stack><legend class=small>What it may do`),Kd=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.`),qd=I(`<div class=row><button type=button class="btn primary">Approve</button><button type=button class="btn danger">Deny`),Jd=I(`<p role=status>`),Yd=I(`<main class=entry><h1 class=display>CLI login for </h1><div class="card stack"><a class=btn href=/>Back to sessions`),Xd=I(`<label class=check><input type=checkbox><span><span class=mono></span> `),Zd=I(`<main class=entry><p class=muted>Loading…`),Qd=I(`<strong>`),$d=I(`<p>`),ef=I(`<p class="small muted">Approve only if this code matches the one shown in OpenCode.`),tf=I(`<p class=small>`),nf=I(`<main class=entry><h1 class=display>Approve machine</h1><div class="card stack"><a class=btn href=/>Back to sessions`),rf=I(`<p>No code given.`),af=I(`<strong class=mono>`),of=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`),sf=I(`<p><strong></strong> wants to use this hub as <!>.`),cf=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.`),lf=I(`<fieldset class=stack><legend class=small>What it may do (untick what it should not)`),uf=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.`),df=I(`<main class="entry consent"><h1 class=display>Connect </h1><div class="card stack">`),ff=I(`<p class=small data-consent-current>It is already connected with <!>. Approving replaces that.`),pf=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 hf(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),Eu()]);if(t?.ok)return Il(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()}}),Il(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=Id(),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=Fd();return y(e,m),e}}),o),s(()=>o.disabled=g()),s(()=>r.value=c()),s(()=>a.value=f()),e})();return(()=>{var i=Bd(),o=i.firstChild,c=o.firstChild;return y(o,n(Pd,{class:`brand-mark`,size:30}),c),y(i,n(l,{get when(){return a()},get fallback(){return Vd()},get children(){return n(l,{get when(){return t()},get fallback(){return[Hd(),r(x)]},get children(){return[Ld(),(()=>{var e=Rd();return s(()=>b(e,`href`,t())),e})(),(()=>{var t=zd();return t.firstChild,y(t,x,null),s(()=>t.open=!!e.error),t})()]}})}}),null),i})()}function gf(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=Yd(),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=Jd();return y(e,c),e})()},get children(){return[(()=>{var t=Ud(),n=t.firstChild.nextSibling;return y(n,()=>e.login.clientName),t})(),(()=>{var t=Wd(),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=Gd();return e.firstChild,y(e,n(m,{each:t,children:e=>(()=>{var t=Xd(),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 Kd()}}),(()=>{var e=qd(),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=Jd();return y(e,a),e}})]}}),p),o})()}function _f(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 Zd()},get children(){return n(l,{get when(){return t()},get fallback(){return n(vf,{get code(){return e.code}})},children:e=>n(gf,{get login(){return e()}})})}})}function vf(e){let t=()=>e.code.toUpperCase(),[i,a]=u(``),[o,c]=u(``),[d,f]=u(!1),[p,m]=u(!qn(X()));fe(async()=>{await fd(),m(!0)});let h=()=>Vl().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=nf(),a=e.firstChild.nextSibling,c=a.firstChild;return y(a,n(l,{get when(){return!o()},get fallback(){return(()=>{var e=Jd();return y(e,o),e})()},get children(){return n(l,{get when(){return t()},get fallback(){return rf()},get children(){return n(l,{get when(){return p()},get fallback(){return Vd()},get children(){return n(l,{get when(){return!qn(X())||h()},get fallback(){return(()=>{var e=$d();return y(e,g),e})()},get children(){return[(()=>{var e=$d();return y(e,n(l,{get when(){return h()},get fallback(){return[`A machine showing code `,(()=>{var e=af();return y(e,t),e})(),` wants to connect to this hub.`]},get children(){return[(()=>{var e=Qd();return y(e,()=>h().machineName),e})(),` wants to connect to this hub.`]}})),e})(),(()=>{var e=ef(),t=e.firstChild;return y(e,(()=>{var e=r(()=>!!h());return()=>e()?`Code ${h().userCode} · requested ${R(h().created)}. `:``})(),t),e})(),(()=>{var e=tf();return y(e,()=>er(X())),e})(),(()=>{var e=qd(),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=Jd();return y(e,i),e}})]}})}})}})}}),c),e})()}function yf(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=of(),t=e.firstChild.nextSibling.firstChild;return y(t,()=>i()||`Loading…`),e})()},children:e=>n(bf,{get flow(){return e()}})})}function bf(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=df(),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=Jd();return y(e,d),e})()},get children(){return[(()=>{var t=sf(),n=t.firstChild,r=n.nextSibling.nextSibling;return r.nextSibling,y(n,()=>e.flow.client.name),y(t,g,r),t})(),(()=>{var t=cf(),n=t.firstChild.nextSibling;return y(n,()=>e.flow.client.redirectOrigin),t})(),n(l,{get when(){return e.flow.connection},children:e=>(()=>{var t=ff(),n=t.firstChild.nextSibling;return n.nextSibling,y(t,()=>e().scopes.join(`, `)||`no scopes`,n),t})()}),(()=>{var e=lf();return e.firstChild,y(e,n(m,{each:t,children:e=>(()=>{var t=Xd(),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 pf()}}),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})(),uf(),(()=>{var e=qd(),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=Fd();return y(e,o),e}})]}})),s(()=>b(c,`data-consent`,e.flow.id)),c})()}z([`input`,`click`]);var xf=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>`),Sf=I(`<svg><rect class=meter-agent width=3></svg>`,!1,!0,!1),Cf=I(`<svg><rect class=meter-human y=12 width=3 height=4></svg>`,!1,!0,!1),wf=4,Tf=11,Ef=4,Df=(e,t,n)=>e<=0||t<=0?0:Math.max(Ef,Math.round(n*Math.log2(1+e)/Math.log2(1+t)));function Of(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*wf;return(()=>{var e=xf(),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=Sf();return s(r=>{var i=t()*wf,o=Tf-Df(e.agent,a(),Tf),s=Df(e.agent,a(),Tf);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=Cf();return s(()=>b(e,`x`,t()*wf)),e})())]}),null),s(()=>b(e,`aria-label`,i())),e})()}var kf=()=>`serviceWorker`in navigator&&`PushManager`in window&&`Notification`in window&&window.isSecureContext;function Af(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 jf=(e,t)=>!e||e.byteLength!==t.byteLength?!1:new Uint8Array(e).every((e,n)=>e===t[n]),[Mf,Nf]=u(0),[Pf,Ff]=u(new Set),If=()=>`Notification`in window?Notification.permission:`default`;async function Lf(){if(`serviceWorker`in navigator)return await navigator.serviceWorker.getRegistration(`/`).catch(()=>void 0)??void 0}async function Rf(){if(kf())return await(await Lf())?.pushManager.getSubscription()??void 0}async function zf(e){let t=await G(`/api/push/prefs${e?`?endpoint=${encodeURIComponent(e)}`:``}`);return Ff(new Set(t.muted??[])),t}async function Bf(){let e=kf(),t=e?await Lf():void 0,n=await t?.pushManager.getSubscription().catch(()=>null)??void 0,r=await zf(n?.endpoint).catch(()=>void 0);return{env:{supported:e,permission:If(),worker:!!t,...n?{endpoint:n.endpoint}:{},hubSubscribed:!!r?.subscribed,hubSubscriptions:r?.subscriptions??0},view:r}}async function Vf(){let{publicKey:e}=await G(`/api/push/key`),t=Af(e);await Lf()||await navigator.serviceWorker.register(`/sw.js`,{scope:`/`});let n=await navigator.serviceWorker.ready,r=await n.pushManager.getSubscription();return r&&!jf(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 Hf(){if(!kf())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 Vf()}async function Uf(){let e=await Rf();e&&(await V(`/api/push/unsubscribe`,{method:`POST`,json:{endpoint:e.endpoint}}).catch(()=>{}),await e.unsubscribe().catch(()=>{}))}async function Wf(e){return(await V(`/api/push/test`,{method:`POST`,json:e?{kind:e}:{}})).json()}async function Gf(e,t){let n=Pf(),r=new Set(n);t?r.add(e):r.delete(e),Ff(r);try{let n=await(await V(`/api/push/mute`,{method:`PUT`,json:{sessionID:e,muted:t}})).json();Ff(new Set(n.muted)),q(t?`Notifications muted for this session`:`Notifications on for this session`)}catch(e){Ff(n),q(e instanceof Error?e.message:String(e),`err`)}}async function Kf(){let{env:e}=await Bf().catch(()=>({env:void 0}));e&&Yt(e)&&await Vf().then(()=>Nf(e=>e+1),e=>console.warn(`push re-subscribe:`,e?.message??e))}function qf(){`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 Jf)e(t)}))}var Jf=new Set;function Yf(e){return Jf.add(e),()=>Jf.delete(e)}function Xf(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 Zf=e=>e===`left`||e===`right`?`vertical`:`horizontal`;function Qf(e,t,n,r){let i=r?t+1:t;if(i<=1)return`single`;let a=Zf(n);return i===2?a:e===`grid`?`grid`:e===a?r&&i>=gn?`grid`:a:`grid`}function $f(e,t,n,r){return r===`grid`&&n===`bottom`?Math.min(e,t+2):n===`left`||n===`top`?t:t+1}var ep=(e,t)=>Number.isInteger(t)&&t>=0&&t<e.panes.length;function tp(e,t,n){if(!ep(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(!ep(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=Qf(e.split,e.panes.length,a,!1),l=$f(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 np(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 tp(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(!ep(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=Qf(e.split,a,s,!0),l=$f(a,o,s,c);return{layout:on(c,[...e.panes.slice(0,l),r,...e.panes.slice(l)],l),outcome:`added`}}var rp={side:{min:180,max:480,default:235},rail:{min:220,max:640,default:260}},ip=`hub.panels`,ap=(e,{min:t,max:n})=>Math.min(n,Math.max(t,e));function op(e,t,n){let{min:r,max:i}=rp[e];return{min:r,max:Math.max(r,Math.min(i,Math.floor(t-420-n)))}}var sp={min:320,max:440,share:.4};function cp(e,t,n){let r=e=>t-(n.concierge&&e?sp.min:0),i=ap(e.side,op(`side`,r(n.side),n.rail?rp.rail.min:0)),a=ap(e.rail,op(`rail`,r(n.rail),n.side?i:0));if(!n.concierge)return{side:i,rail:a};let o=Math.min(sp.max,Math.floor(t*sp.share)),s=t-420-(n.side?i:0)-(n.rail?a:0);return{side:i,rail:a,concierge:Math.max(sp.min,Math.min(o,s))}}function lp(e,t,n,r,i){let a=r?64:16,o=e===`side`?`ArrowRight`:`ArrowLeft`,s=e===`side`?`ArrowLeft`:`ArrowRight`;if(n===o)return ap(t+a,i);if(n===s)return ap(t-a,i);if(n===`Home`)return i.min;if(n===`End`)return i.max}function up(e,t,n,r){let i=e===`side`?t+n:t-n;return e===`side`&&i<r.min-48?{collapse:!0}:{width:ap(Math.round(i),r)}}var dp=(e,t)=>{let{min:n,max:r,default:i}=rp[e];return typeof t==`number`&&Number.isFinite(t)?ap(Math.round(t),{min:n,max:r}):i};function fp(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:dp(`side`,n.side),rail:dp(`rail`,n.rail)}}function pp(e,t,n){try{e.setItem(ip,JSON.stringify({...fp(e),[t]:dp(t,n)}))}catch{}}var mp=window.matchMedia(`(max-width: 760px)`),[hp,gp]=u(mp.matches);mp.addEventListener(`change`,()=>{gp(mp.matches),wp(!mp.matches&&localStorage.getItem(vp)!==`0`)});var Z=hp,_p=`hub.sidebar.collapsed`,vp=`hub.rail.open`,[yp,bp]=u(localStorage.getItem(_p)===`1`),[xp,Sp]=u(!1),[Cp,wp]=u(!mp.matches&&localStorage.getItem(vp)!==`0`);function Tp(e){bp(e),localStorage.setItem(_p,e?`1`:`0`)}function Ep(e){wp(e),hp()||localStorage.setItem(vp,e?`1`:`0`)}function Dp(){hp()?Sp(!xp()):Tp(!yp())}var[Op,kp]=u(window.innerWidth);window.addEventListener(`resize`,()=>kp(window.innerWidth));var[Ap,jp]=u(fp(localStorage)),[Mp,Np]=u(!1),[Pp,Fp]=u(),[Ip,Lp]=u(!1),Rp=()=>cp(Ap(),Op(),{side:!yp()&&!hp(),rail:Mp(),concierge:Ip()&&!hp()});function zp(e){let t=Rp(),n=e===`side`?Mp()?t.rail:0:!yp()&&!hp()?t.side:0;return op(e,Op()-(t.concierge??0),n)}function Bp(e,t,n=!0){jp(n=>({...n,[e]:t})),n&&pp(localStorage,e,t)}var Vp=`application/x-hub-pane`,[Hp,Up]=u(),Wp=``,Gp=0,Kp=Hp,qp=()=>typeof globalThis.crypto?.randomUUID==`function`?crypto.randomUUID():`${Date.now()}-${Math.random()}`;function Jp(e,t){let n=e.dataTransfer;return Z()||!n?!1:(n.clearData(),Wp=qp(),n.setData(Vp,Wp),n.effectAllowed=t.move?`move`:`copyMove`,cancelAnimationFrame(Gp),Gp=requestAnimationFrame(()=>Up(t)),!0)}function Yp(){cancelAnimationFrame(Gp),Gp=0,Wp=``,Up(void 0)}function Xp(e){return!!Hp()&&[...e.dataTransfer?.types??[]].includes(`application/x-hub-pane`)}function Zp(e){let t=Hp();return t?np(xn(),t.target,e).outcome:void 0}function Qp(e,t){let{layout:n,outcome:r}=np(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 $p(e,t){let n=Hp(),r=n&&e.dataTransfer?.getData(`application/x-hub-pane`)===Wp;return Yp(),r?Qp(n.target,t):`invalid`}function em(e,t){let n=xn();return Qp(e,n.panes.length?{index:n.focused,zone:t}:{empty:!0})}if(typeof document<`u`){let e=()=>Hp()&&Yp();document.addEventListener(`dragend`,e,!0),document.addEventListener(`drop`,()=>queueMicrotask(e)),document.addEventListener(`mousemove`,t=>t.buttons===0&&e(),{passive:!0})}var tm=e=>!!e&&typeof e==`object`&&!Array.isArray(e),nm=e=>typeof e==`string`&&e.length>0,rm=e=>typeof e==`number`&&Number.isFinite(e),im=new Set([`online`,`offline`,`archived`,`deleted`,`unknown`]),am=new Set([`current`,`left`,`missing`]),om=new Set([`open`,`in_progress`,`blocked`,`done`,`cancelled`]),sm=new Set([`done`,`cancelled`]),cm=e=>rm(e)&&e>=0?e:0;function lm(e){if(!tm(e)||!nm(e.memberID)||!nm(e.sessionID)||!nm(e.role))return;let t=tm(e.session)&&typeof e.session.state==`string`?e.session:void 0,n=tm(e.assignments)?e.assignments:{};return{memberID:e.memberID,sessionID:e.sessionID,role:e.role,master:e.master===!0,presence:im.has(e.presence)?e.presence:`unknown`,generation:rm(e.generation)?e.generation:1,...t?{session:{state:t.state,online:t.online===!0,...nm(t.machineID)?{machineID:t.machineID}:{},...nm(t.name)?{name:t.name}:{},...rm(t.lastSeen)?{lastSeen:t.lastSeen}:{}}}:{},workload:{open:cm(n.open),in_progress:cm(n.in_progress),blocked:cm(n.blocked)},...tm(e.blockers)&&e.blockers.reported===!0&&rm(e.blockers.count)?{blockers:e.blockers.count}:{}}}function um(e){if(tm(e)&&nm(e.memberID)&&nm(e.supervisorMemberID)&&rm(e.order))return{memberID:e.memberID,supervisorMemberID:e.supervisorMemberID,order:e.order,member:am.has(e.member)?e.member:`missing`,supervisor:am.has(e.supervisor)?e.supervisor:`missing`}}function dm(e){if(tm(e)&&nm(e.id)&&nm(e.memberID)&&nm(e.title)&&om.has(e.status))return{id:e.id,memberID:e.memberID,title:e.title,status:e.status,...nm(e.ref)?{ref:e.ref}:{},assignee:am.has(e.assignee)?e.assignee:`missing`,...Array.isArray(e.stale)?{stale:e.stale.filter(nm)}:{}}}function fm(e){if(tm(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 pm=(e,t)=>Array.isArray(e)?e.map(t).filter(e=>e!==void 0):[];function mm(e){if(!tm(e)||!tm(e.workspace)||!tm(e.members)||!tm(e.supervision))return;let t=e.workspace;if(!nm(t.id)||typeof t.title!=`string`||!nm(t.state)||!rm(t.revision)||!rm(e.supervision.revision))return;let n=tm(e.assignments)?e.assignments:{},r=fm(e.decisions),i=fm(e.artifacts);return{workspace:{id:t.id,title:t.title,state:t.state,revision:t.revision,...nm(t.masterMemberID)?{masterMemberID:t.masterMemberID}:{}},revision:e.supervision.revision,members:pm(e.members.items,lm),membersTruncated:e.members.truncated===!0,links:pm(e.supervision.links,um),linksTruncated:e.supervision.truncated===!0,assignments:pm(n.items,dm),assignmentsTruncated:n.truncated===!0,sections:{...r?{decisions:r}:{},...i?{artifacts:i}:{}}}}function hm(e){return tm(e)?{items:pm(e.items,e=>tm(e)&&nm(e.id)&&typeof e.title==`string`&&nm(e.state)&&rm(e.revision)?{id:e.id,title:e.title,...nm(e.description)?{goal:e.description}:{},state:e.state,revision:e.revision}:void 0),...nm(e.cursor)?{cursor:e.cursor}:{}}:{items:[]}}function gm(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 _m(e){let{links:t,stale:n}=gm(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)sm.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 vm(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}=gm(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 ym(e,t){return e===void 0&&t===void 0?0:e===void 0?t-1:t===void 0?e+1:(e+t)/2}var bm=(e,t)=>e.flat.find(e=>e.member.memberID===t),xm=(e,t)=>t.supervisorMemberID===void 0?e.roots:bm(e,t.supervisorMemberID).children,Sm=(e,t)=>{let n=e.children.filter(e=>e.member.memberID!==t);return n.length?n[n.length-1].order+1:0};function Cm(e,t,n){if(!bm(e,t))return;if(`root`in n)return{memberID:t,supervisorMemberID:null};if(n.memberID===t)return;let r=bm(e,n.memberID);if(!r)return;if(n.position===`inside`)return{memberID:t,supervisorMemberID:r.member.memberID,order:Sm(r,t)};if(r.supervisorMemberID===void 0)return{memberID:t,supervisorMemberID:null};let i=xm(e,r).filter(e=>e.member.memberID!==t),a=i.indexOf(r),o=n.position===`before`?ym(i[a-1]?.order,r.order):ym(r.order,i[a+1]?.order);return{memberID:t,supervisorMemberID:r.supervisorMemberID,order:o}}function wm(e,t,n){let r=bm(e,t);if(!r)return;let i=xm(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:Sm(e)}:void 0}case`outdent`:{if(o===void 0)return;let n=bm(e,o);if(n.supervisorMemberID===void 0)return{memberID:t,supervisorMemberID:null};let r=xm(e,n);return{memberID:t,supervisorMemberID:n.supervisorMemberID,order:ym(n.order,r[r.indexOf(n)+1]?.order)}}case`up`:return o===void 0||a===0?void 0:{memberID:t,supervisorMemberID:o,order:ym(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:ym(i[a+1].order,i[a+2]?.order)};case`detach`:return o===void 0?void 0:{memberID:t,supervisorMemberID:null}}}function Tm(e,t){return{memberID:e.memberID,supervisorMemberID:e.supervisorMemberID,...e.order!==void 0&&e.supervisorMemberID!==null?{order:e.order}:{},expectedRevision:t}}var Em={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.`},Dm=e=>Em[e];function Om(e,t){let n=vm(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. ${Em[n]}`}:{kind:`reapply`,body:Tm(e,t.revision)}}function km(e){let t=e.details?.violation;if(e.status===400&&(t===`cycle`||t===`depth`))return Em[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 Am(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 jm(e,t){let n=Am(e,t);if(!n)return{found:!1};let{machine:r,process:i,session:a}=n,o=a.parentID,s=o?Am(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 Mm(e,t,n){let r=jm(n,e.member.sessionID),i=e.supervisorMemberID?t.members.find(t=>t.memberID===e.supervisorMemberID):void 0,a=i?jm(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 Nm={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 Pm(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:Nm[e.presence]}),n}var Fm=e=>e.length>1?e.replace(/\/+$/,``):e,Im=(e,t)=>{let n=Fm(e),r=Fm(t);return n===r||n.startsWith(`${r}/`)};function Lm(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=>Im(n,e))}}))}var Rm=e=>typeof e==`object`&&!!e&&!Array.isArray(e),zm=e=>typeof e==`string`&&e.length>0,Bm=e=>typeof e==`number`&&Number.isFinite(e),Vm=[`launching`,`ready`,`failed`,`unknown`];function Hm(e){if(Rm(e)&&zm(e.id)&&typeof e.text==`string`)return{id:e.id,role:zm(e.role)?e.role:`message`,text:e.text,...Bm(e.at)?{at:e.at}:{},...e.clipped===!0?{clipped:!0}:{},...e.changed===!0?{changed:!0}:{},...e.stale?{stale:!0}:{}}}function Um(e){if(!Rm(e)||!zm(e.id)||!zm(e.workspaceID)||!zm(e.sourceSessionID)||!Bm(e.revision))return;let t=e.snapshot;if(!Rm(t)||!Bm(t.generation)||!Bm(t.takenAt))return;let n=Rm(e.launch)&&zm(e.launch.state)?e.launch:void 0;return{id:e.id,workspaceID:e.workspaceID,sourceSessionID:e.sourceSessionID,...zm(e.sessionID)?{sessionID:e.sessionID}:{},...zm(e.machineID)?{machineID:e.machineID}:{},revision:e.revision,status:Vm.includes(e.status)?e.status:`unknown`,...n?{launch:{state:n.state,...zm(n.outcome)?{outcome:n.outcome}:{},...zm(n.reason)?{reason:n.reason}:{}}}:{},snapshot:{generation:t.generation,takenAt:t.takenAt,omitted:Bm(t.omitted)?t.omitted:0,items:Array.isArray(t.items)?t.items.map(Hm).filter(e=>e!==void 0):[]},...typeof e.stale==`boolean`?{stale:e.stale}:{}}}function Wm(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 Gm(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 Km(e,t){let n=e.snapshot,r=[`${_n(n.items.length,`message`)} from the main session`,`copied ${Gm(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 qm(e){let t=Rm(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${zm(t.message)?`: ${t.message}`:`.`}`:`Context refreshed.`}var Jm=9900;function Ym(e){if(!e.trim())return`Write what to send to the main session.`;if(e.length>9900)return`At most ${Jm} characters.`}var Xm=encodeURIComponent,Zm=e=>`/api/agent/workspaces/${Xm(e.workspaceID)}/side-chats/${Xm(e.id)}`,Qm={one:e=>`/api/agent/side-chats/${Xm(e)}`,create:e=>`/api/agent/workspaces/${Xm(e)}/side-chats`,refresh:e=>`${Zm(e)}/refresh`,send:e=>`${Zm(e)}/send`},$m=e=>Math.min(3e4,2e3*2**Math.max(0,e)),eh=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function th(e,t){return t?{sourceSessionID:e,bindingID:t}:{sourceSessionID:e}}function nh(e){return(eh(e)&&Array.isArray(e.bindings)?e.bindings:[]).flatMap(e=>eh(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 rh(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 ih=`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 ah(e){return e.status===0?`The hub can't be reached. Check your connection and try again.`:e.status===422&&e.details?.feature===`sideChatHost`?ih: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 oh=I(`<label><span>Workspace</span><select aria-label=Workspace><option value>Choose a workspace…`),sh=I(`<p class=cmp-note role=status>`),ch=I(`<label><span>Host repository</span><select aria-label="Host repository"><option value>Choose a repository…`),lh=I(`<p class="cmp-note err"role=alert>`),uh=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`),dh=I(`<p class=muted role=status>Loading workspaces…`),fh=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.`),ph=I(`<option>`),[mh,hh]=u(),gh=(e,t={})=>hh({sessionID:e,...t});function _h(){return n(l,{get when(){return mh()},keyed:!0,children:e=>n(bh,{request:e,onClose:()=>hh(void 0)})})}var vh=()=>`console-sidechat-${[...crypto.getRandomValues(new Uint8Array(12))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`,yh=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 bh(e){let[t,i]=u(),[a,o]=u(),[c,d]=u(e.request.workspaceID??``),[f,p]=u(),[h,g]=u(``),[_,v]=u(!1),[x,S]=u(),w,T=()=>{let t=_u(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(nh(await G(`/api/agent/workspaces/${K(e)}/bindings`)))}catch(e){p([]),S(ah(yh(e)))}}fe(async()=>{try{i(hm(await G(`/api/agent/workspaces?state=active&limit=50`)).items)}catch(e){i([]),o(ah(yh(e)))}c()&&E(c())});let D=C(()=>f()?rh(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=th(e.request.sessionID,r.kind===`ready`?r.bindingID:void 0),a=JSON.stringify([n,i]);w?.body!==a&&(w={body:a,value:vh()}),v(!0),S(void 0);try{let t=Um((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(ah(yh(e)))}finally{v(!1)}}return n(de,{open:!0,title:`Start a side chat`,get onClose(){return e.onClose},get children(){var i=uh(),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 dh()},get children(){return n(l,{get when(){return!a()},get fallback(){return(()=>{var e=lh();return y(e,a),e})()},get children(){return n(l,{get when(){return t().length},get fallback(){return fh()},get children(){var e=oh(),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=ph();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=sh();return y(e,ih),e}}),p),y(i,n(l,{get when(){return r(()=>!!f())()&&f().length>1},get children(){var e=ch(),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=ph();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=lh();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[xh,Sh]=u(),Ch=(e,t)=>xh()?.id===e&&xh()?.place===t;function wh(e,t){if(!e.length)return;let n=t?`Archived`:`Unarchived`,r=e.length===1?`${n} “${e[0].title}”`:`${n} ${e.length} sessions`;Sd(`hiddenSessions`,e.map(e=>e.id),t,{message:r,undo:!0})}function Th(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:()=>gh(e.id)},...n?[{label:`Rename…`,run:()=>Sh({id:e.id,place:n})}]:[],{label:Dd(e.id)?`Naming…`:`Auto-name`,run:()=>void Ad(e.id),disabled:Dd(e.id)},{label:e.pinned?`Unpin`:`Pin`,run:()=>xd(`pinnedSessions`,e.id,!e.pinned)},{label:e.archived?`Unarchive`:`Archive`,run:()=>wh([e],!e.archived)},...e.running?[{label:`Stop`,run:()=>void Md(e.id),danger:!0}]:[],...e.state===`error`?[{label:`Dismiss error`,run:()=>void jd(e.id)}]:[],`sep`,{label:e.exposed?`Disallow Voice`:`Allow Voice`,run:()=>void Cd(e.id,!e.exposed)},Pf().has(e.id)?{label:`Unmute notifications`,run:()=>void Gf(e.id,!1)}:{label:`Mute notifications`,run:()=>void Gf(e.id,!0)},...n!==`topbar`&&!Z()?[`sep`,...[`left`,`right`,`top`,`bottom`].map(t=>({label:`Open in pane → ${t}`,run:()=>void em({sessionID:e.id},t)}))]:[]]}var Eh=I(`<button type=button class="link-btn small clamp-toggle">`),Dh=I(`<span>`),Oh=I(`<p>`),kh=I(`<span class="muted small cut-note"data-cut>… cut at <!> characters (of <!>)`),Ah=I(`<span class="muted small cut-note"data-more>+<!> more <!> not stored`),jh=I(`<dt>Requested by`),Mh=I(`<dd>`),Nh=I(`<dt>Proposes`),Ph=I(`<dt>Action`),Fh=I(`<dd class=mono data-action>`),Ih=I(`<dt>`),Lh=I(`<span class="muted small cut-note"data-incomplete>The hub received this request already shortened`),Rh=I(`<dd data-resources>`),zh=I(`<dt>Always saves`),Bh=I(`<dd data-saves>`),Vh=I(`<dt>Shown from`),Hh=I(`<dd class=muted>`),Uh=I(`<dt>Prompt`),Wh=I(`<dt>Form`),Gh=I(`<dt>Answer`),Kh=I(`<dd data-answer>`),qh=I(`<dt>Outside its grant`),Jh=I(`<dl class="escalation-details decision-details small">`),Yh=I(`<dt>Session`),Xh=I(`<dd><a>`),Zh=I(`<span class=decision-answer-field><span class=muted>:</span> `),Qh=I(`<dt>Purpose`),$h=I(`<dd data-purpose> <span class=muted>(<!>)`),eg={label:Su,blockers:e=>Br(_u(e)?.session)};function tg(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=Eh();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=Oh();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=Dh();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 ng={live:`Live request`,request:`The hub's record of the request`,text:`From the request text`},rg=new Set([`bash`,`shell`]),ig=e=>e&&rg.has(e)?`the command`:`the request`,ag=e=>e.toLocaleString(`en-US`);function og(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=kh(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(t,()=>ag(cg),n),y(t,()=>ag(e().length),r),t})()})}function sg(e){return n(l,{get when(){return e.count},get children(){var t=Ah(),n=t.firstChild.nextSibling,r=n.nextSibling.nextSibling;return r.nextSibling,y(t,()=>ag(e.count),n),y(t,()=>e.count===1?`item`:`items`,r),t}})}var cg=2e3,lg={stop:`Stop the session`,deny:`Deny its permission request`,prompt:`Send a prompt as you`,answer:`Answer its form as you`},ug=e=>e.verb===`answer`&&e.cancel?`Dismiss its form`:lg[e.verb??``]??e.verb;function dg(e){let t=C(()=>Ae(e.decision,e.context??eg));return n(l,{get when(){return t()},children:t=>(()=>{var i=Jh();return y(i,n(l,{get when(){return t().requester},get children(){return[jh(),(()=>{var n=Mh();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[Nh(),(()=>{var e=Mh();return y(e,()=>ug(t())),s(()=>b(e,`data-verb`,t().verb)),e})()]}}),null),y(i,n(l,{get when(){return t().target},children:e=>[Yh(),(()=>{var t=Xh(),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[Ph(),(()=>{var e=Fh();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=Ih();return y(e,()=>t().resources.length===1?`Resource`:`Resources`),e})(),(()=>{var e=Rh();return y(e,n(m,{get each(){return t().resources},children:(e,r)=>[n(tg,{tag:`span`,class:`escalation-resource mono`,text:e,chars:240,lines:4,get what(){return ig(t().action)},reveal:!0}),n(og,{get detail(){return t()},field:`resources`,get index(){return r()}})]}),null),y(e,n(sg,{get count(){return t().resourcesMore}}),null),y(e,n(l,{get when(){return t().incomplete},get children(){return Lh()}}),null),e})()]}}),null),y(i,n(l,{get when(){return t().saves?.length},get children(){return[zh(),(()=>{var e=Bh();return y(e,n(m,{get each(){return t().saves},children:(e,r)=>[n(tg,{tag:`span`,class:`escalation-resource mono`,text:e,chars:240,lines:4,what:`the saved pattern`,reveal:!0}),n(og,{get detail(){return t()},field:`save`,get index(){return r()}})]}),null),y(e,n(sg,{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[Vh(),(()=>{var e=Hh();return y(e,()=>ng[t().source]),s(()=>b(e,`data-source`,t().source)),e})()]}}),null),y(i,n(l,{get when(){return t().text},get children(){return[Uh(),(()=>{var e=Mh();return y(e,n(tg,{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[Wh(),(()=>{var e=Mh();return y(e,()=>t().form??t().formID),e})()]}}),null),y(i,n(l,{get when(){return t().answer?.length},get children(){return[Gh(),(()=>{var e=Kh();return y(e,n(m,{get each(){return t().answer},children:e=>(()=>{var t=Zh(),r=t.firstChild,i=r.firstChild;return r.nextSibling,y(r,()=>e.key,i),y(t,n(tg,{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[qh(),(()=>{var e=Mh();return y(e,()=>t().outsideGrant),e})()]}}),null),y(i,n(l,{get when(){return t().purpose},children:e=>[Qh(),(()=>{var t=$h(),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 fg=(e,t=eg)=>Ae(e,t)?.purpose?.text;z([`click`]);var pg=I(`<span class="badge-pill agent-request"title="An agent asked to act outside its grant">Agent request`),mg=I(`<span>`),hg=I(`<p role=timer>`),gg=I(`<div role=radiogroup aria-label=Options class=choice-group>`),_g=I(`<p class="muted small decision-why">Why: `),vg=I(`<input type=text class=decision-note aria-label="Note (optional)"placeholder="Note (optional)">`),yg=I(`<p class="muted small decision-tier">`),bg=I(`<div role=group><p class="blocker-head decision-head"><strong>Decision</strong> <span class=muted>from </span></p><p class="blocker-text decision-question"></p><form class=form-card novalidate><fieldset><div class=row><button type=submit class="btn small primary">Answer`),xg=I(`<a>`),Sg=I(`<label class=text-field><span class=field-title>Your answer</span><textarea rows=2 aria-label="Your answer">`),Cg=I(`<span class="badge-pill safe"title="A timeout may pick this option">safe`),wg=I(`<span class="badge-pill recommended">Recommended`),Tg=I(`<label><input type=radio><span>`),Eg={low:`Low urgency`,normal:``,high:`Urgent`};function Dg(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?_u(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?ud(e):dd(i().id)}catch(e){if(e instanceof W&&e.status===409&&e.code===`gone`){q(`Already answered or expired`),dd(i().id);return}q(U(e),`err`),p(!1)}}},w=e=>i().recommendation?.option===e;return(()=>{var u=bg(),p=u.firstChild,g=p.firstChild.nextSibling.nextSibling;g.firstChild;var _=p.nextSibling,T=_.nextSibling,E=T.firstChild,D=E.firstChild,O=x;return typeof O==`function`?t(O,u):x=u,y(g,()=>ve(i(),Su,ou()),null),y(p,n(l,{get when(){return jt(i())},get children(){return pg()}}),null),y(p,n(l,{get when(){return Eg[i().urgency]},get children(){var e=mg();return y(e,()=>Eg[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=xg();return y(t,()=>e().session.title||e().session.id),s(()=>b(t,`href`,Ot(e().session.id))),t})()]}),null),y(_,()=>Re(i(),Su,ou())),y(u,n(dg,{get decision(){return i()}}),T),y(u,n(l,{get when(){return et(i(),h())},get children(){var e=hg();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=Sg(),t=e.firstChild.nextSibling;return t.$$input=e=>d(e.currentTarget.value),s(()=>t.value=c()),e})()},get children(){return[(()=>{var e=gg();return y(e,n(m,{get each(){return i().options},children:e=>(()=>{var t=Tg(),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 Cg()}}),null),y(t,n(l,{get when(){return w(e.id)},get children(){return wg()}}),null),s(n=>{var a=`choice${w(e.id)?` recommended`:``}`,o=`d-${i().id}`;return a!==n.e&&k(t,n.e=a),o!==n.t&&b(r,`name`,n.t=o),n},{e:void 0,t:void 0}),s(()=>r.value=e.id),s(()=>r.checked=a()===e.id),t})()})),e})(),n(l,{get when(){return r(()=>!!i().recommendation?.why)()&&i().recommendation.why!==fg(i())},get children(){var e=_g();return e.firstChild,y(e,()=>i().recommendation.why,null),e}}),(()=>{var e=vg();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=yg();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 Og(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(Dg,{get decision(){return t()},get showSession(){return e.showSession}})})})}z([`input`]);var kg=I(`<span class="naming muted small"role=status><span class="spinner small"aria-hidden=true></span>Naming…`),Ag=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">✨`),jg,Mg=0;function Ng(e){return n(l,{get when(){return Ch(e.id,e.place)},get fallback(){return e.children},get children(){return n(Fg,{get id(){return e.id},get title(){return e.title},get place(){return e.place},get class(){return e.class}})}})}function Pg(e){return n(l,{get when(){return Dd(e.id)},get children(){return kg()}})}function Fg(e){let n,r=!1,i=jg&&jg.id===e.id&&jg.place===e.place?jg.value:void 0,a=()=>{r||(r=!0,jg=void 0,Sh(void 0),Ad(e.id))},o=t=>{if(r)return;r=!0;let i=n.value;jg=void 0,Sh(void 0),t&&i.trim()&&i.trim()!==e.title&&wd(e.id,i)};return fe(()=>{Mg++,n.focus(),i===void 0&&n.select()}),M(()=>{if(Mg--,setTimeout(()=>{Mg>0||(jg=void 0,xh()?.id===e.id&&xh()?.place===e.place&&Sh(void 0))},0),r)return;r=!0;let t=xh();t?.id===e.id&&t.place===e.place&&(jg={id:e.id,place:e.place,value:n.value})}),(()=>{var r=Ag(),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 Ig=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()}},Lg={phase:`off`,voice:`off`,level:0,held:``,paused:!1},Rg=class{deps;state=Lg;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({...Lg,phase:`starting`,sessionID:e,voice:`starting`});let i=await this.deps.expose(e);if(t!==this.run)return;if(!i)return this.set({...Lg,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({...Lg,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(Lg))}});this.conversation=a;let o=await a.start();if(t===this.run){if(!o)return this.run++,this.conversation=void 0,this.set({...Lg,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(Lg),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()}},zg=3e3,Bg=`Voice mode on`,Vg=`Voice mode paused · unlock to talk`,Hg={starting:`starting`,listening:`listening`,hearing:`listening`,transcribing:`thinking`,sent:`thinking`,speaking:`speaking`,paused:`muted`,suspended:`paused`,off:`off`},Ug=(e,t,n,r=``)=>({sessionID:e,title:n===`suspended`?Vg:Bg,body:`${t} · ${Hg[n]??n}${r}`}),Wg=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:Bg,artist:`${n}${r}`},()=>void this.controller.end())),!this.surface.allowed())return;let a=Ug(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+zg-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)}},Gg=3e4,Kg=1e4;function qg(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`)),Kg);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 Jg;function Yg(){return Jg??=Xg().catch(e=>{throw Jg=void 0,e}),Jg}function Xg(){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(),Jg=void 0,i||t(e)},o=setTimeout(()=>a(Error(`the turn model took too long to load`)),Gg);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=qg(n),e(r)):s.type===`error`&&(clearTimeout(o),a(Error(s.message||`the turn model could not load`)))}})}var Zg=16e3,Qg=8*Zg,$g=400;1+Math.floor(Qg/160),27/Math.log(6.4);var e_=new Float64Array($g),t_=new Float64Array($g);for(let e=0;e<$g;e++)e_[e]=Math.cos(2*Math.PI*e/$g),t_[e]=-Math.sin(2*Math.PI*e/$g);var n_=Object.freeze([`timers`,`smart`]);function r_(e){return e===`smart`?`smart`:`timers`}var i_=Object.freeze({threshold:.5,graceMs:150,recheckMs:400,fallbackMs:3e3,slowMs:1500}),a_=5e3;function o_(e,t){if(!t.length)return Math.min(a_,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(a_,Math.max(e,2*i))}var s_=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:a_}]);function c_(e,t){let n=s_.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 l_(...e){let t={...i_};for(let n of s_)for(let r of e){let e=c_(n.key,r(n.key));if(e!==void 0){t[n.field]=e;break}}return t}var u_=class{ring=new Float32Array(Qg);write=0;filled=0;get durationMs(){return this.filled/Zg*1e3}push(e){let t=e.length>128e3?e.subarray(e.length-Qg):e,n=Math.min(t.length,Qg-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)%Qg,this.filled=Math.min(Qg,this.filled+t.length)}snapshot(){let e=new Float32Array(this.filled),t=(this.write-this.filled+Qg)%Qg,n=Math.min(this.filled,Qg-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*Zg)))}reset(){this.write=0,this.filled=0}};function d_(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 f_=1500;function p_({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,f_);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 h_(e){return new Blob([await new Response(e??null).arrayBuffer()],{type:`audio/mpeg`})}var g_=[`image/png`,`image/jpeg`,`image/webp`,`image/gif`],__={maxImages:4,maxSide:1600,perImageBase64:18e4,totalBase64:7e5},v_=[.85,.72,.6,.48,.36],y_=[1,.75,.55,.4,.28,.2],b_=class extends Error{constructor(e=`This image is too large to attach, even after shrinking it`){super(e),this.name=`ImageTooLargeError`}},x_=e=>4*Math.ceil(e/3),S_=e=>g_.includes(e);function C_(e,t,n=__){if(e>=n.maxImages)return`Attach at most ${n.maxImages} images to a message`;if(!S_(t))return`Only PNG, JPEG, WebP or GIF images can be attached`}function w_(e,t=__){return Math.max(0,Math.min(t.perImageBase64,t.totalBase64-e))}function T_(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 E_(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 D_(e,t,n,r=__){if(t<=0)throw new b_(`No room for another image in this message`);let i=T_(e.width,e.height,r.maxSide);for(let r of y_){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}]:[],...v_.map(e=>({type:`image/jpeg`,quality:e,width:a,height:o}))];for(let e of s){let r=await n(e);if(x_(r.size)<=t)return{blob:r,request:e}}}throw new b_}var O_=()=>({draft:``,images:[],pending:[],stopping:!1});function k_(e,t){switch(t.type){case`input`:return{...e,draft:t.text,error:void 0};case`attach`:return e.images.length>=__.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,__.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 A_(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 j_(e,t){return e===202?t.mode===`turn`?`accepted`:`steered`:`result`}function M_(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 N_(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 P_=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)}},F_=-19.5,I_=-50,L_=20,R_=9,z_=2,B_=60,V_=.4,H_=.1,U_=-70,W_=-10,G_=e=>e>0?20*Math.log10(e):-1/0,K_=e=>e>0?-.691+10*Math.log10(e):-1/0;function q_(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 J_(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 Y_(e,t){if(!e.length)return-1/0;let[n,r]=q_(t),i=J_(J_(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(V_*t),s=Math.round(H_*t);if(i.length<o){let e=K_(a[i.length]/i.length);return e>U_?e:-1/0}let c=[];for(let e=0;e+o<=i.length;e+=s){let t=(a[e+o]-a[e])/o;K_(t)>U_&&c.push(t)}if(!c.length)return-1/0;let l=e=>e.reduce((e,t)=>e+t,0)/e.length,u=K_(l(c))+W_,d=c.filter(e=>K_(e)>u);return K_(l(d.length?d:c))}function X_(e){let t=0;for(let n=0;n<e.length;n++)t=Math.max(t,Math.abs(e[n]));return G_(t)}function Z_(e,t){let n=10**(I_/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 Q_(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,z_/1e3*t)),n=Math.exp(-1/Math.max(1,B_/1e3*t)),r=1;for(let t=i-1;t>=0;t--)a[t]=r=Math.min(a[t],1-(1-r)*e);r=1;for(let e=0;e<i;e++)a[e]=r=Math.min(a[e],1-(1-r)*n)}for(let t=0;t<i;t++)s[t]=e[t]*n*a[t];return s}function $_(e,t,n){let r=Z_(e,t),i=Y_(r,t);if(!Number.isFinite(i))return{samples:r,gainDb:0,loudness:i};let a=10**(-1/20),o=Math.min(L_,-1-X_(r)+R_),s=Math.min(n-i,o),c=Q_(r,t,10**(s/20),a);for(let e=0;e<3;e++){let e=n-Y_(c,t);if(e<.1||s>=o)break;s=Math.min(s+e,o),c=Q_(r,t,10**(s/20),a)}return{samples:c,gainDb:s,loudness:i}}function ev(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 tv=`voice.replyLoudness`,nv=8;function rv(e){try{let t=JSON.parse(e.getItem(tv)??`{}`);return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}catch{return{}}}function iv(e,t){let n=rv(e)[t];return Array.isArray(n)?n.filter(e=>typeof e==`number`&&Number.isFinite(e)):[]}function av(e,t,n){if(!(!Number.isFinite(n)||n<-50||n>0))try{let r=rv(e),i=[...iv(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-nv)))delete r[e];e.setItem(tv,JSON.stringify(r))}catch{}}var ov=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 sv(e,t){let n=[];try{t!==void 0&&(n=iv(e,t))}catch{n=[]}return n.length?Math.min(-14,Math.max(-26,ov(n))):F_}var cv={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}]},lv=`hub-cues-v2`,uv=[`hub-cues-v1`],dv=`x-hub-cue-target`,fv=1,pv=`https://hub-cues.invalid`,mv=e=>`${pv}/${encodeURIComponent(e)}/`,hv=(e,t)=>`${mv(e)}${encodeURIComponent(t)}`;async function gv(){try{let e=globalThis.caches;return e?await e.open(lv):void 0}catch{return}}function _v(e,t){e.defaultPlaybackRate=t,e.playbackRate=t,e.preservesPitch=!0,e.webkitPreservesPitch=!0}var vv=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))}},yv=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=vv}){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=cv[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 gv():void 0,i=n?hv(n,e):``,a=this.target?.(n)??-19.5,o=e=>!this.normalize||Math.abs((e??NaN)-a)<=fv,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(dv);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[dv]=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 gv():void 0;if(!t||!e)return;let n=globalThis.caches;for(let e of uv)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,_v(n,this.speed?.()??1);let r=new Promise(e=>{n.onended=n.onpause=n.onerror=()=>e()});await n.play().then(()=>!0,()=>!1)&&(t!==void 0&&this.onPlayed?.({cue:`phrase`,text:t}),await r),n.onended=n.onpause=n.onerror=null,this.setSpeaking(!1)}stop(){this.audio.paused||this.audio.pause(),this.setSpeaking(!1)}setSpeaking(e){e!==this.speaking&&(this.speaking=e,this.onSpeaking?.(e))}close(){this.stop(),this.loading.abort(),this.loading=new AbortController,this.ctx?.close?.().catch(()=>{}),this.ctx=void 0}},bv=new Set([`um`,`umm`,`uh`,`uhh`,`uhm`,`erm`,`er`,`eh`,`ah`,`hmm`,`hm`,`mm`,`mmm`,`mhm`,`mm-hmm`,`uh-huh`]),xv=new Set([...bv,`and`,`but`,`so`,`or`,`because`,`cause`,`then`,`with`,`to`,`the`,`a`,`an`,`of`,`for`,`if`,`that`,`like`,`maybe`]),Sv=new Map([[`stop`,`interrupt`],[`cancel`,`interrupt`],[`never mind`,`interrupt`],[`nevermind`,`interrupt`],[`stop that`,`interrupt`],[`hold on`,`interrupt`],[`pause listening`,`pause`]]);function Cv(e){return String(e??``).toLowerCase().replace(/[^\p{L}\p{N}'\s-]+/gu,` `).split(/\s+/).map(e=>e.replace(/^[-']+|[-']+$/g,``)).filter(Boolean)}function wv(e){return Sv.get(Cv(e).join(` `))}function Tv(e){return Cv(e).every(e=>bv.has(e))}function Ev(e){let t=String(e??``).trim(),n=Cv(t);return!n.length||xv.has(n[n.length-1])||/(\.\.\.|…|[,;:\-–—])["'”’)\]]*$/.test(t)?!1:/[.?!]["'”’)\]]*$/.test(t)?!0:n.length>=3}var Dv=new Set([`e.g.`,`i.e.`,`mr.`,`mrs.`,`ms.`,`dr.`,`st.`,`vs.`,`cf.`,`prof.`,`jr.`,`sr.`,`approx.`,`no.`,`fig.`]),Ov=/[.?!…]+["'”’)\]]*(?=\s|$)/g;function kv(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(Av),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=>jv(e,n))}function Av(e){let t=[],n=0;for(let r of e.matchAll(Ov)){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(Dv.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 jv(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 Mv=16e3;function Nv(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 Pv(e,t){return ev(Nv(e,t,Mv),Mv)}function Fv(e){return{audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,channelCount:1,...e?{deviceId:{exact:e}}:{}}}}var Iv=Object.freeze({minSpeechMs:300,endSilenceMs:350,trailingKeepMs:200,preRollMs:300,holdMs:1600,finishedHoldMs:1e3}),Lv=Iv.trailingKeepMs,Rv=120,zv=4,Bv=e=>e.reduce((e,t)=>e+t.ms,0);function Vv(e,t){for(;e.length>1&&Bv(e)-e[0].ms>=t;)e.shift()}var Hv=class{sampleRate;minSpeechMs;endSilenceMs;preRollMs;maxSegmentMs;onsetGapMs;minVoicedRatio;state=`silence`;preroll=[];frames=[];segmentMs=0;onsetMs=0;voicedMs=0;gapMs=0;silenceMs=0;constructor({sampleRate:e,minSpeechMs:t=Iv.minSpeechMs,endSilenceMs:n=Iv.endSilenceMs,preRollMs:r=Iv.preRollMs,maxSegmentMs:i=6e4,onsetGapMs:a=Rv,minVoicedRatio:o=0}){this.sampleRate=e,this.minSpeechMs=t,this.endSilenceMs=n,this.preRollMs=r,this.maxSegmentMs=i,this.onsetGapMs=a,this.minVoicedRatio=o,this.reset()}get active(){return this.state===`speech`}reset(){this.state=`silence`,this.preroll=[],this.frames=[],this.segmentMs=0,this.onsetMs=0,this.voicedMs=0,this.gapMs=0,this.silenceMs=0}process(e,t){let n={samples:Float32Array.from(e),ms:e.length/this.sampleRate*1e3},r=[];if(this.state===`silence`)t?(this.state=`onset`,this.frames=[...this.preroll,n],this.segmentMs=Bv(this.frames),this.preroll=[],this.onsetMs=this.voicedMs=n.ms,this.gapMs=0):(this.preroll.push(n),Vv(this.preroll,this.preRollMs));else if(this.state===`onset`)this.frames.push(n),this.segmentMs+=n.ms,this.onsetMs+=n.ms,t?(this.voicedMs+=n.ms,this.gapMs=0):((this.gapMs+=n.ms)>this.onsetGapMs||this.voicedMs<this.minVoicedRatio*this.onsetMs)&&(this.preroll=this.frames,Vv(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-Lv;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}}},Uv=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-zv: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}}},Wv=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=[];constructor({send:e,holdMs:t=Iv.holdMs,finishedHoldMs:n=Iv.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}){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.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))},o_(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}){wv(t)?(this.cancelHold(),this.text=``,this.ms=0,this.segments=[],this.sent(t,[e],`command`)):Tv(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=Ev(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}},Gv=2,Kv=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?Gv: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))}},qv=class{parts=new Map;limit;speakable;constructor({limit:e=50,speakable:t}={}){this.limit=e,this.speakable=t}split(e){return kv(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]}},Jv=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)}}},Yv=e=>`${(e/1e3).toFixed(1)} s`;function Xv(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} ${Yv(n-i)}`),i=n)}return{summary:`last turn: ${Yv(e.firstAudio-t)} to first audio`,detail:r.join(` · `)}}var Zv=12,Qv=e=>String(e??``).replace(/\s+/g,` `).trim();function $v(e,t){let n=Qv(e),r=Qv(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>=Zv;e--)if(n.endsWith(r.slice(0,e)))return{mode:`update`,text:n+r.slice(e)};return{mode:`new`,text:t}}function ey(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 ty=16e3,ny=512/ty*1e3,ry=Object.freeze({startProb:.6,endProb:.35,speakingStartProb:.85,minSpeechMs:250,endSilenceMs:Iv.endSilenceMs,maxSegmentMs:6e4,gateDb:3,energyMarginDb:10,energyMinSpeechMs:Iv.minSpeechMs}),iy=Object.freeze([`low`,`normal`,`high`]);function ay(e){return iy.includes(e)?e:`normal`}var oy=Object.freeze({low:Object.freeze({...ry,startProb:.75,endProb:.45,speakingStartProb:.92,minSpeechMs:350,gateDb:6,energyMarginDb:13,energyMinSpeechMs:400}),normal:ry,high:Object.freeze({...ry,startProb:.45,endProb:.25,speakingStartProb:.75,minSpeechMs:180,gateDb:0,energyMarginDb:7,energyMinSpeechMs:250})});function sy(e){return oy[ay(e)]}var cy=.75,ly=class{speaking=!1;segmenter;current;constructor(e,t=ty){this.current=e,this.segmenter=new Hv({sampleRate:t,endSilenceMs:e.endSilenceMs,maxSegmentMs:e.maxSegmentMs})}get params(){return this.current}set params(e){this.current=e,this.segmenter.endSilenceMs=e.endSilenceMs,this.segmenter.maxSegmentMs=e.maxSegmentMs}get state(){return this.segmenter.state}get active(){return this.segmenter.active}reset(){this.segmenter.reset()}process(e,t){let n=this.current;this.segmenter.minSpeechMs=n.minSpeechMs,this.segmenter.minVoicedRatio=cy;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)}},uy=class{from;ratio;input=new Float32Array;pos=0;out=new Float32Array(512);filled=0;constructor(e){this.from=e,this.ratio=e/ty}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}},dy=64,fy=class{sampleRate=ty;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;constructor({sampleRate:e,params:t=ry,onEvents:n,onLevel:r,onChunk:i,warn:a=e=>console.warn(e),now:o=()=>performance.now()}){this.resampler=new uy(e),this.meter=new Uv({marginDb:t.energyMarginDb}),this.vad=new ly(t),this.onEvents=n,this.onLevel=r,this.onChunk=i,this.warn=a,this.now=o}get classifier(){return this.model}set classifier(e){this.model=e}get mode(){return this.model?`silero`:`energy`}get params(){return this.vad.params}set params(e){this.vad.params=e,this.meter.marginDb=e.energyMarginDb}get speaking(){return this.speakingOn}set speaking(e){this.speakingOn&&!e&&(this.tail=Math.ceil(400/ny)),this.speakingOn=e}get active(){return this.vad.active}reset(){this.generation++,this.queue=[],this.inFlight=0,this.vad.reset()}push(e){for(let t of this.resampler.push(e))this.chunk(t)}chunk(e){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,ny,n);this.onLevel?.(a);let s={chunk:e,energyVoiced:o,guarded:t};this.queue.push(s),this.model&&this.inFlight>=dy&&this.drop(`stalled`);let c=this.model;if(!c)s.energy=!0;else if(!n&&r<i+this.vad.params.gateDb+(t?this.meter.speakingBoostDb:0))s.prob=0,this.stats.skipped++;else{let t=this.generation,n=this.now();this.inFlight++,c(e).then(e=>{t===this.generation&&(this.inFlight--,this.record(this.now()-n),s.prob=e,this.drain())},e=>{t===this.generation&&(this.inFlight--,s.energy=!0,this.model===c&&this.drop(e?.message??String(e)),this.drain())})}this.drain()}drop(e){this.model=void 0,this.generation++,this.inFlight=0;for(let e of this.queue)e.prob===void 0&&(e.energy=!0);this.warnOnce(`failed`,`Voice: on-device speech detection stopped (${e}); using the energy detector`)}record(e){let t=this.stats;t.frames++,t.avgMs+=(e-t.avgMs)/t.frames,t.maxMs=Math.max(t.maxMs,e)}drain(){let e=[];for(;this.queue.length&&(this.queue[0].energy||this.queue[0].prob!==void 0);){let t=this.queue.shift();this.vad.speaking=t.guarded,e.push(...t.energy?this.vad.processEnergy(t.chunk,t.energyVoiced):this.vad.process(t.chunk,t.prob))}e.length&&this.onEvents(e)}warnOnce(e,t){this.warned.has(e)||(this.warned.add(e),this.warn(t))}},py=`voice.speed`,my=`voice.cues`,hy=`voice.background`,gy=`voice.micDevice`,_y=`voice.sensitivity`,vy=`voice.turnDetection`,yy=`voice.front`,by,xy,Sy={get speed(){return Ha(localStorage.getItem(py))},set speed(e){localStorage.setItem(py,String(Ha(e))),_v(wy(),Ha(e))},get cues(){return localStorage.getItem(my)!==`0`},set cues(e){localStorage.setItem(my,e?`1`:`0`)},get background(){return localStorage.getItem(hy)===`1`},set background(e){localStorage.setItem(hy,e?`1`:`0`)},get sensitivity(){return by??=ay(localStorage.getItem(_y))},set sensitivity(e){by=ay(e),localStorage.setItem(_y,by)},get turnDetection(){return xy??=r_(localStorage.getItem(vy))},set turnDetection(e){xy=r_(e),localStorage.setItem(vy,xy)},get front(){return localStorage.getItem(yy)!==`0`},set front(e){localStorage.setItem(yy,e?`1`:`0`)},get smartTurn(){let e=new URLSearchParams(location.search);return l_(t=>e.get(t),e=>localStorage.getItem(e))},setSmartTurnKnob(e,t){let n=c_(e,t);return n===void 0?localStorage.removeItem(e):localStorage.setItem(e,String(n)),n===void 0?``:String(n)}},Cy;function wy(){return Cy||(Cy=new Audio,Cy.preload=`none`,Cy.volume=1,_v(Cy,Sy.speed),Cy)}function Ty(){let e=wy();e.paused&&(e.muted=!0,e.play().catch(()=>{}).finally(()=>{e.pause(),e.muted=!1}))}var Ey,Dy=new Set,Oy={get(){return Ey??=localStorage.getItem(gy)??``},set(e){Ey=e,localStorage.setItem(gy,e);for(let t of[...Dy])t(e)},subscribe(e){return Dy.add(e),()=>{Dy.delete(e)}}};async function ky(){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 Ay(e,t){let n=await navigator.mediaDevices.getUserMedia(Fv(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 jy=6e4;function My(){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 Ny({transcribe:e,deviceId:t=Oy.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(Fv(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=My(),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((jy-(Date.now()-s))/1e3))),1e3),d=setTimeout(()=>a.state===`recording`&&a.stop(),jy);return{finish(){return a.state===`recording`&&a.stop(),l},cancel(){c=!0,a.state===`recording`&&a.stop()}}}var Py=wy(),[Fy,Iy]=u(Oy.get());function Ly(e){Iy(e),Oy.set(e)}function Ry(e){return Ny({deviceId:Fy(),...e?{onTick:e}:{},transcribe:async e=>(await V(`/api/transcribe`,{method:`POST`,body:e,headers:{"content-type":e.type}})).json()})}function zy(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 By(e){return e.audioState===`suspended`||e.error===`NotAllowedError`&&!e.activated&&e.micPermission!==`denied`}var Vy=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(`.`)),Hy=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`]),Uy=[/^(?:subtitles?|captions?|subtitled|captioned|transcribed|transcription|translated|translation)\b.*\bby\b/,/\bamara\s*\.?\s*org\b/,/^sous-titr/,/^untertitel\b/],Wy=/^(?:\[[^\]]*\]|\([^)]*\)|\*[^*]*\*|♪[^♪]*♪|\s)+$/u;function Gy(e){return e.toLowerCase().replace(/[^\p{L}\p{N}'\s]+/gu,` `).replace(/\s+/g,` `).trim()}function Ky(e,{speechMs:t}={}){let n=String(e??``).trim();if(!n)return`empty`;if(!/[\p{L}\p{N}]/u.test(n))return`no words`;if(Wy.test(n))return`sound`;let r=Gy(n);if(r.replace(/\s/g,``).length<2)return`too short`;if(Hy.has(r)||Hy.has(r.replace(/ /g,``))||Uy.some(e=>e.test(r)||e.test(n.toLowerCase())))return`noise`;let i=r.split(` `),a=i.some(e=>Vy.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 qy=3e4,Jy;function Yy(){return Jy??=Xy().catch(e=>{throw Jy=void 0,e}),Jy}function Xy(){return new Promise((e,t)=>{let n;try{n=new Worker(new URL(`/assets/silero-worker-e802lB5T.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(),Jy=void 0,a||t(e)},s=setTimeout(()=>o(Error(`the speech model took too long to load`)),qy);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 Zy=()=>Object.assign(Error(`The download was aborted`),{name:`AbortError`}),Qy=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 Zy();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 $y(e,t){let n=new Qy;if(!e)return n.end(),n;let r=e.getReader(),i=()=>{n.fail(Zy()),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?Zy():e)}finally{t?.removeEventListener(`abort`,i)}})(),n}async function eb(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 tb(e){try{return e.MediaSource?.isTypeSupported?.(`audio/mpeg`)===!0}catch{return!1}}var nb=24e3,rb=1,ib=2;async function ab(e){let t=globalThis,n=t.OfflineAudioContext||t.webkitOfflineAudioContext;if(!n)throw Error(`No OfflineAudioContext here`);let r=new n(1,1,nb),i=await new Promise((t,n)=>{r.decodeAudioData(e,t,n)?.then(t,n)}),a=Array.from({length:i.numberOfChannels},(e,t)=>i.getChannelData(t));if(a.length===1)return{samples:a[0],rate:i.sampleRate};let o=new Float32Array(i.length);for(let e of a)for(let t=0;t<o.length;t++)o[t]+=e[t]/a.length;return{samples:o,rate:i.sampleRate}}async function ob(e,t){let{samples:n,rate:r}=await ab(await e.arrayBuffer()),i=$_(n,r,t);return new Blob([ev(i.samples,r)],{type:`audio/wav`})}function sb(e){try{return sv(localStorage,e)}catch{return sv({getItem:()=>null,setItem:()=>{}},e)}}var cb=0,lb=e=>{let t=globalThis;t.requestIdleCallback?t.requestIdleCallback(e,{timeout:5e3}):setTimeout(e,500)};function ub(e,t){!t||!e.length||cb>=ib||(cb++,lb(()=>{(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 ab(n.buffer);if(i.length<a*rb)return;av(localStorage,t,Y_(i,a))}catch{}finally{cb--}})()}))}var db=500,fb=8e3,pb=e=>Math.min(fb,db*2**Math.max(0,e)),mb=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)}},hb=2500,gb=3e3,_b=!1,vb=2,yb=`Tap to start Voice mode`,bb=`GestureRequired`,xb=500,Sb=500,Cb=3e3,wb=()=>navigator.userActivation?.hasBeenActive??!0;async function Tb(){try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return`unknown`}}var Eb=`Voice front unavailable, talking to the session directly`,Db={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`},Ob=.01,kb=Iv.minSpeechMs+Iv.preRollMs,Ab=50,jb=()=>new URL(`/assets/vad-worklet-BfxJhrXy.js`,``+import.meta.url).href,Mb=class{sessionID;transport;unsubscribe;player;ui;opts;rec;heldText=``;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 mb({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=tb(window);says;turns;cueClock;speechEndedAt;silence;silenceURL;wakeLock;warnedAutoplay=!1;state;ignoredTimer;sensitivity=`normal`;cueSpeaking=!1;attempt=0;turnAudio=new u_;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 qv(o?{speakable:o}:{}),this.opts={cues:!0,background:!1,speed:()=>1,title:()=>`OpenCode session`,sensitivity:()=>`normal`,turnDetection:()=>`timers`,smartTurnParams:()=>i_,smartTurn:Yg,warn:e=>console.warn(e),front:()=>!0,voiceKey:async()=>void 0,...s},this.rec=a,a&&(a.onNote=e=>this.ui.note(e)),this.turns=new Jv({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 yv({synthesize:async(e,t)=>h_(await this.transport.speak(e,t?{signal:t}:{})),speed:this.opts.speed,normalize:ob,target:sb,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(Fv(this.opts.deviceId))}catch(e){if(t())return!1;let n=e;return By({error:n.name,micPermission:await Tb(),activated:wb()})?this.ui.note(yb,`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:{...Iv,...this.smartTimings()}}),this.prefetchCues();try{await this.listen()}catch(e){return t()||(e.name===bb?this.ui.note(yb,`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(),Sb),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))]),By({audioState:n.state,activated:wb()}))throw Object.assign(Error(yb),{name:bb});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??jb());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 fy({sampleRate:n.sampleRate,params:sy(this.sensitivity),onEvents:e=>this.vadEvents(e),onLevel:e=>this.ui.level(e),onChunk:e=>this.turnAudio.push(e)});this.detected({mode:`energy`}),this.wantSmartTurn(),Yy().then(e=>{this.vad===r&&(e.reset(),r.classifier=t=>e.classify(t),this.detected({mode:`silero`}))},e=>{_b||console.warn(`Voice: on-device speech detection unavailable (${e?.message??e}); using the energy detector`),_b=!0}),this.endpointer=new Wv({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)}),this.queue=new Kv({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<Ob?Promise.reject(Error(`no speech`)):this.smartModel.predict(e)}turnPredicted(e){this.ui.turn?.(d_(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}}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>Ab&&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=sy(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(kb),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=Pv(n.samples,t.sampleRate);this.rec?.event(`segment.closed`,{...r,bytes:i.byteLength}),this.transcribe(e,i,n.speechMs),this.detected({mode:t.mode,...t.mode===`silero`?{avgMs:t.stats.avgMs}:{}})}this.cueClock.poke(),this.refresh()}}async transcribe(e,t,n){this.inflight++,this.refresh();let r=``,i,a;this.rec?.event(`stt.sent`,{segment:e,bytes:t.byteLength});try{let n=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{this.inflight--}if(!this.active)return;let o=r,s=Ky(r,{speechMs:n});s&&(r.trim()&&this.showIgnored(r.trim()),r=``),this.rec&&(this.rec.event(`stt.received`,{segment:e,text:o,...s&&o.trim()?{junk:!0}:{},...!o.trim()&&i===void 0?{empty:!0}:{},...i===void 0?{}:{failed:i},...a?{audio:a}:{}}),this.rec.segmentAudio(e,a,t)),r.trim()&&this.markTurn(`transcript`),this.endpointer?.transcribed(e,r),this.refresh()}showIgnored(e){clearTimeout(this.ignoredTimer),this.ui.ignored?.(e),this.ignoredTimer=setTimeout(()=>this.ui.ignored?.(``),gb)}async deliver(e,t=!1){let n=wv(e);if(n&&this.rec?.event(`utterance.command`,{command:n,text:e}),n===`pause`)return this.ui.note(`Paused listening.`),this.stop();if(n===`interrupt`){this.hushReplies(`command`),this.ui.note(`“${e}” — interrupting.`);try{await this.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(Eb),!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];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<Cb)&&(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()},pb(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(Fv(this.opts.deviceId))}catch(e){if(!this.active)return;By({error:e.name,micPermission:await Tb(),activated:wb()})&&this.ui.note(yb,`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([Pv(new Float32Array(16e3*vb),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=$y(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=>ub(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 eb(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(Db[e])}catch{}let t=e===`firstAudio`?Xv(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<hb?`sent`:`listening`:`suspended`;e!==this.state&&(this.state=e,this.ui.state(e),this.rec?.event(`state`,{state:e}))}async lockScreen(){if(`wakeLock`in navigator&&document.visibilityState===`visible`&&(!this.wakeLock||this.wakeLock.released))try{this.wakeLock=await navigator.wakeLock.request(`screen`)}catch{}}release(){this.unwatchTrack(),this.stream?.getTracks().forEach(e=>e.stop()),this.stream=void 0}async stop({post:e=!0,keepalive:t=!1}={}){this.attempt++,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?.release().catch(()=>{}),this.wakeLock=void 0,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 Nb({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 Pb(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 Fb(e,t){return n=>e.subscribe(e=>`sessionID`in e&&e.sessionID===t&&n(e))}var Ib=class extends Mb{constructor({sessionID:e,api:t,events:n,player:r,ui:i,options:a={}}){super({sessionID:e,transport:Nb({api:t,sessionID:e,...n?{events:n}:{}}),player:r,ui:i,options:{speakable:Bn,voiceKey:()=>Pb(t),workletURL:`/vad-worklet.js`,...a}})}},[Lb,Rb]=u(Date.now());setInterval(()=>ru()&&Rb(Date.now()),1e3);var[zb,Bb]=u(!1),Vb=e=>Bb(e),Hb=()=>Vs(Ul(),ru(),Math.max(Lb(),Date.now())),Ub=(e,t)=>Ul().find(t=>t.id===e)?.options.find(e=>e.id===t)?.label??t;async function Wb(e,t,n){let r=Ub(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?ud(i):dd(e),q(`Answered “${r}”${n?` by ${n}`:``}`)}catch(t){throw t instanceof W&&t.status===409&&t.code===`gone`?(dd(e),new W(409,`Already answered or expired`)):t}}function Gb(e){return ec(V,{sessionID:e,current:()=>Xl()?.sessionID,armed:()=>Hb(),present:()=>zb()&&document.visibilityState===`visible`,answer:async(e,t)=>{try{await Wb(e,t,`voice`),Ol(`decision.voice`,{decisionID:e,option:t,outcome:`answered`})}catch(n){let r=n instanceof W&&n.status===403;throw Ol(`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 Kb=new m_,qb=new Rg({async expose(e){let t=()=>_u(e)?.session.exposed!==!1;if(t())return!0;if(!await Cd(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 Ib({sessionID:e,api:Gb(e),events:Fb(Kb,e),player:Py,ui:t,options:{cues:Sy.cues,background:Sy.background,speed:()=>Sy.speed,sensitivity:()=>Sy.sensitivity,turnDetection:()=>Sy.turnDetection,smartTurnParams:()=>Sy.smartTurn,front:()=>Sy.front,title:()=>_u(e)?.session.title||`OpenCode session`,status:_u(e)?.session.status,deviceId:Fy()||void 0,recorder:new kl}}),stopPlayback:()=>{Py.paused||Py.pause()},notify:(e,t)=>q(e,t===`err`?`err`:``)}),[Jb,Yb]=u(0);qb.subscribe(()=>Yb(e=>e+1)),p_({mode:Sy.turnDetection,load:Yg});var Xb=`voice-mode`,Zb=Promise.resolve(),Qb=e=>{Zb=Zb.then(async()=>{let t=`serviceWorker`in navigator?await navigator.serviceWorker.getRegistration(`/`):void 0;t&&await e(t)}).catch(()=>{})},$b={allowed:()=>`Notification`in window&&Notification.permission===`granted`&&`serviceWorker`in navigator,show:e=>Qb(t=>t.showNotification(e.title,{body:e.body,tag:Xb,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:()=>Qb(async e=>(await e.getNotifications({tag:Xb})).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{}}},ex=new Wg(qb,$b,{title:e=>_u(e)?.session.title||`OpenCode session`,suffix:()=>vl(gl.get())});gl.subscribe(()=>ex.refresh()),Yf(e=>{e?.type===`voice-end`&&typeof e.sessionID==`string`&&ex.endFromNotification(e.sessionID)});function tx(){return Jb(),ex.needsPermission()}async function nx(){try{await Hf()}catch(e){q(e instanceof Error?e.message:String(e),`err`)}ex.refresh(),Yb(e=>e+1)}function rx(){return Jb(),qb.state}var ix=()=>{let e=rx().sessionID;return e?_u(e)?.session.title||`Session`:``};hu(e=>{e.type===`say`||e.type===`heard`||e.type===`conversation`?Kb.emit(e):e.type===`status`&&typeof e.sessionID==`string`&&Array.isArray(e.sessions)&&qb.onStatus(e.sessionID,e.sessions)}),window.addEventListener(`pagehide`,()=>{qb.stop({keepalive:!0}),$b.close()});var ax=new P_,ox=new Ig({record:e=>Ry(e),deliver:(e,t)=>void ax.append(e,t),notify:(e,t)=>q(e,t),hold:()=>qb.hold()}),[sx,cx]=u(0);ox.subscribe(()=>cx(e=>e+1));function lx(e){return sx(),ox.forSession(e)}var ux=I(`<div class=banner><span></span><a class="btn small"href=/settings/machines>Review`),dx=I(`<div class=banner><span><strong>Set up speech</strong> · </span><a class="btn small"href=/settings/voice#speech>Set up`),fx=I(`<section class=decisions aria-label=Decisions><h2 class=section-title>`),px=I(`<select aria-label=Server><option value>All servers`),mx=I(`<select class=chip-window aria-label="Touched within">`),hx=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`),gx=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.`),_x=I(`<ul class=home-list>`),vx=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>`),yx=I(`<option>`),bx=I(`<button type=button class=chip>`),xx=I(`<p class="muted small offline-line"><strong></strong> · offline · seen `),Sx=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">`),Cx=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>`),wx=I(`<th><button type=button class=th-btn><span class=sort-mark aria-hidden=true>`),Tx=I(`<tr><td colspan=11 class="muted empty-cell">No sessions match.`),Ex=I(`<span class=jobs-badge>`),Dx=I(`<a>`),Ox=I(`<span class=unread-dot role=img aria-label=Unread>`),kx=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>`),Ax=I(`<span class=row-sub data-row-sub>`),jx=I(`<span class=waiting-since>`),Mx=I(`<a class=home-item-link><span class=home-item-text><span class=home-item-title></span><span>`),Nx=I(`<li>`),Px=I(`<span class=home-item-link>`),Fx=I(`<span class="home-item-sub muted"data-row-sub>`),Ix=`hub.table`;function Lx(e){Fl();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=Ml.has(e.id)?Ml.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 Rx=[[`status`,`Status`],[`title`,`Title`],[`project`,`Project`],[`server`,`Server`],[`source`,`Open in`],[`busy`,`24 h`],[`touched`,`Last touched`],[`activity`,`Last activity`]],zx={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`},Bx={"1h":`1 h`,"24h":`24 h`,"7d":`7 days`},Vx=[[`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}]],Hx={touched:`24h`};function Ux(){let[e,t]=u(Oa(localStorage.getItem(Ix))),[i,a]=u(``),o=e=>{t(e),localStorage.setItem(Ix,ka(e))},c=C(()=>Ea(gu(),{...e(),query:i()},N())),[d,f]=u(new Set),p=C(()=>c().filter(e=>d().has(e.id))),h=(e,t)=>{let n=new Set(d());t?n.add(e):n.delete(e),f(n)},g=e=>f(e?new Set(c().map(e=>e.id)):new Set),_=()=>{wh(p(),!e().filters.archived),f(new Set)},[v,x]=u(!1),S=()=>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(zl()??void 0,X()?.publicURL);return(()=>{var t=vx(),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 Vl().length},get children(){var e=ux(),t=e.firstChild;return y(t,(()=>{var e=r(()=>Vl().length===1);return()=>e()?`${Vl()[0].machineName} wants to connect.`:`${Vl().length} machines want to connect.`})()),e}}),O),y(t,n(l,{get when(){return D()},get children(){var e=dx(),t=e.firstChild;return t.firstChild.nextSibling,y(t,()=>D().reason,null),e}}),O),y(t,n(l,{get when(){return Ul().length},get children(){var e=fx(),t=e.firstChild;return y(t,(()=>{var e=r(()=>Ul().length===1);return()=>e()?`A decision waits for you`:`${Ul().length} decisions wait for you`})()),y(e,n(Og,{get decisions(){return Ul()},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=px();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=yx();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?``:Hx.touched}}),y(M,n(l,{get when(){return e().filters.touched},get children(){var t=mx();return t.addEventListener(`change`,t=>o({...e(),filters:{...e().filters,touched:t.currentTarget.value}})),y(t,n(m,{each:ma,children:e=>(()=>{var t=yx();return t.value=e,y(t,()=>`within ${Bx[e]}`),t})()})),s(()=>t.value=e().filters.touched),t}}),null),y(M,n(m,{each:Vx,children:([e,t,n])=>(()=>{var r=bx();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=hx(),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,gu().filter(e=>!e.hidden).length,Ul().length,e().filters.status===`needs`)})()),y(t,n(l,{get when(){return r(()=>!!Y.machines)()&&Y.machines.length===0},get children(){return gx()}}),null),y(t,n(l,{get when(){return Z()},get fallback(){return n(Kx,{get rows(){return c()},get table(){return e()},sortBy:E,get picked(){return d()},pick:h,pickAll:g})},get children(){var e=_x();return y(e,n(m,{get each(){return c()},children:e=>n(qx,{row:e})})),e}}),null),y(t,n(m,{get each(){return S().filter(e=>!e.online)},children:e=>(()=>{var t=xx(),n=t.firstChild;return n.nextSibling,y(n,()=>e.name),y(t,()=>R(e.lastSeen,N()),null),t})()}),null),y(t,n(Gx,{get open(){return v()},get rows(){return gu()},onClose:()=>x(!1)}),null),s(()=>b(ee,`aria-pressed`,e().filters.touched!==``)),s(()=>A.value=i()),t})()}var Wx=30;function Gx(e){let[t,i]=u(String(Wx)),a=C(()=>e.open?Na(e.rows,Number(t()),N()):[]),o=()=>a().length,c=()=>{wh(a(),!0),e.onClose()};return n(de,{get open(){return e.open},title:`Archive inactive sessions`,get onClose(){return e.onClose},get children(){var n=Sx(),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 Kx(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=Cx(),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:Rx,children:([t,n])=>(()=>{var a=wx(),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=zx[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 Tx()},children:t=>(()=>{var i=kx(),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=Ex();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,rx())},get children(){return n(ne,{})}}),null),y(d,n(Ng,{get id(){return t.id},get title(){return t.title},place:`table`,get children(){var e=Dx();return y(e,()=>t.title),s(()=>b(e,`href`,Ot(t.id))),e}}),null),y(d,n(Pg,{get id(){return t.id}}),null),y(d,n(l,{get when(){return t.unread},get children(){return Ox()}}),null),y(d,n(l,{get when(){return Ra(t)},children:e=>(()=>{var t=Ax();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(Of,{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=jx();return y(t,e),s(()=>b(t,`title`,`Waiting for you for ${e()}`)),t})()}),null),y(x,()=>Lx(t),null),y(S,n(O,{get label(){return`More actions for ${t.title}`},class:`icon-btn small`,items:()=>Th(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 qx(e){let t=()=>e.row;return(()=>{var e=Nx();return y(e,n(l,{get when(){return!Ch(t().id,`phone`)},get fallback(){return(()=>{var e=Px();return y(e,n(A,{get state(){return t().state}}),null),y(e,n(Ng,{get id(){return t().id},get title(){return t().title},place:`phone`,children:null}),null),e})()},get children(){var e=Mx(),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(),rx())},get children(){return n(ne,{})}}),null),y(i,()=>t().title,null),y(i,n(Pg,{get id(){return t().id}}),null),y(i,n(l,{get when(){return t().unread},get children(){return Ox()}}),null),y(r,n(l,{get when(){return Ra(t())},children:e=>(()=>{var t=Fx();return y(t,e),t})()}),a),y(a,n(l,{get when(){return za(t(),N())},children:e=>(()=>{var t=jx();return y(t,e),t})()}),null),y(a,()=>Lx(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:()=>Th(t(),{place:`phone`})}),null),s(()=>k(e,`home-item${t().unread?` unread`:``}`)),e})()}z([`input`,`click`]);var Jx=I(`<div role=separator aria-orientation=vertical tabindex=0>`);function Yx(e){let t=0,n=0,r=0,i,a=()=>Rp()[e.panel],o=()=>zp(e.panel),c=()=>{r=0,i!==void 0&&Bp(e.panel,i,!1)},l=()=>{r&&cancelAnimationFrame(r),r=0,i=void 0,Fp(void 0),document.documentElement.classList.remove(`resizing`)},u=(t,n,r)=>{t.hasPointerCapture(n)&&t.releasePointerCapture(n),l(),Bp(e.panel,r)};return fe(()=>e.panel===`rail`&&Np(!0)),M(()=>{e.panel===`rail`&&Np(!1),Pp()===e.panel&&l()}),(()=>{var l=Jx();return l.$$keydown=t=>{let n=lp(e.panel,a(),t.key,t.shiftKey,o());n!==void 0&&(t.preventDefault(),Bp(e.panel,n))},l.$$dblclick=()=>Bp(e.panel,rp[e.panel].default),l.addEventListener(`pointercancel`,t=>Pp()===e.panel&&u(t.currentTarget,t.pointerId,i??a())),l.$$pointerup=t=>Pp()===e.panel&&u(t.currentTarget,t.pointerId,i??a()),l.$$pointermove=a=>{if(Pp()!==e.panel)return;let s=up(e.panel,t,a.clientX-n,o());`collapse`in s?(u(a.currentTarget,a.pointerId,t),Tp(!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,Fp(e.panel),document.documentElement.classList.add(`resizing`))},s(t=>{var n=`panel-handle${Pp()===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 Xx={service:`background service`,standalone:`standalone`};function Zx(e){return(e??[]).map(e=>{let t=!!e.online,n=e.processes.find(e=>e.kind===`service`)??e.processes[0],r=t?n?[Xx[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 Qx(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 $x(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 eS(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:$x(e,i?.machine===t?{key:i.key,dir:i.dir}:{},a?.machine===t?a:void 0)??o}function tS(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 rS(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 iS(e,t){try{e.setItem(nS,JSON.stringify({machine:t.machine,key:t.key,dir:t.dir}))}catch{}}var aS=`hub.railCollapsed`;function oS(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 sS(e,t){let n=oS(e);n.has(t)?n.delete(t):n.add(t);try{e.setItem(aS,JSON.stringify([...n]))}catch{}return n}var cS=0,lS=e=>e.reduce((e,t)=>e+t.data.length,0);async function uS(e,t){let n=C_(t.length,e.type);if(n)throw Error(n);let r=await dS(e);try{let n=e.type!==`image/jpeg`&&pS(r),{blob:i,request:a}=await D_({width:r.width,height:r.height,keepPng:n},w_(lS(t)),e=>mS(r,e)),o=await hS(i);return{id:`img${++cS}`,mime:a.type,data:o.slice(o.indexOf(`,`)+1),name:E_(e.name||`image`,a.type),preview:URL.createObjectURL(i)}}finally{`close`in r&&r.close()}}async function dS(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 fS(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 pS(e){let t=Math.max(1,Math.min(64,e.width)),n=Math.max(1,Math.min(64,e.height)),[,r]=fS(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 mS(e,t){let[n,r]=fS(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 hS(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 gS(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 _S=new Map;function vS(e,t){_S.set(e,t)}function yS(e){let t=_S.get(e);return _S.delete(e),t}var bS=I(`<li class="attachment busy"aria-label="Preparing image"><span class="spinner small">`),xS=I(`<ul class=attachments aria-label="Attached images">`),SS=I(`<span class="spinner small">`),CS=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">`),wS=I(`<span class="meta-chip readonly"title="Branch of this folder"><span class="chip-text mono">`),TS=I(`<label class="meta-chip toggle-chip"><input type=checkbox><span class=chip-text>Open in Herdr tab`),ES=I(`<div class=env-meta role=group aria-label="Where the session runs">`),DS=I(`<p data-new-dir>`),OS=I(`<p class="small new-need-project"role=alert data-need-project>Choose a project first: the session starts in one of <!>'s folders.`),kS=I('<p class="small warn"> has no background service connected; start `opencode serve --service` there to create sessions.'),AS=I(`<p class=error role=alert>`),jS=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?`),MS=I(`<p class=muted>No machine is connected to this hub yet.`),NS=I(`<li class=attachment><img><button type=button class=attachment-remove>`),PS=I(`<span aria-hidden=true>`),FS=I(`<span class=chip-text>`),IS=I(`<button type=button aria-haspopup=dialog aria-label="Choose project folder"><span class=chip-text>`),LS=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>`),RS=I(`<p class="muted small pad">No folder matches.`),zS=I(`<div class=menu-section> · Herdr`),BS=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 VS(e){let i=rS(localStorage),a=()=>Y.machines??[],o=C(()=>Zx(a())),[c,f]=u(),p=()=>{let t=c();return t&&o().some(e=>e.id===t&&e.online)?t:Qx(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=()=>eS(_(),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 uS(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();iS(localStorage,{machine:e.id,key:t.key,dir:n}),vS(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=jS(),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:Dp})}}),a),y(c,n(l,{get when(){return o().length},get fallback(){return MS()},get children(){return[(()=>{var e=CS(),r=e.firstChild,i=r.firstChild,a=i.nextSibling,o=a.nextSibling.firstChild,c=o.nextSibling.nextSibling;e.addEventListener(`drop`,e=>{let t=gS(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=xS();return y(e,n(m,{get each(){return re()},children:e=>(()=>{var t=NS(),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 bS()}}),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=gS(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 SS()}})),s(e=>{var t=g_.join(`,`),n=re().length>=__.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=ES();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=PS();return s(()=>k(e,`online-dot${h()?.online?` on`:``}`)),e})(),(()=>{var e=FS();return y(e,()=>h()?.name??`No environment`),e})(),n(L,{name:`down`,class:`chip-caret`})]}}),null),y(e,n(HS,{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=wS(),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=TS(),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=DS();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=OS(),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=kS(),t=e.firstChild;return y(e,()=>h().name,t),e}}),n(l,{get when(){return se()},get children(){var e=AS();return y(e,se),e}})]}}),null),e})()}function HS(e){let[i,o]=u(!1),[c,d]=u(``),[f,p]=u({top:0,left:0}),h,g,_,v=()=>tS(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=IS(),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=LS(),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 RS()},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=BS(),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=zS(),n=e.firstChild;return y(e,()=>t.label,n),e})(),n(m,{get each(){return e.foldersOf(t)},children:n=>(()=>{var r=BS(),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 US={name:`home`},WS=ce(()=>C(()=>{let e=dt();return e.name===`concierge`?Z()?e:US:US=e})),GS=e=>String(e??``).normalize(`NFD`).replace(/[\u0300-\u036f]/g,``).toLowerCase();function KS(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 qS(e){let t=e?.note;return!Array.isArray(e)&&typeof t==`string`&&t.trim()?t.trim():void 0}var JS=e=>e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)):``;function YS(e,t,{current:n=``,limit:r=200,grouped:i=!1}={}){let a=String(t??``).trim(),o=GS(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=GS(e.id),r=`${n} ${GS(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(JS(t.option.id))||e.set(JS(t.option.id),e.size);u.sort((t,n)=>e.get(JS(t.option.id))-e.get(JS(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 XS(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 ZS=I(`<input type=search class=picker-search autofocus>`),QS=I(`<button type=button class="btn small">Retry`),$S=I(`<p class="muted small"role=status>`),eC=I(`<p class="muted small picker-note">`),tC=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>`),rC=I(`<div class="picker-group muted small">`),iC=I(`<span class="po-id muted">`),aC=I(`<span class=po-mark>✓ Current`),oC=I(`<li><button type=button><span class=po-name>`);function sC(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(()=>YS(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=ZS();return e.$$keydown=e=>{let t={ArrowDown:1,ArrowUp:-1};if(e.key in t)e.preventDefault(),_(XS(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=$S();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=QS();return e.$$click=v,e})()]}}),null),e})(),n(l,{get when(){return p()},get children(){var e=eC();return y(e,p),e}}),(()=>{var e=nC();return y(e,n(m,{get each(){return S().items},children:(e,i)=>(()=>{var a=oC(),o=a.firstChild,c=o.firstChild;return y(a,n(l,{get when(){return r(()=>!!t.request?.grouped)()&&(i()===0||JS(S().items[i()-1].id)!==JS(e.id))},get children(){var t=rC();return y(t,()=>JS(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=iC();return y(t,()=>e.name),t}}),null),y(o,n(l,{get when(){return e.current},get children(){return aC()}}),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=tC(),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 cC=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`),lC=I(`<div class="speech-panel stack">`),uC=I(`<p class=error>`),dC=I(`<p class=muted>Loading…`),fC=I(`<p class="small inherit">`),pC=I(`<p class="small muted">`),mC=I(`<p class=field-error>`),hC=I(`<div class=field><label>`),gC=I(`<input type=text autocomplete=off autocapitalize=off>`),_C=I(`<div class=row><button type=button class="btn small">Browse…`),vC=I(`<input type=password autocomplete=new-password placeholder="Paste the new key"aria-label="New API key">`),yC=I(`<div class=row><button type=button class="btn small">Cancel`),bC=I(`<div class="field key-field"><span class=field-label>API key`),xC=I(`<p>`),SC=I(`<button type=button class="btn small">Undo`),CC=I(`<button type=button class="btn small danger">Clear`),wC=I(`<div class=row><button type=button class="btn small">`),TC=I(`<fieldset class="card speech-card"><legend>`),EC=I(`<div class="row reset-row"><span class="small muted grow"></span><button type=button class="btn small">Reset to server default`),DC=I(`<option>`),OC=I(`<select>`),kC=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.`),AC=I(`<button type=button class=btn>Preview voice`),jC=I(`<form class=stack novalidate><div class=row><button type=submit class="btn primary">Save</button></div><p role=status>`),MC=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.`),NC=[[`openrouter`,`OpenRouter`],[`openai-compatible`,`OpenAI-compatible`]],PC={settings:`from settings`,config:`from hub.json`,env:`from env`,user:`yours`},FC={user:`/api/settings/speech`,default:`/api/settings/speech/default`},IC={stt:`Speech-to-text`,tts:`Text-to-speech`};function LC(){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(FC[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=lC();return y(t,n(l,{get when(){return r()},get children(){var t=cC(),n=t.firstChild,r=n.nextSibling;return n.$$click=()=>p(`user`),r.$$click=()=>p(`default`),s(t=>{var i=e()===`user`,a=e()==="default";return i!==t.e&&b(n,`aria-pressed`,t.e=i),a!==t.t&&b(r,`aria-pressed`,t.t=a),t},{e:void 0,t:void 0}),t}}),null),y(t,n(l,{get when(){return!c()},get fallback(){return(()=>{var e=uC();return y(e,c),e})()},get children(){return n(l,{get when(){return a()},get fallback(){return dC()},keyed:!0,children:t=>n(RC,{settings:t,get scope(){return e()},onSaved:e=>o(e)})})}}),null),t})()}function RC(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:KS(e),note:qS(e)})),w[e].catch(()=>delete w[e]),w[e]),E=(e,t,r,i,a)=>{let s=()=>x()?.[e]?.[t];return(()=>{var c=hC(),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=fC();return y(e,()=>s().note),e}}),null),y(c,n(l,{when:a,get children(){var e=pC();return y(e,a),e}}),null),y(c,n(l,{get when(){return o()[`${e}.${t}`]},get children(){var n=mC();return y(n,()=>o()[`${e}.${t}`]),n}}),null),c})()},D=(e,n,r={})=>(()=>{var s=gC();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=_C(),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=bC();return e.firstChild,y(e,n(l,{get when(){return d().action===`set`},get fallback(){return[(()=>{var e=xC();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}`:``} (${PC[c.source]??c.source})`:`No key set`})()),s(()=>k(e,`key-summary${u()?.inherited&&d().action!==`clear`?` inherit`:``}`)),e})(),(()=>{var e=wC(),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=SC();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=CC();return e.$$click=()=>a(i,`apiKey`,{action:`clear`,value:``}),e}}),null),e})()]},get children(){return[(()=>{var e=vC();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=yC(),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=mC();return y(e,()=>o()[`${i}.apiKey`]),e}}),null),e})()},j=async t=>{if(await P(`Reset ${IC[t].toLowerCase()} to the server default? Your own ${IC[t].toLowerCase()} settings are removed.`,`Reset`,{danger:!0}))try{let n=await(await V(FC.user,{method:`PUT`,json:rr(t)})).json().catch(()=>({})),r=n?.stt&&n?.tts?n:await G(FC.user);Bl(r.ready??null),e.onSaved(r),q(`${IC[t]} reset to the server default`)}catch(e){q(`Could not reset: ${U(e)}`,`err`)}},M=i=>(()=>{var o=TC(),c=o.firstChild;return y(c,()=>IC[i]),y(o,n(l,{get when(){return x()},children:e=>(()=>{var t=EC(),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=OC();return e.addEventListener(`change`,e=>a(i,`provider`,e.currentTarget.value)),b(e,`id`,`sp-${i}-provider`),y(e,n(m,{each:NC,children:([e,t])=>(()=>{var n=DC();return n.value=e,y(n,t),n})()}),null),y(e,n(l,{get when(){return!NC.some(([e])=>e===t[i].provider)},get children(){var e=DC();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()=>KS(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(FC[e.scope],{method:`PUT`,json:o})).json().catch(()=>({})),n=t?.stt&&t?.tts?t:await G(FC[e.scope]);e.scope===`user`?Bl(n.ready??null):pd(),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),Py.src=e,_v(Py,Sy.speed),!await Py.play().then(()=>!0,()=>!1))throw Error(`the browser blocked playback`);f({text:`Playing preview.`,kind:`muted`}),await new Promise(e=>Py.onended=Py.onpause=Py.onerror=()=>e()),f({text:``,kind:``})}catch(e){f({text:`Preview failed: ${U(e)}`,kind:`error`})}finally{Py.onended=Py.onpause=Py.onerror=null,e&&URL.revokeObjectURL(e)}};return(()=>{var t=jC(),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 kC()}}),r),y(t,n(l,{get when(){return S()},children:e=>(()=>{var t=MC(),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=pC();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=AC();return e.$$click=()=>void ee(),e}}),null),y(a,()=>d().text),y(t,n(sC,{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 zC=I(`<p class="small muted">This hub does not record voice conversations.`),BC=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">`),VC=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`),HC=I(`<p class="small muted recording-empty">No recordings.`),UC=I(`<button type=button class="btn small recording-more-page">Show more`),WC=I(`<div class=recording-pane data-recording-pane role=region aria-label="Your recordings"tabindex=0>`),GC=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>`),KC=I(`<section class=settings-section id=recording aria-labelledby=h-recording><h3 class=section-title id=h-recording>Recording`),qC=I(`<li>`),JC=I(`<div class=recording-day><h5 class=recording-day-title></h5><ul class=recording-list>`),YC=I(`<span class=recording-name>`),XC=I(`<select class=recording-segment aria-label=Segment title="Segment to play">`),ZC=I(`<button type=button class="btn small recording-play"aria-label="Play segment">▶ Play`),QC=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>`),$C=I(`<option>/`),ew=I(`<a class="btn small"download>Export`),tw=I(`<button type=button class="btn small danger"data-recording-focus>Delete`),nw=50,rw=200;function iw(e){let t=_u(e)?.session,n=Su(e);return cl({...n.startsWith(`@`)?{name:n}:{},...typeof t?.project==`string`&&t.project||t?.directory?{directory:typeof t?.project==`string`&&t.project||t.directory}:{}})}var aw=e=>ll(e,N(),void 0,iw);function ow(){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),yl.set({supported:!0,settings:e.settings})}catch(e){e instanceof W&&(e.status===404||e.status===405)?(i(!1),yl.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(rw,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(hu(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){let t=a();if(!t)return;let n=e.checked;v(!0);try{let e=await(await V(`/api/settings/recording`,{method:`PUT`,json:{enabled:n,expectedRevision:t.revision}})).json();o(e.settings),Dl(e.settings),q(n?`Recording on from the next Voice start`:`Recording off`)}catch(n){e.checked=t.enabled,n instanceof W&&n.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(n)}`,`err`)}finally{v(!1)}}async function A(e){let t=aw(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=KC();return i.firstChild,y(i,n(l,{get when(){return e()===!1},get children(){return zC()}}),null),y(i,n(l,{get when(){return r(()=>!!e())()&&a()},get children(){return[(()=>{var e=BC(),t=e.firstChild.firstChild,r=t.firstChild,i=r.firstChild,o=i.nextSibling,c=r.nextSibling,l=t.nextSibling;return y(i,()=>rl.label),y(o,()=>rl.description),c.addEventListener(`change`,e=>void k(e.currentTarget)),y(l,n(m,{get each(){return rl.details},children:e=>(()=>{var t=qC();return y(t,e),t})()})),s(()=>c.disabled=_()),s(()=>c.checked=a().enabled),e})(),(()=>{var e=GC(),i=e.firstChild,a=i.firstChild.nextSibling,o=i.nextSibling;return e.addEventListener(`toggle`,e=>T(e.currentTarget.open)),y(a,()=>ul(f().length,!!h(),c())),y(o,n(l,{get when(){return f().length},get children(){var e=VC(),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 HC()}}),null),y(o,n(l,{get when(){return f().length},get children(){var e=WC(),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?fl(e.startedAt,N()):``};return(()=>{var i=JC(),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(sw,{get recording(){return e()},onDelete:()=>void A(e())})})})),i})()}}),null),y(e,n(l,{get when(){return h()},get children(){var e=UC();return e.$$click=()=>void D(!0),e}}),null),e}}),null),s(()=>e.open=w()),e})()]}}),null),i})()}function sw(e){let t=()=>aw(e.recording),[i,a]=u(1),[o,c]=u(!1),d=()=>e.recording.segments;async function f(){c(!0);try{await Al(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=()=>pl(t());return(()=>{var c=QC(),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=YC();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=XC();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=$C(),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=ZC();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=ew();return s(()=>b(e,`href`,p())),e})(),(()=>{var t=tw();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 cw={entries:100,chars:253},lw=new Set([...[`co`,`org`,`ac`,`gov`,`net`,`me`,`ltd`,`plc`,`sch`,`nhs`].map(e=>`${e}.uk`),...[`com`,`net`,`org`,`edu`,`gov`,`id`,`asn`].map(e=>`${e}.au`),...[`co`,`ne`,`or`,`ac`,`go`,`gr`,`ed`,`ad`,`lg`].map(e=>`${e}.jp`),...[`co`,`org`,`net`,`ac`,`govt`,`school`,`geek`,`gen`,`kiwi`,`maori`].map(e=>`${e}.nz`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.br`),...[`com`,`net`,`org`,`gov`,`edu`,`ac`].map(e=>`${e}.cn`),...[`com`,`net`,`org`,`gob`,`edu`].map(e=>`${e}.mx`),...[`co`,`net`,`org`,`firm`,`gen`,`ind`,`ac`,`edu`,`gov`,`res`].map(e=>`${e}.in`),...[`co`,`org`,`net`,`ac`,`gov`,`web`].map(e=>`${e}.za`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.tr`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.sg`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.hk`),...[`co`,`or`,`ne`,`go`,`ac`,`re`].map(e=>`${e}.kr`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.tw`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.ar`),...[`co`,`or`,`ac`,`go`].map(e=>`${e}.id`),...[`co`,`or`,`ac`,`go`].map(e=>`${e}.th`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.my`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.ph`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.pk`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.ua`),...[`com`,`net`,`org`,`gov`,`edu`].map(e=>`${e}.pl`),...[`co`,`or`,`ac`].map(e=>`${e}.at`),...[`co`,`org`,`ac`].map(e=>`${e}.il`),`com.es`,`org.es`,`co.it`,`com.ru`,`co.ca`,`eu.org`,`github.io`,`githubpreview.dev`,`gitlab.io`,`pages.dev`,`workers.dev`,`netlify.app`,`vercel.app`,`herokuapp.com`,`appspot.com`,`blogspot.com`,`cloudfront.net`,`azurewebsites.net`,`web.app`,`firebaseapp.com`,`s3.amazonaws.com`,`ngrok.io`,`ngrok-free.app`,`glitch.me`,`repl.co`,`fly.dev`,`onrender.com`]),uw=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;function dw(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>cw.chars)return{ok:!1,reason:`${fw(t)}: at most ${cw.chars} characters`};if(/[\s/\\:@?#[\]%]/.test(t))return{ok:!1,reason:`${fw(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:`${fw(t)}: a wildcard only as a leading "*."`};let i=pw(r.replace(/\.$/,``));if(i===void 0)return{ok:!1,reason:`${fw(t)}: not a hostname`};let a=i.split(`.`);if(a.some(e=>!uw.test(e)))return{ok:!1,reason:`${fw(t)}: not a hostname`};if(/^\d+$/.test(a[a.length-1]))return{ok:!1,reason:`${fw(t)}: an IP address or numeric domain is not allowed`};if(a.length<2)return{ok:!1,reason:n?`${fw(t)}: too broad (name at least two labels after "*.")`:`${fw(t)}: name a full hostname (like github.com)`};if(lw.has(i))return{ok:!1,reason:`${fw(t)}: too broad (a public suffix: name the site itself)`};let o=n?`*.${i}`:i;return o.length>cw.chars?{ok:!1,reason:`${fw(t)}: at most ${cw.chars} characters`}:{ok:!0,entry:o}}var fw=e=>e.length>60?`${e.slice(0,57)}…`:e;function pw(e){if(e)try{let t=new URL(`http://${e}/`);return t.hostname&&t.hostname===t.host?t.hostname:void 0}catch{return}}function mw(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 hw(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 gw(e){return e.split(`.`).map(e=>e.toLowerCase().startsWith(`xn--`)?_w(e.slice(4))??e:e).join(`.`)}function _w(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 vw=`/api/settings/media`,[yw,bw]=u(),xw;function Sw(){let e=yw();return!e&&!xw&&Cw(),e}function Cw(e=!1){if(xw&&!e)return xw;let t=V(vw).then(e=>e.json()).then(e=>(bw(e),e),()=>{xw===t&&(xw=void 0)});return xw=t,t}async function ww(e){let t=await(await V(vw,{method:`PUT`,json:{allowlist:e}})).json();return bw(t),t}async function Tw(e){let t=yw()??await Cw(),n=t?.allowlist??[];return t&&n.includes(e)?t:ww([...n,e])}var[Ew,Dw]=u(new Map),Ow=e=>Ew().get(e)??[];function kw(e,t){let n=Ew().get(e)??[];if(n.includes(t))return;let r=new Map(Ew());r.set(e,[...n,t]),Dw(r)}var Aw=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.`),jw=I(`<p class="small media-allowlist-error">`),Mw=I(`<ul class=media-allowlist aria-label="Allowed sites">`),Nw=I(`<p class="small media-allowlist-error"role=alert>`),Pw=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`),Fw=I(`<p class="small muted">No sites allowed yet.`),Iw=I(`<span class=muted> (<!>)`),Lw=I(`<li><span class=grow></span><button type=button class="btn small">Remove`);function Rw(){let[e,t]=u(``),[r,i]=u(``),[a,o]=u(!1),[c,d]=u(``);fe(async()=>{await Cw(!0)||d(`Could not load the media settings.`)});let f=()=>Sw()?.allowlist??[],p=async(e,t)=>{o(!0);try{return await ww(e),q(t),!0}catch(e){return i(U(e)),!1}finally{o(!1)}},h=async n=>{n?.preventDefault(),i(``);let r=dw(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>=cw.entries)return void i(`At most ${cw.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=Pw(),u=o.firstChild.nextSibling.nextSibling,d=u.firstChild,p=d.nextSibling;return y(o,n(l,{get when(){return Sw()?.remoteFetch===!1},get children(){return Aw()}}),u),y(o,n(l,{get when(){return c()},get children(){var e=jw();return y(e,c),e}}),u),y(o,n(l,{get when(){return f().length},get fallback(){return Fw()},get children(){var e=Mw();return y(e,n(m,{get each(){return f()},children:e=>(()=>{var t=Lw(),r=t.firstChild,i=r.nextSibling;return y(r,e,null),y(r,n(l,{get when(){return gw(e)!==e},get children(){var t=Iw(),n=t.firstChild.nextSibling;return n.nextSibling,y(t,()=>gw(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=Nw();return y(e,r),e}}),null),s(()=>p.disabled=a()||!e().trim()),s(()=>d.value=e()),o})()}z([`input`,`click`]);var zw=[`queued`,`placing`,`provisioning`,`running`],Bw=e=>typeof e==`object`&&!!e&&!Array.isArray(e),Vw=e=>typeof e==`string`,Hw=e=>typeof e==`number`&&Number.isFinite(e);function Uw(e){if(!Bw(e)||!Vw(e.id)||!Vw(e.state)||!Bw(e.spec)||!Bw(e.spec.workspace)||!Vw(e.spec.workspace.repo))return;let t=e.spec.workspace,n=e.waiting;return{id:e.id,state:e.state,reason:Vw(e.reason)?e.reason:``,repo:t.repo,...Vw(t.branch)?{branch:t.branch}:{},...Vw(e.by)?{by:e.by}:{},...Vw(e.byLabel)?{byLabel:e.byLabel}:{},launcherRevoked:e.launcherRevoked===!0,...Bw(n)&&Vw(n.wait)&&Vw(n.reason)&&Hw(n.since)?{waiting:{wait:n.wait,reason:n.reason,since:n.since}}:{},...Vw(e.name)?{name:e.name}:{},...Vw(e.sessionID)?{sessionID:e.sessionID}:{},...Vw(e.machineID)?{machineID:e.machineID}:{},concierge:e.by===`app:concierge`&&Bw(e.spec.labels)&&e.spec.labels[`hub/system`]===`concierge`,created:Hw(e.created)?e.created:0}}function Ww(e){return!Bw(e)||!Array.isArray(e.launches)?[]:e.launches.map(Uw).filter(e=>e!==void 0)}function Gw(e,t){if(!Bw(t)||t.type!==`launch`)return e;let n=Uw(t.launch);return n?zw.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 Kw(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 qw={queued:`Queued`,placing:`Placing`,provisioning:`Starting`,running:`Running`,ended:`Ended`},Jw=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 Yw(e,t){let n=e.name?`@${e.name.replace(/^@+/,``)}`:`${e.repo}${e.branch?` (${e.branch})`:``}`;return{title:n,status:`${qw[e.state]??e.state} · by ${Kw(e)}`,detail:e.state===`queued`&&e.waiting?`${e.waiting.reason} · ${Jw(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 Xw(e,t){if(e.state!==`ready`&&e.state!==`refreshing`)return;let n=e.latest();return n?Gw(n,t):void 0}var Zw=e=>e.normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase(),Qw=e=>!!e&&/[a-z0-9]/.test(e),$w=(e,t)=>t===0||!Qw(e[t-1]);function eT(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:$w(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)+($w(t,e)?6:0)-(i>=0?(e-i-1)*.2:0),i=e}return Math.min(99,r)}function tT(e,t){let n=Zw(e).split(/\s+/).filter(Boolean);if(!n.length)return 0;let r=Zw(t),i=0;for(let e of n){let t=eT(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 rT(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=tT(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 iT(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 aT(e,t){let n=Zw(t).split(/\s+/).filter(Boolean);return n.length?e.some(e=>{let t=Zw(nT(e));return n.every(e=>t.includes(e))}):!1}var oT=8,sT=120;function cT({below:e,above:t,want:n}){if(n+oT<=e)return{up:!1,maxHeight:n};let r=t>e,i=Math.max(0,Math.min(n,(r?t:e)-oT));return i<Math.min(n,sT)?{up:r,maxHeight:i,cramped:!0}:{up:r,maxHeight:i}}function lT(e){let t=[];return e.forEach((e,n)=>{let r=t.at(-1);r&&r.group===e.group?r.items.push({option:e,index:n}):t.push({group:e.group,items:[{option:e,index:n}]})}),t}var uT=I(`<div role=option>`),dT=I(`<span role=img>`),fT=I(`<span class="po-id muted combo-detail">`),pT=I(`<span class=combo-text><span class="po-name combo-label">`),mT=I(`<span class=combo-text><span class="po-name combo-label">Use “<!>”</span><span class="po-id muted combo-detail">as typed`),hT=I(`<p class="combo-empty muted small">`),gT=I(`<div><div class="combo-list picker-list"role=listbox>`),_T=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>`),vT=I(`<div role=group class=combo-section><div class="picker-group combo-group muted small">`),yT=I(`<span class=pick-chip-kind>`),bT=I(`<span class="pick-chip-detail muted">`),xT=I(`<button type=button class=pick-chip-x>×`),ST=I(`<li class=pick-chip><span class=pick-chip-text><span class=pick-chip-label>`),CT=I(`<ul class=pick-chips>`),wT=I(`<div>`);function TT(e){for(let t=e.parentElement;t;t=t.parentElement){let e=getComputedStyle(t).overflowY;if(e===`auto`||e===`scroll`)return t}}var ET=264;function DT(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:ET}),w=C(()=>rT(e.options,e.query,{exclude:e.exclude,limit:e.limit??60})),E=C(()=>lT(w())),D=C(()=>e.noCustom?void 0:iT(e.query,e.options,e.problem,e.exclude)),O=()=>D()?.problem,A=()=>D()&&!D().problem?D().value:void 0,j=C(()=>!!A()&&!aT(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(ET,f.scrollHeight+2),n=TT(d)?.getBoundingClientRect(),r=Math.max(n?.top??0,0),i=Math.min(n?.bottom??window.innerHeight,window.innerHeight),a=d.getBoundingClientRect(),o=cT({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)));_(XS(g(),t.key===`ArrowDown`?1:-1,n))}else t.key===`Home`&&p()&&!e.query?(t.preventDefault(),_(0)):t.key===`End`&&p()&&!e.query?(t.preventDefault(),_(Math.max(0,n-1))):t.key===`Enter`?p()&&n&&g()>=0&&g()<n?(t.preventDefault(),te(M()[g()])):e.query.trim()&&t.preventDefault():t.key===`Escape`&&p()?(t.preventDefault(),t.stopPropagation(),h(!1)):t.key===`Tab`&&h(!1)},re=e=>(()=>{var t=uT();return t.$$click=()=>te(e.value),t.addEventListener(`pointerenter`,()=>_(e.index)),t.$$mousedown=e=>e.preventDefault(),y(t,()=>e.children),s(n=>{var r=P(e.index),i=`picker-opt combo-opt${e.class?` ${e.class}`:``}${g()===e.index?` active`:``}`,a=g()===e.index,o=e.value;return r!==n.e&&b(t,`id`,n.e=r),i!==n.t&&k(t,n.t=i),a!==n.a&&b(t,`aria-selected`,n.a=a),o!==n.o&&b(t,`data-value`,n.o=o),n},{e:void 0,t:void 0,a:void 0,o:void 0}),t})(),ie=e=>n(re,{get index(){return N(e.index)},get value(){return e.row.value},get children(){return[n(l,{get when(){return e.row.online!==void 0},get children(){var t=dT();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=pT(),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=fT();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=mT(),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=_T(),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=gT(),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=vT(),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=hT();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 OT(e){return(()=>{var t=ST(),r=t.firstChild,i=r.firstChild;return y(t,n(l,{get when(){return e.kind},get children(){var t=yT();return y(t,()=>e.kind),t}}),r),y(i,()=>e.label),y(r,n(l,{get when(){return e.detail},get children(){var t=bT();return y(t,()=>e.detail),t}}),null),y(t,n(l,{get when(){return e.onRemove},get children(){var t=xT();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 kT(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=wT();return y(t,n(l,{get when(){return e.values.length},get children(){var t=CT();return y(t,n(m,{get each(){return e.values},children:t=>n(OT,_(()=>r(t),{title:t,removeLabel:`Remove ${t}`,onRemove:()=>e.onRemove(t)}))})),s(()=>b(t,`aria-label`,`${e.label}: chosen`)),t}}),null),y(t,n(DT,_(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 AT=/^[a-z0-9-]{2,40}$/,jT=e=>AT.test(e),MT=/^([a-z0-9-]{2,40})(?:\.([^./\s#]+))?$/i;function NT(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=MT.exec(e.slice(t?2:1));if(!n||!jT(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 PT=e=>!!e&&typeof e==`object`&&!Array.isArray(e),FT=e=>typeof e==`string`&&e?e:void 0;function IT(e){return(PT(e)&&Array.isArray(e.sessions)?e.sessions:[]).flatMap(e=>{if(!PT(e)||typeof e.sessionID!=`string`||!e.sessionID)return[];let t=Array.isArray(e.roles)?e.roles.flatMap(e=>PT(e)&&typeof e.role==`string`?[e.role]:[]):[];return[{sessionID:e.sessionID,...FT(e.name)?{name:FT(e.name)}:{},...FT(e.title)?{title:FT(e.title)}:{},...FT(e.project)?{project:FT(e.project)}:{},online:e.online===!0,...e.archived===!0?{archived:!0}:{},...e.concierge===!0?{concierge:!0}:{},roles:t}]})}var LT=/^orchestrator/,RT=e=>LT.test(e)||e.startsWith(`concierge`),zT=`holder is @@role, @name, ses_… or app:<token id>`,BT=/^app:[0-9a-f]{16}$/,VT={role:`Reserved roles`,session:`Sessions`,app:`Apps`},HT={role:`Reserved role`,session:`Session`,app:`App`},UT=e=>e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()||e,WT=e=>typeof e.project==`string`&&e.project||e.directory||``;function GT({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(!LT.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:VT.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||WT(n)&&UT(WT(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:VT.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:VT.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:VT.app,detail:`app:${e.id}${e.scopes.length?` · ${e.scopes.join(`, `)}`:``}`}));return[...s,...d,...f,...p]}function KT(e,t){let n=t.find(t=>t.value===e);if(n)return{kind:n.kind,kindLabel:HT[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:HT[r],label:e,detail:i}}function qT(e){if(BT.test(e))return;let t=NT(e);if(!t||t.kind===`name`&&t.name===`me`)return zT;if(t.kind===`role`&&!RT(t.role))return`A role holder must be a reserved role (such as @@orchestrator)`}var JT=e=>/^([A-Za-z]:)?[\\/]/.test(e),YT=e=>e.length>1?e.replace(/[\\/]+$/,``):e;function XT(e){let t=e.trim();return t?JT(t)?void 0:`${t} is not an absolute directory`:`A project directory`}function ZT({sessions:e,grants:t}){let n=new Map,r=e=>{let t=YT(e.trim());t&&JT(t)&&n.set(t,(n.get(t)??0)+1)};for(let t of e)r(WT(t));for(let e of t)for(let t of e.scope.projects)n.has(YT(t))||r(t);return[...n.keys()].map(e=>({value:e,label:UT(e),detail:e}))}var QT=/^[A-Za-z0-9_.*?-]{1,80}$/,$T=1e3;function eE(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 QT.test(r)&&i!==``&&i.length<=$T?void 0:t}var tE=[[`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/`]],rE=[[`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 iE(e,t){let n=new Map,r=(e,t,r)=>{!n.has(e)&&!eE(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:rE)r(t,n,`Common`);if(e===`permit`)for(let[e,t]of tE)r(e,t,`Every resource of an action`);return[...n.values()]}var aE=e=>e.split(`
10
- `).map(e=>e.trim()).filter(Boolean);function oE(e,t){let n=aE(e),r=t.trim();return(r&&!n.includes(r)?[...n,r]:n).join(`
11
- `)}var sE=(e,t)=>aE(e).filter(e=>e!==t).join(`
12
- `),cE={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`},lE=[`30m`,`8h`,`1d`,`7d`,`30d`],uE=60,dE=1,fE=1e3;function pE(e,t){let n=e.trim();return/^\d+$/.test(n)?String(Math.min(fE,Math.max(dE,Number(n)+t))):String(uE)}var mE=(e,t)=>e.allow.includes(`approve`)||!!e.permit.trim()||!!e.never.trim()||e.allowAlways||!!t?.permit.trim()||!!t?.never.trim(),hE={projects:XT,permit:eE,never:eE};function gE(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=hE[e](a);o?n[e]=o:(i={...i,[e]:oE(i[e],a)},r.push(e))}let o=i.holder.trim(),s=o?qT(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 _E=I(`<div id=agent-activity>`),vE=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`),yE=I(`<ul class=list>`),bE=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`),xE=I(`<p class="small muted">`),SE=I(`<p class="small muted">No connected apps.`),CE=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`),wE=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`),TE=I(`<p class="small muted">No app clients registered.`),EE=I(`<span class="badge-pill off">`),DE=I(`<button type=button class="btn small">Edit`),OE=I(`<button type=button class="btn small">Rotate secret`),kE=I(`<button type=button class="btn small">`),AE=I(`<button type=button class="btn small danger">Delete`),jE=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: `),ME=I(`<p role=alert>`),NE=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`),PE=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">`),FE=I(`<label class=check><input type=checkbox><span>`),IE=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`),LE=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`),RE=I(`<p class="small muted">No app tokens yet.`),zE=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`),BE=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`),VE=I(`<p class="small muted">No live launches.`),HE=I(`<div class="small warn"data-launcher-revoked>`),UE=I(`<div class="small muted"data-launch-managed>`),WE=I(`<button type=button class="btn small danger">Stop`),GE=I(`<li class=row><div class=grow><div class=name></div><div class="small muted"></div><div class=small data-launch-reason>`),KE=I(`<span class="field-desc muted small">`),qE=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`),JE=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`),YE=I(`<p class=error role=alert>`),XE=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`),ZE=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>`),QE=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>`),$E=I(`<p class="small warn"role=status data-acting-note>`),eD=I(`<ul class="list grants">`),tD=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).`),rD=I(`<dt>Permissions`),iD=I(`<dd class=mono>`),aD=I(`<dt>Never`),oD=I(`<button type=button class="btn small danger">Revoke`),sD=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>`),cD=I(`<p class="field-error small"role=alert>`),lD=I(`<div class="text-field grant-field"><span class=field-title></span><span class="field-desc muted small">`),uD=I(`<ul class="pick-chips holder-chip"aria-label="Holder: chosen">`),dD=I(`<p class="small warn"data-approve-note>These only apply to approve: tick approve, or remove them.`),fD=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)`),pD=I(`<p class=error role=alert data-error=form>`),mD=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">`),hD=I(`<label><input type=checkbox><span class=verb-text><span class=verb-name></span><span class="verb-help muted small">`),gD=I(`<button type=button class=chip>`),_D=I(`<ol class="list audit agent-audit">`),vD=I(`<p class="small muted">Loading…`),yD=I(`<button type=button class="btn small">Load older`),bD=I(`<div class=stack>`),xD=I(`<p class="small err">Could not load: `),SD=I(`<p class="small muted">No agent actions yet.`),CD=I(`<span>`),wD=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">`),TD=50,ED=`/api/agent/grants`,DD=`/api/agent/app-tokens`,OD=`/api/agent/launches`,kD=`/api/agent/connections`,AD=`/api/agent/app-clients`,[jD,MD]=u(0);function ND(){let e=d(()=>G(DD).then(Je)),t=d(()=>G(kD).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=vE(),c=o.firstChild.nextSibling,u=c.firstChild,d=u.nextSibling;return y(o,n(HD,{}),c),y(o,n(PD,{connections:t}),c),y(o,n(FD,{onChanged:()=>void t[1].refetch()}),c),y(o,n(RD,{tokens:e}),c),y(o,n(zD,{}),c),u.$$click=()=>a(`grants`),d.$$click=()=>a(`activity`),y(o,n(l,{get when(){return i()===`grants`},get children(){return n(UD,{tokens:r})}}),null),y(o,n(l,{get when(){return i()===`activity`},get children(){var e=_E();return y(e,n(GD,{})),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 PD(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(`${kD}/${K(e.id)}`,{method:`DELETE`}),i(t=>(t??[]).filter(t=>t.id!==e.id)),MD(e=>e+1),q(`${e.clientName} revoked`)}catch(e){q(U(e),`err`),a()}};return(()=>{var e=bE(),i=e.firstChild.firstChild.nextSibling;return i.$$click=()=>void a(),y(e,n(l,{get when(){return t()},get fallback(){return(()=>{var e=xE();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 SE()},get children(){var e=yE();return y(e,n(m,{get each(){return t()},children:e=>{let t=()=>rt(e,N());return(()=>{var n=CE(),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 FD(e){let[t,{mutate:i,refetch:a}]=d(()=>G(AD).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(`${AD}/${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(`${AD}/${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(`${AD}/${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=wE(),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(ID,{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(LD,{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=xE();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 TE()},get children(){var e=yE();return y(e,n(m,{get each(){return t()},children:e=>{let t=()=>je(e);return(()=>{var r=jE(),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=EE();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=DE();return t.$$click=()=>c(e),s(()=>b(t,`aria-label`,`Edit ${e.name}`)),t})(),(()=>{var t=OE();return t.$$click=()=>void v(e),s(()=>b(t,`aria-label`,`Rotate the secret of ${e.name}`)),t})(),(()=>{var t=kE();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=AE();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 ID(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?`${AD}/${K(e.client.id)}`:AD,{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=ME();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=PE(),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=FE(),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=NE(),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 LD(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=IE(),i=r.firstChild.nextSibling,a=i.firstChild;return y(r,n(BD,{field:`client-id`,title:`Client ID`,get value(){return e.client.id},onCopy:()=>void t(e.client.id,`Client ID`)}),i),y(r,n(BD,{field:`client-secret`,title:`Client secret`,get value(){return e.secret},onCopy:()=>void t(e.secret,`Secret`)}),i),y(r,n(BD,{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 RD(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(`${DD}/${K(e.id)}`,{method:`DELETE`}),i(t=>(t??[]).filter(t=>t.id!==e.id)),MD(e=>e+1),q(`App token revoked`)}catch(e){q(U(e),`err`),a()}};return(()=>{var e=LE(),a=e.firstChild.firstChild.nextSibling;return a.$$click=()=>c(!0),y(e,n(l,{get when(){return o()},get children(){return n(VD,{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=xE();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 RE()},get children(){var e=yE();return y(e,n(m,{get each(){return t()},children:e=>(()=>{var t=zE(),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 zD(){let[e,{refetch:t,mutate:i}]=d(jD,()=>G(`${OD}?state=${zw.join(`,`)}`).then(e=>Ww(e)));M(hu(t=>{let n=Xw({state:e.state,latest:()=>e.latest},t);n&&i(n)}));let[a,o]=u(),c=async e=>{if(await P(`Stop ${Yw(e,N()).title}? Its session is stopped and its workspace cleaned up by its policy.`,`Stop`,{danger:!0})){o(e.id);try{await V(`${OD}/${K(e.id)}`,{method:`DELETE`}),q(`Launch stopped`)}catch(e){q(U(e),`err`)}finally{o(void 0),t()}}};return(()=>{var i=BE(),o=i.firstChild.firstChild.nextSibling;return o.$$click=()=>void t(),y(i,n(l,{get when(){return e()},get fallback(){return(()=>{var t=xE();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 VE()},get children(){var t=yE();return y(t,n(m,{get each(){return e()},children:e=>{let t=()=>Yw(e,N());return(()=>{var r=GE(),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=HE();return y(e,()=>t().flag),e}}),null),y(i,n(l,{get when(){return t().managed},get children(){var e=UE();return y(e,()=>t().managed),e}}),null),y(r,n(l,{get when(){return t().stopLabel},get children(){var n=WE();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 BD(e){let t=`copy-field-${e.field}`;return(()=>{var r=qE(),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=KE();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 VD(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(DD,{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=XE(),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=FE(),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=YE();return y(e,p),e}}),f),B(h,`click`,e.onClose,!0),s(()=>_.disabled=g()),s(()=>u.value=t()),o})()},get children(){var t=JE(),r=t.firstChild.nextSibling,i=r.firstChild;return y(t,n(BD,{field:`token`,title:`Bearer token`,get value(){return o()},onCopy:()=>void b(o(),`Token`)}),r),y(t,n(BD,{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 HD(){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=xE();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?`Could not load: ${U(e.error)}`:`Loading…`})()),t})()},children:e=>[(()=>{var t=QE(),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=ZE(),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=$E();return y(t,()=>e().note),t}})]})}function UD(e){let[t,{refetch:i,mutate:a}]=d(()=>G(ED).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(`${ED}/${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=tD(),a=i.firstChild.firstChild.nextSibling;return a.$$click=()=>c(`new`),y(i,n(l,{get when(){return o()},keyed:!0,children:r=>n(WD,{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=xE();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=eD();return y(e,n(m,{get each(){return t()},children:e=>{let t=()=>yt(e,f());return(()=>{var r=sD(),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[rD(),(()=>{var e=iD();return y(e,()=>t().permit),e})()]}}),f),y(o,n(l,{get when(){return t().never},get children(){return[aD(),(()=>{var e=iD();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=DE();return t.$$click=()=>c(e),s(()=>b(t,`aria-label`,`Edit grant of ${e.holder}`)),t})(),(()=>{var t=oD();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 WD(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(IT,()=>[])),S=C(()=>GT({who:x()??[],sessions:gu(),tokens:e.tokens,hidden:ou()})),w=C(()=>ZT({sessions:gu(),grants:e.grants})),T=C(()=>iE(`permit`,e.grants)),E=C(()=>iE(`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=gE(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?`${ED}/${K(e.grant.id)}`:ED,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=cD();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=lD(),i=r.firstChild,o=i.nextSibling;return y(i,()=>e.label),y(o,()=>e.hint),y(r,n(kT,{get label(){return e.label},get placeholder(){return e.placeholder},get options(){return e.options},get values(){return aE(t()[e.field])},onAdd:n=>D(e.field,oE(t()[e.field],n)),onRemove:n=>D(e.field,sE(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=()=>KT(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=mD(),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(DT,{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:qT,get invalid(){return!!a().holder},get describedBy(){return`grant-hint-holder${a().holder?` grant-error-holder`:``}`}})},get children(){var i=uD();return y(i,n(OT,{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:XT,chip:M}),d),y(f,n(m,{each:Bt,children:e=>(()=>{var n=hD(),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,()=>cE[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 mE(t(),g())},get children(){var e=fD(),r=e.firstChild,i=r.firstChild;return y(e,n(l,{get when(){return!ee()},get children(){return dD()}}),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:eE,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:eE,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:lE,children:e=>(()=>{var n=gD();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`,pE(t().maxActionsPerHour,-1)),I.$$input=e=>D(`maxActionsPerHour`,e.currentTarget.value),ne.$$click=()=>D(`maxActionsPerHour`,pE(t().maxActionsPerHour,1)),y(F,n(A,{field:`maxActionsPerHour`}),null),y(i,n(l,{get when(){return c()},get children(){var e=pD();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 GD(){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=${TD}${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 ql().values())e.set(t.id,t);return[...e.values()]},v=()=>{let t=e()[0]?.seq??0;return[...su().filter(e=>e.seq>t),...e()]};return(()=>{var e=bD();return y(e,n(l,{get when(){return o()!==`failed`},get fallback(){return(()=>{var e=xD();return e.firstChild,y(e,f,null),e})()},get children(){return[n(l,{get when(){return v().length||o()!==`ready`},get fallback(){return SD()},get children(){var e=_D();return y(e,n(m,{get each(){return v()},children:e=>{let t=()=>kt(e,ft(e,_()),Su);return(()=>{var i=wD(),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=CD();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 vD()}}),n(l,{get when(){return r(()=>o()===`ready`)()&&i()!==void 0},get children(){var e=yD();return e.$$click=()=>void h(i()),e}})]}})),e})()}z([`click`,`input`]);var KD=I(`<fieldset class=stack id=concierge-watchlist><legend class=field-title>Watchlist`),qD=I(`<p class="small muted">`),JD=I(`<span class="field-desc muted small"data-watchlist-count>Watching <!> session<!> now.`),YD=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)`),XD=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)">`),ZD=I(`<label class=check><input type=checkbox><span>Pinned sessions and workspaces<span class=muted> (<!> now)`),QD=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`),$D=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`),eO=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">`),tO=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">`),rO=I(`<li class="small muted">No sessions added.`),iO=I(`<li class=row><span class="small grow"></span><button type=button class="btn small">Remove`),aO=I(`<li class="small muted">Nothing muted.`),oO=I(`<li class=row><span class="small grow"></span><button type=button class="btn small">Unmute`),sO=I(`<option>`),cO=`/api/agent/concierge/watchlist`,lO=e=>Su(e),uO=(e,t)=>e.filter(e=>e.reasons.includes(t)).length,dO=e=>[...new Set(e.split(`
14
- `).map(e=>e.trim()).filter(Boolean))];function fO(){let[e,{refetch:t,mutate:i}]=d(()=>G(cO)),[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(cO,{method:`PUT`,json:{...t,expectedRevision:e().config.revision}}),`Watchlist saved`),v=(e,t)=>g(()=>V(`${cO}/${e}`,{method:`POST`,json:{session:t}}),e===`watch`?`Watching ${lO(t)}`:e===`mute`?`Muted ${lO(t)} for the Concierge`:`Watchlist saved`);return(()=>{var t=KD();return t.firstChild,y(t,n(l,{get when(){return e()},get fallback(){return(()=>{var t=qD();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=JD(),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=YD(),r=n.firstChild,i=r.nextSibling,o=i.firstChild.nextSibling,c=o.nextSibling.nextSibling,l=c.firstChild.nextSibling;return l.nextSibling,r.addEventListener(`change`,e=>void _({autoActive:e.currentTarget.checked})),y(i,()=>t().activeWithinHours,o),y(c,()=>uO(e().entries,`active`),l),s(()=>r.disabled=a()),s(()=>r.checked=t().autoActive),n})(),(()=>{var e=XD(),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=ZD(),r=n.firstChild,i=r.nextSibling.firstChild.nextSibling,o=i.firstChild.nextSibling;return o.nextSibling,r.addEventListener(`change`,e=>void _({usePins:e.currentTarget.checked})),y(i,()=>uO(e().entries,`pinned`)+uO(e().entries,`pinned_project`),o),s(()=>r.disabled=a()),s(()=>r.checked=t().usePins),n})(),(()=>{var e=QD(),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 rO()},children:e=>(()=>{var t=iO(),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,()=>lO(e)),r.$$click=()=>void v(`unwatch`,e),s(t=>{var n=a(),i=`Stop watching ${lO(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=$D(),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 aO()},children:e=>(()=>{var t=oO(),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,()=>lO(e)),r.$$click=()=>void v(`unmute`,e),s(t=>{var n=a(),i=`Unmute ${lO(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=eO(),n=e.firstChild.nextSibling;return n.addEventListener(`change`,e=>void _({projects:dO(e.currentTarget.value)})),s(()=>n.disabled=a()),s(()=>n.value=t().projects.join(`
15
- `)),e})(),(()=>{var e=tO();return y(e,n(m,{get each(){return gu().filter(e=>!e.hidden).slice(0,200)},children:e=>(()=>{var t=sO();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:dO(e.currentTarget.value)})),s(()=>n.disabled=a()),s(()=>n.value=t().mutedProjects.join(`
16
- `)),e})()]}}),null),t})()}z([`input`,`click`]);var pO=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.`),mO=I(`<button type=button class="btn small">Retry`),hO=I(`<p class="small muted"data-concierge-load>`),gO=I(`<button type=button class="btn small">Restart`),_O=I(`<button type=button class="btn small danger">Turn off`),vO=I(`<button type=button class="btn small primary">Turn on`),yO=I(`<p class="small muted"data-concierge-problem>`),bO=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).`),xO=I(`<div class="row concierge-notice err"role=alert data-concierge-suspended><span class=grow>Stopped: </span><button type=button class="btn small">Restart`),SO=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`),CO=I(`<li class="small muted">No machines yet.`),wO=I(`<li class=row><label class="check grow"><input type=radio name=concierge-machine><span><span class="small muted"> · `),TO=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…`),EO=I(`<button type=button class="btn small">Renew`),DO=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`),OO=I(`<optgroup label=Projects>`),kO=I(`<optgroup label="Workspace roots">`),AO=I(`<input class=mono aria-describedby=concierge-directory-hint>`),jO=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>`),MO=I(`<option>`),NO=I(`<input class=mono aria-label="Other model (provider/model)"aria-describedby=concierge-model-hint placeholder=provider/model>`),PO=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>`),FO=I(`<optgroup>`),IO=I(`<p class="field-error small"role=alert>`),LO=I(`<label class=text-field><span class=field-title></span><span class="field-desc muted small"></span><textarea rows=2>`),RO=I(`<p class="small warn"role=note data-shell-warning>`),zO=I(`<p class=error role=alert data-error=form>`),BO=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`),VO=I(`<label class=check><input type=checkbox><span class="mono small">`),HO=I(`<label class=check><input type=checkbox><span>`),UO=I(`<button type=button class="btn small">Turn off quiet hours`),WO=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`),GO=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`),KO=I(`<li class="small muted">No digests.`),qO=I(`<li class=row><input type=time><span class=digest-days></span><button type=button class="btn small danger">Remove`),JO=I(`<label class="check small"><input type=checkbox><span>`),YO=`/api/agent/concierge`;async function XO(){let e=Qo(await G(YO));if(!e)throw Error(`The hub answered an unexpected Concierge view`);return e}async function ZO(e){if(!e)return;let{grants:t}=await G(`/api/agent/grants`);return t?.find(t=>t.id===e)}function QO(){let[t,{refetch:i,mutate:a}]=d(XO),o=()=>t.error?void 0:t(),[c,{refetch:f}]=d(()=>o()?.settings.grantID,ZO),[p,h]=u(!1),[g,_]=u(!1),[v,S]=u({}),[C,w]=u(),T=()=>Xl()??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(()=>Xl()?.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(`${YO}/settings`,{method:`PUT`,json:{...ws(r,e),...n}}))},A=()=>O(`Concierge on`,()=>V(`${YO}/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(`${YO}/disable`,{method:`POST`,json:{expectedRevision:o().settings.revision}}))},ee=()=>O(`Restarting the Concierge`,()=>V(`${YO}/restart`,{method:`POST`,json:{}}));return(()=>{var e=pO();return e.firstChild,y(e,n(l,{get when(){return o()},get fallback(){return(()=>{var e=hO();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=mO();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=SO(),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=gO();return e.$$click=()=>void ee(),s(()=>e.disabled=p()),e})(),(()=>{var e=_O();return e.$$click=()=>void j(),s(()=>e.disabled=p()),e})()]}}),null),y(E,n(l,{get when(){return!t().enabled},get children(){var e=vO();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=yO();return y(e,d),e}}),O),y(x,n(l,{get when(){return!t().enabled},get children(){return bO()}}),O),y(x,n(l,{get when(){return r(()=>!!(t().enabled&&T()?.state===`failed`))()&&T()?.reason},get children(){var e=xO(),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 CO()},children:e=>(()=>{var n=wO(),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($O,{get settings(){return t()},get machine(){return h()},get busy(){return p()},save:k}),P),y(x,n(ek,{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(rk,{get settings(){return t()},get busy(){return p()},save:k}),I),y(x,n(fO,{}),I),y(I,n(l,{get when(){return t().grant},get fallback(){return(()=>{var e=TO(),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=DO(),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=EO();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(tk,{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 $O(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=jO(),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=OO();return y(e,n(m,{get each(){return r().projects},children:e=>(()=>{var t=MO();return t.value=e,y(t,e),t})()})),e}}),u),y(a,n(l,{get when(){return f().length},get children(){var e=kO();return y(e,n(m,{get each(){return f()},children:e=>(()=>{var t=MO();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=AO();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 ek(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(`${YO}/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=PO(),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=MO();return y(t,e),s(()=>t.value=e()),t})()}),u),y(o,n(m,{get each(){return f()},children:e=>(()=>{var t=FO();return b(t,`label`,e),y(t,n(m,{get each(){return c().filter(t=>t.provider===e)},children:e=>(()=>{var t=MO();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=mO();return e.$$click=()=>void a(),e})()]}}),null),y(e,n(l,{get when(){return _()===Ts},get children(){var e=NO();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 tk(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(`${YO}/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=IO();return y(t,()=>i()[e.field]),s(()=>b(t,`data-error`,e.field)),t}}),C=e=>(()=>{var r=LO(),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=BO(),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=VO(),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=HO(),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=RO();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=zO();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=WO(),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=UO();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 rk(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=GO(),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 KO()},children:(a,o)=>(()=>{var c=qO(),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=JO(),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 ik=e=>`/api/sessions/${encodeURIComponent(e)}/context-cards`,ak=(e,t)=>`${ik(e)}/${encodeURIComponent(t)}/refresh`,ok=e=>`/api/context-cards/primary?sessions=${encodeURIComponent(e.join(`,`))}`,sk=`/api/settings/context-cards`,ck=e=>typeof e==`object`&&e&&!Array.isArray(e)?e:void 0,lk=e=>typeof e==`string`,uk=e=>typeof e==`number`&&Number.isFinite(e);function dk(e){if(!Array.isArray(e))return;let t=e.map(ck).filter(e=>!!e&&lk(e.label)&&lk(e.value)).map(e=>({label:e.label,value:e.value}));return t.length===e.length&&t.length?t:void 0}function fk(e){let t=ck(e);if(!t||!lk(t.provider)||!lk(t.sessionID)||!lk(t.title)||!lk(t.headline)||!uk(t.generatedAt))return;let n=dk(t.fields);return{provider:t.provider,sessionID:t.sessionID,title:t.title,headline:t.headline,body:lk(t.body)?t.body:``,...n?{fields:n}:{},generatedAt:t.generatedAt,...lk(t.model)?{model:t.model}:{},inputsHash:lk(t.inputsHash)?t.inputsHash:``,version:uk(t.version)?t.version:0,trigger:lk(t.trigger)?t.trigger:`manual`,...t.primary===!0?{primary:!0}:{}}}function pk(e){let t=ck(e)??{};return{cards:(Array.isArray(t.cards)?t.cards:[]).map(fk).filter(e=>!!e),providers:(Array.isArray(t.providers)?t.providers:[]).map(ck).filter(e=>!!e&&lk(e.id)&&lk(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 mk(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 hk=(e,t)=>`updated ${mk(Math.max(0,t-e.generatedAt))}${e.model?` · ${e.model}`:``}`,gk={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 _k(e){let t=ck(e)??{};if(t.outcome!==`generated`)return t.outcome===`skipped`?gk[String(t.reason)]??`No new card this time.`:`The card could not be made. Try again later.`}var vk=(e,t)=>e.type===`contextCard`&&e.sessionID===t;function yk(e){let t=ck(e)??{},n=ck(t.model),r=ck(t.usage),i=ck(r?.limits);return{enabled:t.enabled===!0,available:t.available===!0,configured:t.configured===!0,...n&&lk(n.provider)&&lk(n.model)?{model:{provider:n.provider,model:n.model,keySource:lk(n.keySource)?n.keySource:``}}:{},...r&&uk(r.calls)&&uk(r.tokens)&&i&&uk(i.calls)&&uk(i.tokens)?{usage:{calls:r.calls,tokens:r.tokens,limits:{calls:i.calls,tokens:i.tokens}}}:{}}}var bk=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,fk(t[n])??null)}catch{for(let t of e)this.requested.delete(t)}}))}},[xk,Sk]=u(0),Ck=new bk({fetch:async e=>(await G(ok(e))).cards??{},schedule:e=>void setTimeout(e,30)});Ck.subscribe(()=>Sk(e=>e+1)),hu(e=>Ck.message(e));function wk(e){return xk(),Ck.line(e)}La(wk);var Tk=e=>Ck.put(e),Ek=()=>Ck.clear(),Dk=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.`),Ok=I(`<p class="muted small">`),kk=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>`),Ak=I(`<p class="muted small">Turned off for this hub (HUB_CONTEXT_CARDS=off or contextCards.enabled false).`),jk=I(`<p class="muted small">No model configured: set an OpenRouter key in Speech, or contextCards.model in hub.json.`),Mk=I(`<p class="muted small">Model: <span class=mono></span> (<!>)`),Nk=I(`<p class="muted small">Daily budget: <!> / <!> calls · <!> / <!> tokens used today`),Pk=I(`<p class=field-error>`);function Fk(){let[e,{mutate:t}]=d(async()=>yk(await G(sk))),[i,a]=u(``),[o,c]=u(!1),f=async e=>{c(!0),a(``);try{t(yk(await(await V(sk,{method:`PUT`,json:{enabled:e}})).json())),e||Ek()}catch(e){a(U(e))}finally{c(!1)}};return(()=>{var t=Dk();return t.firstChild.nextSibling,y(t,n(l,{get when(){return e()},get fallback(){return(()=>{var t=Ok();return y(t,()=>e.error?`Could not load the context card settings.`:`Loading…`),t})()},children:e=>[(()=>{var t=kk(),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 Ak()}}),n(l,{get when(){return r(()=>!!e().available)()&&!e().configured},get children(){return jk()}}),n(l,{get when(){return e().model},children:e=>(()=>{var t=Mk(),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=Nk(),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=Pk();return y(t,e),t})()}),null),t})()}function Ik(e,t){let n=Math.max(0,Math.ceil((e-t)/1e3));return`${Math.floor(n/60)}:${String(n%60).padStart(2,`0`)}`}function Lk(e,t){return t.find(t=>!e.has(t.id))}function Rk(e,t,n){let r=t?Date.parse(t):NaN;return Number.isFinite(r)?n+Math.max(0,e-r-1e3):e}var zk={L:0,M:1,Q:2,H:3},Bk={L:1,M:0,Q:3,H:2},Vk=[[-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]],Hk=[[-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]],Uk=(e,t)=>!!(e>>>t&1);function Wk(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 Gk(e,t){let n=zk[t];return Math.floor(Wk(e)/8)-Vk[n][e]*Hk[n][e]}function Kk(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 qk(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]=Kk(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=Kk(n,2)}return t}function Jk(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]^=Kk(t,e))}return n}function Yk(e,t,n){let r=zk[n],i=Hk[r][t],a=Vk[r][t],o=Math.floor(Wk(t)/8),s=i-o%i,c=Math.floor(o/i),l=qk(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=Jk(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 Xk(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=Gk(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 Zk=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=Bk[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,Uk(r,e));this.set(8,7,Uk(r,6)),this.set(8,8,Uk(r,7)),this.set(7,8,Uk(r,8));for(let e=9;e<15;e++)this.set(14-e,8,Uk(r,e));for(let e=0;e<8;e++)this.set(i-1-e,8,Uk(r,e));for(let e=8;e<15;e++)this.set(8,i-15+e,Uk(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,Uk(t,e)),this.set(r,n,Uk(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]=Uk(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 Qk(e,t={}){let n=t.ecc??`M`,r=new TextEncoder().encode(e),i=1;for(;4+(i<=9?8:16)+r.length*8>Gk(i,n)*8;)if(++i>40)throw Error(`Text too long for a QR code`);let a=new Zk(i,n);a.codewords(Yk(Xk(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 $k(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 eA=.8,tA=1.8,nA=.05,rA=`hub.fontScale`,iA=e=>Math.min(tA,Math.max(eA,e)),aA=(e,t)=>Number((Math.round(e/t)*t).toFixed(2));function oA(e){return Number.isFinite(e)?aA(iA(e),nA):1}function sA(e){return e?oA(Number(e)):1}function cA(e,t,n){return oA(!(t>0)||!(n>0)?e:n/t*e)}function lA(e,t){let n=iA((Number.isFinite(e)?e:1)*Math.exp(-t*.01));return Number(n.toFixed(3))}var uA=e=>`${Math.round(e*100)}%`;function dA(e){try{return sA(e.getItem(rA))}catch{return 1}}function fA(e,t){let n=oA(t);try{n===1?e.removeItem(rA):e.setItem(rA,String(n))}catch{}return n}var pA=()=>typeof localStorage>`u`?void 0:localStorage,[mA,hA]=u(pA()?dA(pA()):1),gA=mA;function _A(e){document.documentElement.style.setProperty(`--font-scale`,String(e))}var vA;function yA(e,t={}){let n=t.settle===!1?e:oA(e);hA(n),_A(n),clearTimeout(vA);let r=()=>{let e=pA();if(!e)return;let t=fA(e,n);t!==mA()&&(hA(t),_A(t))};t.settle===!1?vA=setTimeout(r,250):r()}var bA=`.scroller, .home-scroll`,xA=e=>e instanceof Element&&e.closest(bA)!==null;function SA(e=document){_A(mA());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`&&xA(e.target)&&(t.set(e.pointerId,{x:e.clientX,y:e.clientY}),t.size===2&&(n={scale:mA(),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=cA(n.scale,n.distance,r());e!==mA()&&yA(e,{settle:!1})}},o=e=>{t.delete(e.pointerId)&&t.size<2&&n&&(n=void 0,yA(mA()))},s=e=>{e.touches.length>=2&&xA(e.target)&&e.preventDefault()},c=e=>{e.ctrlKey&&xA(e.target)&&(e.preventDefault(),yA(lA(mA(),e.deltaMode===1?e.deltaY*16:e.deltaY),{settle:!1}))},l,u=e=>{xA(e.target)&&(e.preventDefault(),e.type===`gesturestart`?l=mA():e.type===`gesturechange`&&l!==void 0&&e.scale?yA(cA(l,1,e.scale),{settle:!1}):e.type===`gestureend`&&(l=void 0,yA(mA())))},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 CA=[`light`,`system`,`dark`],wA=`hub.theme`;function TA(e){return e===`light`||e===`dark`||e===`system`?e:`system`}function EA(e){return e===`system`?void 0:e}function DA(){try{return TA(localStorage.getItem(wA))}catch{return`system`}}var[OA,kA]=u(DA());function AA(e){let t=EA(e);t?document.documentElement.dataset.theme=t:delete document.documentElement.dataset.theme;try{e===`system`?localStorage.removeItem(wA):localStorage.setItem(wA,e)}catch{}kA(e)}var jA=[`macos`,`linux`,`windows`],MA={macos:`macOS`,linux:`Linux`,windows:`Windows`},NA=`~/projects`,PA=200,FA=[{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.`}],IA=new Set([`session-only`,`launch-node`]),LA=e=>jA.includes(e);function RA(e,t){let n=LA(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 zA=(e,t)=>e!==`windows`||IA.has(t),BA=e=>FA.map(t=>({...t,comingSoon:!zA(e,t.id)}));function VA(e){let t=e.replace(/\\/g,`/`);return/^[a-z]:\//.test(t)?t[0].toUpperCase()+t.slice(1):t}function HA(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=VA(e)}if(e.length>PA)return`At most ${PA} 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 UA(e){try{let t=new URL(e);return t.protocol===`https:`||t.protocol===`http:`?t.origin:void 0}catch{return}}function WA(e){let t=UA(e.origin);if(!t)return{ok:!1,error:`This hub has no usable public URL (http or https).`};if(!zA(e.os,e.profile))return{ok:!1,error:`${FA.find(t=>t.id===e.profile)?.label??e.profile} is coming soon on ${MA[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=HA(t,e.os);if(r)return{ok:!1,error:`Workspace folder: ${r}`};let i=e.os===`windows`?VA(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 GA=/^(\s{0,3})(`{3,}|~{3,})\s*([^\s`]*)/,KA=/^\s{0,3}(#{1,6})(?:\s+(.*))?$/,qA=/^\s{0,3}(={2,}|-{3,})\s*$/,JA=/^\s{0,3}>\s?(.*)$/,YA=/^(\s*)([-*+]|\d{1,9}[.)])(?:([ \t]+)(.*))?$/,XA=/^\[([ xX])\](?:\s+(.*))?$/,ZA=/^:?-+:?$/,QA=e=>e.length-e.trimStart().length,$A=(e,t)=>e.slice(Math.min(t,QA(e))),ej=e=>GA.test(e);function tj(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=>ej(e)||KA.test(e)||tj(e)||JA.test(e)||YA.test(e),rj=32,ij=20;function aj(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=oj(n,{streaming:r},!0,0).blocks;return gj(i,r?hj(i):void 0)}function oj(e,t,n,r){if(r>rj)return sj(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=GA.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($A(e[s],t.length))}i.push({type:`code`,lang:d[3]??``,text:r.join(`
20
- `)});continue}if(a.length){let e=qA.exec(c);if(e){i.push({type:`heading`,level:e[1][0]===`=`?1:2,text:a.join(`
21
- `)}),a=[];continue}}let f=KA.exec(c);if(f){u(),l(),i.push({type:`heading`,level:f[1].length,text:lj(f[2]??``).trim()});continue}if(tj(c)){u(),l(),i.push({type:`rule`});continue}let p=mj(e,s,t.streaming&&n);if(p){u(),l(),i.push(p.block),s=p.end-1;continue}if(JA.test(c)){u(),l();let a=[],o=s;for(;o<e.length;o++){let t=JA.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:oj(a,t,n&&o===e.length,r+1).blocks}),s=o-1;continue}let m=YA.exec(c);if(m&&(!a.length||uj(m[2]))){u(),l();let a=dj(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 sj(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 cj=e=>e!==void 0&&yj.test(e);function lj(e){let t=e.length;for(;cj(e[t-1]);)t--;let n=t;for(;e[n-1]===`#`;)n--;if(n===t||n>0&&!cj(e[n-1]))return e;for(;cj(e[n-1]);)n--;return e.slice(0,n)}var uj=e=>!/\d/.test(e)||/^0*1[.)]$/.test(e);function dj(e,t,n,r,i){let a=YA.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=YA.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=GA.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=QA(t),r;if(r=h?!0:v?n>=Math.min(p,a+2):n>=p?!0:YA.test(t)?n>=a+2:n>a||!nj(t)&&!ej(m.at(-1)),!r)break;for(;v;v--)m.push(``);let i=$A(t,p);m.push(i),g(i)}u=v>0;let y=XA.exec(m[0]),b=oj(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 fj(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 pj=e=>{let t=e.trim(),n=t.startsWith(`:`),r=t.length>1&&t.endsWith(`:`);return n&&r?`center`:r?`right`:n?`left`:null};function mj(e,t,n){let r=e[t];if(!r.includes(`|`))return;let i=fj(r),a=e[t+1],o;if(a!==void 0){let r=fj(a),s=t+1===e.length-1;r.length===i.length&&r.every(e=>ZA.test(e))?o=r.map(pj):s&&/^[\s|:-]*$/.test(a)&&(a.includes(`-`)||n)&&a.includes(`|`)&&r.length<=i.length&&(o=i.map((e,t)=>r[t]&&ZA.test(r[t])?pj(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(`|`)||ej(t)||JA.test(t)||KA.test(t))break;s.push(fj(t).slice(0,i.length))}return{block:{type:`table`,align:o,head:i,rows:s},end:Math.min(c,e.length)}}function hj(e){let t=e.at(-1);if(t){if(t.type===`paragraph`||t.type===`heading`)return{node:t};if(t.type===`quote`)return hj(t.blocks);if(t.type===`list`)return hj(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 gj(e,t){let n=e=>t?.node===e;return e.map(e=>{switch(e.type){case`paragraph`:return{type:`paragraph`,children:Ij(e.text,{streaming:n(e)})};case`heading`:return{type:`heading`,level:e.level,children:Ij(e.text,{streaming:n(e)})};case`quote`:return{type:`quote`,blocks:gj(e.blocks,t)};case`list`:return{...e,items:e.items.map(e=>({...e.checked===void 0?{}:{checked:e.checked},blocks:gj(e.blocks,t)}))};case`table`:{let r=(r,i,a)=>Ij(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 _j(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 vj=/[!-/:-@[-`{-~]/,yj=/\s/,bj=/[\p{L}\p{N}_]/u,xj={"**":`strong`,__:`strong`,"~~":`del`,"==":`mark`},Sj=(e,t,n)=>{let r=0;for(;e[t+r]===n;)r++;return r},Cj=0,wj=e=>({s:e,closers:new Map}),Tj=e=>new Int32Array(e.s.length+2);function Ej(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=Sj(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 Dj(e,t){let n=e.s[t];if(n===`\\`)return t+2;if(n==="`"){let n=Sj(e.s,t,"`"),r=Ej(e,t+n,n);return(r>=0?r:t)+n}return t+1}function Oj(e,t,n,r,i){let a=e.s,o=e.closers.get(t);o||e.closers.set(t,o=Tj(e));let s=a.length-r.length,c=[],l=-1;for(let t=n;t<=s;){if(o[t]!==Cj){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=Dj(e,t)}for(let e of c)o[e]=l+2;return l}function kj(e,t,n,r){let i=n=>n>=t?-1:e[n]===Cj?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 Aj(e,t){let n=e.s;return kj(e.brackets??=Tj(e),n.length,t+1,t=>{let r=n[t];return r===`]`?t:r===`[`?`open`:{next:Dj(e,t)}})}function jj(e,t){let n=e.s;return kj(e.parens??=Tj(e),n.length,t,e=>{let t=n[e];return t===`)`?e:t===`
24
- `?-1:t===`(`?`open`:{next:e+1}})}function Mj(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 Nj(e){let t=e.trim();return t.startsWith(`<`)?t.slice(1,t.indexOf(`>`)>0?t.indexOf(`>`):void 0):t.split(/\s+/)[0]??``}var Pj=e=>e.map(e=>e.type===`text`||e.type===`code`?e.text:e.type===`image`?e.alt:e.type===`br`?` `:Pj(e.children)).join(``);function Fj(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 Ij(e,t={}){let n=String(e??``),r=!!t.streaming,i=t.depth??0;if(i>ij)return n?[{type:`text`,text:n}]:[];let a=wj(n),o=(e,n,r=t.inLink)=>Ij(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&&vj.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=Sj(n,u,"`"),t=Ej(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=xj[s];if(d&&i!==void 0&&n[u+2]!==void 0&&!yj.test(n[u+2])&&n[u+2]!==e&&(e!==`_`||u===0||!bj.test(n[u-1]))){let t=Oj(a,s,u+3,s,t=>!yj.test(n[t-1])&&(e!==`_`||!bj.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&&!yj.test(i)&&(e===`*`||u===0||!bj.test(n[u-1]))){let t=Oj(a,e,u+1,e,t=>n[t+1]===e||n[t-1]===e?!1:!yj.test(n[t-1])&&(e!==`_`||!bj.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=Aj(a,e);if(i>0&&n[i+1]===`(`){let s=jj(a,i+2),c=()=>o(n.slice(e+1,i),!1,!0);if(s>0){let e=Nj(n.slice(i+2,s)),r=_j(e);f?l({type:`image`,alt:Pj(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&&!Mj(a,i)){l(...f?[{type:`text`,text:Pj(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=_j(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=Fj(n,u),t=e&&_j(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 Lj={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 Rj=e=>typeof e==`string`&&e.length>0&&e.length<=Lj.pathMax&&!/[\u0000\r\n]/.test(e);function zj(e){return!Rj(e)||e.startsWith(`~`)||/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e)&&!/^file:/i.test(e)?!1:/\.html?$/i.test(e)}var Bj=new Set([`html`,`htm`]),Vj=e=>Bj.has(e.toLowerCase());function Hj(e){let t=[],n=e=>{for(let r of e)if(r.type===`code`&&Vj(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 Uj=new Map,Wj=256;function Gj(e){let t=Uj.get(e);if(t!==void 0)return t;let n=e.includes("```")||e.includes(`~~~`)?Hj(aj(e)).length:0;return Uj.size>=Wj&&Uj.delete(Uj.keys().next().value),Uj.set(e,n),n}function Kj(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+Gj(t.text))}return i}function qj(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 Jj(e){let t=e.type===`code`?e.text:e.type===`link`?e.href:e.type===`label`?e.target:void 0;return t!==void 0&&zj(t)?t:void 0}var Yj=Math.round(Lj.fileBytes/1048576);function Xj(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 ${Yj} 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 Zj={missing:`not found`,refused:`not one of this session's files`,too_large:`over ${Yj} 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 Qj(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} — ${Zj[e.reason]??e.reason}`),...t>0?{more:`and ${t} more`}:{}}}var[$j,eM]=u(new Map),tM=e=>$j().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;eM(t=>new Map(t).set(e,{skipped:n,more:r}))}var rM=I(`<span role=alert>`),iM=I(`<button type=button>`);async function aM(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 oM(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 aM(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()?Xj(e):qj(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=rM();return y(t,i),s(()=>k(t,e.inline?`md-preview-err`:`code-preview-err`)),t}}),(()=>{var n=iM();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 sM=`/api/agent/artifacts`,cM={textBytes:2097152,imageBytes:10485760,editBytes:1048576,revisionsPage:20},lM=encodeURIComponent,uM=e=>`${sM}/${lM(e)}`,dM=(e,t)=>`${uM(e)}/revisions?limit=${cM.revisionsPage}${t?`&cursor=${lM(t)}`:``}`,fM=(e,t)=>`${uM(e)}/revisions/${lM(t)}`,pM=(e,t,n)=>`${fM(e,t)}/blobs/${lM(n)}`,mM=e=>typeof e==`object`&&!!e&&!Array.isArray(e),hM=e=>typeof e==`string`&&e.length>0,gM=e=>typeof e==`number`&&Number.isFinite(e),_M=e=>typeof e==`string`&&Tn.includes(e),vM=(e,t)=>mM(e)&&mM(e[t])?e[t]:e;function yM(e){let t=vM(e,`artifact`);if(!mM(t)||!hM(t.id)||typeof t.title!=`string`||!_M(t.kind)||!hM(t.latestRevisionID)||!gM(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:gM(t.createdAt)?t.createdAt:0,updatedAt:gM(t.updatedAt)?t.updatedAt:0,...hM(t.description)?{description:t.description}:{},...hM(t.workspaceID)?{workspaceID:t.workspaceID}:{},...hM(t.createdBySessionID)?{createdBySessionID:t.createdBySessionID}:{},...n?.length?{tags:n}:{},...t.origin===`preview`?{origin:`preview`}:{},...bM(t.provenance)??{}}}function bM(e){if(mM(e)&&hM(e.sessionID)&&hM(e.messageID)){if(hM(e.path))return{provenance:{sessionID:e.sessionID,messageID:e.messageID,path:e.path}};if(gM(e.block))return{provenance:{sessionID:e.sessionID,messageID:e.messageID,block:e.block}}}}function xM(e){if(mM(e)){if(e.kind===`user`)return{kind:`user`};if(e.kind===`session`&&hM(e.sessionID))return{kind:`session`,sessionID:e.sessionID};if(e.kind===`ai_job`&&hM(e.jobID))return{kind:`ai_job`,jobID:e.jobID}}}function SM(e){let t=vM(e,`revision`);if(!mM(t)||!hM(t.id)||!hM(t.artifactID)||!gM(t.number)||!Array.isArray(t.blobs))return;let n=xM(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:gM(t.createdAt)?t.createdAt:0,...hM(t.baseRevisionID)?{baseRevisionID:t.baseRevisionID}:{},...hM(t.entry)?{entry:t.entry}:{}}}function CM(e){let t=mM(e)?e:{};return{items:Array.isArray(t.items)?t.items.flatMap(e=>SM(e)??[]):[],...hM(t.cursor)?{cursor:t.cursor}:{}}}function wM(e){return e.kind===`user`?`You`:e.kind===`session`?`Session ${e.sessionID.slice(0,12)}…`:`AI job`}var TM=[`text/markdown`,`text/plain`,`text/csv`,`text/html`,`text/css`,`text/javascript`,`application/json`],EM=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`,`image/svg+xml`],DM={markdown:{"text/markdown":`markdown`,"text/plain":`markdown`},code:Object.fromEntries(TM.map(e=>[e,`code`])),image:Object.fromEntries(EM.map(e=>[e,`image`])),table:{"text/csv":`table`,"application/json":`table`},chart:{"application/json":`chart`},dashboard:{"application/json":`dashboard`},file:{...Object.fromEntries(EM.map(e=>[e,`image`])),"text/plain":`text`,"text/markdown":`text`}},OM={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:``},kM={"text/javascript":`js`,"text/css":`css`,"application/json":`json`,"text/html":`html`,"text/markdown":`markdown`,"text/csv":`csv`};function AM(e){let t=e.path?.split(`/`).pop()?.split(`.`).slice(1).pop()?.toLowerCase();return t!==void 0&&t in OM?OM[t]:kM[e.mediaType]??``}function jM(e,t){let n=t.blobs;if(Cn.includes(e))return{mode:`isolated`,files:n,...n[0]?{file:MM(t)??n[0]}:{}};if(!n.length)return{mode:`empty`,files:n};let r=DM[e],i=MM(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`?cM.imageBytes:cM.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:AM(i)}:{}}}function MM(e){return e.entry===void 0?void 0:e.blobs.find(t=>t.path===e.entry)}var NM=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 PM(e,t){let n=Number(e.headers.get(`content-length`)??``);if(Number.isFinite(n)&&n>t)throw await e.body?.cancel().catch(()=>{}),new NM(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 NM(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 FM(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 IM=e=>new TextEncoder().encode(e).byteLength;function LM(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 TM.includes(n.mediaType)&&n.bytes<=cM.editBytes}function RM(e,t,n){if(IM(n)>cM.editBytes)throw new NM(cM.editBytes);return{baseRevisionID:e,upload:[{mediaType:t.mediaType,data:n,encoding:`utf8`,...t.path===void 0?{}:{path:t.path}}]}}var zM=e=>`hub.artifactDraft.v1.${e}`;function BM(e,t){try{let n=e?.getItem(zM(t)),r=n?JSON.parse(n):void 0;return mM(r)&&r.v===1&&hM(r.base)&&typeof r.text==`string`?{v:1,base:r.base,text:r.text}:void 0}catch{return}}function VM(e,t){let n=BM(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(zM(e.artifactID)):IM(r.draft)<=cM.editBytes&&t.storage?.setItem(zM(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=RM(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(zM(e.artifactID)),o({status:`saved`,draft:u.draft,baseRevisionID:r.id}),r}catch(e){let t=FM(e),n=e.details;t.kind===`conflict`?o({...u,status:`conflict`,error:t,...hM(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(zM(e.artifactID)),a=void 0,o({status:`editing`,draft:i,baseRevisionID:e.baseRevisionID})}}}var HM=/^\/artifacts\/([^/?#]+)(?:\/revisions\/([^/?#]+))?$/;function UM(e){let t=HM.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 WM=e=>({ok:!1,reason:e});function GM(e){let t=e?.status;return WM(t===404||t===403?`not_found`:`error`)}async function KM(e,t){let n;try{n=await t.artifact(e.id)}catch(e){return GM(e)}if(n.id!==e.id)return WM(`not_found`);if(n.kind!==`image`&&n.kind!==`file`)return WM(`not_image`);let r=e.rev??n.latestRevisionID,i;try{i=await t.revision(n.id,r)}catch(e){return GM(e)}if(i.id!==r||i.artifactID!==n.id)return WM(`not_found`);let a=qM(n,i);return a?a.bytes>Nn.maxBytes?WM(`too_large`):{ok:!0,artifactID:n.id,revisionID:r,title:n.title,file:a,src:pM(n.id,r,a.hash),page:`/artifacts/${encodeURIComponent(n.id)}`}:WM(`not_image`)}function qM(e,t){let n=jM(e.kind,t),r=n.file;if(r&&Mn.includes(r.mediaType))return n.mode===`image`||n.mode===`download`?r:void 0}function JM(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 KM(a,e.reader)}finally{t()}});return i.set(o,{at:t(),answer:c}),c}}}var YM={text:`No longer available from this artifact`,retry:!1},XM={text:`Artifacts aren't available on this hub`,retry:!1};function ZM(e,t){return t===`not_found`||t===void 0&&e===404?{...YM}:t===`unsupported`||t===void 0&&e===422?{...XM}:Ln(e,t)}var QM=I(`<a class=md-image target=_blank rel="noopener noreferrer">`),$M=I(`<span class=md-artifact><a class=md-artifact-link title="Open the artifact">`),eN=()=>new W(404,`No such artifact`),tN=JM({reader:{async artifact(e){let t=yM(await G(uM(e)));if(!t)throw eN();return t},async revision(e,t){let n=SM(await G(fM(e,t)));if(!n)throw eN();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 rN(e){let[t]=d(()=>UM(e.href),e=>tN.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=QM();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=$M(),i=r.firstChild;return y(r,n(zn,{get images(){return[t()]},children:e=>n(Fn,{get image(){return t()},class:`md-media`,explain:ZM,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 iN=e=>`/api/media/remote?url=${encodeURIComponent(e)}`;function aN(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=mw(n.href),i=r??n.host.replace(/\.(?=:|$)/,``),a=gw(i);if(!t.enabled)return{kind:`off`,host:i,unicode:a,url:e};let o=n.username!==``||n.password!==``;return r&&!o&&(hw(t.allowlist,r)||t.sessionHosts.includes(r))?{kind:`auto`,host:r,src:iN(e)}:{kind:`card`,host:i,unicode:a,src:iN(e),url:e}}var oN=I(`<span class=remote-image>`),sN=I(`<span class=remote-card-unicode>(<!>)`),cN=I(`<span class=remote-card-alt>`),lN=I(`<button type=button class="btn small">Always allow `),uN=I(`<span class=remote-card-actions><button type=button class="btn small">Load image`),dN=I(`<button type=button class=remote-card-session>Load all from this domain in this session`),fN=I(`<span class=remote-card><span class=remote-card-head><span class=remote-card-domain></span></span><button type=button class=remote-card-url>`),pN=I(`<span class=remote-card-off>Web images are turned off on this hub`),mN=c(``),hN=e=>aN(e,{origin:location.origin,allowlist:[],sessionHosts:[],enabled:!0}).kind!==`same-origin`,gN=(e,t=64)=>{let n=e.replace(/^https?:\/\//i,``);return n.length>t?`${n.slice(0,t-21)}…${n.slice(-20)}`:n};function _N(e){let t=le(mN),[i,a]=u(!1),[c,d]=u(!1),[f,p]=u(!1),m=C(()=>{let n=Sw();return aN(e.href,{origin:location.origin,allowlist:n?.allowlist??[],sessionHosts:Ow(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 Tw(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=oN();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=fN(),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=sN(),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:gN(i().url)})()),y(o,n(l,{get when(){return e.alt},get children(){var t=cN();return y(t,()=>e.alt),t}}),null),y(o,n(l,{get when(){return i().kind===`card`},get fallback(){return pN()},get children(){return[(()=>{var e=uN(),t=e.firstChild;return t.$$click=()=>a(!0),y(e,n(l,{get when(){return!i().host.includes(`:`)},get children(){var e=lN();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=dN();return e.$$click=()=>kw(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 vN=e=>`/api/media/unfurl?url=${encodeURIComponent(e)}`;function yN(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=mw(n.href);return r?{kind:hw(t.allowlist,r)?`auto`:`tap`,host:r,url:n.href}:{kind:`none`}}function bN(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`)&&bN(n.children,t)}function xN(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=yN(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`)bN(t.children,e);else if(t.type===`table`)for(let n of[t.head,...t.rows])for(let t of n)bN(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 SN(e,t){if(typeof e!=`string`||!e)return;let n=aN(e,{origin:t.origin,allowlist:t.allowlist,sessionHosts:[],enabled:t.enabled});return n.kind===`auto`?n.src:void 0}function CN(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 wN=class extends Error{reason;status;code;constructor(e,t=0,n){super(e.text),this.reason=e,this.status=t,this.code=n}},TN=256,EN={title:200,description:300,siteName:100},DN=(e,t)=>new wN(CN(e,t),e,t),ON=/[\u0000-\u001f\u007f-\u009f\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;function kN(e,t){if(typeof e!=`string`)return;let n=e.replace(ON,``).trim();return n?n.length>t?`${n.slice(0,t-1)}…`:n:void 0}function AN(e,t){let n=e&&typeof e==`object`?e:{},r=typeof n.url==`string`&&/^https?:\/\//i.test(n.url)?n.url:t,i=kN(n.title,EN.title),a=kN(n.description,EN.description),o=kN(n.siteName,EN.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 jN(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(vN(e),{credentials:`same-origin`,referrerPolicy:`no-referrer`,signal:a.signal})}catch{throw o?DN(504,`timeout`):DN(0)}let r=await n.json().catch(()=>void 0);if(!n.ok)throw DN(n.status,typeof r?.code==`string`?r.code:void 0);if(!r||typeof r!=`object`)throw DN(500);return AN(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>TN&&i.delete(i.keys().next().value),t),t=>{o.delete(e);let n=t instanceof wN?t:DN(0);throw a.set(e,n),n});return o.set(e,c),c},forget(e){a.delete(e)}}}var MN=I(`<button type=button class=link-preview-btn>`),NN=I(`<div class=link-cards>`),PN=I(`<div class=link-card>`),FN=I(`<span class=link-card-loading>Loading a preview of <!>…`),IN=I(`<span class=link-card-title>`),LN=I(`<span class=link-card-desc>`),RN=I(`<a class=link-card-link target=_blank rel="noopener noreferrer"><span class=link-card-site>`),zN=I(`<button type=button class="btn small">Retry`),BN=I(`<span class=link-card-failed><span class=link-card-note>`),VN=jN({slots:On}),HN=c(()=>void 0);function UN(e){let t=le(HN),r=C(()=>{let n=t();if(!n)return;let r=yN(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=MN();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 WN(e){let t=le(HN),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=NN();return y(e,n(m,{get each(){return r()},children:e=>n(GN,{url:e,get auto(){return t()?.plan.auto.has(e)===!0},context:()=>t()?.context})})),e}})}function GN(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`}),VN.load(e.url).then(e=>f&&i({at:`shown`,preview:e}),e=>{if(!f)return;let t=e instanceof wN?e.reason:{text:`Couldn't load the preview`,retry:!0};i({at:`failed`,...t})})};x(()=>{a()&&r().at===`waiting`&&m()});let h=()=>{VN.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?SN(t.image,n):void 0});return(()=>{var i=PN(),a=d;return typeof a==`function`?t(a,i):d=i,y(i,n(v,{get fallback(){return(()=>{var e=FN(),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=RN(),i=r.firstChild;return y(i,()=>t().siteName??p()),y(r,n(l,{get when(){return t().title},get children(){var e=IN();return y(e,()=>t().title),e}}),null),y(r,n(l,{get when(){return t().description},get children(){var e=LN();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=BN(),r=t.firstChild;return y(r,()=>e().text),y(t,n(l,{get when(){return e().retry},get children(){var e=zN();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 KN=I(`<span class=md-image>`),qN=I(`<a class=md-image target=_blank rel="noopener noreferrer"title="Image (opens in a new tab)">`),JN=I(`<br>`),YN=I(`<code class=inline-code>`),XN=I(`<a rel="noopener noreferrer">`),ZN=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>`),QN=I(`<span>`),$N=I(`<hr>`),eP=I(`<p>`),tP=I(`<input type=checkbox disabled>`),nP=I(`<li>`),rP=I(`<blockquote>`),iP=I(`<div class=table-wrap><table><thead><tr></tr></thead><tbody>`),aP=I(`<th>`),oP=I(`<tr>`),sP=I(`<td>`),cP=I(`<div class=md>`),[lP,uP]=u(),dP=!1;function fP(){dP||(dP=!0,Hn(()=>import(`./highlight-y4rJE6Tt.js`).then(e=>uP({run:e.highlight,languageOf:e.languageOf}),()=>dP=!1),[]))}var pP=65536;function mP(e,t){fP();let n=lP();return!n||!e||t.length>pP||!n.languageOf(e)?[{text:t}]:n.run(t,e)}function hP(e){let t=le(CP),r=C(()=>{let n=t(),r=n&&!n.streaming&&!e.inLink?Jj(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(oM,{get target(){return e()},get waiting(){return e().waiting},inline:!0})})}var gP=c(()=>void 0);function _P(e){let t=le(gP),i=C(()=>An(e.node,t()?.images)),a=()=>e.node.alt||`image`;return n(v,{get fallback(){return(()=>{var e=KN();return y(e,a),e})()},get children(){return[n(o,{get when(){return r(()=>!!(i().kind===`remote`&&hN(i().href)))()&&i()},children:t=>n(_N,{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(rN,{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=qN();return y(t,a),s(()=>b(t,`href`,e().href)),t})()})]}})}function vP(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 JN()}}),n(o,{get when(){return r(()=>t().type===`code`)()&&t()},children:r=>[(()=>{var e=YN();return y(e,()=>r().text),e})(),n(hP,{get node(){return t()},get inLink(){return e.inLink}})]}),n(o,{get when(){return r(()=>t().type===`link`)()&&t()},children:r=>[(()=>{var e=XN();return y(e,n(vP,{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(UN,{get href(){return r().href}}),n(hP,{get node(){return t()},get inLink(){return e.inLink}})]}),n(o,{get when(){return r(()=>t().type===`image`)()&&t()},children:e=>n(_P,{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(vP,{get nodes(){return r().children},get inLink(){return e.inLink}})}}),n(l,{get when(){return r().type===`label`},get children(){return n(hP,{get node(){return t()},get inLink(){return e.inLink}})}})]})]}})})}async function yP(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 bP(e){let[t,r]=u(!1),[i,a]=u(!1),o;M(()=>clearTimeout(o)),fP();let c=C(()=>{let t=lP();return!t||!e.lang||e.text.length>pP||!t.languageOf(e.lang)?[{text:e.text}]:t.run(e.text,e.lang)}),d=()=>e.lang||`text`;return(()=>{var u=ZN(),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 yP(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=QN();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 xP=E(()=>Hn(()=>import(`./Diagram-CuRIffka.js`),__vite__mapDeps([0,1,2,3,4,5,6]))),SP=c(()=>void 0),CP=c(()=>void 0);function wP(e){let t=e.at(-1);if(t){if(t.type===`code`)return t;if(t.type===`quote`)return wP(t.blocks);if(t.type===`list`)return wP(t.items.at(-1)?.blocks??[])}}function TP(e){let t=le(SP),i=le(CP),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(bP,{get lang(){return e.block.lang},get text(){return e.block.text},get actions(){return n(l,{get when(){return a()},children:e=>n(oM,{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(xP,{get lang(){return e.block.lang},get text(){return e.block.text}})}})}})}var EP={left:`left`,center:`center`,right:`right`};function DP(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=eP();return y(t,n(vP,{get nodes(){return e().children}})),t})(),n(WN,{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(vP,{get nodes(){return e().children}})}}),n(WN,{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=tP();return s(()=>b(t,`aria-label`,e().checked?`Done`:`Not done`)),s(()=>t.checked=e().checked),t}}),null),y(t,n(DP,{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(TP,{get block(){return e()}})}),n(o,{get when(){return r(()=>e().type===`quote`)()&&e()},children:e=>(()=>{var t=rP();return y(t,n(DP,{get blocks(){return e().blocks}})),t})()}),n(o,{get when(){return r(()=>e().type===`table`)()&&e()},children:e=>[(()=>{var t=iP(),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=aP();return y(i,n(vP,{get nodes(){return t()}})),s(t=>h(i,e().align[r]?{"text-align":EP[e().align[r]]}:void 0,t)),i})()})),y(a,n(g,{get each(){return e().rows},children:t=>(()=>{var r=oP();return y(r,n(g,{get each(){return t()},children:(t,r)=>(()=>{var i=sP();return y(i,n(vP,{get nodes(){return t()}})),s(t=>h(i,e().align[r]?{"text-align":EP[e().align[r]]}:void 0,t)),i})()})),r})()})),t})(),n(WN,{get block(){return e()}})]}),n(o,{get when(){return e().type===`rule`},get children(){return $N()}})]}})})}function OP(e){let t=C(()=>aj(e.text,{streaming:e.streaming})),r=C(()=>e.streaming&&kn(e.text)?wP(t()):void 0),i=C(()=>e.preview?new Map(Hj(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=Sw();if(!n)return;let r={origin:location.origin,allowlist:n.allowlist,enabled:n.remoteFetch!==!1};return{context:r,plan:xN(t(),r,{streaming:e.streaming}),tapped:o(),tap:e=>s(new Set([...o(),e]))}}),d=i=>n(HN.Provider,{value:c,get children(){return n(gP.Provider,{value:()=>i&&e.images?.length?{images:e.images,open:i}:void 0,get children(){return n(SP.Provider,{value:r,get children(){return n(CP.Provider,{value:a,get children(){return n(DP,{get blocks(){return t()}})}})}})}})}}),f=C(()=>Pn(t(),e.images));return(()=>{var t=cP();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 kP=I(`<div class=dialog-head><h2 id=setup-machine-title>Set up Hub on a machine`),AP=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: <!>.`),jP=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.`),MP=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>`),NP=I(`<dialog class="dialog setup-machine-dialog"aria-labelledby=setup-machine-title aria-describedby=setup-machine-intro data-setup-machine>`),PP=I(`<label class=sm-seg-item><input type=radio name=setup-os>`),FP=I(`<label class=sm-profile><input type=radio name=setup-profile><span class=grow><span class=name></span><span class="small muted">`),IP=I(`<p class="error small"role=alert>`),LP=I(`<code class=sm-command data-setup-command>`),RP=`hub.setupMachine.os`,zP=`button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`,[BP,VP]=u();function HP(e={}){BP()||VP(e)}var UP=()=>{try{return localStorage.getItem(RP)??void 0}catch{return}};function WP(){let e,i,[a,o]=u(`linux`),[c,d]=u(`session-only`),[f,p]=u(``),[h,g]=u(!1),[_,v]=u(!1),S,w=()=>VP(void 0);x(()=>{let t=BP();e&&(t&&!e.open?(i=t.returnTo?.()??document.activeElement,o(RA(navigator,UP())),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),zA(e,c())||d(`session-only`);try{localStorage.setItem(RP,e)}catch{}},E=()=>X()?.publicURL??location.origin,D=C(()=>WA({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 yP(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=NP();i.$$keydown=t=>{if(t.key!==`Tab`||!e)return;let n=[...e.querySelectorAll(zP)].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 BP()},get children(){return[(()=>{var e=kP();return e.firstChild,y(e,n(F,{icon:`close`,label:`Close`,onClick:w}),null),e})(),(()=>{var e=MP(),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:jA,children:e=>(()=>{var t=PP(),n=t.firstChild;return n.addEventListener(`change`,()=>T(e)),n.value=e,y(t,()=>MA[e],null),s(()=>t.classList.toggle(`on`,a()===e)),s(()=>n.checked=a()===e),t})()})),y(u,n(m,{get each(){return BA(a())},children:e=>(()=>{var t=FP(),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 ${MA[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=AP(),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`,NA),b(t,`spellcheck`,!1),y(n,()=>O()?` (C:\\Users\\you\\projects, C:/… or ~/…)`:``,r),y(n,NA,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=jP(),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=IP();return y(e,()=>D().error),e})()},children:e=>(()=>{var t=LP();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 GP=I(`<h3 class=section-title>`),KP=I(`<section class=settings-section>`),qP=I(`<div class=settings-search role=search><input type=search placeholder="Search settings"aria-label="Search settings">`),JP=I(`<nav class=settings-nav aria-label="Settings sections">`),YP=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`),XP=I(`<a>`),ZP=I(`<ul class=settings-results aria-label="Search results">`),QP=I(`<p class="muted settings-empty">No settings match.`),$P=I(`<li><a><span class=name></span><span class="small muted"> · `),eF=I(`<ul class=settings-list aria-label="Settings sections">`),tF=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`),rF=I(`<div class=settings-page><h2 class=settings-page-title>`),iF=I(`<span class=badge-pill>`),aF=I(`<div class="small muted">`),oF=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`),sF=I(`<h3>Notify me when`),cF=I(`<p class="small notify-summary"data-notify-summary>`),lF=I(`<p class="small warn">These apply once this device is subscribed.`),uF=I(`<p class=activity-hint data-activity-hint><strong>Know what happens with the screen off:</strong> turn on <em>All done</em> for one notification when a session and its subagents finish, or the <em>Activity digest</em> for one quiet, self-replacing summary per session.`),dF=I(`<h4>When`),fF=I(`<ul class=switches><li id=quiet-hours><label class=switch><span>Quiet hours</span><input type=checkbox>`),pF=I(`<p class="small muted"> muted (⋯ menu of a session → Unmute notifications).`),mF=I(`<p class="small muted">Checking this device…`),hF=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>`),gF=I(`<button type=button class="btn small primary">Enable notifications on this device`),_F=I(`<button type=button class="btn small">Turn off on this device`),vF=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`),yF=I(`<div class=row-actions>`),bF=I(`<option>`),xF=I(`<p data-test-result>`),SF=I(`<details class=notify-group><summary><h4></h4><span class="small muted notify-group-summary"data-group-summary></span></summary><ul class=switches>`),CF=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.`),wF=I(`<li><label class=switch><span class=notify-kind><span></span><span class="small muted"></span></span><input type=checkbox>`),TF=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.`),EF=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`),DF=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).`),OF=I(`<button type=button role=radio class=theme-choice><span>`),kF=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.`),AF=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.`),jF=I(`<button type=button class=chip role=radio>`),MF=I(`<label class=small> <input type=number inputmode=decimal> <output class=muted data-turn-effective>in use: `),NF=I(`<h3>Waiting for approval`),PF=I(`<ul class=list>`),FF=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`),IF=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`),LF=I(`<p class="small muted">None yet.`),RF=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`),zF=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`),BF=I(`<p class="small muted">`),VF=I(`<span class=muted> · this device`),HF=I(`<li><div class=grow><div class=name></div><div class="small muted">last seen </div></div><button type=button class="btn small danger">`),UF=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>`),WF=I(`<p class="small muted">Expires in <span class=add-app-countdown></span> · single use`),GF=I(`<div class=row><code class="add-app-link grow"></code><button type=button class="btn small">Copy</button><a class="btn small">Open`),KF=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.`),qF=I(`<div class=add-app-expired><p class="small warn">This code expired.</p><button type=button class="btn small primary">New code`),JF=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`),YF=I(`<p class="small muted">How your <a href=/teams>teams</a> work with the rest of your sessions.`),XF=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>`),ZF=I(`<div class=chips role=group aria-label="Admin sections">`),QF=I(`<p class=error role=alert>`),$F=I(`<div id=admin-machines>`),eI=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=…).`),tI=I(`<div id=admin-audit>`),nI=I(`<span class=count>`),rI=I(`<button type=button class=chip>`),iI=I(`<p class=muted>No machines are waiting for approval.`),aI=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">`),oI=I(`<p class=muted>`),sI=I(`<li class=muted>No users match.`),cI=I(`<span class=badge-pill>Admin`),lI=I(`<span class="badge-pill off">Disabled`),uI=I(`<span class=badge-pill>You`),dI=I(`<li><div class=grow><div class=name></div><div class="small muted"> · <!> · seen `),fI=I(`<button type=button>`),pI=I(`<p class=muted>No machines are connected to this hub yet.`),mI=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`),hI=I(`<ol class="list audit">`),gI=I(`<p class=muted>Nothing recorded yet.`),_I=I(`<li><div class=grow><div class=name></div><div class="small muted"></div></div><time class="small muted">`);function vI(e){return(()=>{var t=KP();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=GP();return y(t,()=>e.title),s(()=>b(t,`id`,`h-${e.id}`)),t}}),null),y(t,()=>e.children,null),t})()}var yI=2400,bI=3e3;function xI(e){if(!e)return;let t=Date.now()+bI,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`),yI)}};requestAnimationFrame(n)}var SI=e=>vt(!0).find(t=>t.id===e)?.label,CI=!1;function wI(){let t=()=>qn(X()),i=()=>{let e=WS();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=>xI(At(decodeURIComponent(e.hash.slice(1))))));let p=()=>{CI?(CI=!1,history.back()):Vt(`/settings`)},h=()=>(()=>{var e=qP(),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=YP(),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:Dp})},get children(){return n(F,{icon:`back`,label:`All settings`,onClick:p})}})}}),u),y(u,(()=>{var e=r(()=>!!(Z()&&a()!==`list`));return()=>e()?SI(a())??`Settings`:`Settings`})()),y(g,n(l,{get when(){return!Z()},get children(){var e=JP();return y(e,h,null),y(e,n(m,{get each(){return vt(t())},children:e=>(()=>{var t=XP();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(TI,{get results(){return f()},onPick:()=>d(``)})},get children(){return n(v,{get fallback(){return n(DI,{})},get children(){return[n(o,{get when(){return a()===`list`},get children(){return n(EI,{onPick:()=>CI=!0})}}),n(o,{get when(){return r(()=>a()!==`list`)()&&a()},keyed:!0,children:e=>n(OI,{id:e})})]}})}}),x),y(x,()=>X()?.publicURL??location.origin,S),y(x,()=>X()?.version??`?`,null),e})()}function TI(e){return n(l,{get when(){return e.results.length},get fallback(){return QP()},get children(){var t=ZP();return y(t,n(m,{get each(){return e.results},children:t=>(()=>{var n=$P(),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,()=>SI(t.section),o),y(a,()=>t.description,null),s(()=>b(r,`href`,`/settings/${t.section}#${t.id}`)),n})()})),t}})}function EI(e){return(()=>{var t=eF();return y(t,n(m,{get each(){return vt(qn(X()))},children:t=>(()=>{var r=tF(),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 DI(){return nF()}function OI(e){return(()=>{var t=rF(),i=t.firstChild;return y(i,()=>SI(e.id)),y(t,n(v,{get children(){return[n(o,{get when(){return e.id===`general`},get children(){return[n(AI,{}),n(MI,{}),n(WI,{})]}}),n(o,{get when(){return e.id===`notifications`},get children(){return n(jI,{})}}),n(o,{get when(){return e.id===`voice`},get children(){return[n(LI,{}),n(ow,{}),n(vI,{id:`speech`,title:`Speech`,get children(){return n(LC,{})}})]}}),n(o,{get when(){return e.id===`media`},get children(){return n(vI,{id:`media-allowlist`,title:`Web images`,get children(){return n(Rw,{})}})}}),n(o,{get when(){return e.id===`machines`},get children(){return[n(BI,{}),n(VI,{})]}}),n(o,{get when(){return e.id===`agents`},get children(){return n(ND,{})}}),n(o,{get when(){return e.id===`concierge`},get children(){return[n(QO,{}),n(vI,{id:`context-cards`,title:`Context cards`,get children(){return n(Fk,{})}})]}}),n(o,{get when(){return e.id===`teams`},get children(){return n(KI,{})}}),n(o,{get when(){return r(()=>e.id===`admin`)()&&qn(X())},get children(){return n(YI,{})}})]}}),null),s(()=>b(t,`data-settings-section`,e.id)),t})()}async function kI(){if(Jn(X()).mode!==`pairing`||await P(`Sign out this device? You will need a new pairing code.`,`Sign out`,{danger:!0})){await(await Rf().catch(()=>void 0))?.unsubscribe().catch(()=>{}),await V(`/api/logout`,{method:`POST`,json:{}}).catch(()=>{});try{as(localStorage)}catch{}Gu(),location.href=`/`}}function AI(){let e=()=>Jn(X());return n(vI,{id:`account`,title:`Account`,get children(){var t=oF(),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=iF();return y(t,()=>e().badge),t}}),null),y(i,n(l,{get when(){return e().subtitle},get children(){var t=aF();return y(t,()=>e().subtitle),t}}),c),y(c,()=>X()?.device?.name??`paired`,null),u.$$click=()=>void kI(),s(()=>k(r,`avatar large${e().badge?` admin`:``}`)),t}})}function jI(){let[e,{refetch:t}]=d(Mf,()=>Bf()),[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 Wf(f()||void 0)))}catch(e){c({ok:!1,text:U(e)})}};return n(vI,{id:`notifications`,label:`Notifications`,get children(){return[n(l,{get when(){return w()},get fallback(){return mF()},children:t=>[(()=>{var n=hF(),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=yF();return y(r,n(l,{get when(){return t().action===`enable`},get children(){var e=gF();return e.$$click=()=>void O(Hf,`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=_F();return e.$$click=()=>void O(Uf,`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=vF(),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=bF();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=xF();return y(t,()=>e().text),s(()=>k(t,e().ok?`small ok`:`small err`)),t})()})]}),n(l,{get when(){return E()},get children(){return[sF(),(()=>{var e=cF();return y(e,()=>be(E())),e})(),n(l,{get when(){return r(()=>!!w())()&&w().state!==`on`},get children(){return lF()}}),n(l,{get when(){return r(()=>`activity`in E()&&!E().activity)()&&!E().done},get children(){return uF()}}),n(m,{get each(){return qt.filter(e=>e.kinds.some(e=>e.key in E()))},children:e=>(()=>{var t=SF(),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=wF(),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=CF(),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=bF();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})()}),dF(),(()=>{var e=fF(),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=TF(),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 Pf().size},get children(){var e=pF(),t=e.firstChild;return y(e,()=>_n(Pf().size,`session`),t),e}})]}})]}})}function MI(){return n(vI,{id:`appearance`,title:`Appearance`,get children(){return[(()=>{var e=EF(),t=e.firstChild,r=t.firstChild.nextSibling,i=t.nextSibling.firstChild.nextSibling,a=i.nextSibling,o=a.nextSibling;return y(r,n(m,{each:CA,children:e=>(()=>{var t=OF(),n=t.firstChild;return t.$$click=()=>AA(e),y(t,e===`light`?`☀`:e===`dark`?`☾`:`▣`,n),y(n,()=>e[0].toUpperCase()+e.slice(1)),s(()=>b(t,`aria-checked`,OA()===e)),t})()})),i.$$input=e=>yA(Number(e.currentTarget.value)),b(i,`min`,eA),b(i,`max`,tA),b(i,`step`,nA),y(a,()=>uA(gA())),o.$$click=()=>yA(1),s(e=>{var t=uA(gA()),n=gA()===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=gA()),e})(),DF()]}})}var NI={low:`Low`,normal:`Normal`,high:`High`},PI={timers:`Timers (current)`,smart:`Smart Turn (experimental)`},FI={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`}},II=s_.flatMap(e=>FI[e.field]?[{...e,...FI[e.field],placeholder:String(i_[e.field])}]:[]);function LI(){let[e,t]=u(Sy.speed),[r,i]=u(Sy.sensitivity),[a,o]=u(Sy.turnDetection),[c,d]=u(Sy.smartTurn);return n(vI,{id:`voice`,title:`Voice`,get children(){var u=AF(),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=>{Sy.speed=Number(e.currentTarget.value),t(Sy.speed)},b(p,`min`,Ba),b(p,`max`,2),b(p,`step`,Va),y(h,()=>Ua(e())),y(_,n(m,{each:iy,children:e=>(()=>{var t=jF();return t.$$click=()=>{Sy.sensitivity=e,i(e)},y(t,()=>NI[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:n_,children:e=>(()=>{var t=jF();return t.$$click=()=>{Sy.turnDetection=e,o(e),p_({mode:e,load:Yg})},y(t,()=>PI[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=kF(),t=e.firstChild.nextSibling;return y(t,n(m,{each:II,children:e=>(()=>{var t=MF(),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=Sy.setSmartTurnKnob(e.key,t.currentTarget.value),d(Sy.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=c_(e.key,localStorage.getItem(e.key))??``),t})()})),e}}),null),w.addEventListener(`change`,e=>Sy.front=e.currentTarget.checked),E.addEventListener(`change`,e=>Sy.cues=e.currentTarget.checked),D.addEventListener(`change`,e=>Sy.background=e.currentTarget.checked),s(()=>b(p,`aria-valuetext`,Ua(e()))),s(()=>p.value=e()),s(()=>w.checked=Sy.front),s(()=>E.checked=Sy.cues),s(()=>D.checked=Sy.background),u}})}async function RI(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`)}fd()}function zI(){return n(l,{get when(){return Vl().length},get children(){return[NF(),(()=>{var e=PF();return y(e,n(m,{get each(){return Vl()},children:e=>(()=>{var t=FF(),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 RI(e,`approve`),s.$$click=()=>void RI(e,`deny`),t})()})),e})()]}})}function BI(){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(vI,{id:`machines`,title:`Machines`,get children(){return[(()=>{var e=IF(),t=e.firstChild.nextSibling;return t.$$click=()=>HP(),e})(),n(zI,{}),n(l,{get when(){return(Y.machines??[]).length},get fallback(){return LF()},get children(){var t=PF();return y(t,n(m,{get each(){return Y.machines},children:t=>(()=>{var n=RF(),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 VI(){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 kI();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(vI,{id:`devices`,title:`Devices`,get children(){return[(()=>{var e=zF(),t=e.firstChild.nextSibling;return t.$$click=()=>o(!0),e})(),n(l,{get when(){return a()},get children(){return n(UI,{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=BF();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?U(e.error):`Loading…`})()),t})()},get children(){var t=PF();return y(t,n(m,{get each(){return e()},children:e=>(()=>{var t=HF(),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 VF()}}),null),y(a,()=>R(e.lastSeen,N()),null),o.$$click=()=>void s(e),y(o,()=>e.current?`Sign out`:`Revoke`),t})()})),t}})]}})}var HI=2e3;function UI(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:Rk(t.expiresAt,e.headers.get(`date`),n)})}catch(e){a(U(e))}},f=()=>(t()?.expiresAt??0)<=o(),p=()=>{let e=t();return e?Qk(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=Lk(e.known,t);n&&(e.onLinked(t),q(`${n.name} linked`),e.onClose())}catch{}finally{h=!1}}},HI);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=BF();return y(e,()=>i()||`Creating a link code…`),e})()},children:e=>(()=>{var t=KF(),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=qF(),t=e.firstChild.nextSibling;return t.$$click=()=>void d(),e})()},get children(){return[(()=>{var e=UF(),t=e.firstChild.nextSibling;return s(n=>{var r=`0 0 ${p().size+8} ${p().size+8}`,i=$k(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=WF(),n=t.firstChild.nextSibling;return y(n,()=>Ik(e().expiresAt,o())),t})(),(()=>{var t=GF(),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 WI(){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(vI,{id:`add-app`,title:`Add the Hub app`,get children(){return[(()=>{var e=JF(),t=e.firstChild.nextSibling;return t.$$click=()=>void r(),e})(),n(l,{get when(){return e()},children:e=>n(UI,{get known(){return e()},onLinked:()=>{},onClose:()=>t(void 0)})})]}})}var GI=`/api/agent/team-settings`;function KI(){let[e,{mutate:t,refetch:i}]=d(()=>G(GI).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(GI,{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(vI,{id:`teams`,label:`Teams`,get children(){return[YF(),n(l,{get when(){return e()},get fallback(){return(()=>{var t=BF();return y(t,(()=>{var t=r(()=>!!e.error);return()=>t()?`Could not load: ${U(e.error)}`:`Loading…`})()),t})()},children:e=>(()=>{var t=XF(),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 qI=(e,t)=>Array.isArray(e)?e:Array.isArray(e?.[t])?e[t]:[],JI=e=>e.id===`local`?`Hub owner (pairing)`:e.name||e.email||e.id;function YI(){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(vI,{id:`admin`,label:`Admin`,get children(){return[(()=>{var i=ZF();return y(i,n(m,{get each(){return e()},children:([e,i])=>(()=>{var o=rI();return o.$$click=()=>(r(e),a(``)),y(o,i,null),y(o,n(l,{get when(){return e===`approvals`&&Vl().length},get children(){var e=nI();return y(e,()=>Vl().length),e}}),null),s(()=>b(o,`aria-pressed`,t()===e)),o})()})),i})(),n(l,{get when(){return i()},get children(){var e=QF();return y(e,i),e}}),n(l,{get when(){return t()===`users`},get children(){return n(XI,{change:o})}}),n(l,{get when(){return t()===`machines`},get children(){var e=$F();return y(e,n(ZI,{change:o})),e}}),n(l,{get when(){return t()===`approvals`},get children(){return[eI(),n(l,{get when(){return Vl().length},get fallback(){return iI()},get children(){return n(zI,{})}})]}}),n(l,{get when(){return t()===`audit`},get children(){var e=tI();return y(e,n(QI,{})),e}})]}})}function XI(e){let[t,{refetch:i}]=d(()=>G(`/api/admin/users`).then(e=>qI(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}),`${JI(t)}: ${n.label.toLowerCase()} done`)&&t.id===X()?.user?.id&&(Il(void 0),await Tu().catch(()=>!1)),i())};return(()=>{var e=aI(),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=bF();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=bF();return n.value=e,y(n,t),n})()})),y(e,n(l,{get when(){return t()},get fallback(){return(()=>{var e=oI();return y(e,(()=>{var e=r(()=>!!t.error);return()=>e()?`Could not load: ${lr(t.error)}`:`Loading…`})()),e})()},get children(){var e=PF();return y(e,n(m,{get each(){return sr(t(),{query:a(),filter:c(),sort:p()})},get fallback(){return sI()},children:e=>(()=>{var i=dI(),a=i.firstChild,o=a.firstChild,c=o.nextSibling,u=c.firstChild,d=u.nextSibling;return d.nextSibling,y(o,()=>JI(e),null),y(o,n(l,{get when(){return e.role===`admin`},get children(){return cI()}}),null),y(o,n(l,{get when(){return e.disabled},get children(){return lI()}}),null),y(o,n(l,{get when(){return e.id===X()?.user?.id},get children(){return uI()}}),null),y(a,n(l,{get when(){return r(()=>!!e.name)()&&e.email},get children(){var t=aF();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=fI();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 ZI(e){let[t,{refetch:i}]=d(()=>G(`/api/admin/machines`).then(e=>qI(e,`machines`)));return n(l,{get when(){return t()},get fallback(){return(()=>{var e=oI();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 pI()},get children(){var a=PF();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=mI(),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 QI(){let[e]=d(async()=>{let[e,t,n]=await Promise.all([G(`/api/admin/audit`),G(`/api/admin/users`).then(e=>qI(e,`users`),()=>[]),G(`/api/admin/machines`).then(e=>qI(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(qI(e,`audit`).length?qI(e,`audit`):qI(e,`entries`),r)});return n(l,{get when(){return e()},get fallback(){return(()=>{var t=oI();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 gI()},get children(){var t=hI();return y(t,n(m,{get each(){return e()},children:e=>(()=>{var t=_I(),n=t.firstChild,i=n.firstChild,a=i.nextSibling,o=n.nextSibling;return y(i,()=>e.action),y(a,()=>e.actor,null),y(a,(()=>{var t=r(()=>!!e.target);return()=>t()?` → ${e.target}`:``})(),null),y(a,(()=>{var t=r(()=>!!e.detail);return()=>t()?` · ${e.detail}`:``})(),null),y(o,()=>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 $I=I(`<a href=/settings/voice#recordings title="This conversation is recorded on this hub (Settings → Voice → Recording)"><span class=recording-dot aria-hidden=true>`),eL=I(`<span class="recording-note small"data-recording-note>`),tL=I(`<span class=sr-only role=status aria-live=polite data-recording-status>`);function nL(){let[e,t]=u(gl.get());return M(gl.subscribe(()=>t(gl.get()))),e}function rL(e){let t=nL(),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(gl.subscribe(()=>{let e=gl.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=$I();return e.firstChild,y(e,()=>_l(t()),null),s(n=>{var r=`recording-indicator${t().audio?``:` no-audio`}`,i=t().audio?`on`:`no-audio`,a=`${_l(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(()=>!(a()||!t().note))()&&i(t())},get children(){var e=eL();return y(e,()=>t().note),e}}),n(l,{get when(){return e.announce},get children(){var e=tL();return y(e,c),e}})]}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 aL(){let e=()=>rx().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,ix),y(t,n(rL,{announce:!0,get sessionID(){return e()}}),a),a.$$click=()=>void qb.end(),s(n=>{var i=`voice-pill ${rx().voice}`,a=`Voice mode is on in ${ix()}`,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 oL=`/api/agent/workspaces`,sL=50,cL=4e3,lL=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)},uL=e=>km(lL(e));function dL(){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=hm(await G(`${oL}?state=active&limit=${sL}`));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(uL(e)),t(`error`))}}async function _(e){p.set(e,Date.now()),s(e,e=>({...e??{},loading:!0}));try{let t=mm(await G(`${oL}/${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:uL(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)+cL-Date.now());m.set(e,setTimeout(()=>{m.delete(e),d().has(e)&&document.visibilityState!==`hidden`&&_(e)},t))}function b(){h||(h=!0,g(),hu(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(`${oL}/${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=vm(r,t);if(i)i!==`unchanged`&&S(e,{text:Dm(i),kind:`warn`});else{s(e,e=>({...e,saving:!0,notice:{text:`Saving: ${n}…`,kind:``}}));try{await T(e,t,Tm(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:uL(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=Om(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:uL(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 fL=ce(dL),pL=`hub.sidebar.sections.collapsed`;function mL(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 hL(e,t){let n=mL(e);n.has(t)?n.delete(t):n.add(t);try{e.setItem(pL,JSON.stringify([...n]))}catch{}return n}var gL=e=>e!==`results`;function _L(e,t,n){if(t&&gL(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 vL=I(`<button type=button class=side-section-toggle><span class=side-section-title>`),yL=I(`<div class=side-section-head>`),bL=I(`<span class=side-section-title>`),xL=I(`<span aria-hidden=true data-section-count>`),[SL,CL]=u(mL(localStorage)),wL=(e,t)=>gL(t)&&SL().has(e),TL=e=>`side-sec-${e.replace(/[^A-Za-z0-9_-]/g,`-`)}`;function EL(e){let t=()=>wL(e.id,e.kind),r=()=>_L(e.kind,e.count,t());return(()=>{var i=yL();return y(i,n(l,{get when(){return gL(e.kind)},get fallback(){return(()=>{var t=bL();return y(t,()=>e.title),t})()},get children(){var i=vL(),a=i.firstChild;return i.$$click=()=>CL(hL(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=xL();return y(n,()=>t().text),s(()=>k(n,`side-count${e.kind===`needs`?` needs`:``}`)),n})()}),null),s(n=>{var a=!t(),o=TL(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 DL=I(`<p class=side-empty>Workspaces are not available to this device.`),OL=I(`<p class=side-empty role=alert>Could not load workspaces: <!> <button type=button class=link-btn>Retry`),kL=I(`<ul class=ws-list>`),AL=I(`<section aria-label=Workspaces data-section=workspaces>`),jL=I(`<p class=ws-goal><span class=sr-only>Goal: `),ML=I(`<div class=ws-panel>`),NL=I(`<li><button type=button class=ws-head><span class=ws-title>`),PL=I(`<p class=ws-notice role=status aria-live=polite>`),FL=I(`<p class=side-empty role=alert>Could not load the board: <!> <button type=button class=link-btn>Retry`),IL=I(`<button type=button class=link-btn>Retry`),LL=I(`<p class=side-empty>Loading…`),RL=I(`<p class=side-empty>No members yet.`),zL=I(`<ul role=tree>`),BL=I(`<div>Drop here: no supervisor`),VL=I(`<p class=ws-keys>Drag to change supervision, or Alt+arrows. Supervision grants nothing.`),HL=I(`<p class=ws-keys>`),UL=I(`<span class="ws-rel ws-spawned"title="Native parent session (unchanged by supervision)">spawned by <a tabindex=-1>`),WL=I(`<span class="ws-rel ws-supervised"title="Workspace supervision link">supervised by `),GL=I(`<ul class=ws-assignments>`),KL=I(`<li role=treeitem><div class=ws-row><a class=ws-member tabindex=-1></a></div><p class=ws-meta>`),qL=I(`<span>`),JL=I(`<span class=ws-assignment-stale> · stale`),YL=I(`<li><span class=ws-assignment-title></span> <span class=ws-assignment-status>`),XL=I(`<ul>`),ZL=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.`),QL=I(`<p>Could not load your grants.`),$L=I(`<p>Loading…`),eR=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.`),tR=I(`<li> · <!> · <!> <span class=muted>(grant <!>)`),nR=new Set([`idle`,`working`,`blocked`,`error`]),rR={open:`open`,in_progress:`in progress`,blocked:`blocked`},iR={ArrowRight:`indent`,ArrowLeft:`outdent`,ArrowUp:`up`,ArrowDown:`down`};function aR(e){let t=fL;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=AL();return y(r,n(EL,{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 DL()}}),null),y(r,n(l,{get when(){return t.availability()===`error`},get children(){var e=OL(),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!wL(`workspaces`,`workspaces`)},get children(){var r=kL();return y(r,n(m,{get each(){return t.workspaces()},children:t=>n(oR,{ws:t,get onPick(){return e.onPick}})})),s(()=>b(r,`id`,TL(`workspaces`))),r}}),null),s(()=>k(r,`side-section ws-section${wL(`workspaces`,`workspaces`)?` collapsed`:``}`)),r}})}function oR(e){let t=fL,r=()=>t.expanded().has(e.ws.id),i=`ws-panel-${e.ws.id}`;return(()=>{var a=NL(),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=jL();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=ML();return b(t,`id`,i),y(t,n(lR,{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 sR=(e,t)=>{let n=e.members.find(e=>e.memberID===t);if(!n)return`a member`;let r=jm(Y.machines,n.sessionID);return r.found?r.title:n.session?.name??n.sessionID};function cR(e,t,n){let r=sR(e,t.memberID);return t.supervisorMemberID===null?`${r} has no supervisor`:n===`reorder`?`${r} reordered`:`${r} supervised by ${sR(e,t.supervisorMemberID)}`}function lR(e){let i=fL,o=()=>e.ws.id,c=()=>i.boards[o()],d=()=>c()?.board,f=C(()=>d()?_m(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,cR(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=wm(r,n.member.memberID,e);return a?j(a,e===`up`||e===`down`?`reorder`:`supervise`,!0):i.notify(o(),{text:`No move that way.`,kind:`warn`})}if(t.altKey||t.ctrlKey||t.metaKey)return;let s=t.key===`ArrowDown`?r.flat[a+1]:t.key===`ArrowUp`?r.flat[a-1]:t.key===`Home`?r.flat[0]:t.key===`End`?r.flat[r.flat.length-1]:void 0;s?(t.preventDefault(),D(s.member.memberID)):t.key===`Enter`&&t.target===t.currentTarget&&(t.preventDefault(),e.onPick?.(),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=wm(t,r,e);s&&!vm(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&&!vm(n,Cm(t,r,{memberID:e.member.memberID,position:`inside`})));if(a.length){i.push({section:`Supervised by`});for(let e of a)i.push({label:sR(n,e.member.memberID),run:()=>j(Cm(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=PL();return y(e,()=>c()?.notice?.text??``,null),y(e,n(l,{get when(){return c()?.notice?.pending},children:e=>(()=>{var t=IL();return t.$$click=()=>j(e(),`supervise`),t})()}),null),e})(),n(l,{get when(){return c()?.error},get children(){var e=FL(),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 LL()}})},children:u=>[n(l,{get when(){return!u().flat.length},get children(){return RL()}}),(()=>{var r=zL(),f=w;return typeof f==`function`?t(f,r):w=r,y(r,n(m,{get each(){return u().flat},children:t=>{let r=()=>jm(Y.machines,t.member.sessionID),c=()=>sR(d(),t.member.memberID),f=()=>t.supervisorMemberID?u().flat.find(e=>e.member.memberID===t.supervisorMemberID)?.children??[]:u().roots,p=()=>Mm(t,d(),Y.machines),x=()=>nR.has(t.member.session?.state??``)?t.member.session.state:`idle`,C=()=>d().workspace.state===`active`&&!i.boards[o()]?.saving;return(()=>{var i=KL(),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(Cm(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`,()=>{Yp(),_(void 0),S(void 0)}),i.addEventListener(`dragstart`,e=>{Jp(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 Pm(t.member,r())},children:e=>(()=>{var t=qL();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=UL(),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=WL();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=GL();return y(e,n(m,{get each(){return t.assignments},children:e=>(()=>{var t=YL(),r=t.firstChild,i=r.nextSibling.nextSibling;return y(r,()=>e.title),y(i,()=>rR[e.status]??e.status),y(t,n(l,{get when(){return e.stale?.length},get children(){var t=JL();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(uR,{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=BL();return e.addEventListener(`drop`,e=>{e.preventDefault();let t=g();_(void 0),S(void 0),t&&j(Cm(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=VL();return s(()=>b(e,`id`,`ws-keys-${o()}`)),e})(),n(l,{get when(){return u().staleLinks||d().membersTruncated||d().linksTruncated},get children(){var e=HL();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 uR(e){let t=fL,i=()=>{let n=t.grants();return Array.isArray(n)?Lm(n,e.supervisorSessionID,e.memberDirectory,Date.now()):n};return(()=>{var t=ZL(),a=t.firstChild.nextSibling;return y(t,n(l,{get when(){return i()!==`error`},get fallback(){return QL()},get children(){return n(l,{get when(){return Array.isArray(i())},get fallback(){return $L()},get children(){return n(l,{get when(){return i().length},get fallback(){return(()=>{var t=eR(),n=t.firstChild;return y(t,()=>e.supervisorTitle,n),t})()},get children(){var e=XL();return y(e,n(m,{get each(){return i()},children:e=>(()=>{var t=tR(),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 dR=I(`<nav aria-label=Primary><ul>`),fR=I(`<a>`),pR=I(`<li>`),mR=I(`<a class="side-link nav-link disabled"aria-disabled=true>`),hR=I(`<div class=nav-rail>`),gR=()=>({signedIn:!!X(),concierge:Xl()?.state});function _R(e){let t=()=>we(Pt().pathname);return(()=>{var r=dR(),i=r.firstChild;return y(i,n(m,{get each(){return Se(gR())},children:r=>(()=>{var i=pR();return y(i,n(l,{get when(){return r.enabled},get fallback(){return(()=>{var t=mR();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=fR();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 vR(e){return(()=>{var t=hR();return y(t,n(F,{icon:`sidebar`,label:`Show sidebar (⌘B)`,get onClick(){return e.onExpand}}),null),y(t,n(_R,{compact:!0}),null),t})()}z([`click`]);var yR=I(`<span class=concierge-btn-text>Concierge`),bR=I(`<span aria-hidden=true>`),xR=I(`<button type=button>`),SR=I(`<a href=/settings/concierge data-concierge-button=disabled data-indicator=off>`),CR;function wR(){let e=CR;return CR=void 0,e}function TR(e){let t=()=>dt().name===`concierge`,i=()=>e.labelled?yR():null,a=e=>n(l,{get when(){return e.indicator!==`running`},get children(){var t=bR();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 Xl()},children:r=>{let o=()=>Ys(r(),ru(),t(),Date.now(),Hs(Ul(),r(),{tiers:`all`}).length,new Set(Ul().filter(e=>e.state===`open`).map(e=>e.id)));return n(l,{get when(){return qs(r())===!0},get fallback(){return(()=>{var t=SR();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=xR();return c.$$click=n=>{if(e.onPick?.(),t())return St(`/`);CR=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 ER=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>`),DR=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>`),OR=I(`<p class=side-empty>`),kR=I(`<a class="icon-btn small">`),AR=I(`<ul class=side-list>`),jR=I(`<section>`),MR=I(`<span aria-hidden=true>`),NR=I(`<span class=account-name>`),PR=I(`<span class=badge title="Machines waiting for approval">`),FR=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`),IR=I(`<span class=jobs-badge>`),LR=I(`<span class=unread-dot role=img aria-label=Unread>`),RR=I(`<a class=side-row-link><span class=side-text><span class=side-title>`),zR=I(`<li>`),BR=I(`<span class=side-row-link>`),VR=I(`<span class=side-sub data-row-sub>`),HR=I(`<span class="waiting-since small">`),UR=`hub.sidebar.groupBy`,WR=`hub.sidebar.sort`;function GR(e){let[t,i]=u(``),[a,o]=u(localStorage.getItem(UR)===`machine`?`machine`:`project`),[c,d]=u(localStorage.getItem(WR)===`title`?`title`:`recent`),f=C(()=>ja(gu(),{query:t(),groupBy:a(),sortBy:c(),now:N()})),p=()=>{let e=WS();return e.name===`session`?e.id:void 0},h=()=>Jn(X()),g=(e,t)=>{e&&(o(e),localStorage.setItem(UR,e)),t&&(d(t),localStorage.setItem(WR,t))};return(()=>{var o=DR(),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(Pd,{class:`brand-mark`}),_),y(v,n(TR,{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(_R,{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 Ul().length},get children(){var t=ER(),n=t.firstChild.firstChild.firstChild,i=n.firstChild.nextSibling;return n.$$click=()=>e.phone&&e.onClose(),y(i,(()=>{var e=r(()=>Ul().length===1);return()=>e()?`A Decision waits for you`:`${Ul().length} Decisions wait for you`})()),s(()=>b(n,`href`,Hs(Ul(),Xl(),{tiers:`all`}).length===Ul().length?`/concierge`:`/`)),t}}),null),y(D,n(l,{get when(){return f().length},get fallback(){return(()=>{var e=OR();return y(e,()=>t()?`No sessions match.`:`No sessions yet.`),e})()},get children(){return n(m,{get each(){return f()},children:t=>(()=>{var i=jR();return y(i,n(EL,{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=kR();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!wL(t.id,t.kind)},get children(){var r=AR();return y(r,n(m,{get each(){return t.rows},children:t=>n(KR,{row:t,get active(){return p()===t.id},onPick:()=>e.phone&&e.onClose()})})),s(()=>b(r,`id`,TL(t.id))),r}}),null),s(e=>{var n=`side-section ${t.kind}${wL(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(aR,{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=MR();return y(e,()=>h().initial),s(()=>k(e,`avatar${h().badge?` admin`:``}`)),e})(),(()=>{var e=NR();return y(e,()=>h().title),e})(),n(l,{get when(){return Vl().length},get children(){var e=PR();return y(e,()=>Vl().length),e}}),n(L,{name:`settings`})]},items:()=>[{label:`Settings`,hint:Vl().length?`${Vl().length} to approve`:void 0,run:()=>{e.phone&&e.onClose(),Vt(`/settings`)}},{label:`Set up Hub on a machine`,run:()=>{e.phone&&e.onClose(),HP({returnTo:()=>document.querySelector(`.side-foot .account`)})}}]})),s(()=>S.value=t()),o})()}function KR(e){let t=()=>e.row,r=()=>rx().phase!==`off`&&rx().sessionID===t().id;return(()=>{var i=zR();return y(i,n(l,{get when(){return!Ch(t().id,`sidebar`)},get fallback(){return(()=>{var e=BR();return y(e,n(A,{get state(){return t().state}}),null),y(e,n(Ng,{get id(){return t().id},get title(){return t().title},place:`sidebar`,class:`side-title`,children:null}),null),e})()},get children(){var r=RR(),i=r.firstChild,a=i.firstChild;return B(r,`dragend`,Yp),r.addEventListener(`dragstart`,e=>Jp(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(),rx())},get children(){return n(ne,{})}}),i),y(a,()=>t().title),y(i,n(l,{get when(){return Ra(t())},children:e=>(()=>{var t=VR();return y(t,e),t})()}),null),y(r,n(Pg,{get id(){return t().id}}),null),y(r,n(l,{get when(){return za(t(),N())},children:e=>(()=>{var t=HR();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 FR()}}),null),y(r,n(l,{get when(){return t().jobs},get children(){var e=IR();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 LR()}}),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:()=>Th(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 qR={cycle:`F6`,close:`Control+Alt+W`,moveEarlier:`Control+Alt+Shift+ArrowLeft`,moveLater:`Control+Alt+Shift+ArrowRight`,focus:e=>`Control+Alt+${e}`},JR=new Set([`ArrowLeft`,`ArrowUp`]),YR=new Set([`ArrowRight`,`ArrowDown`]);function XR(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 JR.has(e.key)?{type:`move`,step:-1}:YR.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 ZR=`hub.paneSizes.v1`,QR={cols:280,rows:160},$R=[`vertical`,`horizontal`,`grid`];function ez(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 tz(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 nz(e){return e>0?Array.from({length:e},()=>1/e):[]}function rz(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 rz(e,t,s,i,a);if(n===l)return rz(e,t,-s,i,a);if(n===`Home`)return rz(e,t,-2*i,i,a);if(n===`End`)return rz(e,t,2*i,i,a)}var az=(e,t,n)=>`${e}:${t}:${n}`;function oz(e){let[t,n,r,...i]=e.split(`:`),a=Number(n);if(i.length||!$R.includes(t)||!Number.isInteger(a)||a<2||a>gn||r!==`cols`&&r!==`rows`)return;let o=ez(t,a)[r];return o>1?o:void 0}function sz(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 cz(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=oz(e),i=n===void 0?void 0:sz(t,n);i&&(r[e]=i)}return r}function lz(e,t,n,r,i,a){let o=az(n,r,i),s=oz(o),c=s===void 0?void 0:sz(a,s);if(!c)return t;let l={...t,[o]:c};try{e?.setItem(ZR,JSON.stringify({v:1,sizes:l}))}catch{}return l}function uz(e,t,n){let r=ez(t,n),i=i=>{let a=e[az(t,n,i)];return a&&a.length===r[i]?a:nz(r[i])};return{cols:i(`cols`),rows:i(`rows`)}}function dz(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 fz=200,pz=10,mz=e=>e instanceof Error?e.message:String(e),hz=e=>e&&typeof e==`object`&&typeof e.status==`number`?e.status:void 0,gz=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=_z(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=mz(t),this.invalid=hz(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=mz(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=_z(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<pz;e++){let e=await this.fetch({limit:fz,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 _z(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 vz=[`native`,`hooks`,`rpc`,`screen`],yz={opencode:`OpenCode`,"claude-code":`Claude Code`,codex:`Codex`},bz=e=>yz[e]??e;function xz(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=vz.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:bz(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 Sz={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 Cz(e){if(e.native)return;let t=Sz[e.evidence];return{level:e.evidence,label:t.label,detail:t.detail(e.harnessName)}}function wz(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 Tz(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 Ez={queued:`queued`,retained:`held`,pending:`pending`,dropped:`not delivered`};function Dz(e){return typeof e==`string`?Ez[e]:void 0}function Oz(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 kz=/data:([\w.+-]+\/[\w.+-]+)?((?:;[\w.+-]+=[^;,\s"'<>]*)*);base64,([A-Za-z0-9+/_-]+={0,2})/gi,Az=/^[A-Za-z0-9+/_-]+={0,2}$/,jz=[`mime`,`mimeType`,`media_type`,`mediaType`];function Mz(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 Nz(e,t){return`[${e||`data`}, ${Mz(t)} — not shown]`}function Pz(e){return e.includes(`base64,`)?e.replace(kz,(e,t,n,r)=>Nz(t?.toLowerCase(),r)):e}function Fz(e){if(typeof e.data!=`string`||!Az.test(e.data))return;let t=jz.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 Iz(e){return Lz(e)}function Lz(e){if(typeof e==`string`)return Pz(e);if(Array.isArray(e))return e.map(Lz);if(!e||typeof e!=`object`)return e;let t=e,n=Fz(t),r={};for(let[e,i]of Object.entries(t))r[e]=e===`data`&&n?Nz(n,i):Lz(i);return r}var Rz=(e,t,n)=>`/api/sessions/${encodeURIComponent(e)}/timeline/messages/${encodeURIComponent(t)}/files/${n}`,zz=(e,t,n)=>`/api/sessions/${encodeURIComponent(e)}/timeline/messages/${encodeURIComponent(t)}/media/${encodeURIComponent(n)}`,Bz=e=>typeof e==`number`&&Number.isInteger(e)&&e>0,Vz=e=>Mn.includes(e),Hz=(e,t)=>typeof e==`string`&&Dn(e)?.kind===t;function Uz(e,t,n,r){let i=zz(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}:{},...Bz(n.width)&&Bz(n.height)?{width:n.width,height:n.height}:{}}}var Wz=e=>typeof e.sessionID==`string`&&typeof e.messageID==`string`,Gz=(e,t)=>typeof e.name==`string`&&e.name?e.name:t;function Kz(e,t,n){let r=n?`tool`:`path`,i=e.media;if(!Array.isArray(i)||!Wz(e))return[];let a=[];for(let o of i){if(a.length>=Nn.perRow)break;o&&Hz(o.ref,r)&&typeof o.mime==`string`&&Vz(o.mime)&&a.push({...Uz(e,`${e.key}:${o.ref}`,o,Gz(o,t)),...n?{tool:!0}:{}})}return a}function qz(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=Gz(n,n.mime.startsWith(`image/`)?`image`:`file`);if(n.ref!==void 0){Hz(n.ref,`file`)&&Vz(n.mime)&&Wz(e)?t.push(Uz(e,r,n,i)):t.push({key:r,name:i,mime:n.mime});continue}let a=S_(n.mime)&&Wz(e);t.push({key:r,name:i,mime:n.mime,...a?{src:Rz(e.sessionID,e.messageID,n.index)}:{}})}return t}function Jz(e,t={}){let n=[];for(let r of e)if(!((r.depth??0)>0))switch(r.kind){case`user`:{let e=qz(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=Kz(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=Kz(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(Qz(r));break;case`error`:n.push(r.declined===!0?{type:`error`,key:r.key,label:`${t.denied?.(r)??`Denied`}: the turn stopped`,denied:!0}:Xz(r));break;case`retry`:n.push({type:`retry`,key:r.key,...Yz(`attempt`,r.attempt),...Yz(`next`,r.next),...typeof r.errorType==`string`?{errorType:r.errorType}:{},...Yz(`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 Yz=(e,t)=>typeof t==`number`&&Number.isFinite(t)?{[e]:t}:{};function Xz(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 Zz(e,t){return{text:Li(e,t),waiting:Mi(e.next,t)!==void 0}}function Qz(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=Dz(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 $z=`The provider returned this thought redacted: an encrypted signature, no readable text.`;function eB(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…`:$z,muted:!0}}function tB(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 nB(e,t){return JSON.stringify(Iz(e??{summary:t.summary||void 0,error:t.error}),null,2)}var rB=I(`<p class=composer-error role=alert>`),iB=I(`<p class="composer-hint muted small">`),aB=I(`<li class="attachment busy"aria-label="Preparing image"><span class="spinner small">`),oB=I(`<ul class=attachments aria-label="Attached images">`),sB=I(`<div><button type=button class=split-main>`),cB=I(`<button type=button class="btn stop"aria-label="Stop the session and its subagents"> Stop`),lB=I(`<span class=sr-only>`),uB=I(`<button type=button class=model-chip title="Voice model (the voice front you talk to in Voice mode)">Voice: `),dB=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>`),fB=I(`<li class=attachment><img><button type=button class=attachment-remove title=Remove>`),pB=I(`<span class="spinner small">`),mB=I(`<button type=button class="session-model pickable"aria-haspopup=dialog><span class=chip-key>Model: `),hB=I(`<span class=session-model><span class=chip-key>Model: `),gB=I(`<button type=button class=split-chev aria-label="Choose microphone"aria-haspopup=dialog>`),_B=I(`<p class="error small pad">`),vB=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>`),yB=I(`<button type=button class=menu-item role=menuitemradio><span class=menu-check></span><span class=menu-label>`),bB=I(`<span class=muted> · “<!>…”`),xB=I(`<span class=voice-ignored title="Heard as background noise, not sent"> · ignored: “<!>”`),SB=I(`<span class="voice-turn muted"title="Smart Turn (experimental): how sure the model is that you finished your turn"> · `),CB=I(`<span class="chip voice-front"title="Voice front: a fast voice agent answers and relays to the session">front`),wB=I(`<p class="voice-hint voice-front-fallback small"role=status>`),TB=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`),EB=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`),DB=I(`<span>`);function OB(e){let r,i,[a,o]=u(!1),c=()=>e.images.length>=__.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=dB(),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=gS(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=rB();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=oB();return y(t,n(m,{get each(){return e.images},children:t=>(()=>{var r=fB(),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 aB()}}),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=gS(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 pB()},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=sB(),r=t.firstChild;return B(r,`click`,e.onVoice,!0),y(r,n(L,{name:`wave`})),y(t,n(kB,{}),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=cB(),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=lB();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=hB();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=mB();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=uB();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=g_.join(`,`),o=c()?`At most ${__.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 kB(){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 Ay(Fy(),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 ky().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=gB();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=vB(),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=yB(),r=n.firstChild,i=r.nextSibling;return n.$$click=()=>{Ly(e.deviceId),S()},y(r,()=>Fy()===e.deviceId?`✓`:``),y(i,()=>e.label||`Microphone ${t()}`),s(()=>b(n,`aria-checked`,Fy()===e.deviceId)),n})()}),r),y(e,n(l,{get when(){return f()},get children(){var e=_B();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 AB={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 jB(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 MB(e){let t=()=>e.state===`listening`&&e.working?`Thinking`:AB[e.state],r=[.5,.8,1,.7,.45];return(()=>{var i=EB(),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=DB();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=bB(),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=xB(),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=SB();return t.firstChild,y(t,()=>e.turn,null),t}}),null),y(i,n(l,{get when(){return e.front?.on},get children(){return CB()}}),u),y(i,n(rL,{announce:!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=wB();return y(e,Eb),e}}),null),y(i,n(l,{get when(){return e.notifyHint},get children(){var t=TB(),n=t.firstChild.nextSibling;return n.$$click=()=>e.onAllowNotifications?.(),t}}),null),s(t=>{var n=`voice-bar ${e.state}`,r=e.detector?.mode,a=jB(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 NB=e=>e===`voice`?`Voice model`:`Session model`,PB=()=>({query:``,active:0}),FB=e=>[void 0,...(e.variants??[]).filter(e=>e!=="default")];function IB(e,t,n=100){if(t.chosen)return{mode:`variants`,model:t.chosen,rows:FB(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 LB=(e,t)=>({...e,query:t,active:0}),RB=(e,t)=>({providerID:e.providerID,modelID:e.modelID,...t?{variant:t}:{}});function zB(e,t,n){let r=IB(e,t);if(r.mode===`variants`)return n<0||n>=r.rows.length?{state:t}:{state:t,pick:RB(r.model,r.rows[n])};let i=r.rows[n];return i?FB(i).length>1?{state:{...t,chosen:i,active:0}}:{state:t,pick:RB(i)}:{state:t}}function BB(e,t,n,{inSearch:r}){let i=IB(e,t).rows.length;if(n===`ArrowDown`||n===`ArrowUp`)return{state:{...t,active:Math.max(0,XS(t.active,n===`ArrowDown`?1:-1,i))},handled:!0};if(n===`Enter`)return{...zB(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}:{...zB(e,t,r),handled:!0}}return{state:t,handled:!1}}var VB=(e,t)=>({[e]:t}),HB={chosen:`chosen for this session`,reply:`the default model (its latest reply ran on it)`,default:`the default model (no reply yet)`},UB=e=>typeof e==`string`&&e.length>0;function WB(e){let t=e;return typeof t==`object`&&!!t&&UB(t.providerID)&&UB(t.modelID)}var GB=`. Click to change the session's model`;function KB(e,t={}){let n=t.pickable?GB:``;if(!WB(e))return{label:`Model: default`,title:`Model: default (not known yet: it shows once the session has run)${n}`};let r=UB(e.variant)?` · ${e.variant}`:``,i=UB(e.name)?e.name:void 0,a=UB(e.source)?HB[e.source]:void 0;return{label:`Model: ${i??e.modelID}${r}`,title:`Model: ${e.providerID}/${e.modelID}${r}${i?` (${i})`:``}${a?`, ${a}`:``}${n}`}}function qB(e){if(WB(e)&&e.source===`chosen`)return{providerID:e.providerID,modelID:e.modelID,...UB(e.variant)?{variant:e.variant}:{}}}var JB=e=>({model:e}),YB=I(`<div>`),XB=I(`<p class="error small"role=alert>Couldn't load models: `),ZB=I(`<p class="muted small">Loading models…`),QB=I(`<input type=search class=picker-search placeholder="Search models"aria-label="Search models"autofocus>`),$B=I(`<p class="muted small"role=status>`),eV=I(`<ul class=picker-list role=listbox aria-label=Models>`),tV=I(`<li class="muted small">No models match.`),nV=I(`<div class="picker-group muted small">`),rV=I(`<span class="po-id muted">variants ›`),iV=I(`<span class=po-mark>✓`),aV=I(`<kbd>`),oV=I(`<li><button type=button role=option><span class=po-name></span><span class="po-id muted">`),sV=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>`),cV=I(`<li><button type=button role=option><span class=po-name></span><kbd>`);function lV(e,t){let n=e?.prefs[t]??e?.defaults[t];return n?`${n.modelID}${n.variant?` · ${n.variant}`:``}`:`default`}function uV(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:VB(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:JB(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 dV(t){let[i,a]=u(PB()),[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(PB()),f(``),t.models.loadCatalog().then(c,e=>f(U(e)))},v=C(()=>o()?IB(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(zB(o(),i(),e)),T=e=>{if(!o()||e.altKey||e.ctrlKey||e.metaKey)return;let t=BB(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 NB(t.kind??`voice`)},get onClose(){return t.onClose},class:`picker`,get children(){var e=YB();return e.$$keydown=T,y(e,n(l,{get when(){return!d()},get fallback(){return(()=>{var e=XB();return e.firstChild,y(e,d,null),e})()},get children(){return n(l,{get when(){return v()},get fallback(){return ZB()},children:e=>n(l,{get when(){return r(()=>e().mode===`models`)()&&e()},get fallback(){return n(fV,{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=QB();return e.$$input=e=>a(t=>LB(t,e.currentTarget.value)),s(()=>e.value=i().query),e})(),(()=>{var t=$B();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=eV();return y(t,n(m,{get each(){return e().rows},get fallback(){return tV()},children:(t,r)=>(()=>{var a=oV(),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=nV();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 rV()}}),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=aV();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 fV(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=sV(),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=cV(),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 pV=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;function mV(e){let t=[],n=0,r=0,i=!1;for(let a of String(e??``).replace(/\r\n?/g,`
29
- `).split(`
30
- `)){let e=pV.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 hV=new Set([`user`,`launch`,`self`,`prompt`,`title`]),gV=e=>`/api/agent/sessions/${encodeURIComponent(e)}/intent`,_V=e=>e.replace(/\s+/g,` `).trim();function vV(e){let t=Array.from(_V(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 yV=(e,t)=>({text:e===null?null:_V(e),expectedRevision:t});function bV(e){if(e?.source===`user`)return{text:null,expectedRevision:e.revision};if(e?.source===`prompt`)return{source:`prompt`,text:null,expectedRevision:e.revision}}function xV(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 SV(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`||!hV.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 CV(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 wV(e,t,n){return e.type===`intent`&&e.sessionID===t&&e.revision!==n}var TV=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`),EV=I(`<div class=intent-field>`),DV=I(`<button type=button class="btn small">Retry`),OV=I(`<button type=button class="btn small">Clear`),kV=I(`<div class=row><button type=button class="btn small">Edit`),AV=I(`<p class="muted small intent-error">Could not load the intent.`),jV=I(`<p class="muted small">Loading…`),MV=I(`<p class="muted small">No intent yet.`),NV=I(`<p class="small intent-text">`),PV=I(`<p class="muted small">`),FV=I(`<p class=field-error>`);function IV(e){let[i,{refetch:a,mutate:o}]=d(()=>e.sessionID,async e=>SV(await G(gV(e)))),[c,f]=u(!1),[p,m]=u(``),[h,g]=u(!1),[_,v]=u(``),x=()=>vV(p()),S=()=>i.error?void 0:i.loading?i.latest:i();M(hu(t=>{!c()&&wV(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?bV(S()):yV(t,S()?.revision??0);if(n){g(!0),v(``);try{let t=SV(await(await V(gV(e.sessionID),{method:`PUT`,json:n})).json());i.error?a():o(t),f(!1)}catch(e){let t=CV(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=EV();return y(o,n(l,{get when(){return c()},get fallback(){return[n(l,{get when(){return!i.error},get fallback(){return AV()},get children(){return n(l,{get when(){return!i.loading||S()},get fallback(){return jV()},get children(){return n(l,{get when(){return S()},get fallback(){return MV()},children:e=>[(()=>{var t=NV();return y(t,()=>e().text),t})(),(()=>{var t=PV();return y(t,()=>xV(e())),t})()]})}})}}),(()=>{var e=kV(),t=e.firstChild;return t.$$click=C,y(e,n(l,{get when(){return i.error},get children(){var e=DV();return e.$$click=()=>void a(),e}}),null),y(e,n(l,{get when(){return bV(S())},get children(){var e=OV();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=TV(),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=FV();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=FV();return y(t,e),t})()}),null),o})()}z([`input`,`keydown`,`click`]);var LV=e=>`/api/agent/subscriptions?session=${encodeURIComponent(e)}`,RV=e=>`/api/agent/subscriptions/${encodeURIComponent(e)}`,zV=e=>typeof e==`string`,BV=e=>typeof e==`number`&&Number.isFinite(e)?e:0;function VV(e){let t=e;if(t&&typeof t==`object`){if(t.kind===`children`)return{kind:`children`};if(t.kind===`session`&&zV(t.sessionID)&&zV(t.addr))return{kind:`session`,sessionID:t.sessionID,addr:t.addr};if((t.kind===`role`||t.kind===`team`)&&zV(t.addr))return{kind:t.kind,addr:t.addr}}}function HV(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`||!zV(t.id)||!zV(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(VV).filter(e=>e!==void 0),types:t.types.filter(zV),delivery:zV(t.delivery)?t.delivery:`queue`,batchMs:BV(t.batchMs),expiresAt:BV(t.expiresAt),pending:BV(t.pending),stats:{delivered:BV(r.delivered),dropped:BV(r.dropped),suppressed:BV(r.suppressed)}})}return n}function UV(e,t){return{listensTo:e.filter(e=>e.subscriber===t),listenedBy:e.filter(e=>e.subscriber!==t)}}function WV(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 GV(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 ${WV(e.expiresAt-t)}`),{title:n,detail:r.join(` · `)}}var KV=I(`<ul class=subscription-list>`),qV=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`),JV=I(`<p class="small subscription-head">Listens to`),YV=I(`<p class="small subscription-head">Listened to by`),XV=I(`<div class=subscriptions-field><div class=row><button type=button class="btn small">Refresh`),ZV=I(`<p class="muted small">Could not load the subscriptions.`),QV=I(`<p class="muted small">Loading…`),$V=I(`<p class="muted small">None. An agent follows other sessions with hub subscribe.`);function eH(e){let[t,{refetch:r}]=d(()=>e.sessionID,async e=>HV(await G(LV(e)))),[i,a]=u(``),o=()=>UV(t.error?[]:t.latest??[],e.sessionID),c=async e=>{if(!i()){a(e.id);try{await V(RV(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=KV();return y(t,n(m,{get each(){return e.items},children:t=>{let n=()=>GV(t,Date.now());return(()=>{var r=qV(),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=XV(),i=e.firstChild,a=i.firstChild;return y(e,n(l,{get when(){return!t.error},get fallback(){return ZV()},get children(){return n(l,{get when(){return!t.loading||t.latest},get fallback(){return QV()},get children(){return n(l,{get when(){return o().listensTo.length||o().listenedBy.length},get fallback(){return $V()},get children(){return[n(l,{get when(){return o().listensTo.length},get children(){return[JV(),n(f,{get items(){return o().listensTo},who:e=>GV(e,Date.now()).title})]}}),n(l,{get when(){return o().listenedBy.length},get children(){return[YV(),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 tH=I(`<div class=context-cards>`),nH=I(`<p class="muted small">Could not load the context cards. <button type=button class="btn small">Retry`),rH=I(`<p class="muted small">Loading…`),iH=I(`<p class="muted small context-cards-off">`),aH=I(`<article><header class=context-card-head><span class=context-card-title></span><button type=button class="btn small">`),oH=I(`<p class="muted small">No card yet.`),sH=I(`<p class=context-card-headline>`),cH=I(`<p class="small context-card-body">`),lH=I(`<dl class="kv context-card-fields">`),uH=I(`<p class="muted small context-card-meta">`),dH=I(`<dt>`),fH=I(`<dd>`),pH=I(`<p class="muted small context-card-note">`);function mH(e){let[t,{refetch:r}]=d(()=>e.sessionID,async e=>{let t=pk(await G(ik(e)));for(let e of t.cards)Tk(e);return t}),[i,a]=u(),[o,s]=u({});M(hu(t=>{vk(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(ak(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=_k(i),o=fk(i.card);o&&Tk(o),s(e=>({...e,[t]:a??``})),await r()}catch(e){s(n=>({...n,[t]:U(e)}))}finally{a(void 0)}}};return(()=>{var e=tH();return y(e,n(l,{get when(){return!t.error},get fallback(){return(()=>{var e=nH(),t=e.firstChild.nextSibling;return t.$$click=()=>void r(),e})()},get children(){return n(l,{get when(){return c()},get fallback(){return rH()},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(hH,{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 hH(e){return(()=>{var t=aH(),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 oH()},children:e=>[(()=>{var t=sH();return y(t,()=>e().headline),t})(),n(l,{get when(){return e().body},get children(){var t=cH();return y(t,()=>e().body),t}}),n(l,{get when(){return e().fields?.length},get children(){var t=lH();return y(t,n(m,{get each(){return e().fields},children:e=>[(()=>{var t=dH();return y(t,()=>e.label),t})(),(()=>{var t=fH();return y(t,()=>e.value),t})()]})),t}}),(()=>{var t=uH();return y(t,()=>hk(e(),N())),t})()]}),null),y(t,n(l,{get when(){return e.note},children:e=>(()=>{var t=pH();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 gH=e=>Array.isArray(e)?e.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`string`):[],_H=e=>typeof e==`string`?e:``,vH=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,yH=new Set([`working`,`blocked`]),bH=e=>Ir[_H(e.state)]??Ir.idle;function xH(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)):bH(r)<bH(n[e])&&(n[e]=r)}return n}function SH(e,t,n){let r=xH(gH(t)),i=e=>{let t=[],n=new Set([e]);for(let e=!0;e;){e=!1;for(let i of r)n.has(_H(i.parentID))&&!n.has(i.id)&&(n.add(i.id),t.push(i),e=!0)}return t},a=new Map;for(let e of gH(n)){let t=vH(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=>_H(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=>vH(e.since)).filter(e=>e!==void 0);o.push({id:t.id,title:_H(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 gH(n)){if(t.parentID!==e||s.has(t.id))continue;s.add(t.id);let n=_H(t.state),r=n===`working`||n===`blocked`||n===`error`?n:`idle`;o.push({id:t.id,title:_H(t.title)||`Subagent`,state:r,nested:0,order:o.length})}let c=({order:e,...t})=>t,l=o.filter(e=>yH.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=>!yH.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 CH(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 wH={working:`Running`,blocked:`Needs you`,error:`Error`,idle:`Done`};function TH(e,t){let n=[wH[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 EH=I(`<section><h3><button type=button class=card-toggle><span>`),DH=I(`<li><a><span class=subagent-text><span class=subagent-title></span><span class="muted small">`),OH=I(`<ul class=job-list>`),kH=I(`<ul class=subagent-list>`),AH=I(`<button type=button class="subagents-more small">`),jH=I(`<ul class=mcp-list>`),MH=I(`<aside class=rail aria-label="Session details"><div class=rail-head><span class=rail-title>Details`),NH=I(`<p class="rail-error small"><strong>`),PH=I(`<p class="muted small">`),FH=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>`),IH=I(`<span class=muted>`),LH=I(`<p class="small retry-note">`),RH=I(`<li><span aria-hidden=true></span><span class="job-command mono"></span><span class="muted small">`),zH=I(`<div class=meter role=meter aria-valuemin=0 aria-valuemax=100 aria-label="Context used"><span>`),BH=I(`<p class=small><strong></strong><span class=muted> `),VH=I(`<li><span aria-hidden=true></span><span class=mcp-name></span><span class="muted small">`),HH=I(`<span class=diffstat><span class=add>+</span> <span class=del>−`),UH=I(`<ul class=file-list>`),WH=I(`<p class="muted small">No changes.`),GH=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>−`),KH=I(`<p class="muted small more-files">+<!> more <!> (only the most-changed files are listed)`),qH=I(`<table class=diff><tbody>`),JH=I(`<p class="muted small pad">The diff is too large to show completely (512 KB).`),YH=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>`),XH=I(`<option>`),ZH=I(`<p class="muted small pad">Loading diff…`),QH=I(`<p class="muted small pad">`),$H=I(`<p class="muted small pad">No textual changes (binary file, or a rename).`),eU=I(`<tr><td class=ln></td><td class=ln></td><td class=code-line><span class=sign>`),tU=e=>e.truncated&&e.totalFiles?Math.max(0,e.totalFiles-e.files.length):0,[nU,rU]=u(oS(localStorage));function iU(e){let t=()=>!nU().has(e.id);return(()=>{var r=EH(),i=r.firstChild,a=i.firstChild,o=a.firstChild;return a.$$click=()=>rU(sS(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 aU=e=>e>=1e3?`${(e/1e3).toFixed(e>=1e5?0:1)}k`:String(e);function oU(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?SH(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=DH(),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,()=>TH(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} (${TH(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=MH(),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=NH(),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=PH();return y(e,()=>Y.machines?`Not reported by any connected machine.`:`Loading…`),e})()},children:e=>(()=>{var a=FH(),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=IH();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(IV,{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=LH();return y(t,e),t})()}),(()=>{var e=OH();return y(e,n(m,{get each(){return c()},children:e=>(()=>{var t=RH(),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 CH(g())},label:`Subagents`,get children(){return[(()=>{var e=kH();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=AH();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(mH,{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(eH,{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=PH();return y(e,()=>t.loading?`Loading…`:`No usage reported yet.`),e})()},children:e=>[(()=>{var t=zH(),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=BH(),n=t.firstChild,i=n.nextSibling;return i.firstChild,y(n,(()=>{var t=r(()=>e().percent!==void 0);return()=>t()?`${e().percent}%`:aU(e().used)})()),y(i,(()=>{var t=r(()=>!!e().limit);return()=>t()?`${aU(e().used)} / ${aU(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=PH();return y(e,()=>t.loading?`Loading…`:`No MCP servers.`),e})()},get children(){var e=jH();return y(e,n(m,{get each(){return t.summary.mcp},children:e=>(()=>{var t=VH(),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=HH(),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=PH();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 WH()},get children(){return[(()=>{var r=UH();return y(r,n(m,{get each(){return e().files},children:e=>(()=>{var n=GH(),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 tU(e())},children:e=>(()=>{var t=KH(),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 sU(e){let[t]=d(()=>e.file,async t=>G(`${H(e.sessionID)}/diff?file=${K(t)}`)),[i,a]=u(!1);return(()=>{var o=YH(),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=XH();return t.value=e,y(t,e),t})()})),y(c,n(l,{get when(){return t()},children:e=>(()=>{var t=HH(),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 ZH()},get children(){return n(l,{get when(){return!t.error},get fallback(){return(()=>{var e=QH();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 $H()},get children(){return[(()=>{var e=qH(),i=e.firstChild;return y(i,n(m,{get each(){return mV(t().patch).filter(e=>e.type!==`meta`)},children:e=>(()=>{var t=eU(),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 JH()}})]}})}})}})),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 cU(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 lU(e,t){return e&&(e.type===`number`||e.type===`integer`)&&typeof t==`string`&&t.trim()?Number(t):typeof t==`string`?t.trim():t}function uU(e,t){let n=new Map(e.map(e=>[e.key,e]));return e.filter(e=>(e.when??[]).every(e=>{let r=lU(n.get(e.key),t[e.key])===e.value;return e.op===`eq`?r:!r}))}var dU=e=>typeof e==`string`?e.trim():``;function fU(e,t){let n={};for(let r of uU(e,t)){let e=pU(r,t[r.key]);e&&(n[r.key]=e)}return n}function pU(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=dU(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=dU(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 mU(e,t){let n={};for(let r of uU(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=dU(e);if(!t)continue;n[r.key]=r.type===`number`||r.type===`integer`?Number(t):t}}}return n}var hU=I(`<p class="muted small"data-answer-unavailable> can't take this answer from the hub; answer it in the terminal.`),gU=I(`<p class="blocker-recommendation small"data-recommendation>`),_U=I(`<p class=blocker-text>`),vU=I(`<div role=group><p class=blocker-head><strong>`),yU=I(`<p class="muted small">This question has nothing to fill in here; answer it in the terminal.`),bU=I(`<p class="answered-by small muted"data-answered-by>`),xU=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`),SU=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`),CU=I(`<p class="field-error small"role=alert>`),wU=I(`<div>`),TU=I(`<span class=field-title>`),EU=I(`<span class="field-desc muted small">`),DU=I(`<a class="btn small"target=_blank rel="noopener noreferrer">Open link`),OU=I(`<label class=check><input type=checkbox>`),kU=I(`<input type=text placeholder="Other (comma separated)">`),AU=I(`<div role=group class=choice-group>`),jU=I(`<input type=text placeholder="Type your own answer">`),MU=I(`<div role=radiogroup class=choice-group>`),NU=I(`<label class=text-field>`),PU=I(`<input type=text>`),FU=I(`<span class="muted small"> — `),IU=I(`<label class=choice><input type=checkbox><span>`),LU=I(`<label class=choice><input type=radio><span>`);function RU(e,t){return!(e instanceof W)||e.status!==409||e.code!==`gone`?!1:(q(`Already answered or expired`),t(),!0)}function zU(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=vU(),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 yU()},get children(){return[n(o,{get when(){return e.canAnswer===!1},get children(){return[n(tg,{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=hU(),n=t.firstChild;return y(t,()=>e.harnessName??`This harness`,n),t})()]}}),n(o,{get when(){return a().kind===`permission`},get children(){return[n(tg,{class:`blocker-text mono`,get text(){return a().summary},what:`the request`,reveal:!0}),n(l,{get when(){return Dt(a().recommendation,Su)},get children(){var e=gU();return y(e,()=>Dt(a().recommendation,Su)),e}}),n(BU,{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=_U();return y(e,()=>a().summary),e}}),n(VU,{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(su(),a().id,Su,pu)},children:e=>(()=>{var t=bU();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 BU(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){RU(t,e.onGone)||q(Oz(t)??U(t),`err`),n(!1)}};return(()=>{var e=xU(),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 VU(e){let[t,r]=u(cU(e.fields)),[i,a]=u({}),[o,c]=u(!1),[d,f]=u(!1),p=C((n=[])=>{let r=uU(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){RU(t,e.onGone)||q(Oz(t)??U(t),`err`),c(!1)}},v=n=>{n.preventDefault();let r=fU(e.fields,t());if(a(r),Object.keys(r).length)return;let i=mU(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=SU(),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=wU();return b(o,`data-key`,r),y(o,n(HU,{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=CU();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 HU(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=TU();return y(e,a,null),y(e,()=>t().required?` *`:``,null),e})(),n(l,{get when(){return t().description},get children(){var e=EU();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=DU();return s(()=>b(e,`href`,t().url)),e})()]}}),n(o,{get when(){return t().type===`boolean`},get children(){var t=OU(),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=AU();return y(r,n(f,{}),null),y(r,n(m,{get each(){return t().options??[]},children:t=>(()=>{var r=IU(),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=FU();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=kU();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=MU();return y(r,n(f,{}),null),y(r,n(m,{get each(){return t().options??[]},children:t=>(()=>{var r=LU(),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=FU();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=jU();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=NU();return y(e,n(f,{})),s(()=>b(e,`for`,i())),e})(),(()=>{var n=PU();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 UU=I(`<span class=file-chip> `),WU=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>`),GU=I(`<div class=pill>`),KU=I(`<p class="msg-note muted small"data-answered-note>`),qU=I(`<div><div class=user-body>`),JU=I(`<div class=msg-images>`),YU=I(`<div class=msg-tools role=toolbar aria-label="Copy, fork, revert">`),XU=I(`<span>`),ZU=I(`<div class=transcript aria-label=Conversation>`),QU=I(`<div>`),$U=I(`<p class="note sys turn-denied">`),eW=I(`<span class=turn-error-status>`),tW=I(`<div class=turn-error-message>`),nW=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>`),rW=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">`),aW=I(`<span class=spinner>`),oW=I(`<span class=hub-msg-kind>`),sW=I(`<span class="hub-msg-state muted">`),cW=I(`<span class="hub-msg-delivery muted"title="Not delivered into a turn yet: the recipient's harness takes it at its next step">`),lW=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>`),uW=I(`<div class="fold-body hub-msg-text">`),dW=I(`<div><button type=button class=fold-head><span class=hub-msg-mark aria-hidden=true>⇄</span><span>`),fW=I(`<a>`),pW=I(`<span class="spinner small">`),mW=I(`<div class="fold thought"><button type=button class=fold-head><span>`),hW=I(`<ul class="fold-body tool-list">`),gW=I(`<div><button type=button class=fold-head><span>`),_W=I(`<pre class=code>`),vW=I(`<div class=tool-detail>`),yW=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">`),bW=I(`<span class="muted small">Loading full details…`),xW=I(`<span class="error small">`),SW=I(`<span class="muted small">No details for this call yet.`),CW={pending:[`…`,`Sending`],sent:[`✓`,`Sent`],queued:[`◷`,`Queued: the harness takes it at its next step`],heard:[`✓✓`,`Heard by the agent`],failed:[`!`,`Not sent`]};function wW(e){return n(l,{get when(){return e.image.src},get fallback(){return(()=>{var t=UU(),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 TW=500;function EW(e){let[t,a]=u(!1),o,c=()=>clearTimeout(o),d=t=>{t.pointerType===`touch`&&e.actions&&(c(),o=setTimeout(()=>a(!0),TW))},f=(e,t)=>()=>{a(!1),e.enabled&&t()};return(()=>{var o=qU(),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=WU();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=JU();return y(r,n(m,{get each(){return e.block.images},children:e=>n(wW,{image:e,onOpen:()=>t(e.key)})})),r})()})}}),null),y(u,n(l,{get when(){return e.block.text},get children(){var t=GU();return y(t,()=>e.block.text),t}}),null),y(u,n(l,{get when(){return e.block.note},get children(){var t=KU();return y(t,()=>e.block.note),t}}),null),y(u,n(l,{get when(){return e.actions},children:t=>(()=>{var i=YU();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=XU();return y(t,()=>CW[e()][0]),s(n=>{var r=`tick ${e()}`,i=CW[e()][1],a=CW[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 DW(e){return n(In,{get children(){return n(OW,e)}})}function OW(e){let t=C(()=>e.previews?Kj(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=ZU();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(EW,{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=QU();return y(a,n(mN.Provider,{get value(){return e.sessionID},get children(){return n(OP,{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(AW,{get block(){return t()},get expanded(){return e.expanded},get onToggle(){return e.onToggle}})}),n(o,{get when(){return d(`tools`)},children:t=>n(jW,{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(kW,{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=$U();return y(t,()=>e().label),s(()=>b(t,`data-key`,e().key)),t})()}),n(o,{get when(){return d(`error`)},children:e=>(()=>{var t=nW(),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=eW();return y(t,()=>e().status),t}}),null),y(r,n(l,{get when(){return e().message},get children(){var t=tW();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=()=>Zz(e(),se());return(()=>{var n=rW(),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()?aW():`◆`})()),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 kW(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=dW(),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=uW();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=lW(),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=oW();return y(t,()=>e.block.kind),t}}),a),y(a,()=>Be(e.block.label,Su)),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=sW();return y(t,()=>e.block.state),t}}),null),y(r,n(l,{get when(){return e.block.delivery},get children(){var t=cW();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=fW();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,Su)}`,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 AW(e){let t=()=>!!e.expanded[e.block.key],r=t=>e.onToggle(e.block.key,t),i=()=>eB(e.block);return(()=>{var a=mW(),o=a.firstChild,c=o.firstChild;return o.$$click=()=>r(!t()),y(o,n(l,{get when(){return e.block.running},get children(){return pW()}}),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=QU();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 jW(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=gW(),o=i.firstChild,c=o.firstChild;return o.$$click=()=>r(!t()),y(o,n(l,{get when(){return e.block.running},get children(){return pW()}}),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=hW();return y(t,n(m,{get each(){return e.block.items},children:t=>n(MW,{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 MW(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=yW(),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()?pW():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=vW();return y(e,n(l,{get when(){return!a()},get fallback(){return bW()},get children(){return n(l,{get when(){return!c()},get fallback(){return(()=>{var e=xW();return y(e,c),e})()},get children(){return n(l,{get when(){return f().detail!==void 0||h()||f().error},get fallback(){return SW()},get children(){var e=_W();return y(e,()=>nB(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 NW={profilesPerUser:200,versionsPerProfile:100,skillsPerProfile:32,commandsPerProfile:64,instructionsChars:32e3,skillChars:32e3,commandChars:8e3,versionBytes:524288,projectsPerProfile:16},PW=[`pending`,`applied`,`partial`,`rejected`,`unsupported`,`restart_required`];function FW(e){if(!Fe(e))return`content must be an object`;if(e.instructions!==void 0&&!ze(e.instructions,NW.instructionsChars))return`instructions must be at most ${NW.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,NW.skillsPerProfile,NW.skillChars,`body`,`skills`],[e.commands,NW.commandsPerProfile,NW.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>NW.versionBytes)return`profile version is too large`}function IW(e){if(e===void 0)return;let t=NW.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 LW(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)??IW(e.projects)??FW(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 RW(e){return Array.isArray(e)?`[${e.map(RW).join(`,`)}]`:Fe(e)?`{${Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${JSON.stringify(t)}:${RW(e[t])}`).join(`,`)}}`:JSON.stringify(e)}var zW=/^[a-z][a-z0-9_]{0,39}$/,BW=/^[A-Z][A-Z0-9_]{0,63}$/,VW=`secret:`;function HW(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(VW)){if(!BW.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(!zW.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`,UW=e=>typeof e==`number`&&Number.isFinite(e),WW=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>=1,GW=e=>Array.isArray(e)?e.filter($):[];function KW(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 qW(e){if(Q(e)&&$(e.id)&&$(e.name)&&$(e.title)&&WW(e.latestVersion)&&UW(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:GW(e.tags),metadata:Q(e.metadata)?Object.fromEntries(Object.entries(e.metadata).filter(e=>$(e[1]))):{},projects:GW(e.projects),latestVersion:e.latestVersion,revision:e.revision,updatedAt:UW(e.updatedAt)?e.updatedAt:0}}var JW=e=>KW(e,qW),YW=[`sessions`,`online`,`olderVersion`,`teamRoles`,`staffedSeats`,`launches`,`liveLaunches`];function XW(e){if(!Q(e))return;let t={};for(let n of YW)UW(e[n])&&(t[n]=e[n]);return Array.isArray(e.teams)&&(t.teams=GW(e.teams)),Array.isArray(e.harnesses)&&(t.harnesses=GW(e.harnesses)),t}function ZW(e){if(Q(e)&&WW(e.version)&&UW(e.skills)&&UW(e.commands))return{version:e.version,skills:e.skills,commands:e.commands,instructions:e.instructions===!0}}function QW(e){let t=JW(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?XW(n[e.id]):void 0,i=r?ZW(r[e.id]):void 0;return{profile:e,...t?{usage:t}:{},...i?{summary:i}:{}}}),...t.cursor?{cursor:t.cursor}:{}}}var $W=e=>!!e&&((e.sessions??0)>0||(e.teamRoles??0)>0||(e.launches??0)>0);function eG(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 tG=e=>[...new Set(e)].sort();function nG(e){return{tags:tG(e.flatMap(e=>e.profile.tags)),projects:tG(e.flatMap(e=>e.profile.projects)),teams:tG(e.flatMap(e=>e.usage?.teams??[])),harnesses:tG(e.flatMap(e=>e.usage?.harnesses??[]))}}function rG(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`===$W(e.usage)))}var iG=e=>(e?.sessions??0)+(e?.teamRoles??0)+(e?.launches??0),aG=(e,t)=>e.profile.name<t.profile.name?-1:+(e.profile.name>t.profile.name);function oG(e,t){let n=[...e];return t===`updated`?n.sort((e,t)=>t.profile.updatedAt-e.profile.updatedAt||aG(e,t)):t===`usage`?n.sort((e,t)=>iG(t.usage)-iG(e.usage)||aG(e,t)):n.sort(aG)}var sG=[`sessions`,`teams`,`launches`,`workspaces`];function cG(e){if(!Q(e)||!$(e.sessionID)||!WW(e.version)||!UW(e.revision))return;let t=Q(e.effective)&&WW(e.effective.version)?e.effective.version:void 0,n=Q(e.ack)&&PW.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,...UW(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 lG(e){if(!Q(e)||!$(e.profileID)||!WW(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:{...XW(e.counts),...Q(e.counts)&&UW(e.counts.workspaces)?{workspaces:e.counts.workspaces}:{}},sessions:(n&&Array.isArray(n.items)?n.items:[]).flatMap(e=>cG(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}:{},...WW(e.version)?{version:e.version}:{},...UW(e.staffed)?{staffed:e.staffed}:{}})),launches:t(e.launches).filter(e=>$(e.id)&&$(e.state)&&WW(e.version)).map(e=>({id:e.id,state:e.state,...$(e.outcome)?{outcome:e.outcome}:{},version:e.version,...$(e.sessionID)?{sessionID:e.sessionID}:{},created:UW(e.created)?e.created:0,updated:UW(e.updated)?e.updated:0})),workspaces:t(e.workspaces).filter(e=>$(e.workspaceID)).map(e=>({workspaceID:e.workspaceID,...$(e.title)?{title:e.title}:{},sessions:UW(e.sessions)?e.sessions:0})),projects:GW(e.projects),hidden:GW(e.hidden).filter(e=>sG.includes(e)),truncated:GW(e.truncated)}}var uG=(e,t)=>t?`/teams/${encodeURIComponent(e)}`:`/watchtower?group=team&team=${encodeURIComponent(e)}`;function dG(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)??IW(r);return i?{ok:!1,error:i}:{ok:!0,patch:{metadata:Object.keys(n).length?n:null,projects:r.length?r:null}}}function fG(e){if(!Q(e)||!$(e.profileID)||!WW(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:UW(e.createdAt)?e.createdAt:0,bytes:UW(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:GW(e.params)}]:[]}),secretRefs:GW(e.secretRefs)}}function pG(e){if(Q(e)&&WW(e.version)&&$(e.digest))return{version:e.version,digest:e.digest,bytes:UW(e.bytes)?e.bytes:0,createdAt:UW(e.createdAt)?e.createdAt:0}}var mG=e=>KW(e,pG);function hG(e){let t=Q(e)?e.version:void 0;if(!Q(t)||!$(t.profileID)||!WW(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:UW(t.createdAt)?t.createdAt:0,content:r}}function gG(e){if(Q(e)&&PW.includes(e.status)&&$(e.digest))return{status:e.status,digest:e.digest,notes:GW(e.notes),at:UW(e.at)?e.at:0,offline:e.offline===!0}}function _G(e){if(Q(e)&&$(e.profileID)&&WW(e.version)&&$(e.digest)&&(e.status===`applied`||e.status===`partial`))return{profileID:e.profileID,version:e.version,digest:e.digest,status:e.status,at:UW(e.at)?e.at:0}}function vG(e){if(!Q(e)||!$(e.sessionID)||!$(e.profileID)||!WW(e.version)||!UW(e.revision))return;let t=gG(e.ack),n=_G(e.effective);return{sessionID:e.sessionID,profileID:e.profileID,version:e.version,revision:e.revision,...t?{ack:t}:{},...n?{effective:n}:{}}}function yG(e){if(!Q(e)||!(`assignment`in e))return;if(e.assignment===null)return{assignment:null};let t=vG(e.assignment);if(!t)return;let n=qW(e.profile),r=fG(e.version);return{assignment:t,...n?{profile:n}:{},...r?{version:r}:{}}}var bG={pending:`Pending`,applied:`Applied`,partial:`Partly applied`,rejected:`Rejected`,unsupported:`Unsupported`,restart_required:`Restart required`},xG={applied:`ok`,partial:`warn`,restart_required:`warn`,pending:`pending`,unsupported:`err`,rejected:`err`};function SG(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:xG[r],detail:`${e.profile?.title??n} v${t.version}: ${bG[r]}${t.ack?.offline?` (machine offline)`:``}${s?` · v${s} available`:``}`,requested:t.version,...a===void 0?{}:{effective:a},...s?{upgrade:s}:{}}}function CG(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 wG=`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.`,TG={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.`},EG=e=>TG[e]??`This harness reports what took effect after you pin; presets can't apply profiles.`,DG=()=>({instructions:``,model:``,skills:[],commands:[]}),OG=e=>({instructions:e.instructions??``,model:e.model??``,skills:e.skills.map(e=>({...e})),commands:e.commands.map(e=>({...e}))});function kG(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=FW(r);if(i)return{ok:!1,error:i};for(let e of r.commands){let t=HW(e.template);if(typeof t==`string`)return{ok:!1,error:`commands.${e.name}: ${t}`}}return{ok:!0,content:r}}function AG(e,t){let n=kG(e);return!n.ok||RW(n.content)!==RW(t)}function jG(e,t){let n=kG(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=LW(a);return o?{ok:!1,error:o}:{ok:!0,body:a}}function MG(e){let t=HW(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 NG=4e3;function PG(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 ${NG} characters`};n[r]=e}return{ok:!0,body:{params:n}}}function FG(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 IG=`Control+Alt+P`,LG=e=>e.ctrlKey&&e.altKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyP`,RG=(e,t)=>e?e.endsWith(`
31
- `)?e+t:`${e}\n${t}`:t,zG=(e,t,n)=>({profileID:e,version:t,expectedRevision:n.assignment?.revision??0});function BG(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 VG=e=>!!e.assignment&&(e.assignment.ack?.status??`pending`)===`pending`,HG=15e3,UG=16,WG=e=>e>=UG?void 0:Math.min(HG,1e3*2**e);function GG(e){let t=e,n=t?.message??String(e);switch(t?.code){case`conflict`:return`Changed elsewhere meanwhile${UW(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 KG=encodeURIComponent,qG=`/api/agent`,JG={list:(e=`active`,t=!0)=>`${qG}/profiles?state=${e}&limit=200${t?`&include=usage,summary`:``}`,usage:(e,t)=>`${qG}/profiles/${KG(e)}/usage?limit=200${t?`&cursor=${KG(t)}`:``}`,create:()=>`${qG}/profiles`,one:e=>`${qG}/profiles/${KG(e)}`,versions:e=>`${qG}/profiles/${KG(e)}/versions`,version:(e,t)=>`${qG}/profiles/${KG(e)}/versions/${t}`,session:e=>`${qG}/sessions/${KG(e)}/profile`,unpin:(e,t)=>`${qG}/sessions/${KG(e)}/profile?expectedRevision=${t}`,render:(e,t)=>`${qG}/sessions/${KG(e)}/profile/commands/${KG(t)}/render`},YG=()=>globalThis.crypto?.randomUUID?.()??`${Date.now()}-${Math.random().toString(36).slice(2)}`,XG=async e=>e.json().catch(()=>({})),ZG=async(e=`active`)=>JW(await G(JG.list(e,!1))),QG=async(e=`active`)=>QW(await G(JG.list(e)));async function $G(e,t){let n=lG(await G(JG.usage(e,t)));if(!n)throw Error(`The hub sent an unreadable usage answer`);return n}async function eK(e,t){let n=qW((await XG(await V(JG.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 tK(e){let t=await G(JG.one(e)),n=qW(t.profile);if(!n)throw Error(`The hub sent an unreadable profile`);return{profile:n,latest:fG(t.latest)}}var nK=async e=>mG(await G(`${JG.versions(e)}?limit=200`));async function rK(e,t){let n=hG(await G(JG.version(e,t)));if(!n)throw Error(`The hub sent an unreadable version`);return n}async function iK(e,t){let n=qW((await XG(await V(JG.create(),{method:`POST`,json:e,headers:{"idempotency-key":t}}))).profile);if(!n)throw Error(`The hub sent an unreadable profile`);return n}async function aK(e,t,n){let r=qW((await XG(await V(JG.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 oK(e,t){let n=qW((await XG(await V(JG.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 sK(e){let t=yG(await G(JG.session(e)));if(!t)throw Error(`The hub sent an unreadable profile pin`);return t}async function cK(e,t){await V(JG.session(e),{method:`PUT`,json:t})}async function lK(e,t){await V(JG.unpin(e,t),{method:`DELETE`})}async function uK(e,t,n){let r=await XG(await V(JG.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 dK=I(`<p class="error small"role=alert>`),fK=I(`<input type=search role=combobox aria-label="Search commands"aria-controls=prof-commands aria-expanded=true placeholder="Type a command…"autofocus>`),pK=I(`<ul class=prof-commands id=prof-commands role=listbox aria-label=Commands>`),mK=I(`<p class=prof-note>Inserted text goes into this session's composer; review it, then send.`),hK=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.`),gK=I(`<p class="muted small">Loading commands…`),_K=I(`<p class="muted small">`),vK=I(`<li role=option class=prof-command><strong>/</strong><span class=prof-sub>`),yK=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.`),bK=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`),xK=I(`<label><textarea>`);function SK(e){let t=e.view.assignment,[i]=d(async()=>{if(!t)return[];let n=e.view.version?.commands??[];try{return(await rK(t.profileID,t.version)).content.commands.map(e=>{let t=MG(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(()=>FG(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=PG(t.params,g());if(!n.ok)return x(n.error);w(!0),x(``);try{let{prompt:r}=await uK(e.sessionID,t.name,n.body);ax.set(e.sessionID,RG(ax.get(e.sessionID),r)),e.onInserted()}catch(e){x(GG(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 hK()},get children(){return[(()=>{var e=fK();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 gK()},get children(){return n(l,{get when(){return T().length},get fallback(){return(()=>{var n=_K();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=pK();return y(e,n(m,{get each(){return T()},children:(e,t)=>(()=>{var n=vK(),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}})}}),mK()]}})},children:e=>(()=>{var t=bK(),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=xK(),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=yK(),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=dK();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=dK();return y(e,v),e}})]}})}z([`input`,`keydown`,`click`]);var CK=I(`<span class=prof-up aria-hidden=true>↑v`),wK=I(`<button type=button>`),TK=I(`<section aria-label="Pinned profile"><h3>Pinned`),EK=I(`<label>Profile<select aria-label=Profile>`),DK=I(`<label>Version<select aria-label=Version>`),OK=I(`<div class=row><button type=button class="btn small primary">`),kK=I(`<section aria-label="Pin a profile"><h3></h3><p class=prof-note>`),AK=I(`<p class="error small"role=alert>`),jK=I(`<p class="muted small">No profile is pinned to this session.`),MK=I(`<div class=prof-status><span></span><strong class=small>`),NK=I(`<ul class=prof-guidance aria-label="What took effect">`),PK=I(`<p class=prof-note>`),FK=I(`<div class=row><button type=button class="btn small">Unpin</button><button type=button class="btn small">Commands… (Ctrl+Alt+P)`),IK=I(`<li>`),LK=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`),RK=I(`<p class="muted small">`),zK=I(`<p class="muted small">No active profiles. Create one under Agent profiles (/profiles).`),BK=I(`<option> (<!>)`),VK=I(`<option>v`),HK=e=>{let t=_u(e)?.session.title;return typeof t==`string`&&t?t:`this session`};function UK(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 sK(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||!VG(e))return void(_=0);let t=WG(_++);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=>{LG(t)&&e.takesInput()&&o()&&i()&&(t.preventDefault(),m(!0))};document.addEventListener(`keydown`,t),M(()=>document.removeEventListener(`keydown`,t))});let w=()=>SG(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=wK();e.$$click=()=>{f(!0),x()};var a=h;return typeof a==`function`?t(a,e):h=e,b(e,`aria-keyshortcuts`,IG),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=CK();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: ${IG}`,o=i().assignment?`Agent profile: ${w().label}, ${bG[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(WK,{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(SK,{get sessionID(){return e.sessionID},get title(){return HK(e.sessionID)},get view(){return i()},onClose:()=>m(!1),onInserted:()=>{m(!1),requestAnimationFrame(T)}})}})]}})}function WK(t){let[i]=d(()=>ZG(`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=>nK(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=()=>SG(t.view),C=()=>CG(t.view),w=()=>BG(t.view,a(),c()),T=async(e,n,r)=>{_(!0),h(``);try{await cK(t.sessionID,zG(e,n,t.view)),q(r),t.onChanged()}catch(e){h(GG(e)),t.onChanged()}finally{_(!1)}},E=async()=>{let e=t.view.assignment;if(e){_(!0),h(``);try{await lK(t.sessionID,e.revision),q(`Unpinned. What the session already applied stays until it restarts.`),t.onChanged()}catch(e){h(GG(e)),t.onChanged()}finally{_(!1)}}};return n(de,{open:!0,get title(){return`Agent profile · ${HK(t.sessionID)}`},get onClose(){return t.onClose},class:`prof-dialog`,get children(){return[(()=>{var e=TK();return e.firstChild,y(e,n(l,{get when(){return t.view.assignment},get fallback(){return jK()},children:e=>[(()=>{var t=MK(),n=t.firstChild,r=n.nextSibling;return y(n,()=>S().label),y(r,()=>bG[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=NK();return y(e,n(m,{get each(){return C()},children:e=>(()=>{var t=IK();return y(t,e),t})()})),e})(),n(l,{get when(){return S().upgrade},children:n=>(()=>{var r=LK(),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=PK();return y(e,wG),e})(),(()=>{var e=FK(),n=e.firstChild,r=n.nextSibling;return n.$$click=()=>void E(),B(r,`click`,t.onCommands,!0),b(r,`aria-keyshortcuts`,IG),s(()=>n.disabled=g()),e})()]}),null),e})(),(()=>{var e=kK(),u=e.firstChild,d=u.nextSibling;return y(u,()=>t.view.assignment?`Change the pin`:`Pin a profile`),y(d,()=>EG(t.harness)),y(e,n(l,{get when(){return r(()=>!i.error)()&&i()},get fallback(){return(()=>{var e=RK();return y(e,(()=>{var e=r(()=>!!i.error);return()=>e()?GG(i.error):`Loading profiles…`})()),e})()},get children(){return n(l,{get when(){return i().length},get fallback(){return zK()},get children(){return[(()=>{var e=EK(),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=BK(),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=DK(),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=VK();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=OK(),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=AK();return y(e,p),e}})]}})}z([`click`]);var GK=10;function KK(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 ${bz(t)} sessions yet`};return{fork:r(`fork`,`Fork`),revert:r(`revert`,`Revert`)}}var qK=e=>Number.isSafeInteger(e)&&e>=0?e:0;function JK(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:qK(t.hidden),...typeof t.at==`number`&&Number.isFinite(t.at)?{at:t.at}:{},files:n,filesTotal:Math.max(qK(t.filesTotal),n.length),...YK(t.stagedAt)?{stagedAt:t.stagedAt}:{}}}var YK=e=>typeof e==`number`&&Number.isFinite(e);function XK(e){let t=e?.revertCommitted;if(t&&typeof t==`object`&&typeof t.messageID==`string`&&t.messageID&&YK(t.until)&&YK(t.at))return{messageID:t.messageID,...YK(t.from)?{from:t.from}:{},until:t.until,at:t.at}}function ZK(e){let t=XK(e);return`${JK(e)?.messageID??``}|${t?`${t.messageID}@${t.at}`:``}`}function QK(e){let t=Math.max(e.filesTotal,e.files.length);return{text:`${_n(e.hidden,`message`)} reverted`,...t?{files:`${_n(t,`file`)} restored`}:{}}}function $K(e){let t=Math.max(e.filesTotal,e.files.length);if(!t)return;let n=e.files.slice(0,GK).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 eq(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 tq(e,t){return t===void 0?e:e.trim()===t.trim()?``:e}var nq=new Map;function rq(e,t){t.length&&nq.set(e,t)}function iq(e){let t=nq.get(e)??[];return nq.delete(e),t}var aq=I(`<button type=button class="btn small changes"aria-label="Show changes"><span class=add>+</span> <span class=del>−`),oq=I(`<div class="banner warn">No connected OpenCode process reports this session. It is read-only until its machine reconnects.`),sq=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.`),cq=I(`<div class=history-sentinel aria-hidden=true>`),lq=I(`<p class="history-edge loading muted small"role=status><span class="spinner small"></span> Loading earlier messages…`),uq=I(`<p class="history-edge muted small">Beginning of conversation`),dq=I(`<p class="history-edge error small"role=alert>Couldn't load earlier messages: <!> <button type=button class="btn small">Retry`),fq=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.`),pq=I(`<p class="working-line muted"role=status><span class="spinner small"></span> `),mq=I(`<p class="idle-line muted small"> · last activity `),hq=I(`<button type=button class="btn primary tap-to-start">Tap to start Voice mode`),gq=I(`<p class="note err voice-error"role=alert>Voice mode: `),_q=I(`<div class=sheet-backdrop>`),vq=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>`),yq=I(`<a class="crumb muted"> <span class=crumb-sep aria-hidden=true>/`),bq=I(`<h1 class=title>`),xq=I(`<h1 class=title><button type=button class=title-btn>`),Sq=I(`<span class=chip-server><span aria-hidden=true></span><span class=place-sep aria-hidden=true>·</span><span class=place-where>`),Cq=I(`<span> · `),wq=I(`<span class=place-branch>`),Tq=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>`),Eq=I(`<span class=session-error-status>`),Dq=I(`<span class="session-error-where muted">in subagent `),Oq=I(`<div class=session-error-message>`),kq=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>`),Aq=I(`<p class="muted pad">Loading conversation…`),jq=I(`<p class="muted pad empty-session">No messages yet. Type below, or start Voice mode.`),Mq=I(`<p>`),Nq=I(`<p class="answered-by small muted">`),Pq=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`),Fq=I(`<span class=muted> · `),Iq=I(`<button type=button class="btn stop"aria-label="Stop the session and its subagents"> Stop`),Lq=I(`<div class=composer-unavailable data-no-prompt><p class="muted small">`),Rq=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`),zq=3e4,Bq=80,Vq=100,Hq=2e3,Uq;function Wq(i){let a=i.id,c=Cc(a,i.visible);M(()=>c.release()),x(()=>i.focused?.()&&c.focus());let d=()=>Cp()&&(i.rail?.()??!0),f,p=()=>{let e=f??d();f=void 0,Ep(!e)},h=()=>document.visibilityState===`visible`&&(i.visible?.()??!0),g=()=>_u(a),S=()=>gu().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(()=>xz(g()?.process)),ee=()=>Cz(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();dz(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||_u(e)?.session.title||`Parent session`}},[ce,le]=u(),de=()=>{let e=ce();return e?e.value:JK(g()?.session)};x(()=>{let e=ce();e&&JK(g()?.session)?.messageID===e.value?.messageID&&le(void 0)});let pe=C(()=>KK(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=su(),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,tB(z.rows(),e),pu):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=XK(g()?.session),r=Jz(t||n?z.rows().filter(e=>!eq(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=${Vq}`).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 gz(z,e=>G(`${H(a)}/timeline?${Ge(e)}`),{limit:Bq,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??``}|${ZK({revertCommitted:XK(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()||Oz(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=Ml.feed(ne());t.load(e.activity??[]),e.status&&t.status(e.status)}catch{}}let lt=ae(()=>T()),dt=hu(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 ey(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 Qu(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()&&Qu(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,Hq-(Date.now()-wt)))}let[At,jt]=u(),Mt=uV(()=>a),[Nt,Pt]=u(),Ft=()=>j().sessionModel&&j().models,[It,Lt]=u({...O_(),draft:ax.get(a)}),Rt=e=>{Lt(t=>k_(t,e)),ax.set(a,It().draft)};M(ax.subscribe(e=>{e===a&&ax.get(a)!==It().draft&&Lt(e=>k_(e,{type:`input`,text:ax.get(a)}))}));let zt=()=>wz(j(),E()),Bt=()=>{let e=A_(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 uS(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(S_(i.mime))try{let n=await(await V(Rz(e,t,i.index))).blob();r.push(await uS(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&&ax.set(n.sessionID,n.text),rq(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(Oz(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=$K(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:JK({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(Oz(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:tq(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:``}),qb.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=j_(s.status,c);Rt({type:`accepted`,id:n});let u=Tz(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 N_(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=Oz(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(su(),new Set([a,...ie()]),Date.now(),void 0,pu),o=M_(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(Oz(e)??`Could not stop: ${U(e)}`,`err`)}finally{Rt({type:`stopped`})}}let ln=()=>lx(a),un=()=>c.takesInput()?ox.toggle(a):c.focus(),dn=rx,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(zl()??void 0,X()?.publicURL)?.micBlocked?`Set up speech in Settings to use the microphone`:void 0;M(qb.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}=$v(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()||(Ty(),ox.cancel()),await qb.toggle(a),qb.isOn(a)&&qb.state.phase===`on`&&De(`Voice mode on${qb.state.agent?` (${qb.state.agent} agent)`:``}. Speak naturally; say “stop” to interrupt, “pause listening” to end.`,`sys`)}let vn=zy(location.href);vn.voice&&(Uq=a,Vt(vn.path,{replace:!0})),x(()=>{Uq===a&&g()&&!gn()&&(Uq=void 0,fn()||_n())}),fe(()=>{for(let e of iq(a))Rt({type:`attach`,image:e});let e=yS(a);e&&(he(()=>{Rt({type:`input`,text:e.text});for(let t of e.images)Rt({type:`attach`,image:t})}),nn()),st(),Qu(a,h()),pt(h()),gt=setInterval(()=>h()&&void pt(!0),zq),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(su(),new Set([a,...ie()]),kn(),En(),new Set([...an(),...Pe()]),Su,pu).filter(t=>!e.has(t.key))},On=()=>(Fl(),N(),Ml.has(ne())?Ml.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=vq(),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:Dp})}}),x),y(x,n(l,{get when(){return se()},children:e=>(()=>{var t=yq(),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=bq();return y(e,()=>g()?.session.title||(Y.machines?`Session`:`Loading…`)),e})()},children:e=>[n(A,{get state(){return e().state}}),n(Ng,{get id(){return e().id},get title(){return e().title},place:`topbar`,class:`title`,get children(){var t=xq(),n=t.firstChild;return n.$$click=()=>Sh({id:e().id,place:`topbar`}),y(n,()=>e().title),s(()=>b(n,`title`,`${e().title} · click to rename`)),t}}),n(Pg,{get id(){return e().id}}),n(O,{label:`Session actions`,class:`icon-btn small`,items:()=>Th(e(),{open:!1,place:`topbar`})})]}),null),y(h,n(l,{get when(){return w()},children:e=>(()=>{var t=Sq(),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=Cq(),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(UK,{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=aq(),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(aL,{})}}),null),y(h,n(l,{get when(){return Z()},get children(){return n(TR,{})}}),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=Tq(),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=wq();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=kq(),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=Eq();return y(t,()=>e().status),t}}),null),y(o,n(l,{get when(){return r(()=>e().sessionID!==a)()&&e().title},get children(){var t=Dq();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=Oq();return y(t,()=>e().message),t}}),null),y(t,n(F,{icon:`close`,label:`Dismiss error`,class:`session-error-dismiss`,onClick:()=>void jd(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 oq()}}),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(Gq,{})},get children(){return[n(l,{get when(){return ve()},get fallback(){return Aq()},get children(){return[n(l,{get when(){return te()},get children(){var e=sq(),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 jq()}})},get children(){return[(()=>{var e=cq();return t(Qe,e),e})(),n(v,{get children(){return[n(o,{get when(){return qe().state===`loading`},get children(){return lq()}}),n(o,{get when(){return r(()=>qe().state===`done`)()&&Ie().length},get children(){return uq()}}),n(o,{get when(){return qe().state===`error`},get children(){var e=dq(),t=e.firstChild.nextSibling,n=t.nextSibling.nextSibling;return y(e,()=>qe().error,t),n.$$click=()=>void Ke.retry(),e}})]}}),n(DW,{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=Mq();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(Og,{get decisions(){return Oe(Ul(),a)}}),n(m,{get each(){return Tn()},children:e=>n(l,{get when(){return Cn().get(e)},children:e=>n(zU,{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=Nq();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 fq()}}),n(l,{get when(){return Mn()},get children(){var e=pq();return e.firstChild.nextSibling,y(e,Mn,null),e}}),n(l,{get when(){return r(()=>!(E()||!g()))()&&S()},get children(){var e=mq(),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(MB,{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 lV(Mt.prefs(),`voice`)},onMute:()=>qb.mute(),onEnd:()=>void qb.end(),onModel:()=>Pt(`voice`),get notifyHint(){return tx()},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=hq();return e.$$click=()=>void _n(),e}}),null),y(M,n(l,{get when(){return mn()},get children(){var e=gq();return e.firstChild,y(e,mn,null),e}}),null),y(M,n(l,{get when(){return de()},children:e=>(()=>{var t=Pq(),r=t.firstChild,i=r.firstChild,a=r.nextSibling;return y(t,n(L,{name:`undo`}),r),y(r,()=>QK(e()).text,i),y(r,n(l,{get when(){return QK(e()).files},children:e=>(()=>{var t=Fq();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=Lq(),t=e.firstChild;return y(t,()=>zt().hint),y(e,n(l,{get when(){return Bt().showStop},get children(){var e=Iq(),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(OB,_({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`:lV(Mt.prefs(),`voice`)}},()=>j().summary?{sessionModel:KB(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(sU,{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=_q();return e.$$click=()=>Ep(!1),e}}),n(l,{get when(){return!Z()},get children(){return n(Yx,{panel:`rail`,label:`Resize details`})}}),n(oU,{get found(){return g()},get summary(){return vt()},get summaryError(){return bt()},get loading(){return St()},onFile:e=>jt(e),onClose:()=>Ep(!1)})]}}),null),y(e,n(dV,{get kind(){return Nt()},models:Mt,onClose:()=>Pt(void 0),get sessionCurrent(){return qB(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 Gq(){return Rq()}z([`focusin`,`pointerdown`,`click`]);var Kq=I(`<span class=pane-drop-label>`),qq=I(`<div class=pane-drop-area><span class=pane-drop-hint>`),Jq=I(`<div aria-hidden=true>`),Yq=I(`<div class=pane-dock-map>`),Xq=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.`),Zq={left:`Split left`,right:`Split right`,top:`Stack above`,bottom:`Stack below`,center:`Replace`};function Qq(e,t){let n=Zp(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: ${Zq[t].replace(`Split `,``).replace(`Stack `,``)}`,refused:!1}:n===`added`&&`empty`in e?{text:`Open in a pane`,refused:!1}:{text:Zq[t],refused:!1}}function $q(e){let[t,r]=u(),i=t=>e.index===void 0?{empty:!0}:{index:e.index,zone:t},a=t=>{if(!Xp(t))return;t.preventDefault(),t.stopPropagation();let n=t.currentTarget.getBoundingClientRect(),i=e.index===void 0?`center`:Xf(t.clientX-n.left,t.clientY-n.top,n.width,n.height);r(i),t.dataTransfer&&(t.dataTransfer.dropEffect=Kp()?.move||t.dataTransfer.effectAllowed===`move`?`move`:`copy`)},o=()=>t()?Qq(i(t()),t()):void 0;return(()=>{var c=Jq();return c.addEventListener(`drop`,e=>{if(!Xp(e))return;e.preventDefault(),e.stopPropagation();let n=t()??`center`;r(void 0),$p(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=Kq();return y(t,()=>e.label),t}}),null),y(c,n(l,{get when(){return t()},get children(){var e=qq(),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 eJ=e=>{if(rn(e)!==void 0)return`Artifact`;let t=_u(e.sessionID)?.session.title,n=typeof t==`string`&&t?t:`Session`;return e.sideChatID?`Side chat: ${n}`:n};function tJ(){let e=xn,t=()=>e().panes.length,i=()=>ez(e().split,t()),o=n=>{let r=tz(e().split,t(),n);return{"grid-column":`${r.col+1} / span ${r.colSpan}`,"grid-row":`${r.row+1}`}};return(()=>{var c=Xq(),u=c.firstChild,d=u.firstChild,f=d.nextSibling;return y(d,(()=>{var e=r(()=>!!Kp()?.label);return()=>e()?`Open “${Kp().label}” in a pane`:`Open in a pane`})()),y(u,n(l,{get when(){return t()},get fallback(){return n($q,{class:`pane-dock-empty`,label:`No panes open: drop here`})},get children(){var t=Yq();return y(t,n(m,{get each(){return e().panes},children:(e,t)=>n($q,{get index(){return t()},get label(){return eJ(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 nJ=I(`<div role=separator tabindex=0>`);function rJ(e){let[t,n]=u(!1),r=[],i=0,a=0,o,c=()=>QR[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=nJ();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(nz(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=rz(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.`),aJ=I(`<button type=submit class="btn small primary">Send`),oJ=I(`<button type=button class="btn small">Back`),sJ=I(`<form class=sidechat-send><label class=muted>Message for </label><textarea rows=3></textarea><div class=sidechat-row>`),cJ=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…`),lJ=I(`<p class="muted sidechat-note">`),uJ=I(`<span role=status>`),dJ=I(`<ol class=sidechat-context aria-label="Copied context">`),fJ=I(`<li><span class=muted></span><div class=sidechat-context-text>`),pJ=I(`<p class="muted sidechat-problem"role=alert>`),mJ=I(`<button type=submit class="btn small">Review`),hJ=I(`<button type=button class=btn>Close pane`),gJ=I(`<div class=empty><p class=display>Side chat</p><p class=muted role=status>`),_J=e=>{let t=_u(e)?.session.title;return typeof t==`string`&&t?t:`the main session`};function vJ(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),Wm(e).kind===`launching`?T=setTimeout(k,$m(E++)):E=0};async function k(){try{let t=await G(Qm.one(e.sideChatID));if(!D)return;let n=Um(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(Qm.refresh(e),{method:`POST`,json:{expectedRevision:e.revision}})).json(),n=Um(t.sideChat);n&&O(n),q(qm(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()||Ym(x()))){d(!0);try{await V(Qm.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?Wm(e):void 0},ee=()=>{let e=N();return e?.kind===`ready`?e.sessionID:void 0},P=()=>{let e=t();return e?Km(e,C()):void 0};return[(()=>{var i=cJ(),a=i.firstChild.firstChild.nextSibling;a.firstChild;var o=a.nextSibling,u=o.firstChild,d=u.nextSibling,C=d.nextSibling;return y(a,()=>_J(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=lJ();return y(t,()=>e().summary,null),y(t,n(l,{get when(){return e().stale},children:e=>[` · `,(()=>{var t=uJ();return y(t,e),t})()]}),null),t})()}),null),y(i,n(l,{get when(){return r(()=>!!f())()&&t()},children:e=>(()=>{var t=dJ();return y(t,n(m,{get each(){return e().snapshot.items},children:e=>(()=>{var t=fJ(),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=sJ(),a=i.firstChild;a.firstChild;var o=a.nextSibling,u=o.nextSibling;return i.addEventListener(`submit`,e=>{e.preventDefault(),_()?j():Ym(x())||v(!0)}),y(a,()=>_J(t()?.sourceSessionID??``),null),o.$$input=e=>S(e.currentTarget.value),y(i,n(l,{get when(){return r(()=>!!x())()&&Ym(x())},children:e=>(()=>{var t=pJ();return y(t,e),t})()}),u),y(u,n(l,{get when(){return _()},get fallback(){return(()=>{var e=mJ();return s(()=>e.disabled=!!Ym(x())),e})()},get children(){return[iJ(),(()=>{var e=aJ();return s(()=>e.disabled=c()),e})(),(()=>{var e=oJ();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=gJ(),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=hJ();return t.$$click=()=>e.onClose(),t}}),null),t})()},children:t=>n(Wq,{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 yJ=()=>{try{return globalThis.localStorage}catch{return}},[bJ,xJ]=u(cz(yJ())),[SJ,CJ]=u();function wJ(e,t){let n=uz(bJ(),e,t),r=SJ();if(!r)return n;let[i,a,o]=r.key.split(`:`);return i===e&&Number(a)===t?{...n,[o]:r.sizes}:n}function TJ(e,t,n,r,i=!0){if(!i)return void CJ({key:`${e}:${t}:${n}`,sizes:r});CJ(void 0),xJ(i=>lz(yJ(),i,e,t,n,r))}var EJ=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>`),DJ=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.`),OJ=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`),kJ=I(`<div class=pane-tabs role=tablist aria-label="Open sessions">`),AJ=I(`<div><div class=pane-grid>`),jJ=I(`<button type=button>`),MJ=I(`<div role=presentation><button type=button role=tab>`),NJ=I(`<section class=pane tabindex=-1>`),PJ=I(`<p class="muted cmp-empty">Loading the artifact…`),FJ=E(()=>Hn(()=>import(`./ArtifactPane-B9weO8L6.js`).then(e=>({default:e.ArtifactPane})),__vite__mapDeps([7,1,8,9,10,11,12,13]))),IJ=6,LJ=[{split:`vertical`,label:`Side by side`,icon:`split`},{split:`horizontal`,label:`Stacked`,icon:`stack`},{split:`grid`,label:`Grid`,icon:`grid`}],RJ=e=>{let t=rn(e);return t===void 0?e.sideChatID?`${e.sessionID}#${e.sideChatID}`:e.sessionID:`!${t}`},zJ=e=>e.startsWith(`!`)?e.slice(1):void 0,BJ=e=>e.split(`#`)[0],VJ=e=>encodeURIComponent(e).replace(/%/g,`_`),HJ=e=>{let t=_u(e)?.session.title;return typeof t==`string`&&t?t:`Session`},UJ=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]);function WJ(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=ou();e.size&&En(t=>ic(t,e))});let c=xn,d=()=>c().panes.length,p=C(()=>c().panes.map(RJ),[],{equals:UJ}),g=e=>p().indexOf(e),_=()=>p()[c().focused],v=()=>c().split,w=()=>Z()&&d()>1,[T,E]=u({}),D=e=>{let t=zJ(e);return t===void 0?e.includes(`#`)?`Side chat: ${HJ(BJ(e))}`:HJ(BJ(e)):`Artifact: ${T()[t]??`…`}`},O=()=>!Z()&&d()>1,A=()=>!!Kp()&&!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=XR(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()?ez(v(),d()):{cols:1,rows:1},se=()=>wJ(v(),d()),ce=e=>(e===`cols`?re().w:re().h)-(oe()[e]-1)*IJ,le=(e,t)=>t>1?e.map(e=>`minmax(0, ${e}fr)`).join(` ${IJ}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=tz(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)=>TJ(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=EJ(),a=i.firstChild;return B(a,`dragend`,Yp),a.addEventListener(`dragstart`,n=>{let r=c().panes[t()];(!r||!Jp(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 qR.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 qR.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 qR.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(Wq,{id:e})})},get children(){return[n(l,{get when(){return!d()},get children(){var e=DJ();return e.firstChild.nextSibling.nextSibling,y(e,n(l,{get when(){return A()},get children(){return n($q,{label:`Open in a pane`})}}),null),e}}),(()=>{var e=AJ(),r=e.firstChild;y(e,n(l,{get when(){return O()},get children(){var e=OJ(),t=e.firstChild,r=t.nextSibling,i=r.firstChild,a=i.nextSibling;return a.nextSibling,e.$$keydown=z,y(t,n(m,{each:LJ,children:e=>(()=>{var t=jJ();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=kJ();return e.$$keydown=me,y(e,n(m,{get each(){return p()},children:e=>{let t=()=>_()===e,r=()=>D(e);return(()=>{var i=MJ(),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-${VJ(e)}`,s=`pane-${VJ(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=BJ(e),r=()=>g(e),i=()=>_()===e,a=()=>!w()||i();return(()=>{var o=NJ();return o.$$pointerdown=()=>N(g(e)),o.$$focusin=()=>N(g(e)),y(o,n(l,{get when(){return zJ(e)===void 0},get fallback(){return n(f,{get fallback(){return PJ()},get children(){return n(FJ,{get artifactID(){return zJ(e)},get paneTools(){return n(he,{key:e})},onTitle:t=>E(n=>({...n,[zJ(e)]:t}))})}})},get children(){return n(l,{get when(){return!e.includes(`#`)},get fallback(){return n(vJ,{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(Wq,{id:t,visible:a,focused:i,onGone:()=>I(e),rail:()=>!O()||i(),get paneTools(){return n(he,{key:e})}})}})}})),s(t=>{var n=`pane-${VJ(e)}`,s=w()?`tabpanel`:`region`,c=w()?`pane-tab-${VJ(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($q,{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(rJ,{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(rJ,{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 GJ={artifacts:E(()=>Hn(()=>import(`./Library-rv5DGtrm.js`),__vite__mapDeps([14,1,9,10,11,3,12,15]))),teams:E(()=>Hn(()=>import(`./TeamsPage-D_17MkvN.js`),__vite__mapDeps([16,1,9,17,18,19]))),watchtower:E(()=>Hn(()=>import(`./Watchtower-DlrNOJ7X.js`).then(e=>e.t),__vite__mapDeps([20,1,9,10,11,3,18,17,19,21]))),profiles:E(()=>Hn(()=>import(`./ProfilesDestination-DUuQ9jmd.js`),__vite__mapDeps([22,1,9,17])))},KJ=I(`<div class=feature-page><header class=topbar><h1 class=title></h1></header><div class=feature-scroll><div class=feature-body>`);function qJ(e){return(()=>{var t=KJ(),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:Dp})}}),i),y(i,()=>e.title),y(r,()=>e.actions,null),y(a,()=>e.children),t})()}var JJ=I(`<p class=feature-note> isn't available yet. <a href=/>Back to All sessions`),YJ=I(`<p class=muted>Loading…`);function XJ(e){let t=C(()=>Ye.find(t=>t.id===e.id)),r=C(()=>{let e=t();return e&&Ve(e,{signedIn:!!X()})===`ok`?GJ[e.id]:void 0});return n(l,{get when(){return r()},get fallback(){return n(qJ,{get title(){return t()?.label??`Not found`},get children(){var e=JJ(),n=e.firstChild;return y(e,()=>t()?.label??`This page`,n),e}})},children:r=>n(f,{get fallback(){return n(qJ,{get title(){return t().label},get children(){return YJ()}})},get children(){return n(D,{get component(){return r()},get rest(){return e.rest}})}})})}var ZJ=I(`<span class="badge-pill armed-left"role=timer title="How long this stays armed for a spoken answer">`),QJ=I(`<p class="muted small armed-why">Why: `),$J=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">`),eY=I(`<button type=button>`);function tY(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=ru()?.expiresAt;return e===void 0?``:Ze(e,o())},p=async e=>{a(!0);try{await Wb(t().id,e)}catch(e){q(U(e),`err`),a(!1)}};return(()=>{var e=$J(),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(),Su,ou()),null),y(a,n(l,{get when(){return f()},get children(){var e=ZJ();return y(e,f),e}}),null),y(c,()=>Re(t(),Su,ou())),y(e,n(dg,{get decision(){return t()}}),u),y(e,n(l,{get when(){return r(()=>!!t().recommendation?.why)()&&t().recommendation.why!==fg(t())},get children(){var e=QJ();return e.firstChild,y(e,()=>t().recommendation.why,null),e}}),u),y(u,n(m,{get each(){return t().options},children:e=>(()=>{var t=eY();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(!!zl()&&!zl().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 nY=I(`<button type=button class="btn small"aria-label="Restart the Concierge"title="Restart the Concierge (a new session)">Restart`),rY=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>`),aY=I(`<div class=concierge-asked aria-label="Decisions from the Concierge"role=group>`),oY=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>`),sY=I(`<div class=concierge-idle><form class=concierge-composer><textarea rows=1 aria-label="Ask the Concierge"placeholder="The Concierge is not running"disabled>`),cY=I(`<aside class="concierge-panel side"aria-label=Concierge tabindex=-1>`),lY=I(`<section class="concierge-panel page"aria-label=Concierge tabindex=-1>`),uY=I(`<p class="working-line muted small"role=status><span class="spinner small"></span> Working…`),dY=I(`<div class=concierge-scroll>`),fY=I(`<p class="note err"role=alert>Voice: `),pY=I(`<button type=button>`),mY=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)">`),hY=I(`<p class="muted small pad">Loading…`),gY=I(`<p class="muted small pad">`),_Y=I(`<p>`),vY=3e4,yY=80,bY=/^#decision-(dec_[A-Za-z0-9]{1,64})$/,xY=new Set([`starting`,`running`,`waiting_machine`,`backoff`,`failed`]),SY=()=>!!zl()&&!zl().reason;function CY(i){let a=Xl,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(()=>Hb()),m=C(()=>cc(Ul(),a(),p())),[h,g]=u(!1),[_,v]=u(),S,w=wR(),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();ld(e).then(e=>{e&&e.state!==`open`&&v(e),t()})}x(e(Pt,e=>{let t=bY.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&&bY.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=rY(),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(rL,{get sessionID(){return a().sessionID}})}}),null),y(e,n(l,{get when(){return r(()=>!!a())()&&xY.has(a().state)},get children(){var e=nY();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(tY,{get decision(){return e()}})}),n(l,{get when(){return m().length},get children(){var e=aY();return y(e,n(Og,{get decisions(){return m()}})),e}}),n(l,{get when(){return _()},keyed:!0,children:e=>(()=>{var t=oY(),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,Su,ou())),y(t,n(dg,{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=sY();return e.firstChild.addEventListener(`submit`,e=>e.preventDefault()),e})()},children:e=>n(wY,{id:e,get autofocus(){return i.mode===`side`}})})];return n(l,{get when(){return i.mode===`side`},get fallback(){return(()=>{var e=lY(),n=S;return typeof n==`function`?t(n,e):S=e,y(e,O),e})()},get children(){var e=cY(),n=S;return typeof n==`function`?t(n,e):S=e,y(e,O),e}})}function wY(r){let i=r.id,a=()=>_u(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),Jz(d.rows()))),A=C(()=>EY(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(),ql()))ld(e)});let te=e=>new URLSearchParams(Object.entries(e).flatMap(([e,t])=>t===void 0?[]:[[e,String(t)]])).toString(),I=new gz(d,e=>G(`${H(i)}/timeline?${te(e)}`),{limit:yY,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=hu(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)=>(Vb(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=rx,pe=()=>R().phase!==`off`&&R().sessionID===i,me=()=>R().error?.sessionID===i?R().error.message:void 0;M(qb.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}=$v(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()||(Ty(),ox.cancel()),await qb.toggle(i),qb.isOn(i)&&qb.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=M_(e);i&&D(i.text,i.kind),h()}async function Se(){let e=B().trim();if(!e||_e())return;let t=Hb(),n=Ws(e,t);if(n.kind===`answer`){ve(!0);try{await Wb(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()){qb.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=j_(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),vY),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=dY();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 hY()},get children(){return n(l,{get when(){return A().length},get fallback(){return(()=>{var e=gY();return y(e,()=>Xs(SY())),e})()},get children(){return n(DW,{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=_Y();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 uY()}}),null),e})(),(()=>{var e=mY(),r=e.firstChild,i=r.firstChild,a=i.nextSibling;y(e,n(l,{get when(){return pe()},get children(){return n(MB,{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:()=>qb.mute(),onEnd:()=>void qb.end(),onModel:()=>q(`The Concierge keeps its own model: change it in Settings → Concierge`),get notifyHint(){return tx()},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=fY();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 SY()||pe()},get children(){var e=pY();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 TY={unknown:`link`};function EY(e){let t=vu,n=[...ql().values()].map(e=>({...e,question:Be(e.question,Su)})),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,TY)}):i.type===`assistant`&&i.text.includes(`dec_`)?r.push({...i,text:zo(i.text,n,TY)}):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 DY=I(`<main class=entry><p></p><button type=button class=btn>Retry`),OY=I(`<main class=entry><p class=muted>Loading…`),kY=I(`<div class=drawer-backdrop>`),AY=I(`<div class=voice-strip>`),jY=I(`<div class=conn-banner role=status>Reconnecting to the hub…`),MY=I(`<div role=status aria-live=polite>`),NY=I(`<p class="muted cmp-empty"data-concierge-wait>Loading…`),PY=I(`<div><main class=main>`),FY=I(`<button type=button class="btn small">`),IY=I(`<div role=status aria-live=polite><span>`),LY=I(`<header class=topbar><span class="title display grow">Hub`),RY=I(`<div class=home-shell><div class=home-scroll>`),zY=()=>dt().name===`concierge`&&!Z(),BY=()=>{let e=WS();return e.name===`session`?ns(e.id,Xl(),nu(),Y.machines,Ql(),Ql()?[]:au()):void 0},VY=()=>{let e=WS();return BY()===`session`?e.id:void 0},HY=()=>pc(Sc(rx().phase===`off`,VY()),dt().name===`concierge`?Xl()?.sessionID:void 0);function UY(){Lu(()=>rx().phase!==`off`),x(()=>Ru(HY()));let[t,i]=u(``),[a,c]=u(!1),d=async()=>{i(``);try{if(!await Tu())return;Vu(HY()),pd(),Kf(),c(!0)}catch(e){i(`Cannot reach the hub: ${e.message}`)}};return x(e(()=>dt().name,e=>{e!==`pair`&&!a()&&d(),Z()&&Sp(!1)})),x(()=>{!X()&&a()&&dt().name!==`pair`&&c(!1)}),x(()=>{let e=dt();e.name===`session`&&ou().has(e.id)&&Vt(`/concierge`,{replace:!0})}),x(()=>ox.viewing(xc()??VY())),fe(()=>M(SA())),fe(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`b`&&(e.preventDefault(),Dp())};document.addEventListener(`keydown`,e),M(()=>document.removeEventListener(`keydown`,e))}),x(()=>Lp(zY())),x(()=>{let e=Rp(),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(hf,{get next(){return e().next},get error(){return e().error}})}),n(o,{get when(){return t()},get children(){var e=DY(),n=e.firstChild,r=n.nextSibling;return y(n,t),r.$$click=()=>void d(),e}}),n(o,{get when(){return!a()},get children(){return OY()}}),n(o,{get when(){return r(()=>dt().name===`approve`)()&&dt()},children:e=>n(_f,{get code(){return e().code}})}),n(o,{get when(){return r(()=>dt().name===`consent`)()&&dt()},children:e=>n(yf,{get flow(){return e().flow}})}),n(o,{when:!0,get children(){var e=PY(),t=e.firstChild;return y(e,n(l,{get when(){return!Z()||xp()},get children(){return[n(l,{get when(){return Z()},get children(){var e=kY();return e.$$click=()=>Sp(!1),e}}),n(l,{get when(){return!yp()||Z()},get children(){return[n(GR,{get phone(){return Z()},onClose:()=>Sp(!1),onCollapse:Dp}),n(l,{get when(){return!Z()},get children(){return n(Yx,{panel:`side`,label:`Resize sidebar`})}})]}})]}}),t),y(e,n(l,{get when(){return r(()=>!!yp())()&&!Z()},get children(){return n(vR,{onExpand:Dp})}}),t),y(t,n(l,{get when(){return r(()=>rx().phase!==`off`)()&&WS().name!==`session`},get children(){var e=AY();return y(e,n(aL,{})),e}}),null),y(t,n(l,{get when(){return Y.connection===`down`},get children(){return jY()}}),null),y(t,n(l,{get when(){return r(()=>Y.connection!==`down`)()&&Mu()},get children(){var e=MY();return y(e,()=>Mu()===`reconnecting`?`Reconnecting…`:`Updated`),s(()=>k(e,`sync-note ${Mu()}`)),e}}),null),y(t,n(l,{get when(){return r(()=>!(!Kp()||Z()||VY()))()&&WS().name!==`panes`},get children(){return n(tJ,{})}}),null),y(t,n(v,{get children(){return[n(o,{get when(){return r(()=>!nu())()&&(WS().name===`session`||WS().name===`panes`)||BY()===`wait`},get children(){return NY()}}),n(o,{get when(){return VY()||WS().name===`panes`},get children(){return n(WJ,{get routed(){return VY()}})}}),n(o,{get when(){return r(()=>WS().name===`new`)()&&WS()},children:e=>n(VS,_(()=>e()))}),n(o,{get when(){return r(()=>WS().name===`feature`)()&&WS()},children:e=>n(XJ,_(()=>e()))}),n(o,{get when(){return WS().name===`settings`},get children(){return n(wI,{})}}),n(o,{get when(){return WS().name===`concierge`},get children(){return n(CY,{mode:`page`})}}),n(o,{when:!0,get children(){return n(WY,{})}})]}}),null),y(e,n(l,{get when(){return zY()},get children(){return n(CY,{mode:`side`})}}),null),s(()=>k(e,`shell${yp()&&!Z()?` collapsed`:``}${Z()?` phone`:``}${xp()?` drawer`:``}`)),e}})]}}),n(_h,{}),n(WP,{}),n(re,{}),n(l,{get when(){return Ut()},children:e=>(()=>{var t=IY(),r=t.firstChild;return y(r,()=>e().text),y(t,n(l,{get when(){return e().action},get children(){var t=FY();return t.$$click=()=>{e().action.run(),Mt()},y(t,()=>e().action.label),t}}),null),s(()=>k(t,`toast ${e().kind}`)),t})()})]}function WY(){return(()=>{var e=RY(),t=e.firstChild;return y(e,n(l,{get when(){return Z()},get children(){var e=LY(),t=e.firstChild;return y(e,n(F,{icon:`menu`,label:`Open sidebar`,onClick:Dp}),t),y(e,n(TR,{}),null),e}}),t),y(t,n(Ux,{})),e})()}z([`click`]),me(()=>n(UY,{}),document.getElementById(`root`)),qf();export{OA as $,bP as A,LM as B,GG as C,NW as D,eG as E,uM as F,PM as G,yM as H,wM as I,jM as J,fM as K,pM as L,yP as M,mP as N,bz as O,cM as P,Qj as Q,VM as R,dG as S,uG as T,SM as U,FM as V,CM as W,tM as X,aM as Y,Xj as Z,kG as _,tK as a,Y as at,rG as b,cK as c,eK as d,gh as et,nK as f,AG as g,jG as h,rK as i,Dp as it,OP as j,HP as k,$G as l,MG as m,aK as n,Jp as nt,QG as o,hu as ot,bG as p,dM as q,iK as r,Z as rt,YG as s,gu as st,qJ as t,Yp as tt,oK as u,OG as v,oG as w,nG as x,DG as y,zM as z};