@openchamber/web 1.13.4 → 1.13.5

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 (34) hide show
  1. package/bin/cli-output.js +2 -0
  2. package/bin/cli-output.test.js +36 -0
  3. package/bin/cli.test.js +12 -0
  4. package/bin/lib/cli-http.js +1 -0
  5. package/bin/lib/cli-network.js +1 -0
  6. package/bin/lib/cli-paths.js +2 -0
  7. package/bin/lib/commands-tunnel.js +6 -2
  8. package/dist/assets/{DiagramView-BAoYIAGR.js → DiagramView-Bbj-QI7h.js} +1 -1
  9. package/dist/assets/{MarkdownRendererImpl-B0NE4mIY.js → MarkdownRendererImpl-BNr_9Jsb.js} +1 -1
  10. package/dist/assets/{MultiRunWindow-BT4kt6aB.js → MultiRunWindow-DMMu53kw.js} +1 -1
  11. package/dist/assets/{NewWorktreeDialog-Bx-zQyBp.js → NewWorktreeDialog-5TYBoMMA.js} +1 -1
  12. package/dist/assets/{OnboardingScreen-CbJOPUxm.js → OnboardingScreen-BucKVBD7.js} +1 -1
  13. package/dist/assets/{SessionSwitcherDropdown-BbUzUNEi.js → SessionSwitcherDropdown-B6kvduse.js} +1 -1
  14. package/dist/assets/{SettingsWindow-CSb8eo8p.js → SettingsWindow-BEfDro9b.js} +1 -1
  15. package/dist/assets/{TerminalView-ME5MOz7S.js → TerminalView-CMdqMpTy.js} +1 -1
  16. package/dist/assets/{main-fsOGbLGZ.js → main-DOdUrt3s.js} +3 -3
  17. package/dist/assets/{main-D6eC2bnV.js → main-KEVf2Yak.js} +2 -2
  18. package/dist/assets/{miniChat-DKGU29GZ.js → miniChat-Nlzqr3Df.js} +2 -2
  19. package/dist/assets/{mobile-YHQHMYWC.js → mobile-BIhOFhia.js} +2 -2
  20. package/dist/assets/{renderElectronMiniChatApp-3vxeddJO.js → renderElectronMiniChatApp-Cb1iUq8M.js} +2 -2
  21. package/dist/assets/{renderMobileApp-BrvLHYCY.js → renderMobileApp-7chEBHPK.js} +3 -3
  22. package/dist/assets/{useAppFontEffects-b7bqtGFf.js → useAppFontEffects-Bd0ks39c.js} +3 -3
  23. package/dist/index.html +1 -1
  24. package/dist/mini-chat.html +1 -1
  25. package/dist/mobile.html +1 -1
  26. package/package.json +1 -1
  27. package/server/lib/git/routes.test.js +4 -4
  28. package/server/lib/github/routes.js +1 -0
  29. package/server/lib/package-manager.js +1 -1
  30. package/server/lib/package-manager.test.js +8 -1
  31. package/server/lib/quota/providers/google/index.js +14 -6
  32. package/server/lib/quota/providers/index.js +3 -3
  33. package/server/lib/quota/providers/index.test.js +17 -0
  34. package/server/lib/tunnels/providers/ngrok.js +1 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-By2L9XvG.js","assets/vendor--Dwc_TRgJ.css","assets/MarkdownRendererImpl-B0NE4mIY.js","assets/index-BsXkdBYx.js","assets/index-B82A6jBD.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-By2L9XvG.js","assets/vendor--Dwc_TRgJ.css","assets/MarkdownRendererImpl-BNr_9Jsb.js","assets/index-BsXkdBYx.js","assets/index-B82A6jBD.css"])))=>i.map(i=>d[i]);
2
2
  import{e as de,R as g,a as on,d as Cs,p as qs,b as so,b4 as Ia,H as ae,_ as rn,j as a,b5 as Lv,b6 as Q4,b7 as Nv,b8 as Vv,b9 as Rv,ba as zv,bb as Ov,bc as $v,bd as Zv,be as qv,bf as Uv,bg as Wv,bh as Gv,bi as Kv,bj as Yv,bk as Jv,bl as Qv,bm as Xv,bn as ey,bo as ty,bp as ny,bq as sy,br as oy,bs as ry,bt as iy,bu as ay,bv as ly,bw as sm,k as ca,ad as cy,aa as om,bx as dy,by as uy,bz as fy,a9 as rm,a8 as im,bA as my,ae as am,bB as hy,af as py,ag as gy,u as I0,l as da,n as by,bC as X4,D as T0,q as j0,S as H0,v as Dd,w as gl,C as bl,I as lm,a7 as e3,bD as cm,F as dm,bE as um,bF as vy,bG as yy,bH as wy,bI as xy,bJ as Cy,bK as ky,bL as Sy,bM as My,bN as Ay,bO as Fy,bP as _y,bQ as By,bR as gi,bS as Dy,bT as Py,a4 as Ey,bU as Iy,bV as Ty,bW as fm,bX as mm,bY as Pd,bZ as hm,b_ as pm,b$ as gm,c0 as Wi,c1 as bm,aU as jy,aS as Hy,aT as Ke,c2 as Ly,c3 as Ny,c4 as Vy,aj as y2,T as Ry,ai as s6,c5 as zy,c6 as Oy,c7 as $y,c8 as Zy,c9 as qy,ca as Uy,L as o6,cb as Wy}from"./vendor-.bun-By2L9XvG.js";import{a as bi,e as nt,o as We,u as Zt,am as vl,an as yl,q as Ao,f as ds,D as qn,S as Tt,ao as c0,h as qt,w as Lt,_ as yo,b as Fe,ap as vm,aq as ym,ar as Gy,r as Ky,as as Yy,g as wm,at as Jy,au as Qy,av as Xy,aw as ew,ax as tw,ay as nw,az as sw,aA as ow,aB as rw,aC as iw,aD as aw,aE as lw,aF as cw,aG as dw,aH as uw,aI as fw,aJ as mw,aK as hw,aL as pw,aM as gw,aN as bw,aO as vw,aP as yw,aQ as ww,aR as xw,aS as Cw,aT as kw,aU as Sw,aV as Mw,aW as Aw,aX as Fw,aY as _w,aZ as Bw,a_ as Dw,a$ as Pw,b0 as Ew,b1 as Iw,b2 as Tw,b3 as jw,b4 as Hw,b5 as Lw,b6 as Nw,b7 as Vw,b8 as Rw,b9 as zw,ba as Ow,bb as $w,bc as Zw,bd as qw,be as Uw,bf as Ww,bg as Gw,bh as Kw,bi as Yw,bj as Jw,bk as Qw,bl as Xw,bm as ex,bn as tx,bo as nx,bp as sx,bq as ox,br as rx,bs as ix,bt as ax,bu as lx,bv as cx,bw as wl,x as U1,L as xm,a5 as d0,a6 as Ed,s as dx,i as ux,bx as fx,by as Cm,j as km,bz as W1,bA as Gr,a8 as Ys,G as mx,E as hx,F as px,bB as r6,bC as i6,bD as w2,bE as a6,bF as x2,bG as Id,bH as gx,bI as C2,bJ as ua,bK as bx,bL as vx,bM as u0,K as xl,v as yx,bN as Td,bO as jd,ab as wx,ad as xx}from"./index-BsXkdBYx.js";const Hd=new Set;function Cl(t){return Hd.add(t),()=>{Hd.delete(t)}}function to(t,e){const n=Array.isArray(t)?t:[t],s=Array.from(new Set(n));if(s.length===0)return;s.includes("all")&&s.splice(0,s.length,"all");const o={scopes:s,source:e?.source,timestamp:Date.now()};for(const r of Hd)try{const i=r(o);i instanceof Promise&&i.catch(l=>{console.error("[ConfigSync] Async listener failed:",l)})}catch(i){console.error("[ConfigSync] Listener threw:",i)}}function F1(t,e){return t.scopes.includes("all")||t.scopes.includes(e)}const t3="Updating OpenCode configuration...";let wo=0,Pr=t3;const Ld=new Set;function L0(){const t={isUpdating:wo>0,message:Pr};Ld.forEach(e=>e(t))}function no(t){wo+=1,wo===1?(Pr=t||t3,L0()):t&&(Pr=t,L0())}function xs(){wo!==0&&(wo-=1,wo===0&&(Pr=t3,L0()))}function Yn(t){Pr===t&&wo>0||(Pr=t,wo>0&&L0())}function KQ(t){return Ld.add(t),t({isUpdating:wo>0,message:Pr}),()=>{Ld.delete(t)}}function YQ(){return{isUpdating:wo>0,message:Pr}}const Cx=200,Js=new Map,kx=[{key:"code",Icon:"code-box",label:"Code"},{key:"terminal",Icon:"terminal-box",label:"Terminal"},{key:"rocket",Icon:"rocket",label:"Rocket"},{key:"flask",Icon:"flask",label:"Lab"},{key:"gamepad",Icon:"gamepad",label:"Game"},{key:"briefcase",Icon:"briefcase",label:"Work"},{key:"home",Icon:"home",label:"Home"},{key:"globe",Icon:"global",label:"Web"},{key:"leaf",Icon:"leaf",label:"Nature"},{key:"shield",Icon:"shield",label:"Security"},{key:"palette",Icon:"palette",label:"Design"},{key:"server",Icon:"server",label:"Server"},{key:"phone",Icon:"smartphone",label:"Mobile"},{key:"database",Icon:"database-2",label:"Data"},{key:"lightbulb",Icon:"lightbulb",label:"Idea"},{key:"music",Icon:"music",label:"Music"},{key:"camera",Icon:"camera",label:"Media"},{key:"book",Icon:"book-open",label:"Docs"},{key:"heart",Icon:"heart",label:"Favorite"}],Sm=Object.fromEntries(kx.map(t=>[t.key,t.Icon])),Mm=[{key:"keyword",label:"Purple",cssVar:"var(--syntax-keyword)"},{key:"string",label:"Green",cssVar:"var(--syntax-string)"},{key:"number",label:"Pink",cssVar:"var(--syntax-number)"},{key:"type",label:"Gold",cssVar:"var(--syntax-type)"},{key:"constant",label:"Cyan",cssVar:"var(--syntax-constant)"},{key:"comment",label:"Muted",cssVar:"var(--syntax-comment)"},{key:"error",label:"Red",cssVar:"var(--status-error)"},{key:"primary",label:"Blue",cssVar:"var(--primary)"},{key:"success",label:"Green",cssVar:"var(--status-success)"}],Am=Object.fromEntries(Mm.map(t=>[t.key,t.cssVar])),Sx=(t,e)=>{if(typeof t!="number"||t<=0)return null;const n=new URLSearchParams({v:String(t)});return typeof e?.iconColor=="string"&&e.iconColor.trim()&&n.set("iconColor",e.iconColor.trim()),(e?.themeVariant==="light"||e?.themeVariant==="dark")&&n.set("theme",e.themeVariant),n},Mx=(t,e)=>t?[bi()||"same-origin",t,e.toString()].join("|"):null,Ax=(t,e,n)=>{const s=Sx(e,n);if(!s)return null;const o=Mx(t,s);return o?{cacheKey:o,projectId:t,query:s}:null},Fx=()=>{for(;Js.size>Cx;){const t=Js.keys().next().value;if(typeof t!="string")return;const e=Js.get(t);e?.url&&typeof URL<"u"&&typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(e.url),Js.delete(t)}},_x=t=>{const e=Js.get(t.cacheKey);if(e?.url)return Promise.resolve(e.url);if(e?.promise)return e.promise;const n=nt(`/api/projects/${encodeURIComponent(t.projectId)}/icon`,{method:"GET",headers:{Accept:"image/*"},query:t.query}).then(async s=>{if(!s.ok||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;const o=await s.blob(),r=URL.createObjectURL(o);return Js.set(t.cacheKey,{url:r}),Fx(),r}).catch(()=>null).finally(()=>{const s=Js.get(t.cacheKey);s?.promise===n&&!s.url&&Js.delete(t.cacheKey)});return Js.set(t.cacheKey,{promise:n}),n},Bx=(t,e)=>{const n=de.c(10),s=t.id,o=t.iconImage?.updatedAt,r=e?.themeVariant,i=e?.iconColor;let l;n[0]!==i||n[1]!==s||n[2]!==r||n[3]!==o?(l=Ax(s,o,{themeVariant:r,iconColor:i}),n[0]=i,n[1]=s,n[2]=r,n[3]=o,n[4]=l):l=n[4];const c=l;let d;n[5]!==c?(d=()=>c?Js.get(c.cacheKey)?.url??null:null,n[5]=c,n[6]=d):d=n[6];const[u,f]=g.useState(d);let m,h;return n[7]!==c?(m=()=>{if(!c){f(null);return}const p=Js.get(c.cacheKey)?.url;if(p){f(p);return}let b=!1;return f(null),_x(c).then(w=>{b||f(w)}),()=>{b=!0}},h=[c],n[7]=c,n[8]=m,n[9]=h):(m=n[8],h=n[9]),g.useEffect(m,h),u},Fm=t=>{const e=de.c(21),{project:n,options:s,className:o,alt:r,draggable:i,fallback:l,onError:c}=t,d=r===void 0?"":r,u=i===void 0?!1:i,f=l===void 0?null:l,m=Bx(n,s),[h,p]=g.useState(!1);let b;e[0]===Symbol.for("react.memo_cache_sentinel")?(b=()=>{p(!1)},e[0]=b):b=e[0];const w=n.iconImage?.updatedAt;let v;if(e[1]!==n.id||e[2]!==m||e[3]!==w?(v=[m,n.id,w],e[1]=n.id,e[2]=m,e[3]=w,e[4]=v):v=e[4],g.useEffect(b,v),!m||h){let y;return e[5]!==f?(y=g.createElement(g.Fragment,null,f),e[5]=f,e[6]=y):y=e[6],y}let x;if(e[7]!==d||e[8]!==o||e[9]!==u||e[10]!==c||e[11]!==m){let y;e[13]!==c?(y=C=>{p(!0),c?.(C)},e[13]=c,e[14]=y):y=e[14];let k;e[15]!==d||e[16]!==o||e[17]!==u||e[18]!==m||e[19]!==y?(k={src:m,alt:d,className:o,draggable:u,onError:y},e[15]=d,e[16]=o,e[17]=u,e[18]=m,e[19]=y,e[20]=k):k=e[20],x=g.createElement("img",k),e[7]=d,e[8]=o,e[9]=u,e[10]=c,e[11]=m,e[12]=x}else x=e[12];return x},Dx=t=>{const e=Mm.map(r=>r.key),n=new Map;for(const r of e)n.set(r,0);for(const r of t)r.color&&n.has(r.color)&&n.set(r.color,(n.get(r.color)??0)+1);const s=Math.min(...n.values()),o=e.filter(r=>n.get(r)===s);return o[Math.floor(Math.random()*o.length)]},_r=qn(),Nd="projects",Vd="activeProjectId",Px=()=>{if(typeof window>"u")return"";const t=window.__OPENCHAMBER_LOCAL_ORIGIN__;return typeof t=="string"?t.trim().replace(/\/+$/,""):""},n3=()=>{const t=bi().trim().replace(/\/+$/,"");return t||""},_m=()=>{const t=n3();return t?`${Nd}:${encodeURIComponent(t)}`:Nd},Bm=()=>{const t=n3();return t?`${Vd}:${encodeURIComponent(t)}`:Vd},Dm=()=>{const t=n3();if(!t)return!0;const e=Px();return!!(e&&t===e)},Ex=(t,e)=>{const n=t.trim();return!n.startsWith("~")||!e?n:n==="~"?e:n.startsWith("~/")||n.startsWith("~\\")?`${e}${n.slice(1)}`:n},Ix=/^#(?:[\da-fA-F]{3}|[\da-fA-F]{6})$/,Pm=t=>{if(typeof t!="string")return null;const e=t.trim();return e&&Ix.test(e)?e.toLowerCase():null},ba=t=>{const e=t.trim();if(!e)return"";const n=_r.getItem("homeDirectory")||Zt.getState().homeDirectory||"",o=Ex(e,n).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},Em=t=>{const e=ba(t);if(!e||e==="/")return"Root";const n=e.split("/").filter(Boolean);return(n[n.length-1]||e).replace(/[-_]/g," ").replace(/\b\w/g,o=>o.toUpperCase())},Tx=t=>{if(!t||typeof t!="object")return;const e=t,n=typeof e.mime=="string"?e.mime.trim():"",s=typeof e.updatedAt=="number"&&Number.isFinite(e.updatedAt)?Math.max(0,Math.round(e.updatedAt)):0,o=e.source==="custom"||e.source==="auto"?e.source:null;if(!(!n||!s||!o))return{mime:n,updatedAt:s,source:o}},jx=t=>{const e=typeof t.type=="string"?t.type.trim().toLowerCase():"";if(e==="image/png"||e==="image/jpeg"||e==="image/svg+xml")return e;const n=t.name.toLowerCase();return n.endsWith(".png")?"image/png":n.endsWith(".jpg")||n.endsWith(".jpeg")?"image/jpeg":n.endsWith(".svg")?"image/svg+xml":null},Hx=async t=>await new Promise((e,n)=>{const s=new FileReader;s.onerror=()=>{n(new Error("Failed to read icon file"))},s.onload=()=>{const o=typeof s.result=="string"?s.result:"";if(!o){n(new Error("Failed to read icon file"));return}e(o)},s.readAsDataURL(t)}),Im=t=>{if(!Array.isArray(t))return[];const e=[],n=new Set,s=new Set;for(const o of t){if(!o||typeof o!="object")continue;const r=o,i=typeof r.path=="string"?r.path.trim():"";if(!i)continue;const l=ba(i);if(!l)continue;const c=vl(l);if(!c||n.has(c)||s.has(l))continue;n.add(c),s.add(l);const d={id:c,path:l};if(typeof r.label=="string"&&r.label.trim().length>0&&(d.label=r.label.trim()),typeof r.icon=="string"&&r.icon.trim().length>0&&(d.icon=r.icon.trim()),r.iconImage===null)d.iconImage=null;else{const u=Tx(r.iconImage);u&&(d.iconImage=u)}if(typeof r.color=="string"&&r.color.trim().length>0&&(d.color=r.color.trim()),r.iconBackground===null)d.iconBackground=null;else{const u=Pm(r.iconBackground);u&&(d.iconBackground=u)}typeof r.addedAt=="number"&&Number.isFinite(r.addedAt)&&r.addedAt>=0&&(d.addedAt=r.addedAt),typeof r.lastOpenedAt=="number"&&Number.isFinite(r.lastOpenedAt)&&r.lastOpenedAt>=0&&(d.lastOpenedAt=r.lastOpenedAt),typeof r.sidebarCollapsed=="boolean"&&(d.sidebarCollapsed=r.sidebarCollapsed),e.push(d)}return e},Tm=()=>{try{const t=_r.getItem(_m())||(Dm()?_r.getItem(Nd):null);return t?Im(JSON.parse(t)):[]}catch{return[]}},jm=()=>{try{const t=_r.getItem(Bm())||(Dm()?_r.getItem(Vd):null);if(typeof t=="string"&&t.trim().length>0)return t.trim()}catch{return null}return null},Gi=(t,e)=>{try{_r.setItem(_m(),JSON.stringify(t))}catch{}try{const n=Bm();e?_r.setItem(n,e):_r.removeItem(n)}catch{}},Bi=(t,e)=>{Gi(t,e),ds({projects:t,activeProjectId:e??void 0})},Lx=Tm(),Rd=t=>{const e=[],n=new Set;for(const s of t){const o=ba(s.path);!o||n.has(o)||(n.add(o),e.push({name:s.name?.trim(),path:o}))}return e},Nx=(t,e,n,s)=>{const o=ba(t.path);if(!o)return null;const r=vl(o),i=s===o;return{...e,id:r,path:o,label:Em(o),addedAt:e?.addedAt??n,lastOpenedAt:i?n:e?.lastOpenedAt??n}},Vx=()=>{if(typeof window>"u"||!Ao()?.runtime?.isVSCode)return null;const e=window.__VSCODE_CONFIG__,n=Array.isArray(e?.workspaceFolders)?e.workspaceFolders.map(o=>{const r=o,i=typeof r.path=="string"?r.path.trim():"";return i?{name:typeof r.name=="string"?r.name.trim():"",path:i}:null}).filter(o=>o!==null):[];if(n.length>0)return Rd(n);const s=e?.workspaceFolder;return typeof s!="string"||s.trim().length===0?null:Rd([{path:s}])},Hm=(t,e,n)=>{const s=Rd(t),o=n?ba(n):null,r=s.length===0&&o?[{path:o}]:o&&!s.some(u=>u.path===o)?[...s,{path:o}]:s;if(r.length===0)return null;const i=Date.now(),l=r.map(u=>Nx(u,e.find(f=>f.path===u.path)??null,i,o)).filter(u=>u!==null);if(l.length===0)return null;const c=o?l.find(u=>u.path===o)??null:l[0]??null,d=c?.id??l[0]?.id??null;return yl()&&console.log("[OpenChamber][VSCode][projects] Using workspace projects",l),{projects:l,activeProjectId:d,activeProject:c??l[0]??null}},Rx=(t,e)=>t===e?!0:!t||!e?t===e:t.mime===e.mime&&t.updatedAt===e.updatedAt&&t.source===e.source,zx=(t,e)=>t.length!==e.length?!1:t.every((n,s)=>{const o=e[s];return o?n.id===o.id&&n.path===o.path&&n.label===o.label&&n.icon===o.icon&&n.color===o.color&&n.iconBackground===o.iconBackground&&n.addedAt===o.addedAt&&n.lastOpenedAt===o.lastOpenedAt&&n.sidebarCollapsed===o.sidebarCollapsed&&Rx(n.iconImage,o.iconImage):!1}),Ox=()=>{const t=Vx();if(!t)return null;const e=Hm(t,[]);return e?{projects:e.projects,activeProjectId:e.activeProjectId}:null},s3=Ox(),ls=typeof window>"u"?!1:!!Ao()?.runtime?.isVSCode,N0=s3?.projects??(ls?[]:Lx),l6=s3?.activeProjectId??(ls?null:jm()),Lm=N0.some(t=>t.id===l6)?l6:N0[0]?.id??null;s3&&Gi(N0,Lm);const $t=on()(Cs((t,e)=>({projects:N0,activeProjectId:Lm,validateProjectPath:n=>{if(typeof n!="string"||n.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const s=ba(n);return s?{ok:!0,normalizedPath:s}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(n,s)=>{if(ls)return null;const{validateProjectPath:o}=e(),r=o(n);if(!r.ok||!r.normalizedPath)return null;const i=r.normalizedPath,l=e().projects.find(h=>h.path===i);if(l)return e().setActiveProject(l.id),l;const c=Date.now(),d=s?.label?.trim()||Em(i),f={id:vl(i),path:i,label:d,color:Dx(e().projects),addedAt:c,lastOpenedAt:c},m=[...e().projects,f];return t({projects:m}),yl()&&console.info("[ProjectsStore] Added project",f),e().setActiveProject(f.id),e().discoverProjectIcon(f.id),f},removeProject:n=>{if(ls)return;const s=e(),o=s.projects.find(l=>l.id===n),r=s.projects.filter(l=>l.id!==n);let i=s.activeProjectId;if(s.activeProjectId===n&&(i=r[0]?.id??null),t({projects:r,activeProjectId:i}),Bi(r,i),o){const l=o.path.replace(/\\/g,"/").replace(/\/+$/,"")||"/";Ie.setState(c=>{const d=new Map(c.availableWorktreesByProject);return d.delete(l),{availableWorktreesByProject:d}})}if(i){const l=r.find(c=>c.id===i);l&&(We.setDirectory(l.path),Zt.getState().setDirectory(l.path,{showOverlay:!1}))}else Zt.getState().goHome()},setActiveProject:n=>{if(ls)return;const{projects:s,activeProjectId:o}=e();if(o===n)return;const r=s.find(c=>c.id===n);if(!r)return;const i=Date.now(),l=s.map(c=>c.id===n?{...c,lastOpenedAt:i}:c);t({projects:l,activeProjectId:n}),Bi(l,n),We.setDirectory(r.path),Zt.getState().setDirectory(r.path,{showOverlay:!1})},setActiveProjectIdOnly:n=>{if(ls)return;const{projects:s,activeProjectId:o}=e();if(o===n||!s.find(c=>c.id===n))return;const i=Date.now(),l=s.map(c=>c.id===n?{...c,lastOpenedAt:i}:c);t({projects:l,activeProjectId:n}),Bi(l,n)},renameProject:(n,s)=>{if(ls)return;const o=s.trim();if(!o)return;const{projects:r,activeProjectId:i}=e(),l=r.map(c=>c.id===n?{...c,label:o}:c);t({projects:l}),Bi(l,i)},updateProjectMeta:(n,s)=>{if(ls)return;const{projects:o,activeProjectId:r}=e(),i=o.map(l=>{if(l.id!==n)return l;const c={...l};if(s.label!==void 0){const d=s.label.trim();d&&(c.label=d)}return s.icon!==void 0&&(c.icon=s.icon),s.color!==void 0&&(c.color=s.color),s.iconBackground!==void 0&&(c.iconBackground=Pm(s.iconBackground)),c});t({projects:i}),Bi(i,r)},uploadProjectIcon:async(n,s)=>{if(ls)return{ok:!1,error:"Custom icons are not supported in this runtime"};const o=jx(s);if(!o)return{ok:!1,error:"Only PNG, JPEG, and SVG are supported"};if(!Number.isFinite(s.size)||s.size<=0)return{ok:!1,error:"Icon file is empty"};if(s.size>5*1024*1024)return{ok:!1,error:"Icon exceeds size limit (5 MB)"};try{const i=(await Hx(s)).replace(/^data:[^;]+;/i,`data:${o};`),l=await nt(`/api/projects/${encodeURIComponent(n)}/icon`,{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({dataUrl:i})});if(!l.ok)return{ok:!1,error:(await l.json().catch(()=>null))?.error||"Failed to upload project icon"};const c=await l.json().catch(()=>null);return c?.settings&&e().synchronizeFromSettings(c.settings),{ok:!0}}catch(r){return{ok:!1,error:(r instanceof Error?r.message:String(r))||"Failed to upload project icon"}}},removeProjectIcon:async n=>{if(ls)return{ok:!1,error:"Custom icons are not supported in this runtime"};try{const s=await nt(`/api/projects/${encodeURIComponent(n)}/icon`,{method:"DELETE",headers:{Accept:"application/json"}});if(!s.ok)return{ok:!1,error:(await s.json().catch(()=>null))?.error||"Failed to remove project icon"};const o=await s.json().catch(()=>null);return o?.settings&&e().synchronizeFromSettings(o.settings),{ok:!0}}catch(s){return{ok:!1,error:(s instanceof Error?s.message:String(s))||"Failed to remove project icon"}}},discoverProjectIcon:async(n,s)=>{if(ls)return{ok:!1,error:"Custom icons are not supported in this runtime"};try{const o=await nt(`/api/projects/${encodeURIComponent(n)}/icon/discover`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({force:s?.force===!0})}),r=await o.json().catch(()=>null);return o.ok?(r?.settings&&e().synchronizeFromSettings(r.settings),{ok:!0,skipped:r?.skipped===!0,reason:typeof r?.reason=="string"?r.reason:void 0}):{ok:!1,error:r?.error||"Failed to discover project icon"}}catch(o){return{ok:!1,error:(o instanceof Error?o.message:String(o))||"Failed to discover project icon"}}},reorderProjects:(n,s)=>{if(ls)return;const{projects:o,activeProjectId:r}=e();if(n<0||n>=o.length||s<0||s>=o.length||n===s)return;const i=[...o],[l]=i.splice(n,1);i.splice(s,0,l),t({projects:i}),Bi(i,r)},resetForRuntimeSwitch:()=>{if(ls)return;const n=Tm(),s=jm(),o=n.some(r=>r.id===s)?s:n[0]?.id??null;t({projects:n,activeProjectId:o})},synchronizeFromSettings:n=>{if(ls)return;const s=Im(n.projects??[]),o=typeof n.activeProjectId=="string"&&n.activeProjectId.trim()?n.activeProjectId.trim():null,r=e();if(s.length===0&&r.projects.length>0){o!==r.activeProjectId&&(!o||r.projects.some(d=>d.id===o))&&(t({activeProjectId:o}),Gi(r.projects,o));return}const i=JSON.stringify(r.projects)!==JSON.stringify(s),l=r.activeProjectId!==o;if(!(!i&&!l)&&(t({projects:s,activeProjectId:o}),Gi(s,o),o)){const c=s.find(d=>d.id===o);c&&(We.setDirectory(c.path),Zt.getState().setDirectory(c.path,{showOverlay:!1}))}},syncVSCodeWorkspaceFolders:(n,s)=>{if(!ls)return null;const o=e(),r=o.activeProjectId?o.projects.find(u=>u.id===o.activeProjectId)??null:null,i=s??r?.path??null,l=Hm(n,o.projects,i);if(!l)return n.length===0&&!s&&o.projects.length>0&&(t({projects:[],activeProjectId:null}),Gi([],null)),null;const c=!zx(o.projects,l.projects),d=o.activeProjectId!==l.activeProjectId;return(c||d)&&(t({projects:l.projects,activeProjectId:l.activeProjectId}),Gi(l.projects,l.activeProjectId)),l.activeProject&&(We.setDirectory(l.activeProject.path),Zt.getState().setDirectory(l.activeProject.path,{showOverlay:!1})),l.activeProject},getActiveProject:()=>{const{projects:n,activeProjectId:s}=e();return s?n.find(o=>o.id===s)??null:null}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",t=>{const e=t.detail;e&&typeof e=="object"&&$t.getState().synchronizeFromSettings(e)});const $x=new Set(["init","review"]),JQ=t=>$x.has(t.name),c1="useCommandsStore",zd=t=>new Promise(e=>setTimeout(e,t)),Zx=5e3,qx="__default__",Od=new Map,fc=new Map,Nm=t=>t?.trim()||qx,d1=(t=t1())=>{Od.delete(Nm(t))},c6=t=>t.map(e=>[e.name,e.scope??"",e.description??"",e.agent??"",e.model??"",String(e.isBuiltIn===!0)].join("|")).join("||"),t1=()=>{try{const e=$t.getState().getActiveProject?.();if(e?.path?.trim())return e.path.trim();const n=We.getDirectory();if(n?.trim())return n.trim()}catch(t){console.warn("[CommandsStore] Error resolving config directory:",t)}return null},Ux=2e4,d6=300,u6=4,Wx=800,Gx=200,Kx=2e3,xo=on()(Cs(qs((t,e)=>({selectedCommandName:null,commands:[],isLoading:!1,commandDraft:null,setSelectedCommand:n=>{t({selectedCommandName:n})},setCommandDraft:n=>{t({commandDraft:n})},loadCommands:async()=>{const n=t1(),s=Nm(n),o=Date.now(),r=Od.get(s)??0;if(e().commands.length>0&&o-r<Zx)return!0;const l=fc.get(s);if(l)return l;const c=(async()=>{t({isLoading:!0});const d=e().commands,u=c6(d);let f=null;for(let m=0;m<3;m++)try{const h=n?`?directory=${encodeURIComponent(n)}`:"",b=(await We.withDirectory(n,()=>We.listCommandsWithDetails())).filter(x=>x.source!=="skill"),w=await Promise.all(b.map(async x=>{try{const y=await nt(`/api/config/commands/${encodeURIComponent(x.name)}${h}`,{headers:{"Cache-Control":"no-cache",...n?{"x-opencode-directory":n}:{}}});if(y.ok){const k=await y.json();let C=k.scope;if(!C&&k.sources){const S=k.sources;C=(S.md?.exists?S.md.scope:void 0)??(S.json?.exists?S.json.scope:void 0)??S.md?.scope??S.json?.scope}return C==="project"||C==="user"?{...x,scope:C}:{...x,scope:void 0}}}catch(y){console.warn(`[CommandsStore] Failed to fetch config for command ${x.name}:`,y)}return x})),v=c6(w);return t(u!==v?{commands:w,isLoading:!1}:{isLoading:!1}),Od.set(s,Date.now()),!0}catch(h){f=h;const p=200*(m+1);await new Promise(b=>setTimeout(b,p))}return console.error("Failed to load commands:",f),t({commands:d,isLoading:!1}),!1})();fc.set(s,c);try{return await c}finally{fc.delete(s)}},createCommand:async n=>{no("Creating command configuration…");let s=!1;try{console.log("[CommandsStore] Creating command:",n.name);const o={template:n.template||""};n.description&&(o.description=n.description),n.agent&&(o.agent=n.agent),n.model&&(o.model=n.model),n.scope&&(o.scope=n.scope),console.log("[CommandsStore] Command config to save:",o);const r=t1(),i=r?`?directory=${encodeURIComponent(r)}`:"",l=await nt(`/api/config/commands/${encodeURIComponent(n.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...r?{"x-opencode-directory":r}:{}},body:JSON.stringify(o)}),c=await l.json().catch(()=>null);if(!l.ok){const f=c?.error||"Failed to create command";throw new Error(f)}console.log("[CommandsStore] Command created successfully");const d=c?.requiresReload??!0;if(d1(r),d)return s=!0,await mc({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await e().loadCommands();return u&&to("commands",{source:c1}),u}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{s||xs()}},updateCommand:async(n,s)=>{no("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",n),console.log("[CommandsStore] Config received:",s);const r={};s.description!==void 0&&(r.description=s.description),s.agent!==void 0&&(r.agent=s.agent),s.model!==void 0&&(r.model=s.model),s.template!==void 0&&(r.template=s.template),console.log("[CommandsStore] Command config to update:",r);const i=t1(),l=i?`?directory=${encodeURIComponent(i)}`:"",c=await nt(`/api/config/commands/${encodeURIComponent(n)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(r)}),d=await c.json().catch(()=>null);if(!c.ok){const m=d?.error||"Failed to update command";throw new Error(m)}console.log("[CommandsStore] Command updated successfully");const u=d?.requiresReload??!0;if(d1(i),u)return o=!0,await mc({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const f=await e().loadCommands();return f&&to("commands",{source:c1}),f}catch(r){return console.error("[CommandsStore] Failed to update command:",r),!1}finally{o||xs()}},deleteCommand:async n=>{no("Deleting command configuration…");let s=!1;try{const o=t1(),r=o?`?directory=${encodeURIComponent(o)}`:"",i=await nt(`/api/config/commands/${encodeURIComponent(n)}${r}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await i.json().catch(()=>null);if(!i.ok){const u=l?.error||"Failed to delete command";throw new Error(u)}console.log("[CommandsStore] Command deleted successfully");const c=l?.requiresReload??!0;if(d1(o),c)return s=!0,await mc({message:l?.message,delayMs:l?.reloadDelayMs}),!0;const d=await e().loadCommands();return d&&to("commands",{source:c1}),e().selectedCommandName===n&&t({selectedCommandName:null}),d}catch(o){return console.error("Failed to delete command:",o),!1}finally{s||xs()}},getCommandByName:n=>{const{commands:s}=e();return s.find(o=>o.name===n)}}),{name:"commands-store",storage:so(()=>qn()),partialize:t=>({selectedCommandName:t.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=xo);async function Yx(t){const e=typeof t=="number"&&t>0?Math.min(t,d6):0;e>0&&await zd(e);const n=Date.now();let s=0,o=null;for(;Date.now()-n<Ux;){s+=1,Yn(`Waiting for OpenCode… (attempt ${s})`);try{if(await We.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const r=Date.now()-n,i=s<=u6&&r<1200?d6:Math.min(Wx+Math.max(0,s-u6)*Gx,Kx);await zd(i)}throw o||new Error("OpenCode did not become ready in time")}async function mc(t={}){const{message:e,delayMs:n}=t;try{Yn(e||"Refreshing commands…")}catch{}try{await Yx(n),Yn("Refreshing commands…");const s=xo.getState();d1(),await s.loadCommands(),to("commands",{source:c1})}catch(s){throw console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",s),Yn("OpenCode refresh failed. Please retry refreshing configuration manually."),await zd(1500),s}finally{xs()}}let f6=null;f6||(f6=Cl(t=>{if(t.source!==c1&&F1(t,"commands")){const{loadCommands:e}=xo.getState();e()}}));const Ho=()=>{const t=We.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const e=window.__zustand_directory_store__;if(e)return e.getState().currentDirectory}catch{}return null};function Jx(t){const e=t.replace(/\\/g,"/"),n=e.lastIndexOf("/skills/");if(n===-1)return;const o=e.substring(n+8).split("/");return o.length>=3?o[0]:void 0}const u1="useSkillsStore",$d=t=>new Promise(e=>setTimeout(e,t)),Qx=5e3,Xx="__default__",Zd=new Map,hc=new Map,Vm=t=>t?.trim()||Xx,Xi=(t=Ho())=>{Zd.delete(Vm(t))},eC=2e4,m6=300,h6=4,tC=800,nC=200,sC=2e3,ns=on()(Cs(qs((t,e)=>({selectedSkillName:null,skills:[],isLoading:!1,skillDraft:null,setSelectedSkill:n=>{t({selectedSkillName:n})},setSkillDraft:n=>{t({skillDraft:n})},loadSkills:async()=>{const n=Ho(),s=Vm(n),o=Date.now(),r=Zd.get(s)??0;if(e().skills.length>0&&o-r<Qx)return!0;const l=hc.get(s);if(l)return l;const c=(async()=>{t({isLoading:!0});const d=e().skills;let u=null;for(let f=0;f<3;f++)try{const m=n?`?directory=${encodeURIComponent(n)}`:"",h=await nt(`/api/config/skills${m}`);if(!h.ok)throw new Error(`Failed to list skills: ${h.status}`);const w=((await h.json()).skills||[]).map(v=>({name:v.name,path:v.path,scope:v.scope??"user",source:v.source??"opencode",description:v.sources?.md?.description||"",group:Jx(v.path)}));return t({skills:w,isLoading:!1}),Zd.set(s,Date.now()),!0}catch(m){u=m;const h=200*(f+1);await new Promise(p=>setTimeout(p,h))}return console.error("Failed to load skills:",u),t({skills:d,isLoading:!1}),!1})();hc.set(s,c);try{return await c}finally{hc.delete(s)}},getSkillDetail:async n=>{try{const s=Ho(),o=s?`?directory=${encodeURIComponent(s)}`:"",r=await nt(`/api/config/skills/${encodeURIComponent(n)}${o}`);return r.ok?await r.json():null}catch{return null}},createSkill:async n=>{no("Creating skill...");let s=!1;try{const o={name:n.name,description:n.description};n.instructions&&(o.instructions=n.instructions),n.scope&&(o.scope=n.scope),n.source&&(o.source=n.source),n.supportingFiles&&(o.supportingFiles=n.supportingFiles);const r=Ho(),i=r?`?directory=${encodeURIComponent(r)}`:"",l=await nt(`/api/config/skills/${encodeURIComponent(n.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),c=await l.json().catch(()=>null);if(!l.ok){const f=c?.error||"Failed to create skill";throw new Error(f)}const d=c?.requiresReload??!1;if(Xi(r),d)return s=!0,await f0({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await e().loadSkills();return u&&to("skills",{source:u1}),u}catch{return!1}finally{s||xs()}},updateSkill:async(n,s)=>{no("Updating skill...");let o=!1;try{const r={};s.description!==void 0&&(r.description=s.description),s.instructions!==void 0&&(r.instructions=s.instructions),s.supportingFiles!==void 0&&(r.supportingFiles=s.supportingFiles),s.targetPath!==void 0&&(r.targetPath=s.targetPath);const i=Ho(),l=i?`?directory=${encodeURIComponent(i)}`:"",c=await nt(`/api/config/skills/${encodeURIComponent(n)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),d=await c.json().catch(()=>null);if(!c.ok){const m=d?.error||"Failed to update skill";throw new Error(m)}const u=d?.requiresReload??!1;if(Xi(i),u)return o=!0,await f0({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const f=await e().loadSkills();return f&&to("skills",{source:u1}),f}catch{return!1}finally{o||xs()}},deleteSkill:async n=>{no("Deleting skill...");let s=!1;try{const o=Ho(),r=o?`?directory=${encodeURIComponent(o)}`:"",i=await nt(`/api/config/skills/${encodeURIComponent(n)}${r}`,{method:"DELETE"}),l=await i.json().catch(()=>null);if(!i.ok){const u=l?.error||"Failed to delete skill";throw new Error(u)}const c=l?.requiresReload??!1;if(Xi(o),c)return s=!0,await f0({message:l?.message,delayMs:l?.reloadDelayMs}),!0;const d=await e().loadSkills();return d&&to("skills",{source:u1}),e().selectedSkillName===n&&t({selectedSkillName:null}),d}catch{return!1}finally{s||xs()}},getSkillByName:n=>{const{skills:s}=e();return s.find(o=>o.name===n)},readSupportingFile:async(n,s)=>{try{const o=Ho(),r=o?`&directory=${encodeURIComponent(o)}`:"",i=await nt(`/api/config/skills/${encodeURIComponent(n)}/files/${encodeURIComponent(s)}?${r.slice(1)}`);return i.ok?(await i.json()).content??null:null}catch{return null}},writeSupportingFile:async(n,s,o)=>{try{const r=Ho(),i=r?`?directory=${encodeURIComponent(r)}`:"";return(await nt(`/api/config/skills/${encodeURIComponent(n)}/files/${encodeURIComponent(s)}${i}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(n,s)=>{try{const o=Ho(),r=o?`?directory=${encodeURIComponent(o)}`:"";return(await nt(`/api/config/skills/${encodeURIComponent(n)}/files/${encodeURIComponent(s)}${r}`,{method:"DELETE"})).ok}catch{return!1}}}),{name:"skills-store",storage:so(()=>qn()),partialize:t=>({selectedSkillName:t.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=ns);async function oC(t){const e=typeof t=="number"&&t>0?Math.min(t,m6):0;e>0&&await $d(e);const n=Date.now();let s=0,o=null;for(;Date.now()-n<eC;){s+=1,Yn(`Waiting for OpenCode… (attempt ${s})`);try{if(await We.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const r=Date.now()-n,i=s<=h6&&r<1200?m6:Math.min(tC+Math.max(0,s-h6)*nC,sC);await $d(i)}throw o||new Error("OpenCode did not become ready in time")}async function f0(t){try{Yn(t?.message||"Refreshing skills…")}catch{}try{await oC(t?.delayMs),Yn("Refreshing skills…");const e=ns.getState();Xi(),await e.loadSkills()&&to("skills",{source:u1})}catch(e){throw Yn("OpenCode refresh failed. Please retry."),await $d(1500),e}finally{xs()}}let p6=null;p6||(p6=Cl(t=>{if(t.source!==u1&&F1(t,"skills")){const{loadSkills:e}=ns.getState();e()}}));const g6=[{id:"anthropic",label:"Anthropic",description:"Anthropic's public skills repository",source:"anthropics/skills",defaultSubpath:"skills",sourceType:"github"},{id:"clawdhub",label:"ClawdHub",description:"Community skill registry with vector search",source:"clawdhub:registry",sourceType:"clawdhub"}],rC=5e3,iC="__default__",b6=new Map,pc=new Map,aC=t=>t?.trim()||iC,Ta=()=>{const t=We.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const e=window.__zustand_directory_store__;if(e)return e.getState().currentDirectory}catch{}return null},lC=on()(Cs((t,e)=>({sources:g6,itemsBySource:{},selectedSourceId:g6[0]?.id??null,pageInfoBySource:{},loadedSourceIds:{},clawdhubHasMoreBySource:{},isLoadingCatalog:!1,isLoadingSource:!1,isLoadingMore:!1,isScanning:!1,isInstalling:!1,lastCatalogError:null,lastScanError:null,lastInstallError:null,scanResults:null,setSelectedSource:n=>t({selectedSourceId:n}),loadCatalog:async n=>{const s=Ta(),o=aC(s),r=Date.now(),i=b6.get(o)??0,l=e().sources.length>0;if(!n?.refresh&&l&&r-i<rC)return!0;const c=pc.get(o);if(!n?.refresh&&c)return c;const d=(async()=>{t({isLoadingCatalog:!0,lastCatalogError:null});const u={sources:e().sources,itemsBySource:e().itemsBySource,pageInfoBySource:e().pageInfoBySource,loadedSourceIds:e().loadedSourceIds,clawdhubHasMoreBySource:e().clawdhubHasMoreBySource};let f=null;try{const m=n?.refresh?"?refresh=true":"",h=new AbortController,p=window.setTimeout(()=>h.abort(),3e3);try{const b=await nt(`/api/config/skills/catalog${m}`,{method:"GET",headers:{Accept:"application/json"},signal:h.signal}),w=await b.json().catch(()=>null);if(!b.ok||!w?.ok)throw f=w?.error||{kind:"unknown",message:`Failed to load catalog (${b.status})`},new Error(f.message);const v=w.sources&&w.sources.length>0?w.sources:u.sources,x=n?.refresh?{}:e().itemsBySource||{},y=n?.refresh?{}:e().pageInfoBySource||{},k=n?.refresh?{}:e().loadedSourceIds||{},C=n?.refresh?{}:e().clawdhubHasMoreBySource||{},S=e().selectedSourceId,M=S&&v.some(A=>A.id===S)?S:v[0]?.id??null;return t({sources:v,itemsBySource:x,pageInfoBySource:y,loadedSourceIds:k,clawdhubHasMoreBySource:C,selectedSourceId:M}),b6.set(o,Date.now()),!0}finally{window.clearTimeout(p)}}catch(m){return f=f||{kind:"unknown",message:m instanceof Error?m.message:String(m)},t({sources:u.sources,itemsBySource:u.itemsBySource,pageInfoBySource:u.pageInfoBySource,loadedSourceIds:u.loadedSourceIds,clawdhubHasMoreBySource:u.clawdhubHasMoreBySource,lastCatalogError:f||{kind:"unknown",message:"Failed to load catalog"}}),!1}finally{t({isLoadingCatalog:!1})}})();pc.set(o,d);try{return await d}finally{pc.delete(o)}},loadSource:async(n,s)=>{if(!n)return!1;t({isLoadingSource:!0,lastCatalogError:null});try{const o=Ta(),r=s?.refresh?"&refresh=true":"",i=o?`?directory=${encodeURIComponent(o)}&sourceId=${encodeURIComponent(n)}${r}`:`?sourceId=${encodeURIComponent(n)}${r}`,l=await nt(`/api/config/skills/catalog/source${i}`,{method:"GET",headers:{Accept:"application/json"}}),c=await l.json().catch(()=>null),d=Array.isArray(c?.items);if(!l.ok||!c?.ok&&!d){const m=await nt(`/api/config/skills/catalog${i}`,{method:"GET",headers:{Accept:"application/json"}}),h=await m.json().catch(()=>null),p=h?.itemsBySource?.[n];return m.ok&&h?.ok&&Array.isArray(p)?(t(b=>({itemsBySource:{...b.itemsBySource,[n]:p},pageInfoBySource:{...b.pageInfoBySource,[n]:{nextCursor:null}},loadedSourceIds:{...b.loadedSourceIds,[n]:!0},clawdhubHasMoreBySource:{...b.clawdhubHasMoreBySource,[n]:!1}})),!0):(t({lastCatalogError:c?.error||{kind:"unknown",message:`Failed to load source (${l.status})`}}),!1)}const u=c?.items||[],f=c?.nextCursor??null;return t(m=>({itemsBySource:{...m.itemsBySource,[n]:u},pageInfoBySource:{...m.pageInfoBySource,[n]:{nextCursor:f}},loadedSourceIds:{...m.loadedSourceIds,[n]:!0},clawdhubHasMoreBySource:{...m.clawdhubHasMoreBySource,[n]:u.length>0}})),!0}catch(o){return t({lastCatalogError:{kind:"unknown",message:o instanceof Error?o.message:String(o)}}),!1}finally{t({isLoadingSource:!1})}},loadMoreClawdHub:async()=>{const n=e().selectedSourceId;if(!n)return!1;const o=e().pageInfoBySource[n]?.nextCursor||null;t({isLoadingMore:!0});try{const r=Ta(),i=[`sourceId=${encodeURIComponent(n)}`];r&&i.push(`directory=${encodeURIComponent(r)}`),o&&i.push(`cursor=${encodeURIComponent(o)}`);const l=`?${i.join("&")}`,c=await nt(`/api/config/skills/catalog/source${l}`,{method:"GET",headers:{Accept:"application/json"}}),d=await c.json().catch(()=>null);if(!c.ok||!d?.ok)return!1;const u=d.nextCursor??null,f=e().itemsBySource[n]||[],m=d.items||[],h=new Map(f.map(w=>[`${w.sourceId}:${w.skillDir}`,w]));let p=0;for(const w of m){const v=`${w.sourceId}:${w.skillDir}`;h.has(v)||(p+=1),h.set(v,w)}const b=m.length===0||p===0;return t(w=>({itemsBySource:{...w.itemsBySource,[n]:Array.from(h.values())},pageInfoBySource:{...w.pageInfoBySource,[n]:{nextCursor:u}},clawdhubHasMoreBySource:{...w.clawdhubHasMoreBySource,[n]:!b}})),!0}catch{return!1}finally{t({isLoadingMore:!1})}},scanRepo:async n=>{t({isScanning:!0,lastScanError:null,scanResults:null});try{const s=Ta(),o=s?`?directory=${encodeURIComponent(s)}`:"",r=await nt(`/api/config/skills/scan${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)}),i=await r.json().catch(()=>null);if(!r.ok||!i){const l=i?.error||{kind:"unknown",message:"Failed to scan repository"};return t({lastScanError:l}),{ok:!1,error:l}}return i.ok?(t({scanResults:i.items||[]}),i):(t({lastScanError:i.error||{kind:"unknown",message:"Failed to scan repository"}}),i)}finally{t({isScanning:!1})}},installSkills:async(n,s)=>{no("Installing skills…"),t({isInstalling:!0,lastInstallError:null});let o=!1;try{const i=(typeof s?.directory=="string"&&s.directory.trim().length>0?s.directory.trim():null)??Ta(),l=i?`?directory=${encodeURIComponent(i)}`:"",c=await nt(`/api/config/skills/install${l}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(n)}),d=await c.json().catch(()=>null);if(!d){const u={kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:u}),Yn("Failed to install skills. Please retry."),{ok:!1,error:u}}if(!c.ok||!d.ok){const u=d.error||{kind:"unknown",message:"Failed to install skills"};return t({lastInstallError:u}),Yn(u.message||"Failed to install skills. Please retry."),{ok:!1,error:u}}return d.requiresReload?(o=!0,await f0({message:d.message,delayMs:d.reloadDelayMs})):(Yn(d.message||"Refreshing skills…"),Xi(i),ns.getState().loadSkills()),d}catch(r){const i={kind:"unknown",message:r instanceof Error?r.message:String(r)};return t({lastInstallError:i}),Yn("Failed to install skills. Please retry."),{ok:!1,error:i}}finally{t({isInstalling:!1}),o||xs()}}}),{name:"skills-catalog-store"})),cC=()=>{const t=We.getDirectory();if(typeof t=="string"&&t.trim().length>0)return t;try{const e=window.__zustand_directory_store__;if(e)return e.getState().currentDirectory}catch{}return null},n1=()=>{try{const e=$t.getState().getActiveProject?.();if(e?.path?.trim())return e.path.trim();const n=We.getDirectory();if(n?.trim())return n.trim()}catch(t){console.warn("[AgentsStore] Error resolving config directory:",t)}return null},dC=5e3,uC="__default__",qd=new Map,gc=new Map,Rm=t=>t?.trim()||uC,m0=(t=n1())=>{qd.delete(Rm(t))},v6=t=>t.map(e=>{const n=e;return[e.name,n.mode??"",typeof n.model=="object"&&n.model?`${n.model.providerID??""}/${n.model.modelID??""}`:String(n.model??""),String(n.temperature??""),String(n.topP??n.top_p??""),n.prompt??"",JSON.stringify(n.permission??null),n.scope??"",n.group??"",n.description??"",String(n.hidden===!0),String(n.native===!0)].join("|")}).join("||");function fC(t){if(!t)return;const e=t.replace(/\\/g,"/"),n=e.lastIndexOf("/agents/");if(n===-1)return;const o=e.substring(n+8).split("/");return o.length>1?o[0]:void 0}const QQ=t=>{const e=t;return e.native===!0||e.builtIn===!0},mC=t=>{const e=t;return e.hidden===!0||e.options?.hidden===!0},o3=t=>t.filter(e=>!mC(e)),h0="useAgentsStore",V0=t=>new Promise(e=>setTimeout(e,t)),hC=2e4,y6=300,w6=4,pC=800,gC=200,bC=2e3,ii=on()(Cs(qs((t,e)=>({selectedAgentName:null,agents:[],isLoading:!1,agentDraft:null,setSelectedAgent:n=>{t({selectedAgentName:n})},setAgentDraft:n=>{t({agentDraft:n})},loadAgents:async()=>{const n=n1(),s=Rm(n),o=Date.now(),r=qd.get(s)??0;if(e().agents.length>0&&o-r<dC)return!0;const l=gc.get(s);if(l)return l;const c=(async()=>{t({isLoading:!0});const d=e().agents,u=v6(d);for(let f=0;f<3;f++)try{const m=n?`?directory=${encodeURIComponent(n)}`:"",h=await We.listAgents(n),p=await Promise.all(h.map(async w=>{try{const v=await nt(`/api/config/agents/${encodeURIComponent(w.name)}${m}`,{headers:{"Cache-Control":"no-cache",...n?{"x-opencode-directory":n}:{}}});if(v.ok){const x=await v.json();let y=x.scope;if(!y&&x.sources){const S=x.sources;y=(S.md?.exists?S.md.scope:void 0)??(S.json?.exists?S.json.scope:void 0)??S.md?.scope??S.json?.scope}const k=x.sources?.md?.path,C=fC(k);return y==="project"||y==="user"?{...w,scope:y,group:C}:{...w,scope:void 0,group:C}}}catch(v){console.warn(`[AgentsStore] Failed to fetch config for agent ${w.name}:`,v)}return w})),b=v6(p);return t(u!==b?{agents:p,isLoading:!1}:{isLoading:!1}),qd.set(s,Date.now()),!0}catch{}return t({isLoading:!1}),!1})();gc.set(s,c);try{return await c}finally{gc.delete(s)}},createAgent:async n=>{no("Creating agent configuration…");let s=!1;try{console.log("[AgentsStore] Creating agent:",n.name);const o={mode:n.mode||"subagent"};n.description&&(o.description=n.description),n.model&&(o.model=n.model),n.variant&&(o.variant=n.variant),n.temperature!==void 0&&(o.temperature=n.temperature??null),n.top_p!==void 0&&(o.top_p=n.top_p??null),n.prompt&&(o.prompt=n.prompt),n.permission&&(o.permission=n.permission),n.disable!==void 0&&(o.disable=n.disable),n.scope&&(o.scope=n.scope),console.log("[AgentsStore] Agent config to save:",o);const r=n1(),i=r?`?directory=${encodeURIComponent(r)}`:"",l=await nt(`/api/config/agents/${encodeURIComponent(n.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...r?{"x-opencode-directory":r}:{}},body:JSON.stringify(o)}),c=await l.json().catch(()=>null);if(!l.ok){const f=c?.error||"Failed to create agent";throw new Error(f)}if(m0(r),c?.requiresManualRestart)return{ok:!0,requiresManualRestart:!0};if(c?.requiresReload??!0)return s=!0,await f1({message:c?.message,delayMs:c?.reloadDelayMs,scopes:["agents"],mode:"projects"}),{ok:!0};const u=await e().loadAgents();return u&&to("agents",{source:h0}),{ok:u}}catch(o){return console.error("Failed to create agent:",o),{ok:!1}}finally{s||xs()}},updateAgent:async(n,s)=>{no("Updating agent configuration…");let o=!1;try{const r={};s.mode!==void 0&&(r.mode=s.mode),s.description!==void 0&&(r.description=s.description),s.model!==void 0&&(r.model=s.model),"variant"in s&&(r.variant=s.variant??null),"temperature"in s&&(r.temperature=s.temperature??null),"top_p"in s&&(r.top_p=s.top_p??null),s.prompt!==void 0&&(r.prompt=s.prompt),s.permission!==void 0&&(r.permission=s.permission),s.disable!==void 0&&(r.disable=s.disable);const i=n1(),l=i?`?directory=${encodeURIComponent(i)}`:"",c=await nt(`/api/config/agents/${encodeURIComponent(n)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(r)}),d=await c.json().catch(()=>null);if(!c.ok){const m=d?.error||"Failed to update agent";throw new Error(m)}if(m0(i),d?.requiresManualRestart)return{ok:!0,requiresManualRestart:!0};if(d?.requiresReload??!0)return o=!0,await f1({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"projects"}),{ok:!0};const f=await e().loadAgents();return f&&to("agents",{source:h0}),{ok:f}}catch(r){throw console.error("Failed to update agent:",r),r}finally{o||xs()}},deleteAgent:async(n,s)=>{no("Deleting agent configuration…");let o=!1;try{const r=n1(),i=r?`?directory=${encodeURIComponent(r)}`:"",l=await nt(`/api/config/agents/${encodeURIComponent(n)}${i}`,{method:"DELETE",headers:{"Content-Type":"application/json",...r?{"x-opencode-directory":r}:{}},body:JSON.stringify({scope:s})}),c=await l.json().catch(()=>null);if(!l.ok){const f=c?.error||"Failed to delete agent";throw new Error(f)}if(m0(r),e().selectedAgentName===n&&t({selectedAgentName:null}),c?.requiresManualRestart)return{ok:!0,requiresManualRestart:!0};if(c?.requiresReload??!0)return o=!0,await f1({message:c?.message,delayMs:c?.reloadDelayMs,scopes:["agents"],mode:"projects"}),{ok:!0};const u=await e().loadAgents();return u&&to("agents",{source:h0}),{ok:u}}catch(r){throw console.error("Failed to delete agent:",r),r}finally{o||xs()}},getAgentByName:n=>{const{agents:s}=e();return s.find(o=>o.name===n)},getVisibleAgents:()=>{const{agents:n}=e();return o3(n)}}),{name:"agents-store",storage:so(()=>qn()),partialize:t=>({selectedAgentName:t.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=ii);async function vC(t){const e=typeof t=="number"&&t>0?Math.min(t,y6):0;e>0&&await V0(e);const n=Date.now();let s=0,o=null;for(;Date.now()-n<hC;){s+=1,Yn(`Waiting for OpenCode… (attempt ${s})`);try{if(await We.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const r=Date.now()-n,i=s<=w6&&r<1200?y6:Math.min(pC+Math.max(0,s-w6)*gC,bC);await V0(i)}throw o||new Error("OpenCode did not become ready in time")}const yC=t=>{if(!t||t.length===0)return["all"];const e=Array.from(new Set(t));return e.includes("all")?["all"]:e};async function wC(t={}){const{message:e,delayMs:n}=t,s=yC(t.scopes),o=t.mode??(s.includes("all")?"projects":"active");try{Yn(e||"Refreshing configuration…")}catch{}try{await vC(n);const r=Pe.getState(),i=ii.getState(),l=xo.getState(),c=ns.getState(),d=lC.getState(),u=s.includes("all")||s.includes("providers"),f=s.includes("all")||s.includes("agents"),m=s.includes("all")||s.includes("agents"),h=s.includes("all")||s.includes("commands"),p=s.includes("all")||s.includes("skills"),b=cC(),w=o==="projects"?$t.getState().projects:[],v=Array.from(new Set([...b?[b]:[],...w.map(k=>k.path).filter(Boolean)]));s.includes("all")&&o==="projects"&&Pe.setState({directoryScoped:{}}),u&&(Pe.getState().invalidateModelMetadataCache(),Pe.getState().invalidateProviderCache(o==="active"?b:void 0));const x=[];for(const k of v)u&&x.push(r.loadProviders({directory:k,source:"agentsStore:refreshConfig"}).then(()=>{})),f&&x.push(r.loadAgents({directory:k,source:"agentsStore:refreshConfig"}).then(()=>{}));const y=[];m&&(m0(b),y.push(i.loadAgents().then(()=>{}))),h&&(d1(b),y.push(l.loadCommands().then(()=>{}))),p&&(Xi(b),y.push(c.loadSkills().then(()=>{})),y.push(d.loadCatalog({refresh:!0}).then(()=>{}))),Yn("Refreshing configuration…"),await Promise.all([...x,...y])}catch(r){throw Yn("OpenCode refresh failed. Please retry."),await V0(1500),r}finally{xs()}}async function f1(t){await wC(t)}async function XQ(t){no(t?.message||"Reloading OpenCode configuration…");try{const e=await nt("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),n=await e.json().catch(()=>null);if(!e.ok){const o=n?.error||"Failed to reload configuration";throw new Error(o)}const s={...t,scopes:t?.scopes??["all"],mode:t?.mode??"projects"};n?.requiresReload?await f1({...s,message:n.message,delayMs:n.reloadDelayMs}):await f1(s)}catch(e){throw console.error("[reloadOpenCodeConfiguration] Failed:",e),Yn("Failed to reload configuration. Please try again."),await V0(2e3),xs(),e}}let x6=null;x6||(x6=Cl(t=>{if(t.source!==h0&&F1(t,"agents")){const{loadAgents:e}=ii.getState();e()}}));const ni=t=>typeof t=="string"?t.trim():"",C6=(t,e)=>!e||e<=0||t.length<=e?t:e<=3?t.slice(0,e):`${t.slice(0,e-3)}...`,xC={ai:"AI",api:"API",ernie:"ERNIE",glm:"GLM",gpt:"GPT",it:"IT",lfm:"LFM",lm:"LM",oss:"OSS",pdf:"PDF",rp:"RP",slerp:"SLERP",tars:"TARS",ui:"UI",vl:"VL",vlm:"VLM",aion:"Aion",anthropic:"Anthropic",chatgpt:"ChatGPT",claude:"Claude",codex:"Codex",codestral:"Codestral",command:"Command",deepseek:"DeepSeek",gemini:"Gemini",gemma:"Gemma",grok:"Grok",hunyuan:"Hunyuan",kimi:"Kimi",llama:"Llama",minimax:"MiniMax",mistral:"Mistral",mixtral:"Mixtral",nemotron:"Nemotron",openai:"OpenAI",qwen:"Qwen",rekaai:"RekaAI"},k6=t=>t?t[0].toUpperCase()+t.slice(1).toLowerCase():"",CC=t=>{const e=t.startsWith("~")?t.slice(1):t,n=e.lastIndexOf("/");return n>=0?e.slice(n+1):e},kC=t=>{const e=t.lastIndexOf(":");return e<=0||e>=t.length-1?{base:t,suffix:""}:{base:t.slice(0,e),suffix:t.slice(e+1)}},SC=t=>{const e=t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").split(/[-_\s]+/).map(s=>s.trim()).filter(Boolean),n=[];for(let s=0;s<e.length;s+=1){const o=e[s],r=e[s+1],i=e[s+2];if(/^(19|20)\d{2}$/.test(o)&&/^\d{2}$/.test(r??"")&&/^\d{2}$/.test(i??"")){n.push(`${o}-${r}-${i}`),s+=2;continue}if(/^\d$/.test(o)&&/^\d$/.test(r??"")){n.push(`${o}.${r}`),s+=1;continue}n.push(o)}return n},MC=t=>{const e=t.toLowerCase(),n=xC[e];if(n)return n;const s=e.match(/^qwen(\d(?:\.\d+)?)$/);return s?`Qwen${s[1]}`:/^o\d/.test(e)?e:/^v\d/.test(e)?`V${t.slice(1).toUpperCase()}`:/^\d+[on]$/.test(e)?e:/^[a-z]\d+[a-z]?$/.test(e)?e.toUpperCase():/^\d+(?:x\d+)?[a-z]+$/.test(e)?e.replace(/[a-z]+$/i,o=>o.toUpperCase()):/^\d+(?:\.\d+)?[a-z]$/.test(e)?e.replace(/[a-z]$/i,o=>o.toUpperCase()):/^[a-z]+\d+(?:\.\d+)?[a-z]*$/.test(e)?k6(e).replace(/([a-z])(\d)/i,"$1$2"):k6(t)},AC=t=>{const e=[...t];return e[0]==="GPT"&&e[1]&&/^(?:\d|\d+[a-z]|OSS$)/i.test(e[1])&&e.splice(0,2,`GPT-${e[1]}`),e[0]==="GLM"&&e[1]&&/^\d/.test(e[1])&&e.splice(0,2,`GLM-${e[1]}`),e[0]==="LFM"&&e[1]&&/^\d/.test(e[1])&&e.splice(0,2,`LFM${e[1]}`),e[0]==="Qwen"&&e[1]&&/^\d/.test(e[1])&&e.splice(0,2,`Qwen${e[1]}`),e},FC=t=>{const e=ni(t).toLowerCase();return e?e==="free"||e==="thinking"?e:zm(e):""},zm=t=>{const e=ni(t);if(!e)return"";const{base:n,suffix:s}=kC(CC(e)),o=AC(SC(n).map(MC));if(o.length>=2){const c=o[o.length-1],d=o[o.length-2];c==="Reasoning"&&d==="Non"&&o.splice(o.length-2,2,"(Non-Reasoning)")}const r=o[o.length-1];/^(19|20)\d{2}-\d{2}-\d{2}$/.test(r??"")&&(o[o.length-1]=`(${r})`);const i=o.join(" ").replace(/\s+\(/g," (").trim(),l=FC(s);return l?`${i} (${l})`:i},r3=(t,e,n={})=>{const s=ni(t?.name);if(s)return C6(s,n.maxLength);const o=ni(t?.id)||ni(e);return o?C6(zm(o),n.maxLength):n.fallbackLabel??""},_C=(t,e)=>{const n=t?.models;if(!(!n||!e))return Array.isArray(n)?n.find(s=>ni(s.id)===e):n[e]},Om=(t,e,n={})=>{const s=ni(e),o=_C(t,s);return r3(o,s,n)},ai=t=>t==="primary"||t==="all"||t===void 0||t===null,BC=t=>t.filter(e=>ai(e.mode)),i3=(t,e,n=1)=>{const s=BC(t);if(s.length<=1)return null;const o=s.findIndex(l=>l.name===e),i=((o>=0?o:0)+n+s.length)%s.length;return s[i]?.name??null},p0=t=>t.charAt(0).toUpperCase()+t.slice(1),DC=(t,e)=>{if(e){const r=t.find(i=>i.name===e);return p0(r?r.name:e)}const n=t.filter(r=>ai(r.mode)),o=n.find(r=>r.name==="build")||n[0]||t[0];return o?p0(o.name):"Select agent"},PC=(t,e,n="")=>Om(t,e,{fallbackLabel:n}),bc=t=>{if(!t||t.trim().length===0)return"Default";const e=t.trim();return/^\d+(\.\d+)?$/.test(e)?e:p0(e)},EC=t=>typeof t=="object"&&t!==null,k2=new Map,Ht=on()(qs((t,e)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,lastUsedProvider:null,saveSessionModelSelection:(n,s,o)=>t(r=>{const i=new Map(r.sessionModelSelections);return i.delete(n),i.set(n,{providerId:s,modelId:o}),{sessionModelSelections:i,lastUsedProvider:{providerID:s,modelID:o}}}),getSessionModelSelection:n=>e().sessionModelSelections.get(n)??null,saveSessionAgentSelection:(n,s)=>t(o=>{if(o.sessionAgentSelections.get(n)===s)return o;const r=new Map(o.sessionAgentSelections);return r.delete(n),r.set(n,s),{sessionAgentSelections:r}}),getSessionAgentSelection:n=>e().sessionAgentSelections.get(n)??null,saveAgentModelForSession:(n,s,o,r)=>t(i=>{const l=i.sessionAgentModelSelections.get(n)?.get(s);if(l?.providerId===o&&l?.modelId===r)return i;const c=new Map(i.sessionAgentModelSelections),d=new Map(c.get(n)??new Map);return c.delete(n),d.set(s,{providerId:o,modelId:r}),c.set(n,d),{sessionAgentModelSelections:c}}),getAgentModelForSession:(n,s)=>e().sessionAgentModelSelections.get(n)?.get(s)??null,saveAgentModelVariantForSession:(n,s,o,r,i)=>{const l=`${o}/${r}`;let c=k2.get(n);if(!c&&i&&(c=new Map,k2.set(n,c)),!c)return;let d=c.get(s);if(!d&&i&&(d=new Map,c.set(s,d)),!!d){if(!i){d.delete(l),d.size===0&&c.delete(s),c.size===0&&k2.delete(n);return}d.set(l,i)}},getAgentModelVariantForSession:(n,s,o,r)=>{const i=`${o}/${r}`;return k2.get(n)?.get(s)?.get(i)}}),{name:"selection-store",version:1,storage:so(()=>qn()),partialize:t=>{const e=Array.from(t.sessionModelSelections.entries()).slice(-150),n=Array.from(t.sessionAgentSelections.entries()).slice(-150),s=Array.from(t.sessionAgentModelSelections.entries()).slice(-150).map(([o,r])=>[o,Array.from(r.entries())]);return{sessionModelSelections:e,sessionAgentSelections:n,sessionAgentModelSelections:s,lastUsedProvider:t.lastUsedProvider}},merge:(t,e)=>{const n=EC(t)?t:void 0,s=new Map;return Array.isArray(n?.sessionAgentModelSelections)&&n.sessionAgentModelSelections.forEach(([o,r])=>{s.set(o,new Map(r))}),{...e,lastUsedProvider:n?.lastUsedProvider??e.lastUsedProvider,sessionModelSelections:new Map(n?.sessionModelSelections??[]),sessionAgentSelections:new Map(n?.sessionAgentSelections??[]),sessionAgentModelSelections:s}},migrate:t=>t})),Vo=t=>{if(typeof t!="string")return null;const e=t.trim();if(!e)return null;const n=e.replace(/\\/g,"/");return n==="/"?"/":n.length>1?n.replace(/\/+$/,""):n},$m=(t,e)=>{const n=Vo(e);if(!n)return null;let s=null;for(const o of t){const r=Vo(o.path);r&&(n!==r&&!n.startsWith(`${r}/`)||(!s||r.length>(Vo(s.path)?.length??0))&&(s=o))}return s},IC=(t,e,n)=>{const s=Vo(n);if(!s)return null;let o=null,r=null,i=-1;for(const[c,d]of e.entries())for(const u of d){const f=Vo(u.path);f&&(s!==f&&!s.startsWith(`${f}/`)||f.length>i&&(i=f.length,o=u,r=Vo(c)))}if(!o)return null;const l=[Vo(o.projectDirectory),r].filter(c=>!!c);for(const c of l){const d=t.find(f=>Vo(f.path)===c)??null;if(d)return d;const u=$m(t,c);if(u)return u}return null},Uo=(t,e,n)=>IC(t,e,n)??$m(t,n),a3=t=>{if(!t)return null;const e=t.indexOf("/");return e<=0||e>=t.length-1?null:{providerId:t.slice(0,e),modelId:t.slice(e+1)}};var hn;(t=>{function e(n,s,o){let r=0,i=n.length-1;for(;r<=i;){const l=Math.floor((r+i)/2),c=o(n[l]);if(c===s)return{found:!0,index:l};c<s?r=l+1:i=l-1}return{found:!1,index:r}}t.search=e})(hn||(hn={}));const l3=(t,e)=>t<e?-1:t>e?1:0;function Zm(t){return t.filter(e=>!!e?.id).sort((e,n)=>l3(e.id,n.id))}const TC=(t,e)=>t?e.every(n=>hn.search(t,n.id,s=>s.id).found):e.length===0,jC=(t,e)=>{if(!t)return Zm(e);const n=[...t];let s=!1;for(const o of e){const r=hn.search(n,o.id,i=>i.id);r.found||(n.splice(r.index,0,o),s=!0)}return s?n:t};function HC(t,e){if(e.length===0)return{...t,confirmed:[]};const n=[...t.session],s=new Map(t.part.map(r=>[r.id,Zm(r.part)])),o=[];for(const r of e){const i=hn.search(n,r.message.id,d=>d.id),l=i.found;l||n.splice(i.index,0,r.message);const c=s.get(r.message.id);if(l&&TC(c,r.parts)){o.push(r.message.id);continue}s.set(r.message.id,jC(c,r.parts))}return{cursor:t.cursor,complete:t.complete,session:n,part:[...s.entries()].sort((r,i)=>l3(r[0],i[0])).map(([r,i])=>({id:r,part:i})),confirmed:o}}function LC(t,e){const n=new Map(t.map(o=>[o.id,o]));let s=!1;for(const o of e)n.has(o.id)||(n.set(o.id,o),s=!0);return s?[...n.values()].sort((o,r)=>l3(o.id,r.id)):t}const c3=(t,e)=>t<e?-1:t>e?1:0,qm=["text","output"];function NC(t,e){return t.filter(n=>!!n?.id&&!e.has(n.type)).sort((n,s)=>c3(n.id,s.id))}function VC(t,e){if(!t)return e.length===0;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1){const s=t[n],o=e[n];if(!s||!o||s.id!==o.id||JSON.stringify(s)!==JSON.stringify(o))return!1}return!0}function Um(t){const e=t.state?.time?.end;if(typeof e=="number")return e;const n=t.time?.end;return typeof n=="number"?n:void 0}function Ud(t,e){const n=t[e];return typeof n=="string"?n:void 0}function RC(t){return Um(t)!==void 0?!1:qm.some(e=>{const n=Ud(t,e);return typeof n=="string"&&n.length>0})}function S6(t){const e=t.state?.time;if(!e||typeof e!="object")return;const n=typeof e.start=="number"?e.start:void 0,s=typeof e.end=="number"?e.end:void 0;if(!(n===void 0&&s===void 0))return{start:n,end:s}}function zC(t,e){if(!t||Um(e)!==void 0)return e;let n=e;for(const o of qm){const r=Ud(t,o);if(!r)continue;const i=Ud(e,o);if(typeof i=="string"&&i.length>=r.length||typeof i=="string"&&i.length>0&&!r.startsWith(i))continue;n===e&&(n={...e});const l=n;l[o]=r}const s=S6(t);if(s){const o=S6(e),r=o?.start??s.start,i=o?.end??s.end;if(r!==o?.start||i!==o?.end){n===e&&(n={...e});const l=n,d={...e.state??{},time:{start:r,end:i}};l.state=d}}return n}function OC(t,e,n,s){if(!t||t.length===0||!s)return e;const o=new Map(t.map(d=>[d.id,d]));let r=e,i=!1;for(let d=0;d<e.length;d+=1){const u=e[d],f=zC(o.get(u.id),u);f!==u&&(i||(r=[...e]),r[d]=f,i=!0)}const l=new Set(e.map(d=>d.id)),c=t.filter(d=>!!d?.id&&!l.has(d.id)&&!n.has(d.type)&&RC(d));return c.length===0?r:[...r,...c].sort((d,u)=>c3(d.id,u.id))}function G1(t,e,n,s={}){const o=s.skipPartTypes??new Set,r=n.filter(p=>!!p?.info?.id).sort((p,b)=>c3(p.info.id,b.info.id)),i=r.map(p=>p.info),l=t.message[e],c=l??[],d=LC(c,i),u=d!==c||l===void 0&&r.length===0;let f=!1;const m={...t.part},h=s.mode==="prepend";for(const p of r){const b=p.info.id;if(h&&m[b])continue;const w=m[b],v=OC(w,NC(p.parts??[],o),o,p.info.role==="assistant");VC(w,v)||(v.length===0?delete m[b]:m[b]=v,f=!0)}return{message:u?{...t.message,[e]:d}:t.message,part:f?m:t.part,messages:d,messagesChanged:u,partsChanged:f}}function vi(t,e){const n=t.message[e];if(!n)return{hasMessages:!1,renderable:!1,missingPartMessageIDs:[]};const s=[];for(const o of n){if(o.role!=="assistant")continue;const r=t.part[o.id];(!r||r.length===0)&&s.push(o.id)}return{hasMessages:!0,renderable:s.length===0,missingPartMessageIDs:s}}let _1=null,Wm="",Gm=null;const Wd=new Set;function $C(t,e,n,s){_1=e,Wm=n,s&&(Gm=s)}function d3(t,e){Gm?.(t,e)}function ZC(){if(!_1)throw new Error("ChildStoreManager not initialized — is SyncProvider mounted?");return _1}function Jo(t){const e=_1;if(!e)return;const n=t||Wm;if(n)return e.getState(n)}function Di(t){const e=Jo(t)?.config;return e&&Object.keys(e).length>0?e:void 0}function qC(t){return Wd.add(t),()=>{Wd.delete(t)}}function M6(t,e){if(t)for(const n of Wd)n(t,e)}function Ki(t){return Jo(t)?.session??[]}function Er(){const t=_1;if(!t)return[];const e=new Map;for(const n of t.children.values())for(const s of n.getState().session)s?.id&&e.set(s.id,s);return Array.from(e.values())}function us(t,e){return Jo(e)?.message[t]??[]}function eX(t,e){const n=Jo(e);return n?vi(n,t):{hasMessages:!1,renderable:!1,missingPartMessageIDs:[]}}function Es(t,e){return Jo(e)?.part[t]??[]}function Km(t,e){return Jo(e)?.session_status[t]}const UC="https://models.dev/api.json",WC="/api/openchamber/models-metadata",GC=-100,KC=0,YC=250,JC=1e4,R0="opencode",z0="big-pickle",QC="__add_provider__",Wr="zen",A6="big-pickle",XC=4,F6=t=>{if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(GC,Math.min(KC,t))},_6=t=>{if(!(typeof t!="number"||!Number.isFinite(t)))return Math.max(YC,Math.min(JC,Math.round(t)))},ek=async()=>{Tt("config.defaults:start");const t=typeof performance<"u"?performance.now():Date.now(),e=(n,s)=>{const o=typeof performance<"u"?performance.now():Date.now();return Tt("config.defaults:end",{source:n,durationMs:Math.round(o-t),hasDefaultModel:!!s.defaultModel,hasDefaultAgent:!!s.defaultAgent}),s};try{const n=Ao()?.settings;if(n)try{const y=(await n.load())?.settings;if(y){const k=typeof y?.defaultModel=="string"?y.defaultModel.trim():"",C=typeof y?.defaultVariant=="string"?y.defaultVariant.trim():"",S=typeof y?.defaultAgent=="string"?y.defaultAgent.trim():"",M=typeof y?.gitmojiEnabled=="boolean"?y.gitmojiEnabled:void 0,A=typeof y?.defaultFileViewerPreview=="boolean"?y.defaultFileViewerPreview:void 0,B=typeof y?.zenModel=="string"?y.zenModel.trim():"",F=y?.messageStreamTransport==="ws"||y?.messageStreamTransport==="sse"||y?.messageStreamTransport==="auto"?y.messageStreamTransport:void 0,_=y?.sttProvider==="browser"||y?.sttProvider==="server"||y?.sttProvider==="wasm"?y.sttProvider:void 0,D=typeof y?.sttServerUrl=="string"?y.sttServerUrl.trim():void 0,E=typeof y?.sttModel=="string"?y.sttModel.trim():void 0,I=typeof y?.sttLanguage=="string"?y.sttLanguage.trim():void 0,T=F6(y?.sttSilenceThresholdDb),j=_6(y?.sttSilenceHoldMs);return e("runtime-settings",{defaultModel:k.length>0?k:void 0,defaultVariant:C.length>0?C:void 0,defaultAgent:S.length>0?S:void 0,autoCreateWorktree:typeof y?.autoCreateWorktree=="boolean"?y.autoCreateWorktree:void 0,gitmojiEnabled:M,defaultFileViewerPreview:A,zenModel:B.length>0?B:void 0,messageStreamTransport:F,sttProvider:_,sttServerUrl:D,sttModel:E,sttLanguage:I,sttSilenceThresholdDb:T,sttSilenceHoldMs:j})}}catch{}const s=await nt("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!s.ok)return e("settings-route-not-ok",{});const o=await s.json(),r=typeof o?.defaultModel=="string"?o.defaultModel.trim():"",i=typeof o?.defaultVariant=="string"?o.defaultVariant.trim():"",l=typeof o?.defaultAgent=="string"?o.defaultAgent.trim():"",c=typeof o?.gitmojiEnabled=="boolean"?o.gitmojiEnabled:void 0,d=typeof o?.defaultFileViewerPreview=="boolean"?o.defaultFileViewerPreview:void 0,u=typeof o?.zenModel=="string"?o.zenModel.trim():"",f=o?.messageStreamTransport==="ws"||o?.messageStreamTransport==="sse"||o?.messageStreamTransport==="auto"?o.messageStreamTransport:void 0,m=o?.sttProvider==="browser"||o?.sttProvider==="server"?o.sttProvider:void 0,h=typeof o?.sttServerUrl=="string"?o.sttServerUrl.trim():void 0,p=typeof o?.sttModel=="string"?o.sttModel.trim():void 0,b=typeof o?.sttLanguage=="string"?o.sttLanguage.trim():void 0,w=F6(o?.sttSilenceThresholdDb),v=_6(o?.sttSilenceHoldMs);return e("settings-route",{defaultModel:r.length>0?r:void 0,defaultVariant:i.length>0?i:void 0,defaultAgent:l.length>0?l:void 0,autoCreateWorktree:typeof o?.autoCreateWorktree=="boolean"?o.autoCreateWorktree:void 0,gitmojiEnabled:c,defaultFileViewerPreview:d,zenModel:u.length>0?u:void 0,messageStreamTransport:f,sttProvider:m,sttServerUrl:h,sttModel:p,sttLanguage:b,sttSilenceThresholdDb:w,sttSilenceHoldMs:v})}catch(n){return Tt("config.defaults:error",{error:n instanceof Error?n.message:String(n)}),e("error",{})}},ea=t=>a3(t),tk=t=>t?.toLowerCase?.()??"",vr=t=>{if(typeof t!="string")return;const e=t.trim();return e.length>0?e:void 0},Qs=(t,e,n)=>{const s=t.find(o=>o.id===e);return s?s.models.some(o=>o.id===n):!1},nk=({providers:t,currentProviderId:e,currentModelId:n,currentVariant:s,settingsDefaultModel:o,settingsDefaultVariant:r})=>{const i=(d,u,f)=>{if(!f)return;const m=t.find(h=>h.id===d)?.models.find(h=>h.id===u);return m?.variants&&Object.prototype.hasOwnProperty.call(m.variants,f)?f:void 0};if(e&&n&&Qs(t,e,n))return{providerId:e,modelId:n,variant:i(e,n,s)};if(o){const d=ea(o);if(d&&Qs(t,d.providerId,d.modelId))return{providerId:d.providerId,modelId:d.modelId,variant:i(d.providerId,d.modelId,r)}}if(Qs(t,R0,z0))return{providerId:R0,modelId:z0};const l=t[0],c=l?.models[0];return l&&c?{providerId:l.id,modelId:c.id}:null},vc=({agents:t,providers:e,settingsDefaultAgent:n,settingsDefaultModel:s,settingsDefaultVariant:o,opencodeDefaultAgent:r,opencodeDefaultModel:i})=>{if(t.length===0)return{agentName:void 0};const l=(h,p,b)=>{if(!b)return;const w=e.find(v=>v.id===h)?.models.find(v=>v.id===p);return w?.variants&&Object.prototype.hasOwnProperty.call(w.variants,b)?b:void 0},c=t.filter(h=>ai(h.mode));let d;if(n&&(d=t.find(h=>h.name===n)),!d&&r){const h=t.find(p=>p.name===r);h&&ai(h.mode)&&h.hidden!==!0&&(d=h)}if(d||(d=c.find(h=>h.name==="build")||c[0]||t[0]),!d)return{agentName:void 0};let u,f,m;if(s){const h=ea(s);h&&Qs(e,h.providerId,h.modelId)&&(u=h.providerId,f=h.modelId,m=l(u,f,o))}if(!u&&d.model?.providerID&&d.model?.modelID&&Qs(e,d.model.providerID,d.model.modelID)&&(u=d.model.providerID,f=d.model.modelID,m=l(u,f,d.variant)),!u&&i){const h=ea(i);h&&Qs(e,h.providerId,h.modelId)&&(u=h.providerId,f=h.modelId)}if(!u)if(Qs(e,R0,z0))u=R0,f=z0;else{const h=e[0],p=h?.models[0];h&&p&&(u=h.id,f=p.id)}return{agentName:d.name,providerId:u,modelId:f,variant:m}},yc=({providers:t,settingsZenModel:e})=>{const n=vr(e);if(!Array.isArray(t)||t.length===0)return n?{providerId:Wr,modelId:n}:null;if(n&&Qs(t,Wr,n))return{providerId:Wr,modelId:n};if(Qs(t,Wr,A6))return{providerId:Wr,modelId:A6};const s=t.find(o=>o.id===Wr);if(s?.models.length){const o=Math.floor(Math.random()*s.models.length),r=vr(s.models[o]?.id);if(r)return{providerId:Wr,modelId:r}}return null},B1=t=>typeof t=="object"&&t!==null,O0=t=>Array.isArray(t)&&t.every(e=>typeof e=="string"),sk=t=>{if(!B1(t))return!1;const e=t;if(e.modalities){const{input:n,output:s}=e.modalities;if(n&&!O0(n)||s&&!O0(s))return!1}return!0},ok=t=>{if(!B1(t))return!1;const e=t;return e.models===void 0||B1(e.models)},Ym=(t,e)=>{const n=tk(t);return!n||!e?"":`${n}/${e}`},B6=t=>{if(!t)return[];const e=[];return t.text&&e.push("text"),t.audio&&e.push("audio"),t.image&&e.push("image"),t.video&&e.push("video"),t.pdf&&e.push("pdf"),e},rk=(t,e)=>({id:e.id,providerId:t,name:e.name,tool_call:e.capabilities?.toolcall,reasoning:e.capabilities?.reasoning,temperature:e.capabilities?.temperature,attachment:e.capabilities?.attachment,modalities:e.capabilities?{input:B6(e.capabilities.input),output:B6(e.capabilities.output)}:void 0,cost:e.cost?{input:e.cost.input,output:e.cost.output,cache_read:e.cost.cache?.read,cache_write:e.cost.cache?.write}:void 0,limit:e.limit,release_date:e.release_date}),ik=t=>{const e=new Map;if(!B1(t))return e;for(const[n,s]of Object.entries(t)){if(!ok(s))continue;const o=typeof s.id=="string"&&s.id.length>0?s.id:n,r=s.models;if(!(!r||!B1(r)))for(const[i,l]of Object.entries(r)){if(!sk(l))continue;const c=typeof i=="string"&&i.length>0?i:l.id;if(!c||typeof c!="string"||c.length===0)continue;const d={id:typeof l.id=="string"&&l.id.length>0?l.id:c,providerId:o,name:typeof l.name=="string"?l.name:void 0,tool_call:typeof l.tool_call=="boolean"?l.tool_call:void 0,reasoning:typeof l.reasoning=="boolean"?l.reasoning:void 0,temperature:typeof l.temperature=="boolean"?l.temperature:void 0,attachment:typeof l.attachment=="boolean"?l.attachment:void 0,modalities:l.modalities?{input:O0(l.modalities.input)?l.modalities.input:void 0,output:O0(l.modalities.output)?l.modalities.output:void 0}:void 0,cost:l.cost,limit:l.limit,knowledge:typeof l.knowledge=="string"?l.knowledge:void 0,release_date:typeof l.release_date=="string"?l.release_date:void 0,last_updated:typeof l.last_updated=="string"?l.last_updated:void 0},u=Ym(o,c);u&&e.set(u,d)}}return e},ak=async()=>{if(typeof fetch!="function")return new Map;const t=[WC,UC];for(const e of t){const n=typeof AbortController<"u"?new AbortController:void 0,s=n?setTimeout(()=>n.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(e),r={signal:n?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?r.mode="cors":r.credentials="same-origin";const i=o?await fetch(e,r):await nt(e,r);if(!i.ok)throw new Error(`Metadata request to ${e} returned status ${i.status}`);const l=await i.json();return ik(l)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${e})`):console.warn(`Failed to fetch model metadata from ${e}:`,o)}finally{s&&clearTimeout(s)}}return new Map};let g0=null;const lk=(t,e)=>{t().size>0||g0||(Tt("modelsMetadata:queued"),g0=c0("modelsMetadata",ak).then(s=>(s.size>0&&(Tt("modelsMetadata:set",{entries:s.size}),e(s)),s)).catch(()=>new Map).finally(()=>{g0=null}))},b0=t=>new Promise(e=>setTimeout(e,t)),ck=800,dk=async(t=ck)=>Promise.race([We.checkHealth().catch(()=>!1),b0(Math.max(1,t)).then(()=>!1)]),u3="__global__",wr=t=>{const e=typeof t=="string"?t.trim():"";return e.length>0?e:u3},ys=t=>t===u3?null:t,uk=()=>{if(typeof window>"u")return u3;const t=We.getDirectory()??Zt.getState().currentDirectory;return o1(t)},Jm="oc.worktreeProjectMap";let S2=null;const Qm=()=>{if(S2===null)try{const t=typeof localStorage<"u"?localStorage.getItem(Jm):null;S2=t?JSON.parse(t):{}}catch{S2={}}return S2},fk=(t,e)=>{if(!t||!e||t===e)return;const n=Qm();if(n[t]!==e){n[t]=e;try{localStorage.setItem(Jm,JSON.stringify(n))}catch{}}},m1=t=>{const e=typeof t=="string"?t.trim():"";return e?e.replace(/\\/g,"/").replace(/\/+$/,"")||"/":null},mk=()=>{try{return $t.getState().projects.map(t=>m1(t.path)).filter(t=>!!t)}catch{return[]}},hk=()=>{try{const{projects:t,activeProjectId:e}=$t.getState(),n=e?t.find(s=>s.id===e):null;return m1(n?.path??t[0]?.path??null)}catch{return null}},s1=t=>{const e=m1(t),n=mk();if(!e)return null;if(n.includes(e))return e;const s=m1(Qm()[e]);if(s)return s;try{const o=Uo($t.getState().projects,Ie.getState().availableWorktreesByProject,e),r=m1(o?.path??null);if(r&&r!==e)return fk(e,r),r}catch{return null}return null},o1=t=>wr(s1(t)),D6=new Map,wc=new Map,pk=3e4,gk=1e3,P6=(t,e)=>{const n=t.get(e);return typeof n=="number"&&Date.now()-n<pk},bk=t=>{const e=t.directoryScoped,n=t.activeDirectoryKey;if(!e||!n)return t;const s=e[n];if(!s)return t;const o={...t};return(!t.providers||t.providers.length===0)&&s.providers?.length&&(o.providers=s.providers),(!t.agents||t.agents.length===0)&&s.agents?.length&&(o.agents=s.agents),(!t.defaultProviders||Object.keys(t.defaultProviders).length===0)&&s.defaultProviders&&Object.keys(s.defaultProviders).length>0&&(o.defaultProviders=s.defaultProviders),s.opencodeDefaultAgent!==void 0&&(o.opencodeDefaultAgent=s.opencodeDefaultAgent),s.opencodeDefaultModel!==void 0&&(o.opencodeDefaultModel=s.opencodeDefaultModel),s.selectionSource&&(o.selectionSource=s.selectionSource),o},vk=(t=[],e=[])=>({providers:t,agents:e,currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{},opencodeDefaultAgent:void 0,opencodeDefaultModel:void 0,selectionSource:"auto"}),yk=(t,e,n,s)=>{if(!s)return!0;const o=t.find(r=>r.id===e)?.models.find(r=>r.id===n);return!!o?.variants&&Object.prototype.hasOwnProperty.call(o.variants,s)},E6=({agents:t,providers:e,currentAgentName:n,currentProviderId:s,currentModelId:o,currentVariant:r,selectionSource:i,resolvedAgentName:l,resolvedProviderId:c,resolvedModelId:d,resolvedVariant:u})=>{const f=n&&t.some(p=>p.name===n)?n:void 0,m=!!s&&!!o&&Qs(e,s,o)&&yk(e,s,o,r),h=i==="manual"&&(!!f||m);return{agentName:h?f??l:l,providerId:h&&m?s:c,modelId:h&&m?o:d,variant:h&&m?r:u,selectionSource:h?"manual":"auto"}},M2=new Map,xc=new Map;let A2=null;const Pe=on()(Cs(qs((t,e)=>({activeDirectoryKey:uk(),directoryScoped:{},providers:[],agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{},selectionSource:"auto",isConnected:!1,hasEverConnected:!1,connectionPhase:"connecting",lastDisconnectReason:null,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultVariant:void 0,settingsDefaultAgent:void 0,opencodeDefaultAgent:void 0,opencodeDefaultModel:void 0,settingsAutoCreateWorktree:!1,settingsGitmojiEnabled:!1,settingsDefaultFileViewerPreview:!1,settingsZenModel:void 0,settingsMessageStreamTransport:"auto",voiceProvider:(()=>{if(typeof window<"u"){const n=localStorage.getItem("voiceProvider");if(n==="openai"||n==="browser"||n==="say"||n==="openai-compatible")return n}return"browser"})(),speechRate:(()=>{if(typeof window<"u"){const n=localStorage.getItem("speechRate");if(n){const s=parseFloat(n);if(!isNaN(s)&&s>=.5&&s<=2)return s}}return 1})(),speechPitch:(()=>{if(typeof window<"u"){const n=localStorage.getItem("speechPitch");if(n){const s=parseFloat(n);if(!isNaN(s)&&s>=.5&&s<=2)return s}}return 1})(),speechVolume:(()=>{if(typeof window<"u"){const n=localStorage.getItem("speechVolume");if(n){const s=parseFloat(n);if(!isNaN(s)&&s>=0&&s<=1)return s}}return 1})(),sayVoice:(()=>{if(typeof window<"u"){const n=localStorage.getItem("sayVoice");if(n)return n}return"Samantha"})(),browserVoice:(()=>{if(typeof window<"u"){const n=localStorage.getItem("browserVoice");if(n)return n}return""})(),openaiVoice:(()=>{if(typeof window<"u"){const n=localStorage.getItem("openaiVoice");if(n)return n}return"nova"})(),openaiApiKey:(()=>{if(typeof window<"u"){const n=localStorage.getItem("openaiApiKey");if(n)return n}return""})(),openaiCompatibleUrl:(()=>{if(typeof window<"u"){const n=localStorage.getItem("openaiCompatibleUrl");if(n)return n}return""})(),openaiCompatibleApiKey:(()=>{if(typeof window<"u"){const n=localStorage.getItem("openaiCompatibleApiKey");if(n)return n}return""})(),openaiCompatibleVoice:(()=>{if(typeof window<"u"){const n=localStorage.getItem("openaiCompatibleVoice");if(n)return n}return"af_sky"})(),openaiCompatibleTtsModel:(()=>{if(typeof window<"u"){const n=localStorage.getItem("openaiCompatibleTtsModel");if(n&&n!=="speaches-ai/Kokoro-82M-v1.0-ONNX")return n}return"kokoro"})(),sttProvider:(()=>{if(typeof window<"u"){const n=localStorage.getItem("sttProvider");if(n==="browser"||n==="server"||n==="wasm")return n;if(window.__OPENCHAMBER_ELECTRON__?.runtime==="electron")return"wasm"}return"browser"})(),sttServerUrl:(()=>{if(typeof window<"u"){const n=localStorage.getItem("sttServerUrl");if(n)return n}return"http://localhost:8001/v1"})(),sttApiKey:(()=>{if(typeof window<"u"){const n=localStorage.getItem("sttApiKey");if(n)return n}return""})(),sttModel:(()=>{if(typeof window<"u"){const n=localStorage.getItem("sttModel");if(n)return n}return"deepdml/faster-whisper-large-v3-turbo-ct2"})(),wasmSttModel:(()=>{if(typeof window<"u"){const n=localStorage.getItem("wasmSttModel");if(n)return n}return"Xenova/whisper-base.en"})(),sttLanguage:(()=>{if(typeof window<"u"){const n=localStorage.getItem("sttLanguage");if(n!==null)return n}return""})(),sttSilenceThresholdDb:(()=>{if(typeof window<"u"){const n=localStorage.getItem("sttSilenceThresholdDb");if(n){const s=parseFloat(n);if(!isNaN(s))return s}}return-45})(),sttSilenceHoldMs:(()=>{if(typeof window<"u"){const n=localStorage.getItem("sttSilenceHoldMs");if(n){const s=parseInt(n,10);if(!isNaN(s))return s}}return 1500})(),sttTranscribeOnStop:typeof window<"u"&&localStorage.getItem("sttTranscribeOnStop")==="true",showMessageTTSButtons:typeof window<"u"&&localStorage.getItem("showMessageTTSButtons")==="true",ttsInputMode:typeof window<"u"&&localStorage.getItem("ttsInputMode")==="raw"?"raw":"sanitized",voiceModeEnabled:typeof window<"u"&&localStorage.getItem("voiceModeEnabled")==="true",summarizeMessageTTS:typeof window<"u"&&localStorage.getItem("summarizeMessageTTS")==="true",summarizeVoiceConversation:typeof window<"u"&&localStorage.getItem("summarizeVoiceConversation")==="true",summarizeCharacterThreshold:(()=>{if(typeof window<"u"){const n=localStorage.getItem("summarizeCharacterThreshold");if(n){const s=parseInt(n,10);if(!isNaN(s)&&s>=50&&s<=2e3)return s}}return 200})(),summarizeMaxLength:(()=>{if(typeof window<"u"){const n=localStorage.getItem("summarizeMaxLength");if(n){const s=parseInt(n,10);if(!isNaN(s)&&s>=50&&s<=2e3)return s}}return 500})(),activateDirectory:async n=>{const s=s1(n);if(!s){Tt("activateDirectory:skippedUnknownDirectory",{directory:n});return}const o=wr(s);let r=!1,i=!1;t(l=>{const c=l.directoryScoped[o];return c?(r=c.providers.length>0,i=c.agents.length>0,{activeDirectoryKey:o,providers:c.providers,agents:c.agents,currentProviderId:c.currentProviderId,currentModelId:c.currentModelId,currentVariant:c.currentVariant,currentAgentName:c.currentAgentName,selectedProviderId:c.selectedProviderId,agentModelSelections:c.agentModelSelections,defaultProviders:c.defaultProviders,opencodeDefaultAgent:c.opencodeDefaultAgent,opencodeDefaultModel:c.opencodeDefaultModel,selectionSource:c.selectionSource??"auto"}):{activeDirectoryKey:o,providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{},opencodeDefaultAgent:void 0,opencodeDefaultModel:void 0,selectionSource:"auto"}}),e().isConnected&&(r?P6(D6,o)?Tt("activateDirectory:providersFresh",{directoryKey:o}):(Tt("activateDirectory:refreshProvidersBackground",{directoryKey:o}),e().loadProviders({directory:ys(o),source:"activateDirectory:refresh"})):await e().loadProviders({directory:ys(o),source:"activateDirectory"}),i?P6(wc,o)?Tt("activateDirectory:agentsFresh",{directoryKey:o}):(Tt("activateDirectory:refreshAgentsBackground",{directoryKey:o}),e().loadAgents({directory:ys(o),source:"activateDirectory:refresh"})):await e().loadAgents({directory:ys(o),source:"activateDirectory"}))},invalidateProviderCache:n=>{const s=n===void 0?null:wr(n);t(o=>{const r={};let i=!1;const l={...o.directoryScoped},c=d=>d.providers.length===0&&Object.keys(d.defaultProviders).length===0?d:(i=!0,{...d,providers:[],defaultProviders:{}});if(s){const d=o.directoryScoped[s];d&&(l[s]=c(d))}else for(const[d,u]of Object.entries(o.directoryScoped))l[d]=c(u);return i&&(r.directoryScoped=l),(s===null||s===o.activeDirectoryKey)&&(o.providers.length>0&&(r.providers=[]),Object.keys(o.defaultProviders).length>0&&(r.defaultProviders={})),Object.keys(r).length>0?r:o})},loadProviders:async n=>{const s=n?.directory??ys(e().activeDirectoryKey),o=s1(s);if(!o){Tt("loadProviders:skippedUnknownDirectory",{requestedDirectory:s,source:n?.source??"unknown"});return}const r=o??We.getDirectory()??null,i=wr(o),l=n?.source??"unknown";Tt("loadProviders:called",{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r});const c=M2.get(i);if(c)return Tt("loadProviders:deduped",{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r}),c;const d=(async()=>{const u=typeof performance<"u"?performance.now():Date.now();Tt("loadProviders:start",{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r});const f=e().directoryScoped[i],m=f?.providers??(e().activeDirectoryKey===i?e().providers:[]),h=f?.defaultProviders??(e().activeDirectoryKey===i?e().defaultProviders:{});let p=null;for(let b=0;b<3;b++)try{lk(()=>e().modelsMetadata,C=>t({modelsMetadata:C}));const w=await c0("loadProviders:api",()=>We.getProvidersForConfig(ys(i)),{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r,attempt:b+1}),v=Array.isArray(w?.providers)?w.providers:[],x=w?.default||{},y=v.map(C=>{const S=C.models??{},M=Object.keys(S).map(A=>S[A]);return{...C,models:M}});t(C=>{const S=C.directoryScoped[i]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},M=C.activeDirectoryKey===i?C.currentProviderId:S.currentProviderId,A=C.activeDirectoryKey===i?C.currentModelId:S.currentModelId,B=C.activeDirectoryKey===i?C.currentVariant:S.currentVariant,F=nk({providers:y,currentProviderId:M,currentModelId:A,currentVariant:B,settingsDefaultModel:C.settingsDefaultModel,settingsDefaultVariant:C.settingsDefaultVariant}),_=C.activeDirectoryKey===i?C.selectedProviderId:S.selectedProviderId,D=_===QC||y.some(T=>T.id===_)?_:F?.providerId??y[0]?.id??"",E={...S,providers:y,defaultProviders:x,currentProviderId:F?.providerId??"",currentModelId:F?.modelId??"",currentVariant:F?.variant,selectedProviderId:D},I={directoryScoped:{...C.directoryScoped,[i]:E}};return C.activeDirectoryKey===i&&(I.providers=y,I.defaultProviders=x,I.currentProviderId=E.currentProviderId,I.currentModelId=E.currentModelId,I.currentVariant=E.currentVariant,I.selectedProviderId=D),I});const k=typeof performance<"u"?performance.now():Date.now();Tt("loadProviders:end",{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r,durationMs:Math.round(k-u),providers:y.length,models:y.reduce((C,S)=>C+S.models.length,0)}),D6.set(i,Date.now());return}catch(w){p=w,Tt("loadProviders:attemptError",{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r,attempt:b+1,error:w instanceof Error?w.message:String(w)});const v=200*(b+1);await new Promise(x=>setTimeout(x,v))}console.error("Failed to load providers:",p),Tt("loadProviders:error",{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r,error:p instanceof Error?p.message:String(p)}),t(b=>{const v={...b.directoryScoped[i]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:m,defaultProviders:h},x={directoryScoped:{...b.directoryScoped,[i]:v}};if(b.activeDirectoryKey===i&&(x.providers=m,x.defaultProviders=h,!b.currentProviderId&&!b.currentModelId&&b.settingsDefaultModel)){const y=ea(b.settingsDefaultModel);if(y){const k=m.find(C=>C.id===y.providerId);if(k?.models.some(C=>C.id===y.modelId)){const C=k.models.find(M=>M.id===y.modelId),S=b.settingsDefaultVariant&&C?.variants?.[b.settingsDefaultVariant]?b.settingsDefaultVariant:void 0;x.currentProviderId=y.providerId,x.currentModelId=y.modelId,x.currentVariant=S,x.selectedProviderId=y.providerId,v.currentProviderId=y.providerId,v.currentModelId=y.modelId,v.currentVariant=S,v.selectedProviderId=y.providerId}}}return x})})().finally(()=>M2.delete(i));return M2.set(i,d),d},setProvider:n=>{const{providers:s}=e(),o=s.find(l=>l.id===n);if(!o)return;const i=o.models[0]?.id||"";t(l=>{const c=l.activeDirectoryKey,u={...l.directoryScoped[c]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentVariant:l.currentVariant,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentProviderId:n,currentModelId:i,selectedProviderId:n,selectionSource:"manual"};return{currentProviderId:n,currentModelId:i,selectedProviderId:n,selectionSource:"manual",directoryScoped:{...l.directoryScoped,[c]:u}}})},setModel:n=>{t(s=>{const o=s.activeDirectoryKey,i={...s.directoryScoped[o]??{providers:s.providers,agents:s.agents,currentProviderId:s.currentProviderId,currentModelId:s.currentModelId,currentVariant:s.currentVariant,currentAgentName:s.currentAgentName,selectedProviderId:s.selectedProviderId,agentModelSelections:s.agentModelSelections,defaultProviders:s.defaultProviders},currentModelId:n,selectionSource:"manual"};return{currentModelId:n,selectionSource:"manual",directoryScoped:{...s.directoryScoped,[o]:i}}})},setCurrentVariant:n=>{t(s=>{if(s.currentVariant===n)return s;const o=s.activeDirectoryKey,i={...s.directoryScoped[o]??{providers:s.providers,agents:s.agents,currentProviderId:s.currentProviderId,currentModelId:s.currentModelId,currentVariant:s.currentVariant,currentAgentName:s.currentAgentName,selectedProviderId:s.selectedProviderId,agentModelSelections:s.agentModelSelections,defaultProviders:s.defaultProviders},currentVariant:n,selectionSource:"manual"};return{currentVariant:n,selectionSource:"manual",directoryScoped:{...s.directoryScoped,[o]:i}}})},getCurrentModelVariants:()=>{const s=e().getCurrentModel()?.variants;return s?Object.keys(s):[]},cycleCurrentVariant:()=>{const n=e().getCurrentModelVariants();if(n.length===0)return;const s=e().currentVariant;if(!s){e().setCurrentVariant(n[0]);return}const o=n.indexOf(s);if(o===-1||o===n.length-1){e().setCurrentVariant(void 0);return}e().setCurrentVariant(n[o+1])},setSelectedProvider:n=>{t(s=>{const o=s.activeDirectoryKey,i={...s.directoryScoped[o]??{providers:s.providers,agents:s.agents,currentProviderId:s.currentProviderId,currentModelId:s.currentModelId,currentAgentName:s.currentAgentName,selectedProviderId:s.selectedProviderId,agentModelSelections:s.agentModelSelections,defaultProviders:s.defaultProviders},selectedProviderId:n,selectionSource:"manual"};return{selectedProviderId:n,selectionSource:"manual",directoryScoped:{...s.directoryScoped,[o]:i}}})},saveAgentModelSelection:(n,s,o)=>{t(r=>{const i=r.activeDirectoryKey,l={...r.agentModelSelections,[n]:{providerId:s,modelId:o}},d={...r.directoryScoped[i]??{providers:r.providers,agents:r.agents,currentProviderId:r.currentProviderId,currentModelId:r.currentModelId,currentAgentName:r.currentAgentName,selectedProviderId:r.selectedProviderId,agentModelSelections:r.agentModelSelections,defaultProviders:r.defaultProviders},agentModelSelections:l,selectionSource:"manual"};return{agentModelSelections:l,selectionSource:"manual",directoryScoped:{...r.directoryScoped,[i]:d}}})},getAgentModelSelection:n=>{const{agentModelSelections:s}=e();return s[n]||null},loadAgents:async n=>{const s=n?.directory??ys(e().activeDirectoryKey),o=s1(s);if(!o)return Tt("loadAgents:skippedUnknownDirectory",{requestedDirectory:s,source:n?.source??"unknown"}),!1;const r=o??We.getDirectory()??null,i=wr(o),l=n?.source??"unknown";Tt("loadAgents:called",{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r});const c=xc.get(i);if(c)return Tt("loadAgents:deduped",{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r}),c;const d=(async()=>{const u=typeof performance<"u"?performance.now():Date.now();Tt("loadAgents:start",{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r});const m=e().directoryScoped[i]?.agents??(e().activeDirectoryKey===i?e().agents:[]);let h=null;for(let p=0;p<3;p++)try{const b=ys(i);(Di(s??void 0)??Di(b??void 0))&&Tt("loadAgents:syncConfigHit",{directoryKey:i,source:l});const[v,x]=await Promise.all([c0("loadAgents:api",()=>We.listAgents(b),{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r,attempt:p+1}),ek()]),y=Array.isArray(v)?v:[],k=M2.get(i);k&&(Tt("loadAgents:awaitProviders",{directoryKey:i,source:l}),await k);const C=Di(s??void 0)??Di(b??void 0),S=C!==void 0,M=S?vr(C.default_agent):void 0,A=S?vr(C.model):void 0,B=e().activeDirectoryKey===i?e().providers:e().directoryScoped[i]?.providers??[],F=vr(e().settingsZenModel),_=vr(x.zenModel),D=yc({providers:B,settingsZenModel:F}),E=yc({providers:B,settingsZenModel:_}),j=(D||E)?.modelId||_||F;t(re=>{const se=re.directoryScoped[i]??{providers:B,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},te=S?M:se.opencodeDefaultAgent??(re.activeDirectoryKey===i?re.opencodeDefaultAgent:void 0),ke=S?A:se.opencodeDefaultModel??(re.activeDirectoryKey===i?re.opencodeDefaultModel:void 0),be={...se,providers:B,agents:y,opencodeDefaultAgent:te,opencodeDefaultModel:ke},X={settingsDefaultModel:x.defaultModel,settingsDefaultVariant:x.defaultVariant,settingsDefaultAgent:x.defaultAgent,settingsAutoCreateWorktree:x.autoCreateWorktree??!1,settingsGitmojiEnabled:x.gitmojiEnabled??!1,settingsDefaultFileViewerPreview:x.defaultFileViewerPreview??!1,settingsZenModel:j,settingsMessageStreamTransport:x.messageStreamTransport??re.settingsMessageStreamTransport??"auto",sttProvider:x.sttProvider??re.sttProvider,sttServerUrl:x.sttServerUrl??re.sttServerUrl,sttModel:x.sttModel??re.sttModel,sttLanguage:x.sttLanguage??re.sttLanguage,sttSilenceThresholdDb:x.sttSilenceThresholdDb??re.sttSilenceThresholdDb,sttSilenceHoldMs:x.sttSilenceHoldMs??re.sttSilenceHoldMs,directoryScoped:{...re.directoryScoped,[i]:be}};return re.activeDirectoryKey===i&&(X.agents=y,X.opencodeDefaultAgent=te,X.opencodeDefaultModel=ke),X});const V=e(),H=V.directoryScoped[i],N=H?.opencodeDefaultAgent??(V.activeDirectoryKey===i?V.opencodeDefaultAgent:void 0),R=H?.opencodeDefaultModel??(V.activeDirectoryKey===i?V.opencodeDefaultModel:void 0);if(j&&j!==_&&j&&ds({zenModel:j,gitProviderId:"",gitModelId:""}).catch(()=>{}),y.length===0){t(se=>{const ke={...se.directoryScoped[i]??{providers:B,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:B,agents:[],currentAgentName:void 0},be={directoryScoped:{...se.directoryScoped,[i]:ke}};return se.activeDirectoryKey===i&&(be.currentAgentName=void 0),be});const re=typeof performance<"u"?performance.now():Date.now();return Tt("loadAgents:end",{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r,durationMs:Math.round(re-u),agents:y.length}),wc.set(i,Date.now()),!0}const U=(re,se)=>{const te=B.find(ke=>ke.id===re);return te?te.models.some(ke=>ke.id===se):!1},L={};if(x.defaultAgent&&!y.some(re=>re.name===x.defaultAgent)&&(L.defaultAgent=""),x.defaultModel){const re=ea(x.defaultModel);if(!re||!U(re.providerId,re.modelId))L.defaultModel="";else if(x.defaultVariant){const ke=B.find(be=>be.id===re.providerId)?.models.find(be=>be.id===re.modelId)?.variants;ke&&Object.prototype.hasOwnProperty.call(ke,x.defaultVariant)||(L.defaultVariant="")}}const Z=vc({agents:y,providers:B,settingsDefaultAgent:x.defaultAgent,settingsDefaultModel:x.defaultModel,settingsDefaultVariant:x.defaultVariant,opencodeDefaultAgent:N,opencodeDefaultModel:R}),Y=Z.agentName??y[0].name,fe=Z.providerId,Q=Z.modelId,pe=Z.variant;t(re=>{const se=re.directoryScoped[i]??{providers:B,agents:y,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},te=re.activeDirectoryKey===i,ke=te?re.currentAgentName:se.currentAgentName,be=te?re.currentProviderId:se.currentProviderId,X=te?re.currentModelId:se.currentModelId,ee=te?re.currentVariant:se.currentVariant,G=te?re.selectionSource:se.selectionSource??"auto",O=E6({agents:y,providers:B,currentAgentName:ke,currentProviderId:be,currentModelId:X,currentVariant:ee,selectionSource:G,resolvedAgentName:Y,resolvedProviderId:fe,resolvedModelId:Q,resolvedVariant:pe}),ie={...se,providers:B,agents:y,currentAgentName:O.agentName,currentProviderId:O.providerId??se.currentProviderId,currentModelId:O.modelId??se.currentModelId,currentVariant:O.variant,opencodeDefaultAgent:N,opencodeDefaultModel:R,selectionSource:O.selectionSource},oe={directoryScoped:{...re.directoryScoped,[i]:ie}};return te&&(oe.currentAgentName=O.agentName,oe.opencodeDefaultAgent=N,oe.opencodeDefaultModel=R,O.providerId&&O.modelId&&(oe.currentProviderId=O.providerId,oe.currentModelId=O.modelId,oe.currentVariant=O.variant),oe.selectionSource=O.selectionSource),oe}),Object.keys(L).length>0&&(t({settingsDefaultModel:L.defaultModel!==void 0?void 0:e().settingsDefaultModel,settingsDefaultVariant:L.defaultVariant!==void 0?void 0:e().settingsDefaultVariant,settingsDefaultAgent:L.defaultAgent!==void 0?void 0:e().settingsDefaultAgent}),ds(L).catch(()=>{}));const ne=typeof performance<"u"?performance.now():Date.now();return Tt("loadAgents:end",{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r,durationMs:Math.round(ne-u),agents:y.length}),wc.set(i,Date.now()),!0}catch(b){h=b,Tt("loadAgents:attemptError",{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r,attempt:p+1,error:b instanceof Error?b.message:String(b)});const w=200*(p+1);await new Promise(v=>setTimeout(v,w))}return console.error("Failed to load agents:",h),Tt("loadAgents:error",{directoryKey:i,source:l,requestedDirectory:s,effectiveDirectory:r,error:h instanceof Error?h.message:String(h)}),t(p=>{const b=p.activeDirectoryKey===i?p.providers:p.directoryScoped[i]?.providers??[],v={...p.directoryScoped[i]??{providers:b,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:b,agents:m},x={directoryScoped:{...p.directoryScoped,[i]:v}};return p.activeDirectoryKey===i&&(x.agents=m),x}),!1})().finally(()=>xc.delete(i));return xc.set(i,d),d},invalidateModelMetadataCache:()=>{g0=null,t({modelsMetadata:new Map})},setAgent:n=>{const{agents:s,providers:o,settingsDefaultModel:r,settingsDefaultVariant:i,currentProviderId:l,currentModelId:c}=e();if(t(d=>{const u=d.activeDirectoryKey,m={...d.directoryScoped[u]??{providers:d.providers,agents:d.agents,currentProviderId:d.currentProviderId,currentModelId:d.currentModelId,currentAgentName:d.currentAgentName,selectedProviderId:d.selectedProviderId,agentModelSelections:d.agentModelSelections,defaultProviders:d.defaultProviders},currentAgentName:n,selectionSource:"manual"};return{currentAgentName:n,selectionSource:"manual",directoryScoped:{...d.directoryScoped,[u]:m}}}),n){const{currentSessionId:d}=Ie.getState(),u=Ht.getState();d&&u.saveSessionAgentSelection(d,n),d&&Ie.getState().isOpenChamberCreatedSession(d)&&(u.getAgentModelForSession(d,n)||Ie.getState().initializeNewOpenChamberSession(d,s))}if(n){const{currentSessionId:d}=Ie.getState(),u=(p,b,w)=>{t(v=>{const x=v.activeDirectoryKey,k={...v.directoryScoped[x]??{providers:v.providers,agents:v.agents,currentProviderId:v.currentProviderId,currentModelId:v.currentModelId,currentVariant:v.currentVariant,currentAgentName:v.currentAgentName,selectedProviderId:v.selectedProviderId,agentModelSelections:v.agentModelSelections,defaultProviders:v.defaultProviders},currentProviderId:p,currentModelId:b,currentVariant:w,selectedProviderId:p,selectionSource:"manual"};return{currentProviderId:p,currentModelId:b,currentVariant:w,selectedProviderId:p,selectionSource:"manual",directoryScoped:{...v.directoryScoped,[x]:k}}})},f=(p,b,w)=>{const x=o.find(k=>k.id===p)?.models.find(k=>k.id===b)?.variants;if(!x)return;const y=d?Ht.getState().getAgentModelVariantForSession(d,n,p,b):void 0;for(const k of[y,w,i])if(k&&Object.prototype.hasOwnProperty.call(x,k))return k},m=s.find(p=>p.name===n),h=m?.model;if(h?.providerID&&h?.modelID){const{providerID:p,modelID:b}=h;if(o.find(x=>x.id===p)?.models.find(x=>x.id===b)){u(p,b,f(p,b,m?.variant));return}}if(d){const p=Ht.getState().getAgentModelForSession(d,n);if(p&&Qs(o,p.providerId,p.modelId)){const b=f(p.providerId,p.modelId,m?.variant);(l!==p.providerId||c!==p.modelId||e().currentVariant!==b)&&u(p.providerId,p.modelId,b);return}}if(r){const p=ea(r);if(p&&o.find(w=>w.id===p.providerId)?.models.some(w=>w.id===p.modelId)){u(p.providerId,p.modelId,f(p.providerId,p.modelId,m?.variant));return}}}},applyDefaultModelAgentSelection:()=>{const{agents:n,providers:s,settingsDefaultModel:o,settingsDefaultVariant:r,settingsDefaultAgent:i,opencodeDefaultAgent:l,opencodeDefaultModel:c}=e();if(n.length===0||s.length===0)return;const{agentName:d,providerId:u,modelId:f,variant:m}=vc({agents:n,providers:s,settingsDefaultAgent:i,settingsDefaultModel:o,settingsDefaultVariant:r,opencodeDefaultAgent:l,opencodeDefaultModel:c});d&&t(h=>{const p=h.activeDirectoryKey,w={...h.directoryScoped[p]??{providers:h.providers,agents:h.agents,currentProviderId:h.currentProviderId,currentModelId:h.currentModelId,currentVariant:h.currentVariant,currentAgentName:h.currentAgentName,selectedProviderId:h.selectedProviderId,agentModelSelections:h.agentModelSelections,defaultProviders:h.defaultProviders},currentAgentName:d,...u&&f?{currentProviderId:u,currentModelId:f,currentVariant:m,selectedProviderId:u}:{},selectionSource:"auto"},v={currentAgentName:d,selectionSource:"auto",directoryScoped:{...h.directoryScoped,[p]:w}};return u&&f&&(v.currentProviderId=u,v.currentModelId=f,v.currentVariant=m,v.selectedProviderId=u),v})},applyOpenCodeConfigDefaults:(n,s="syncConfig",o)=>{const r=n??ys(e().activeDirectoryKey),i=o1(r),l=ys(i),c=o??Di(r??void 0)??Di(l??void 0);if(!c)return;const d=vr(c.default_agent),u=vr(c.model);t(f=>{const m=f.directoryScoped[i],h=f.activeDirectoryKey===i,p=h?f.providers:m?.providers??[],b=h?f.agents:m?.agents??[],w=m??vk(p,b),v=w.opencodeDefaultAgent!==d||w.opencodeDefaultModel!==u||h&&(f.opencodeDefaultAgent!==d||f.opencodeDefaultModel!==u),x={...w,providers:p,agents:b,opencodeDefaultAgent:d,opencodeDefaultModel:u},y={directoryScoped:{...f.directoryScoped,[i]:x}};h&&(y.opencodeDefaultAgent=d,y.opencodeDefaultModel=u);const k=h?f.selectionSource:m?.selectionSource??"auto";if(p.length===0||b.length===0)return v?y:f;const C=vc({agents:b,providers:p,settingsDefaultAgent:f.settingsDefaultAgent,settingsDefaultModel:f.settingsDefaultModel,settingsDefaultVariant:f.settingsDefaultVariant,opencodeDefaultAgent:d,opencodeDefaultModel:u});if(!C.agentName)return v?y:f;const S=h?f.currentAgentName:w.currentAgentName,M=h?f.currentProviderId:w.currentProviderId,A=h?f.currentModelId:w.currentModelId,B=h?f.currentVariant:w.currentVariant,F=E6({agents:b,providers:p,currentAgentName:S,currentProviderId:M,currentModelId:A,currentVariant:B,selectionSource:k,resolvedAgentName:C.agentName,resolvedProviderId:C.providerId,resolvedModelId:C.modelId,resolvedVariant:C.variant}),_={...x,providers:p,agents:b,currentAgentName:F.agentName,...F.providerId&&F.modelId?{currentProviderId:F.providerId,currentModelId:F.modelId,currentVariant:F.variant,selectedProviderId:F.providerId}:{},selectionSource:F.selectionSource},D=w.currentAgentName!==_.currentAgentName||w.currentProviderId!==_.currentProviderId||w.currentModelId!==_.currentModelId||w.currentVariant!==_.currentVariant||w.selectedProviderId!==_.selectedProviderId||(w.selectionSource??"auto")!==_.selectionSource||h&&(f.currentAgentName!==F.agentName||f.selectionSource!==F.selectionSource||F.providerId!==void 0&&F.modelId!==void 0&&(f.currentProviderId!==F.providerId||f.currentModelId!==F.modelId||f.currentVariant!==F.variant||f.selectedProviderId!==F.providerId));return!v&&!D?f:(y.directoryScoped={...f.directoryScoped,[i]:_},h&&(y.currentAgentName=F.agentName,y.selectionSource=F.selectionSource,F.providerId&&F.modelId&&(y.currentProviderId=F.providerId,y.currentModelId=F.modelId,y.currentVariant=F.variant,y.selectedProviderId=F.providerId)),Tt("loadAgents:opencodeConfigDefaultsApplied",{directoryKey:i,eventDirectory:r,source:s}),y)})},setSettingsDefaultModel:n=>{t({settingsDefaultModel:n})},setSettingsDefaultVariant:n=>{t({settingsDefaultVariant:n})},setSettingsDefaultAgent:n=>{t({settingsDefaultAgent:n})},setSettingsAutoCreateWorktree:n=>{t({settingsAutoCreateWorktree:n})},setSettingsGitmojiEnabled:n=>{t({settingsGitmojiEnabled:n})},setSettingsDefaultFileViewerPreview:n=>{t({settingsDefaultFileViewerPreview:n})},setSettingsZenModel:n=>{t({settingsZenModel:n})},setSettingsMessageStreamTransport:n=>{t({settingsMessageStreamTransport:n})},getResolvedGitGenerationModel:()=>{const n=e();return yc({providers:n.providers,settingsZenModel:n.settingsZenModel})},setVoiceProvider:n=>{t({voiceProvider:n}),typeof window<"u"&&localStorage.setItem("voiceProvider",n)},setSpeechRate:n=>{const s=Math.max(.5,Math.min(2,n));t({speechRate:s}),typeof window<"u"&&localStorage.setItem("speechRate",String(s))},setSpeechPitch:n=>{const s=Math.max(.5,Math.min(2,n));t({speechPitch:s}),typeof window<"u"&&localStorage.setItem("speechPitch",String(s))},setSpeechVolume:n=>{const s=Math.max(0,Math.min(1,n));t({speechVolume:s}),typeof window<"u"&&localStorage.setItem("speechVolume",String(s))},setSayVoice:n=>{t({sayVoice:n}),typeof window<"u"&&localStorage.setItem("sayVoice",n)},setBrowserVoice:n=>{t({browserVoice:n}),typeof window<"u"&&localStorage.setItem("browserVoice",n)},setOpenaiVoice:n=>{t({openaiVoice:n}),typeof window<"u"&&localStorage.setItem("openaiVoice",n)},setOpenaiApiKey:n=>{t({openaiApiKey:n}),typeof window<"u"&&localStorage.setItem("openaiApiKey",n)},setOpenaiCompatibleUrl:n=>{t({openaiCompatibleUrl:n}),typeof window<"u"&&localStorage.setItem("openaiCompatibleUrl",n)},setOpenaiCompatibleApiKey:n=>{t({openaiCompatibleApiKey:n}),typeof window<"u"&&localStorage.setItem("openaiCompatibleApiKey",n)},setOpenaiCompatibleVoice:n=>{t({openaiCompatibleVoice:n}),typeof window<"u"&&localStorage.setItem("openaiCompatibleVoice",n)},setOpenaiCompatibleTtsModel:n=>{t({openaiCompatibleTtsModel:n}),typeof window<"u"&&localStorage.setItem("openaiCompatibleTtsModel",n)},setSttProvider:n=>{t({sttProvider:n}),typeof window<"u"&&localStorage.setItem("sttProvider",n),ds({sttProvider:n}).catch(()=>{})},setSttServerUrl:n=>{t({sttServerUrl:n}),typeof window<"u"&&localStorage.setItem("sttServerUrl",n),ds({sttServerUrl:n}).catch(()=>{})},setSttApiKey:n=>{t({sttApiKey:n}),typeof window<"u"&&localStorage.setItem("sttApiKey",n)},setSttModel:n=>{t({sttModel:n}),typeof window<"u"&&localStorage.setItem("sttModel",n),ds({sttModel:n}).catch(()=>{})},setWasmSttModel:n=>{t({wasmSttModel:n}),typeof window<"u"&&localStorage.setItem("wasmSttModel",n),ds({wasmSttModel:n}).catch(()=>{})},setSttLanguage:n=>{t({sttLanguage:n}),typeof window<"u"&&localStorage.setItem("sttLanguage",n),ds({sttLanguage:n}).catch(()=>{})},setSttSilenceThresholdDb:n=>{t({sttSilenceThresholdDb:n}),typeof window<"u"&&localStorage.setItem("sttSilenceThresholdDb",String(n)),ds({sttSilenceThresholdDb:n}).catch(()=>{})},setSttSilenceHoldMs:n=>{t({sttSilenceHoldMs:n}),typeof window<"u"&&localStorage.setItem("sttSilenceHoldMs",String(n)),ds({sttSilenceHoldMs:n}).catch(()=>{})},setSttTranscribeOnStop:n=>{t({sttTranscribeOnStop:n}),typeof window<"u"&&localStorage.setItem("sttTranscribeOnStop",String(n)),ds({sttTranscribeOnStop:n}).catch(()=>{})},setShowMessageTTSButtons:n=>{t({showMessageTTSButtons:n}),typeof window<"u"&&localStorage.setItem("showMessageTTSButtons",String(n))},setTtsInputMode:n=>{t({ttsInputMode:n}),typeof window<"u"&&localStorage.setItem("ttsInputMode",n)},setVoiceModeEnabled:n=>{t({voiceModeEnabled:n}),typeof window<"u"&&localStorage.setItem("voiceModeEnabled",String(n))},setSummarizeMessageTTS:n=>{t({summarizeMessageTTS:n}),typeof window<"u"&&localStorage.setItem("summarizeMessageTTS",String(n))},setSummarizeVoiceConversation:n=>{t({summarizeVoiceConversation:n}),typeof window<"u"&&localStorage.setItem("summarizeVoiceConversation",String(n))},setSummarizeCharacterThreshold:n=>{const s=Math.max(50,Math.min(2e3,n));t({summarizeCharacterThreshold:s}),typeof window<"u"&&localStorage.setItem("summarizeCharacterThreshold",String(s))},setSummarizeMaxLength:n=>{const s=Math.max(50,Math.min(2e3,n));t({summarizeMaxLength:s}),typeof window<"u"&&localStorage.setItem("summarizeMaxLength",String(s))},probeConnection:async n=>{if(await dk(n?.timeoutMs))return t({isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}),!0;const o=e();return o.isConnected?!0:(t({isConnected:!1,connectionPhase:o.hasEverConnected?"reconnecting":"connecting",lastDisconnectReason:"health_probe_unhealthy"}),!1)},checkConnection:async()=>{Tt("checkConnection:start");const n=5;let s=0,o=null;for(;s<n;)try{Tt("checkConnection:attempt",{attempt:s+1});const r=await c0("checkConnection:health",()=>We.checkHealth(),{attempt:s+1});if(!r&&s<n-1){const l=e().hasEverConnected;t({isConnected:!1,connectionPhase:l?"reconnecting":"connecting",lastDisconnectReason:"health_check_unhealthy"}),s+=1,await b0(400*s);continue}const i=e().hasEverConnected;return t(r?{isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}:{isConnected:!1,connectionPhase:i?"reconnecting":"connecting",lastDisconnectReason:"health_check_unhealthy"}),Tt("checkConnection:end",{healthy:r,attempts:s+1}),r}catch(r){o=r,s+=1;const i=400*s;await b0(i)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),t({isConnected:!1,connectionPhase:e().hasEverConnected?"reconnecting":"connecting",lastDisconnectReason:"health_check_failed"}),Tt("checkConnection:end",{healthy:!1,attempts:n}),!1},initializeApp:async()=>{if(A2)return Tt("initializeApp:deduped"),A2;const n=(async()=>{const s=typeof performance<"u"?performance.now():Date.now();Tt("initializeApp:start");try{const o=yl();o&&console.log("Starting app initialization...");const r=await e().checkConnection();if(o&&console.log("Connection check result:",r),!r){o&&console.log("Server not connected"),t({isConnected:!1,connectionPhase:e().hasEverConnected?"reconnecting":"connecting"});return}o&&console.log("Initializing app..."),Tt("initApp:skipped",{reason:"checkConnection already verified health"});const i=We.getDirectory()??Zt.getState().currentDirectory??ys(e().activeDirectoryKey),l=Uo($t.getState().projects,Ie.getState().availableWorktreesByProject,i??null),c=s1(l?.path??i??null),d=c??hk();if(!d){Tt("initializeApp:noProjectConfigDirectory"),t({isInitialized:!0,isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"});return}!c&&i!==d&&(Tt("initializeApp:normalizedUnknownDirectoryToProject",{initialDirectory:i,configDirectory:d}),We.setDirectory(d),Zt.getState().setDirectory(d,{showOverlay:!1}));const u=wr(d);e().activeDirectoryKey!==u&&t({activeDirectoryKey:u}),o&&console.log("Loading providers and agents..."),await Promise.all([e().loadProviders({directory:d,source:"initializeApp"}),e().loadAgents({directory:d,source:"initializeApp"})]),t({isInitialized:!0,isConnected:!0,hasEverConnected:!0,connectionPhase:"connected"}),e().prewarmProjectConfigs(d);const f=typeof performance<"u"?performance.now():Date.now();Tt("initializeApp:end",{durationMs:Math.round(f-s),providers:e().providers.length,agents:e().agents.length}),o&&console.log("App initialized successfully")}catch(o){console.error("Failed to initialize app:",o),t({isInitialized:!1,isConnected:!1,connectionPhase:e().hasEverConnected?"reconnecting":"connecting",lastDisconnectReason:"init_error"}),Tt("initializeApp:error",{error:o instanceof Error?o.message:String(o)})}})().finally(()=>{A2=null});return A2=n,n},prewarmProjectConfigs:async n=>{if(!e().isConnected)return;const s=o1(n??ys(e().activeDirectoryKey)),o=$t.getState().projects.map(l=>l.path).filter(l=>typeof l=="string"&&l.trim().length>0),r=new Set([s]),i=[];for(const l of o){const c=o1(l);if(r.has(c))continue;r.add(c);const d=e().directoryScoped[c];if(d?.providers.length&&d.agents.length)continue;const u=ys(c);u&&i.push(u)}for(const l of i){if(await b0(gk),!e().isConnected)return;const c=o1(l),d=e().directoryScoped[c],u=[];d?.providers.length||u.push(e().loadProviders({directory:l,source:"projectConfigPrewarm"})),d?.agents.length||u.push(e().loadAgents({directory:l,source:"projectConfigPrewarm"})),u.length>0&&await Promise.allSettled(u)}},getCurrentProvider:()=>{const{providers:n,currentProviderId:s}=e();return n.find(o=>o.id===s)},getCurrentModel:()=>{const n=e().getCurrentProvider(),{currentModelId:s}=e();if(n)return n.models.find(o=>o.id===s)},getCurrentAgent:()=>{const{agents:n,currentAgentName:s}=e();if(s)return n.find(o=>o.name===s)},getModelMetadata:(n,s)=>{const o=Ym(n,s);if(!o)return;const{modelsMetadata:r,providers:i}=e(),l=r.get(o);if(l)return l;const c=i.find(u=>u.id===n);if(!c)return;const d=c.models.find(u=>u.id===s);if(d)return rk(n,d)},getVisibleAgents:()=>{const{agents:n}=e();return o3(n)}}),{name:"config-store",storage:so(()=>qn()),merge:(t,e)=>bk({...e,...t&&typeof t=="object"?t:{}}),partialize:t=>({activeDirectoryKey:t.activeDirectoryKey,directoryScoped:t.directoryScoped,providers:t.providers,agents:t.agents,currentProviderId:t.currentProviderId,currentModelId:t.currentModelId,currentVariant:t.currentVariant,currentAgentName:t.currentAgentName,selectedProviderId:t.selectedProviderId,agentModelSelections:t.agentModelSelections,defaultProviders:t.defaultProviders,settingsDefaultModel:t.settingsDefaultModel,settingsDefaultVariant:t.settingsDefaultVariant,settingsDefaultAgent:t.settingsDefaultAgent,settingsAutoCreateWorktree:t.settingsAutoCreateWorktree,settingsGitmojiEnabled:t.settingsGitmojiEnabled,settingsDefaultFileViewerPreview:t.settingsDefaultFileViewerPreview,settingsZenModel:t.settingsZenModel,settingsMessageStreamTransport:t.settingsMessageStreamTransport,speechRate:t.speechRate,speechPitch:t.speechPitch,speechVolume:t.speechVolume})})));typeof window<"u"&&(window.__zustand_config_store__=Pe);const wk=async t=>{const e=Pe.getState(),n=Array.from(new Set([e.activeDirectoryKey,...Object.keys(e.directoryScoped)])).filter(i=>i.length>0);e.invalidateProviderCache();let s=0;const o=Math.min(XC,n.length),r=Array.from({length:o},async()=>{for(;s<n.length;){const i=n[s];s+=1,await Pe.getState().loadProviders({directory:ys(i),source:t})}});await Promise.all(r)};let I6=null;I6||(I6=Cl(async t=>{const e=[];if(We.clearConfigCache(),F1(t,"agents")){const{loadAgents:n}=Pe.getState();e.push(n({source:"configChange:agents"}).then(()=>{}))}F1(t,"providers")&&e.push(wk("configChange:providers")),e.length>0&&await Promise.all(e)}));let T6=null,j6=null;j6||(j6=qC((t,e)=>{Pe.getState().applyOpenCodeConfigDefaults(t,"syncConfig",e)}));typeof window<"u"&&!T6&&(T6=Zt.subscribe((t,e)=>{const n=wr(t.currentDirectory),s=wr(e.currentDirectory);n!==s&&(Tt("directoryStore:changed",{previous:s,next:n}),Pe.getState().activateDirectory(t.currentDirectory))}));const xk=["load failed","network connection was lost","network request failed","failed to fetch","econnreset","econnrefused","etimedout","socket hang up","opencode api unavailable","503","502"];function Ck(t){if(!t)return!1;const e=String(t instanceof Error?t.message:t).toLowerCase();if(xk.some(s=>e.includes(s)))return!0;const n=t?.status;return typeof n=="number"&&n>=500&&n<600}async function Dn(t,e={}){const{attempts:n=3,delay:s=500,factor:o=2,maxDelay:r=1e4,retryIf:i=Ck}=e;let l;for(let c=0;c<n;c++)try{return await t()}catch(d){if(l=d,c===n-1||!i(d))throw d;const u=Math.min(s*Math.pow(o,c),r);await new Promise(f=>setTimeout(f,u))}throw l}const kk=t=>{if(!t||typeof t!="object"||Array.isArray(t))return;const e={},n=t;return typeof n.messageID=="string"&&(e.messageID=n.messageID),typeof n.partID=="string"&&(e.partID=n.partID),Object.keys(e).length>0?e:void 0},Sk=t=>t===void 0?!1:!t||typeof t!="object"||Array.isArray(t)?!0:Object.keys(t).some(e=>e!=="messageID"&&e!=="partID"),Xm=(t,e)=>{if(!t||typeof t!="object"||!(typeof t.before=="string"||typeof t.after=="string"||typeof t.from=="string"||typeof t.to=="string"||e&&"patch"in t&&typeof t.patch=="string"))return t;const s={...t};return delete s.before,delete s.after,delete s.from,delete s.to,e&&delete s.patch,s};function Ir(t){const e=t.summary,n=t.revert;let s=t,o=!1;if(n&&(typeof n.snapshot=="string"||typeof n.diff=="string")){const i={...n};delete i.snapshot,delete i.diff,s={...s,revert:i},o=!0}if(!e?.diffs||!Array.isArray(e.diffs))return s;const r=e.diffs.map(i=>{const l=Xm(i,!0);return l!==i&&(o=!0),l});return o?{...s,summary:{...e,diffs:r}}:s}function Mk(t){const e=t;if(!(Sk(e.revert)||Array.isArray(e.summary?.diffs)||"permission"in e))return t;const s=Ir(t),o={...s};delete o.permission;const r=kk(s.revert);r?o.revert=r:delete o.revert;const i=s.summary;if(i&&typeof i=="object"&&!Array.isArray(i)){const l={...i};delete l.diffs,o.summary=l}return o}function fa(t){const e=t.summary;if(!e?.diffs||!Array.isArray(e.diffs))return t;let n=!1;const s=e.diffs.map(o=>{const r=Xm(o,!1);return r!==o&&(n=!0),r});return n?{...t,summary:{...e,diffs:s}}:t}const Ak=t=>{if(!t)return null;const e=Number(t);return Number.isFinite(e)?e:null},Fk=(t,e)=>{if(!t||typeof t!="object")return null;const s=t.headers;if(!s||typeof s!="object")return null;const o=s;if(typeof o.get=="function")return o.get(e);const r=s,i=r[e]??r[e.toLowerCase()];return typeof i=="string"?i:null},_k=t=>{if(t instanceof Error)return t.message;if(typeof t=="string")return t;if(t&&typeof t=="object"&&"message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}},Bk=(t,e)=>{if(t.error){const n=t.response?.status,s=new Error(`${e} failed${n?` (${n})`:""}: ${_k(t.error)}`);throw n!==void 0&&(s.status=n),s}if(!Array.isArray(t.data)){const n=new Error(`${e} returned no data`);throw n.status=503,n}return t.data};async function $0(t,e){const n=[],s=new Set;let o;for(;;){const r=await Dn(()=>t.experimental.session.list({...e.directory?{directory:e.directory}:{},archived:e.archived,...e.roots!==void 0?{roots:e.roots}:{},limit:e.pageSize,...o!==void 0?{cursor:o}:{}}),{attempts:3,delay:500,retryIf:()=>!0}),i=Bk(r,"experimental.session.list").map(f=>Mk(f));if(i.length===0)break;let l=0;for(const f of i)!f?.id||s.has(f.id)||(s.add(f.id),n.push(f),l+=1);if(l>0&&e.onPage?.(i),i.length<e.pageSize)break;const c=Ak(Fk(r,"x-next-cursor")),d=i[i.length-1]?.time?.updated,u=c??(typeof d=="number"&&Number.isFinite(d)?d:void 0);if(u===void 0||o!==void 0&&u>=o||l===0)break;o=u}return n}const kl="/api/magic-prompts",Dk=[{id:"git.commit.generate.visible",title:"Commit Generation Visible Prompt",group:"Git",description:"Visible user message for commit message generation.",template:"You are generating a Conventional Commits subject line using session context and selected file paths."},{id:"git.commit.generate.instructions",title:"Commit Generation Instructions",group:"Git",description:"Hidden instructions for commit message generation.",placeholders:[{key:"selected_files",description:"Bullet list of currently selected file paths."}],template:`Return exactly one JSON object and nothing else. Do not include prose, markdown, explanations, or code fences.
3
3
 
4
4
  The JSON object must have exactly this shape:
@@ -468,7 +468,7 @@ ${Object.entries(Cm).map(([o,r])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowe
468
468
  }
469
469
  `,n=document.getElementById(Q8);if(n){n.textContent=e;return}const s=document.createElement("style");s.id=Q8,s.textContent=e,document.head.appendChild(s)},NX=()=>{J8||typeof window>"u"||(J8=!0,KT())},bp="app-region-no-drag transition-all duration-150 ease-out data-[starting-style]:opacity-0 data-[starting-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:scale-95 z-50 max-h-[var(--available-height)] min-w-[8rem] origin-[var(--transform-origin)] overflow-visible rounded-xl p-1 shadow-[inset_0_1px_0_0_rgba(255,255,255,0.8),inset_0_0_0_1px_rgba(0,0,0,0.04),0_0_0_1px_rgba(0,0,0,0.10),0_1px_2px_-0.5px_rgba(0,0,0,0.08),0_4px_8px_-2px_rgba(0,0,0,0.08),0_12px_20px_-4px_rgba(0,0,0,0.08)] dark:shadow-[inset_0_1px_0_0_rgba(255,255,255,0.12),inset_0_0_0_1px_rgba(255,255,255,0.08),0_0_0_1px_rgba(0,0,0,0.36),0_1px_1px_-0.5px_rgba(0,0,0,0.22),0_3px_3px_-1.5px_rgba(0,0,0,0.20),0_6px_6px_-3px_rgba(0,0,0,0.16)]",YT="data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",JT="data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-pointer items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",QT="bg-border -mx-1 my-0.5 h-px",Vl=ae.createContext(null),XT=t=>t?t.closest('[data-slot="dialog-content"], [role="dialog"]'):null;function vp(t,e){return t&&ae.isValidElement(e)?{render:e}:{children:e}}function si(t){const e=de.c(9);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];const[s,o]=ae.useState(null);let r;e[2]!==s?(r={portalContainer:s,setPortalContainer:o},e[2]=s,e[3]=r):r=e[3];const i=r;let l;e[4]!==n?(l=a.jsx(dy,{...n}),e[4]=n,e[5]=l):l=e[5];let c;return e[6]!==i||e[7]!==l?(c=a.jsx(Vl.Provider,{value:i,children:l}),e[6]=i,e[7]=l,e[8]=c):c=e[8],c}function oi(t){const e=de.c(22);let n,s,o,r,i;e[0]!==t?({asChild:n,children:s,onPointerDownCapture:r,onFocusCapture:o,...i}=t,e[0]=t,e[1]=n,e[2]=s,e[3]=o,e[4]=r,e[5]=i):(n=e[1],s=e[2],o=e[3],r=e[4],i=e[5]);const l=ae.useContext(Vl);let c;e[6]!==l?(c=b=>{if(!l)return;const w=b instanceof HTMLElement?b:null;l.setPortalContainer(XT(w))},e[6]=l,e[7]=c):c=e[7];const d=c;let u;e[8]!==n||e[9]!==s?(u=vp(n,s),e[8]=n,e[9]=s,e[10]=u):u=e[10];const f=u;let m;e[11]!==r||e[12]!==d?(m=b=>{d(b.currentTarget),r?.(b)},e[11]=r,e[12]=d,e[13]=m):m=e[13];let h;e[14]!==o||e[15]!==d?(h=b=>{d(b.currentTarget),o?.(b)},e[14]=o,e[15]=d,e[16]=h):h=e[16];let p;return e[17]!==i||e[18]!==f||e[19]!==m||e[20]!==h?(p=a.jsx(uy,{"data-slot":"dropdown-menu-trigger",onPointerDownCapture:m,onFocusCapture:h,...i,...f}),e[17]=i,e[18]=f,e[19]=m,e[20]=h,e[21]=p):p=e[21],p}function ri(t){const e=de.c(32);let n,s,o,r,i,l,c,d,u,f;if(e[0]!==t){const{className:S,sideOffset:M,align:A,side:B,alignOffset:F,portalToBody:_,positionerClassName:D,style:E,children:I,onCloseAutoFocus:T,...j}=t;r=S,u=M,n=A,c=B,s=F,f=_,i=D,d=E,o=I,l=j,e[0]=t,e[1]=n,e[2]=s,e[3]=o,e[4]=r,e[5]=i,e[6]=l,e[7]=c,e[8]=d,e[9]=u,e[10]=f}else n=e[1],s=e[2],o=e[3],r=e[4],i=e[5],l=e[6],c=e[7],d=e[8],u=e[9],f=e[10];const m=u===void 0?4:u,h=f===void 0?!1:f,p=ae.useContext(Vl),b=h?void 0:p?.portalContainer||void 0;let w;e[11]!==i?(w=z("app-region-no-drag z-50",i),e[11]=i,e[12]=w):w=e[12];let v;e[13]!==d?(v={backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)",...d},e[13]=d,e[14]=v):v=e[14];let x;e[15]!==r?(x=z(bp,r),e[15]=r,e[16]=x):x=e[16];let y;e[17]!==o||e[18]!==l||e[19]!==v||e[20]!==x?(y=a.jsx(om,{"data-slot":"dropdown-menu-content",style:v,className:x,...l,children:o}),e[17]=o,e[18]=l,e[19]=v,e[20]=x,e[21]=y):y=e[21];let k;e[22]!==n||e[23]!==s||e[24]!==c||e[25]!==m||e[26]!==w||e[27]!==y?(k=a.jsx(rm,{sideOffset:m,align:n,side:c,alignOffset:s,className:w,children:y}),e[22]=n,e[23]=s,e[24]=c,e[25]=m,e[26]=w,e[27]=y,e[28]=k):k=e[28];let C;return e[29]!==b||e[30]!==k?(C=a.jsx(im,{container:b,children:k}),e[29]=b,e[30]=k,e[31]=C):C=e[31],C}function eo(t){const e=de.c(24);let n,s,o,r,i,l,c,d;e[0]!==t?({className:o,inset:r,variant:d,asChild:n,children:s,onSelect:l,onClick:i,...c}=t,e[0]=t,e[1]=n,e[2]=s,e[3]=o,e[4]=r,e[5]=i,e[6]=l,e[7]=c,e[8]=d):(n=e[1],s=e[2],o=e[3],r=e[4],i=e[5],l=e[6],c=e[7],d=e[8]);const u=d===void 0?"default":d;let f;e[9]!==n||e[10]!==s?(f=vp(n,s),e[9]=n,e[10]=s,e[11]=f):f=e[11];const m=f;let h;e[12]!==i||e[13]!==l?(h=v=>{i?.(v),v.defaultPrevented||l?.(v)},e[12]=i,e[13]=l,e[14]=h):h=e[14];const p=h;let b;e[15]!==o?(b=z(YT,o),e[15]=o,e[16]=b):b=e[16];let w;return e[17]!==p||e[18]!==r||e[19]!==c||e[20]!==m||e[21]!==b||e[22]!==u?(w=a.jsx(cy,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":u,className:b,...c,onClick:p,...m}),e[17]=p,e[18]=r,e[19]=c,e[20]=m,e[21]=b,e[22]=u,e[23]=w):w=e[23],w}function VX(t){const e=de.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let s;return e[2]!==n?(s=a.jsx(hy,{"data-slot":"dropdown-menu-radio-group",...n}),e[2]=n,e[3]=s):s=e[3],s}function RX(t){const e=de.c(11);let n,s,o;e[0]!==t?({className:s,children:n,...o}=t,e[0]=t,e[1]=n,e[2]=s,e[3]=o):(n=e[1],s=e[2],o=e[3]);let r;e[4]!==s?(r=z("data-[highlighted]:bg-interactive-hover hover:bg-interactive-hover data-[checked]:bg-interactive-selection data-[checked]:text-interactive-selection-foreground relative flex cursor-pointer items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",s),e[4]=s,e[5]=r):r=e[5];let i;e[6]===Symbol.for("react.memo_cache_sentinel")?(i=a.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:a.jsx(my,{children:a.jsx(q,{name:"check",className:"size-3"})})}),e[6]=i):i=e[6];let l;return e[7]!==n||e[8]!==o||e[9]!==r?(l=a.jsxs(fy,{"data-slot":"dropdown-menu-radio-item",className:r,...o,children:[i,n]}),e[7]=n,e[8]=o,e[9]=r,e[10]=l):l=e[10],l}function ej(t){const e=de.c(10);let n,s,o;e[0]!==t?({className:n,inset:s,...o}=t,e[0]=t,e[1]=n,e[2]=s,e[3]=o):(n=e[1],s=e[2],o=e[3]);let r;e[4]!==n?(r=z("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",n),e[4]=n,e[5]=r):r=e[5];let i;return e[6]!==s||e[7]!==o||e[8]!==r?(i=a.jsx("div",{"data-slot":"dropdown-menu-label","data-inset":s,className:r,...o}),e[6]=s,e[7]=o,e[8]=r,e[9]=i):i=e[9],i}function X8(t){const e=de.c(8);let n,s;e[0]!==t?({className:n,...s}=t,e[0]=t,e[1]=n,e[2]=s):(n=e[1],s=e[2]);let o;e[3]!==n?(o=z(QT,n),e[3]=n,e[4]=o):o=e[4];let r;return e[5]!==s||e[6]!==o?(r=a.jsx(am,{"data-slot":"dropdown-menu-separator",className:o,...s}),e[5]=s,e[6]=o,e[7]=r):r=e[7],r}function zX(t){const e=de.c(4);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];let s;return e[2]!==n?(s=a.jsx(py,{...n}),e[2]=n,e[3]=s):s=e[3],s}function OX(t){const e=de.c(13);let n,s,o,r;e[0]!==t?({className:s,inset:o,children:n,...r}=t,e[0]=t,e[1]=n,e[2]=s,e[3]=o,e[4]=r):(n=e[1],s=e[2],o=e[3],r=e[4]);let i;e[5]!==s?(i=z(JT,s),e[5]=s,e[6]=i):i=e[6];let l;e[7]===Symbol.for("react.memo_cache_sentinel")?(l=a.jsx(q,{name:"arrow-right-s",className:"ml-auto size-3.5"}),e[7]=l):l=e[7];let c;return e[8]!==n||e[9]!==o||e[10]!==r||e[11]!==i?(c=a.jsxs(gy,{"data-slot":"dropdown-menu-sub-trigger","data-inset":o,className:i,...r,children:[n,l]}),e[8]=n,e[9]=o,e[10]=r,e[11]=i,e[12]=c):c=e[12],c}function $X(t){const e=de.c(14);let n,s,o;e[0]!==t?({className:s,children:n,...o}=t,e[0]=t,e[1]=n,e[2]=s,e[3]=o):(n=e[1],s=e[2],o=e[3]);const i=ae.useContext(Vl)?.portalContainer||void 0;let l;e[4]===Symbol.for("react.memo_cache_sentinel")?(l={backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},e[4]=l):l=e[4];let c;e[5]!==s?(c=z(bp,s),e[5]=s,e[6]=c):c=e[6];let d;e[7]!==n||e[8]!==o||e[9]!==c?(d=a.jsx(rm,{className:"z-50",children:a.jsx(om,{"data-slot":"dropdown-menu-sub-content",style:l,className:c,...o,children:n})}),e[7]=n,e[8]=o,e[9]=c,e[10]=d):d=e[10];let u;return e[11]!==i||e[12]!==d?(u=a.jsx(im,{container:i,children:d}),e[11]=i,e[12]=d,e[13]=u):u=e[13],u}const tj=1e3,e7=.5,t7={length:0,offset:0},n7=(t,e)=>Math.abs(t.length-e.length)<e7&&Math.abs(t.offset-e.offset)<e7,yp=t=>{const e=de.c(66),{containerRef:n,minThumbSize:s,hideDelayMs:o,className:r,disableHorizontal:i,observeMutations:l,suppressVisibility:c,userIntentOnly:d}=t,u=s===void 0?32:s,f=o===void 0?1e3:o,m=i===void 0?!1:i,h=l===void 0?!0:l,p=c===void 0?!1:c,b=d===void 0?!1:d,[w,v]=g.useState(!1);let x;e[0]===Symbol.for("react.memo_cache_sentinel")?(x={length:0,offset:0},e[0]=x):x=e[0];const[y,k]=g.useState(x);let C;e[1]===Symbol.for("react.memo_cache_sentinel")?(C={length:0,offset:0},e[1]=C):C=e[1];const[S,M]=g.useState(C),A=g.useRef(null),B=g.useRef(null),F=g.useRef(null),_=g.useRef(!1),D=g.useRef(!1),E=g.useRef(0);let I;e[2]===Symbol.for("react.memo_cache_sentinel")?(I={pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0},e[2]=I):I=e[2];const T=g.useRef(I),j=g.useRef(null);let V;e[3]===Symbol.for("react.memo_cache_sentinel")?(V=new Set,e[3]=V):V=e[3];const H=g.useRef(V);let N;e[4]!==n||e[5]!==m||e[6]!==u?(N=()=>{const ge=n.current;if(!ge)return;const{scrollHeight:ce,clientHeight:Ae,scrollTop:He,scrollWidth:he,clientWidth:Ee,scrollLeft:Le}=ge;let Ve=t7;if(ce>Ae){const qe=Math.max(Ae-16,0),Ge=Ae/ce*qe,vt=Math.max(u,Math.min(qe,Ge)),St=Math.max(qe-vt,0),Pt=Math.max(ce-Ae,1),yt=He/Pt*St;Ve={length:vt,offset:yt}}k(qe=>n7(qe,Ve)?qe:Ve);let Ue=t7;if(!m&&he>Ee){const qe=Math.max(Ee-16,0),Ge=Ee/he*qe,vt=Math.max(u,Math.min(qe,Ge)),St=Math.max(qe-vt,0),Pt=Math.max(he-Ee,1),yt=Le/Pt*St;Ue={length:vt,offset:yt}}M(qe=>n7(qe,Ue)?qe:Ue)},e[4]=n,e[5]=m,e[6]=u,e[7]=N):N=e[7];const R=N;let $;e[8]!==R?($=()=>{F.current===null&&(F.current=requestAnimationFrame(()=>{F.current=null,R()}))},e[8]=R,e[9]=$):$=e[9];const U=$;let L;e[10]===Symbol.for("react.memo_cache_sentinel")?(L=(ge,ce)=>{if(!ce){H.current.clear();return}const Ae=new Set;Ae.add(ge),Array.from(ge.children).forEach(He=>{Ae.add(He)}),H.current.forEach(He=>{Ae.has(He)||ce.unobserve(He)}),Ae.forEach(He=>{H.current.has(He)||ce.observe(He)}),H.current=Ae},e[10]=L):L=e[10];const Z=L;let Y;e[11]!==f?(Y=()=>{A.current&&clearTimeout(A.current),!D.current&&(A.current=setTimeout(()=>v(!1),f))},e[11]=f,e[12]=Y):Y=e[12];const fe=Y;let Q;e[13]===Symbol.for("react.memo_cache_sentinel")?(Q=()=>{E.current=Date.now()},e[13]=Q):Q=e[13];const pe=Q;let ne;e[14]!==fe||e[15]!==p||e[16]!==R||e[17]!==b?(ne=()=>{B.current&&cancelAnimationFrame(B.current),B.current=requestAnimationFrame(()=>{if(R(),p&&!_.current){v(!1);return}if(b&&!_.current&&!(Date.now()-E.current<=tj)){v(!1);return}v(!0),fe()})},e[14]=fe,e[15]=p,e[16]=R,e[17]=b,e[18]=ne):ne=e[18];const re=ne;let se,te;e[19]!==n||e[20]!==re||e[21]!==h||e[22]!==U||e[23]!==R||e[24]!==b?(se=()=>{const ge=n.current;if(!ge)return;R(),v(!1);const ce=()=>re(),Ae=Ve=>{(Ve.key==="ArrowUp"||Ve.key==="ArrowDown"||Ve.key==="PageUp"||Ve.key==="PageDown"||Ve.key==="Home"||Ve.key==="End"||Ve.key===" ")&&pe()};ge.addEventListener("scroll",ce,{passive:!0}),b&&(ge.addEventListener("wheel",pe,{passive:!0}),ge.addEventListener("touchstart",pe,{passive:!0}),ge.addEventListener("touchmove",pe,{passive:!0}),ge.addEventListener("keydown",Ae));const He=typeof ResizeObserver<"u"?new ResizeObserver(()=>{U()}):null;Z(ge,He);const he=h&&typeof MutationObserver<"u"?new MutationObserver(()=>{Z(ge,He),U()}):null;he?.observe(ge,{childList:!0});const Ee=()=>U(),Le=()=>U();return ge.addEventListener("input",Ee,!0),ge.addEventListener("load",Le,!0),()=>{ge.removeEventListener("scroll",ce),ge.removeEventListener("input",Ee,!0),ge.removeEventListener("load",Le,!0),b&&(ge.removeEventListener("wheel",pe),ge.removeEventListener("touchstart",pe),ge.removeEventListener("touchmove",pe),ge.removeEventListener("keydown",Ae)),He?.disconnect(),he?.disconnect(),H.current.clear(),A.current&&clearTimeout(A.current),B.current&&cancelAnimationFrame(B.current),F.current&&cancelAnimationFrame(F.current)}},te=[n,re,pe,h,U,Z,R,b],e[19]=n,e[20]=re,e[21]=h,e[22]=U,e[23]=R,e[24]=b,e[25]=se,e[26]=te):(se=e[25],te=e[26]),g.useEffect(se,te);let ke,be;e[27]!==p?(ke=()=>{p&&(_.current||(v(!1),A.current&&(clearTimeout(A.current),A.current=null)))},be=[p],e[27]=p,e[28]=ke,e[29]=be):(ke=e[28],be=e[29]),g.useEffect(ke,be);let X;e[30]!==n?(X=(ge,ce)=>{const Ae=n.current;Ae&&(_.current=!0,T.current={pointerX:ge.clientX,pointerY:ge.clientY,scrollTop:Ae.scrollTop,scrollLeft:Ae.scrollLeft},j.current=ce,pe(),v(!0),A.current&&clearTimeout(A.current),ge.currentTarget.setPointerCapture(ge.pointerId))},e[30]=n,e[31]=X):X=e[31];const ee=X;let G;e[32]!==n||e[33]!==S.length||e[34]!==y.length?(G=ge=>{if(!_.current)return;const ce=n.current;if(!ce)return;const Ae=j.current;if(Ae==="vertical"){const{pointerY:He,scrollTop:he}=T.current,Ee=ge.clientY-He,Le=ce.clientHeight,Ve=Math.max(Le-y.length,1),Ue=Math.max(ce.scrollHeight-ce.clientHeight,1),qe=Ee/Ve*Ue;ce.scrollTop=he+qe}else if(Ae==="horizontal"){const{pointerX:He,scrollLeft:he}=T.current,Ee=ge.clientX-He,Le=ce.clientWidth,Ve=Math.max(Le-S.length,1),Ue=Math.max(ce.scrollWidth-ce.clientWidth,1),qe=Ee/Ve*Ue;ce.scrollLeft=he+qe}},e[32]=n,e[33]=S.length,e[34]=y.length,e[35]=G):G=e[35];const O=G;let ie;e[36]!==fe?(ie=ge=>{_.current&&(_.current=!1,ge.currentTarget.releasePointerCapture(ge.pointerId),fe())},e[36]=fe,e[37]=ie):ie=e[37];const oe=ie;let Ce;e[38]===Symbol.for("react.memo_cache_sentinel")?(Ce=()=>{D.current=!0,A.current&&(clearTimeout(A.current),A.current=null)},e[38]=Ce):Ce=e[38];const ue=Ce;let Me;e[39]!==fe?(Me=()=>{D.current=!1,fe()},e[39]=fe,e[40]=Me):Me=e[40];const ye=Me,K=y.length>0,W=S.length>0;if(!K&&!W)return null;let le;e[41]!==r?(le=z("overlay-scrollbar",r),e[41]=r,e[42]=le):le=e[42];const xe=w?1:0;let Se;e[43]!==xe?(Se={opacity:xe},e[43]=xe,e[44]=Se):Se=e[44];let we;e[45]!==ee||e[46]!==O||e[47]!==oe||e[48]!==ye||e[49]!==K||e[50]!==y.length||e[51]!==y.offset?(we=K&&a.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical","data-overlay-scrollbar-thumb":"vertical",style:{height:`${y.length}px`,top:`${8+y.offset}px`,right:"4px"},onPointerDown:ge=>ee(ge,"vertical"),onPointerMove:O,onPointerUp:oe,onPointerCancel:oe,onMouseEnter:ue,onMouseLeave:ye}),e[45]=ee,e[46]=O,e[47]=oe,e[48]=ye,e[49]=K,e[50]=y.length,e[51]=y.offset,e[52]=we):we=e[52];let me;e[53]!==ee||e[54]!==O||e[55]!==oe||e[56]!==ye||e[57]!==S.length||e[58]!==S.offset||e[59]!==W?(me=W&&a.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal","data-overlay-scrollbar-thumb":"horizontal",style:{width:`${S.length}px`,left:`${8+S.offset}px`,bottom:"4px"},onPointerDown:ge=>ee(ge,"horizontal"),onPointerMove:O,onPointerUp:oe,onPointerCancel:oe,onMouseEnter:ue,onMouseLeave:ye}),e[53]=ee,e[54]=O,e[55]=oe,e[56]=ye,e[57]=S.length,e[58]=S.offset,e[59]=W,e[60]=me):me=e[60];let _e;return e[61]!==le||e[62]!==Se||e[63]!==we||e[64]!==me?(_e=a.jsxs("div",{className:le,"aria-hidden":"true",style:Se,children:[we,me]}),e[61]=le,e[62]=Se,e[63]=we,e[64]=me,e[65]=_e):_e=e[65],_e};yp.displayName="OverlayScrollbar";const wp=yp;function nj(...t){return e=>{t.forEach(n=>{typeof n=="function"?n(e):n&&typeof n=="object"&&(n.current=e)})}}const Rl=g.forwardRef((t,e)=>{const n=de.c(25),{as:s,orientation:o,offset:r,size:i,isEnabled:l,hideTopShadow:c,hideBottomShadow:d,observeMutations:u,onVisibilityChange:f,style:m,className:h,children:p,...b}=t,w=s===void 0?"div":s,v=o===void 0?"vertical":o,x=r===void 0?0:r,y=i===void 0?48:i,k=l===void 0?!0:l,C=c===void 0?!1:c,S=d===void 0?!1:d,M=u===void 0?!0:u,A=g.useRef(null),B=g.useRef("none"),F=b["data-scroll-shadow"];delete b["data-scroll-shadow"];const _=m;let D;n[0]!==y||n[1]!==_?(D={..._},D["--scroll-shadow-size"]=`${y}px`,n[0]=y,n[1]=_,n[2]=D):D=n[2];const E=D,I=sj,T=oj;let j;n[3]!==S||n[4]!==C||n[5]!==k||n[6]!==x||n[7]!==f||n[8]!==v?(j=()=>{const L=A.current;if(!L)return;if(!k){T(L);return}const Z=v==="vertical"?L.scrollTop>x+1:L.scrollLeft>x+1;let Y=v==="vertical"?L.scrollHeight-(L.scrollTop+L.clientHeight)>x+1:L.scrollWidth-(L.scrollLeft+L.clientWidth)>x+1;const fe=C&&v==="vertical"?!1:Z;S&&v==="vertical"&&(Y=!1),I(L,fe,Y,v==="vertical"?"top":"left",v==="vertical"?"bottom":"right");const Q=fe&&Y?"both":fe?v==="vertical"?"top":"left":Y?v==="vertical"?"bottom":"right":"none";Q!==B.current&&(B.current=Q,f?.(Q))},n[3]=S,n[4]=C,n[5]=k,n[6]=x,n[7]=f,n[8]=v,n[9]=j):j=n[9];const V=j;let H,N;n[10]!==V||n[11]!==M?(H=()=>{const L=A.current;if(!L)return;let Z=null;const Y=()=>{Z===null&&(Z=requestAnimationFrame(()=>{Z=null,V()}))},fe=()=>V(),Q=typeof ResizeObserver<"u"?new ResizeObserver(Y):null,pe=M&&typeof MutationObserver<"u"?new MutationObserver(Y):null;return V(),L.addEventListener("scroll",fe,{passive:!0}),Q?.observe(L),pe?.observe(L,{childList:!0,subtree:!0,characterData:!0}),()=>{Z!==null&&cancelAnimationFrame(Z),L.removeEventListener("scroll",fe),Q?.disconnect(),pe?.disconnect()}},N=[V,M],n[10]=V,n[11]=M,n[12]=H,n[13]=N):(H=n[12],N=n[13]),g.useEffect(H,N);let R;n[14]!==e?(R=nj(A,e),n[14]=e,n[15]=R):R=n[15];const $=F??!0;let U;return n[16]!==w||n[17]!==p||n[18]!==h||n[19]!==E||n[20]!==v||n[21]!==b||n[22]!==R||n[23]!==$?(U=a.jsx(w,{...b,ref:R,className:h,"data-orientation":v,"data-scroll-shadow":$,style:E,children:p}),n[16]=w,n[17]=p,n[18]=h,n[19]=E,n[20]=v,n[21]=b,n[22]=R,n[23]=$,n[24]=U):U=n[24],U});Rl.displayName="ScrollShadow";function sj(t,e,n,s,o){const r=`${s}${o.charAt(0).toUpperCase()}${o.slice(1)}Scroll`;e&&n?(t.dataset[r]="true",t.removeAttribute(`data-${s}-scroll`),t.removeAttribute(`data-${o}-scroll`)):(t.dataset[`${s}Scroll`]=String(e),t.dataset[`${o}Scroll`]=String(n),t.removeAttribute(`data-${s}-${o}-scroll`))}function oj(t){["top","bottom","top-bottom","left","right","left-right"].forEach(e=>{t.removeAttribute(`data-${e}-scroll`)})}const Zn=g.forwardRef((t,e)=>{const n=de.c(45);let s,o,r,i,l,c,d,u,f,m,h,p,b,w,v,x;n[0]!==t?({className:o,outerClassName:l,children:s,style:f,minThumbSize:i,hideDelayMs:r,as:m,scrollbarClassName:u,disableHorizontal:h,observeMutations:p,fillContainer:b,preventOverscroll:w,useScrollShadow:v,scrollShadowSize:d,userIntentOnly:x,...c}=t,n[0]=t,n[1]=s,n[2]=o,n[3]=r,n[4]=i,n[5]=l,n[6]=c,n[7]=d,n[8]=u,n[9]=f,n[10]=m,n[11]=h,n[12]=p,n[13]=b,n[14]=w,n[15]=v,n[16]=x):(s=n[1],o=n[2],r=n[3],i=n[4],l=n[5],c=n[6],d=n[7],u=n[8],f=n[9],m=n[10],h=n[11],p=n[12],b=n[13],w=n[14],v=n[15],x=n[16]);const y=m===void 0?"div":m,k=h===void 0?!1:h,C=p===void 0?!0:p,S=b===void 0?!0:b,M=w===void 0?!1:w,A=v===void 0?!1:v,B=x===void 0?!1:x,F=g.useRef(null);let _,D;n[17]===Symbol.for("react.memo_cache_sentinel")?(_=()=>F.current,D=[],n[17]=_,n[18]=D):(_=n[17],D=n[18]),g.useImperativeHandle(e,_,D);const E=M&&"overscroll-none";let I;n[19]!==l||n[20]!==E?(I=z("relative flex flex-col min-h-0 w-full overflow-hidden",E,l),n[19]=l,n[20]=E,n[21]=I):I=n[21];let T;n[22]!==y||n[23]!==s||n[24]!==o||n[25]!==k||n[26]!==S||n[27]!==C||n[28]!==M||n[29]!==c||n[30]!==d||n[31]!==f||n[32]!==A?(T=A?a.jsx(Rl,{as:y,ref:F,size:d,className:z("overlay-scrollbar-target overlay-scrollbar-container",M&&"overscroll-none",S?"flex-1 min-h-0 w-full":"flex-none w-full h-auto",k?"overflow-y-auto overflow-x-hidden":"overflow-auto",o),style:f,observeMutations:C,...c,children:s}):a.jsx(y,{ref:F,className:z("overlay-scrollbar-target overlay-scrollbar-container",M&&"overscroll-none",S?"flex-1 min-h-0 w-full":"flex-none w-full h-auto",k?"overflow-y-auto overflow-x-hidden":"overflow-auto",o),style:f,...c,children:s}),n[22]=y,n[23]=s,n[24]=o,n[25]=k,n[26]=S,n[27]=C,n[28]=M,n[29]=c,n[30]=d,n[31]=f,n[32]=A,n[33]=T):T=n[33];let j;n[34]!==k||n[35]!==r||n[36]!==i||n[37]!==C||n[38]!==u||n[39]!==B?(j=a.jsx(wp,{containerRef:F,minThumbSize:i,hideDelayMs:r,className:u,disableHorizontal:k,observeMutations:C,userIntentOnly:B}),n[34]=k,n[35]=r,n[36]=i,n[37]=C,n[38]=u,n[39]=B,n[40]=j):j=n[40];let V;return n[41]!==I||n[42]!==T||n[43]!==j?(V=a.jsxs("div",{className:I,children:[T,j]}),n[41]=I,n[42]=T,n[43]=j,n[44]=V):V=n[44],V});Zn.displayName="ScrollableOverlay";const s7="mobile-overlay-root",rj=16,ij=200,aj=()=>{if(typeof document>"u")return null;let t=document.getElementById(s7);return t||(t=document.createElement("div"),t.id=s7,document.body.appendChild(t)),t},bo=({open:t,title:e,onClose:n,children:s,footer:o,className:r,contentMaxHeightClassName:i,renderHeader:l})=>{const c=g.useRef(null),[d,u]=g.useState(!1);if(typeof document<"u"&&!c.current&&(c.current=aj()),g.useEffect(()=>{if(!t){u(!1);return}const h=window.setTimeout(()=>u(!0),rj);return()=>window.clearTimeout(h)},[t]),g.useEffect(()=>{if(!t)return;const h=document.body.style.overflow;document.body.style.overflow="hidden";const p=b=>{b.key==="Escape"&&n()};return document.addEventListener("keydown",p),()=>{document.body.style.overflow=h,document.removeEventListener("keydown",p)}},[t,n]),!t||!c.current)return null;const f=i??"max-h-[min(70vh,520px)]",m=a.jsx("div",{className:z("fixed inset-0 z-[60] flex flex-col bg-[rgb(0_0_0_/_0.45)] transition-opacity duration-200 ease-out",d?"opacity-100":"opacity-0"),role:"dialog","aria-modal":"true",onClick:n,children:a.jsxs("div",{className:z("mt-auto flex max-h-[calc(100dvh-0.75rem)] min-h-0 w-full flex-col rounded-t-xl border-x border-t border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",r),style:{transform:d?"none":"translateY(100%)",transition:`transform ${ij}ms cubic-bezier(0.32, 0.72, 0, 1)`},onClick:h=>h.stopPropagation(),children:[(()=>{const h=a.jsx("button",{type:"button",onClick:n,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-interactive-hover",children:a.jsx(q,{name:"close",className:"h-4 w-4"})});return l?l(h):a.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[a.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:e}),h]})})(),a.jsx(Zn,{useScrollShadow:!0,disableHorizontal:!0,outerClassName:z("min-h-0 flex-1",f),className:"px-2 py-2 pwa-overlay-scroll",children:s}),o?a.jsx("div",{className:"shrink-0 border-t border-border/40 px-3 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))]",children:o}):null]})});return ca.createPortal(m,c.current)},Oi={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},xp={isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1,hasTouchOnlyPointer:!1},lj=t=>{if(typeof navigator>"u")return{isExplicitTablet:!1};const e=navigator.userAgent||"",n=navigator.platform||"",s=/iPad/i.test(e)||(/Macintosh|MacIntel/i.test(e)||/MacIntel/i.test(n))&&t>1,o=/Android/i.test(e)&&!/Mobile/i.test(e),r=/Tablet/i.test(e);return{isExplicitTablet:s||o||r}},cj=(t,e,n)=>{if(typeof window>"u")return;const s=document.documentElement,o=e==="mobile",r=e==="tablet";s.classList.remove("device-mobile","device-tablet","device-desktop"),s.classList.add(e==="mobile"?"device-mobile":e==="tablet"?"device-tablet":"device-desktop"),t?(s.classList.add("desktop-runtime"),s.style.setProperty("--is-mobile","0"),s.style.setProperty("--device-type","desktop"),s.style.setProperty("--font-scale","1"),s.style.setProperty("--has-coarse-pointer","0"),s.style.setProperty("--has-touch-input","0"),s.classList.remove("mobile-pointer")):(s.classList.remove("desktop-runtime"),s.style.setProperty("--is-mobile",o?"1":"0"),s.style.setProperty("--device-type",e),s.style.setProperty("--font-scale",o?"0.9":r?"0.95":"1"),s.style.setProperty("--has-coarse-pointer",n?"1":"0"),s.style.setProperty("--has-touch-input",n?"1":"0"),n?s.classList.add("mobile-pointer"):s.classList.remove("mobile-pointer"))};function t5(){const t=window.innerWidth,e=typeof window.matchMedia=="function",n=e?window.matchMedia("(pointer: coarse)"):null,s=e?window.matchMedia("(hover: none)"):null,o=n?.matches??!1,r=s?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,l=qt()||Lt(),{isExplicitTablet:c}=lj(i),d=o||r||i>0,u=o||r,f=t>Oi.md&&t<=Oi.lg,m=t<=Oi.md;let h=d&&m,p=d&&!h&&(f||c),b=!d||!p&&t>Oi.lg,w="desktop";l?(h=!1,p=!1,b=!0,w="desktop"):h?w="mobile":p?w="tablet":(b=!0,w="desktop"),cj(l,w,d);let v="xs";for(const[x,y]of Object.entries(Oi))t>=y&&(v=x);return{isMobile:h,isTablet:p,isDesktop:b,deviceType:w,screenWidth:t,breakpoint:v,hasTouchInput:d,hasTouchOnlyPointer:u}}const dj=(t,e)=>t.isMobile===e.isMobile&&t.isTablet===e.isTablet&&t.isDesktop===e.isDesktop&&t.deviceType===e.deviceType&&t.screenWidth===e.screenWidth&&t.breakpoint===e.breakpoint&&t.hasTouchInput===e.hasTouchInput&&t.hasTouchOnlyPointer===e.hasTouchOnlyPointer,A0=new Set;let Dr=null,sa,za=null;const uj=()=>typeof window>"u"?xp:(Dr||(Dr=t5()),Dr),fj=()=>{for(const t of A0)t()},mj=()=>{sa=void 0;const t=t5();Dr&&dj(Dr,t)||(Dr=t,fj())},N2=()=>{typeof window>"u"||sa!==void 0||(sa=window.requestAnimationFrame(mj))},o7=(t,e)=>t?typeof t.addEventListener=="function"?(t.addEventListener("change",e),()=>t.removeEventListener("change",e)):typeof t.addListener=="function"?(t.addListener(e),()=>t.removeListener(e)):()=>{}:()=>{},hj=()=>{if(typeof window>"u")return()=>{};Dr=t5(),window.addEventListener("resize",N2);const t=typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)"):null,e=typeof window.matchMedia=="function"?window.matchMedia("(hover: none)"):null,n=o7(t,N2),s=o7(e,N2);return()=>{window.removeEventListener("resize",N2),n(),s(),sa!==void 0&&(window.cancelAnimationFrame(sa),sa=void 0)}},pj=t=>typeof window>"u"?()=>{}:(A0.add(t),za||(za=hj()),()=>{A0.delete(t),A0.size===0&&za&&(za(),za=null,Dr=null)});function ZX(){if(typeof window>"u"||typeof window<"u"&&qt())return!1;const t=document.documentElement,e=t.style.getPropertyValue("--is-mobile")||getComputedStyle(t).getPropertyValue("--is-mobile");return e==="1"||e==="true"}const gj=()=>typeof window>"u"?!1:!!(navigator.standalone===!0||window.matchMedia?.("(display-mode: standalone)")?.matches||window.matchMedia?.("(display-mode: fullscreen)")?.matches),Cp=()=>{if(typeof window>"u"||qt())return!1;const t=typeof navigator<"u"?navigator.maxTouchPoints??0:0;return gj()&&t>0&&window.innerWidth>Oi.md};function qX(){const t=de.c(2),[e,n]=g.useState(bj);let s,o;return t[0]===Symbol.for("react.memo_cache_sentinel")?(s=()=>{if(typeof window>"u")return;const r=()=>n(Cp()),i=window.matchMedia?.("(display-mode: standalone)"),l=window.matchMedia?.("(display-mode: fullscreen)");r(),window.addEventListener("resize",r),window.addEventListener("focus",r);const c=u=>{u&&(typeof u.addEventListener=="function"?u.addEventListener("change",r):typeof u.addListener=="function"&&u.addListener(r))},d=u=>{u&&(typeof u.removeEventListener=="function"?u.removeEventListener("change",r):typeof u.removeListener=="function"&&u.removeListener(r))};return c(i),c(l),()=>{window.removeEventListener("resize",r),window.removeEventListener("focus",r),d(i),d(l)}},o=[],t[0]=s,t[1]=o):(s=t[0],o=t[1]),g.useEffect(s,o),e}function bj(){return Cp()}function oo(){return g.useSyncExternalStore(pj,uj,vj)}function vj(){return xp}const r7="openchamber:chunk-import-reload",yj=250,wj=3e4,xj=[/Importing a module script failed/i,/Failed to fetch dynamically imported module/i,/error loading dynamically imported module/i,/Loading chunk \S+ failed/i,/ChunkLoadError/i];function kp(t){if(t instanceof Error)return`${t.name}
470
470
  ${t.message}
471
- ${t.stack??""}`;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function i7(t){const e=kp(t);return xj.some(n=>n.test(e))}function Cj(t){return`1.13.4:${kp(t).slice(0,500)}`}function kj(t){if(typeof window>"u")return;const e=Date.now(),n=Cj(t);let s=null;try{const r=window.sessionStorage.getItem(r7);if(r)try{s=JSON.parse(r)}catch{s=null}}catch{return}const o=typeof s?.timestamp=="number"?s.timestamp:0;if(!(s?.signature===n&&e-o<wj)){try{window.sessionStorage.setItem(r7,JSON.stringify({signature:n,timestamp:e}))}catch{return}window.setTimeout(()=>{window.location.reload()},0)}}async function Sj(t,e={}){const n=e.retries??1;let s;for(let o=0;o<=n;o+=1)try{return await t()}catch(r){if(s=r,!i7(r)||o>=n)break;await new Promise(i=>setTimeout(i,yj*(o+1)))}throw i7(s)&&kj(s),s}const n5=t=>ae.lazy(()=>Sj(t)),Mj=n5(()=>rn(()=>import("./MarkdownRendererImpl-B0NE4mIY.js"),__vite__mapDeps([2,0,1,3,4])).then(t=>({default:t.MarkdownRenderer}))),Aj=n5(()=>rn(()=>import("./MarkdownRendererImpl-B0NE4mIY.js"),__vite__mapDeps([2,0,1,3,4])).then(t=>({default:t.SimpleMarkdownRenderer}))),Sp=a.jsx("div",{className:"break-words w-full min-w-0"}),Mp=t=>{const e=de.c(2);let n;return e[0]!==t?(n=a.jsx(g.Suspense,{fallback:Sp,children:a.jsx(Mj,{...t})}),e[0]=t,e[1]=n):n=e[1],n},yi=t=>{const e=de.c(2);let n;return e[0]!==t?(n=a.jsx(g.Suspense,{fallback:Sp,children:a.jsx(Aj,{...t})}),e[0]=t,e[1]=n):n=e[1],n},zl=t=>{try{return new URL(t)}catch{return null}},UX=t=>{const e=zl(t.trim());return e?e.protocol==="http:"||e.protocol==="https:":!1},Fj=t=>{const e=zl(t.trim());return!e||e.protocol!=="http:"&&e.protocol!=="https:"?null:`https://icons.duckduckgo.com/ip3/${e.hostname.toLowerCase()}.ico`},_j=new Set(["localhost","127.0.0.1","0.0.0.0","::1"]),Bj=t=>{const e=zl(t.trim());return!e||e.protocol!=="http:"&&e.protocol!=="https:"?!1:_j.has(e.hostname.toLowerCase())},Dj=/\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d{2,5})?(?:\/[^\s<>"'`\u0000-\u001f]*)?/gi,a7=t=>{if(!t)return[];const e=t.match(Dj);if(!e||e.length===0)return[];const n=new Set,s=[];for(const o of e){const r=o.replace(/[),.;:!?'"`]+$/g,"");!r||!Bj(r)||n.has(r)||(n.add(r),s.push(r))}return s},l7=async t=>{if(typeof window>"u")return!1;const e=t.trim();if(!e)return!1;const n=zl(e);if(!n||n.protocol!=="http:"&&n.protocol!=="https:")return!1;const s=n.toString(),o=Ao();if(o?.runtime?.isVSCode&&o.vscode?.openExternalUrl)try{return await o.vscode.openExternalUrl(s),!0}catch{return!1}const r=window.__OPENCHAMBER_DESKTOP__;if(r?.openExternal)try{return await r.openExternal(s),!0}catch{}try{return window.open(s,"_blank","noopener,noreferrer"),!0}catch{return!1}},Pj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M26.9568%209.88184H22.1265L30.7753%2031.7848H35.4917L26.9568%209.88184ZM13.028%209.88184L4.4917%2031.7848H9.32203L11.2305%2027.1793H20.2166L22.0126%2031.6724H26.8444L18.0832%209.88184H13.028ZM12.5783%2023.1361L15.4987%2015.3853L18.5315%2023.1361H12.5783Z'%20fill='currentColor'/%3e%3c/svg%3e",Ej="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M37.9998%2023.021C33.7998%2025.2889%2029.5698%2027.3649%2024.8614%2028.3069C23.8114%2028.5154%2022.6474%2028.5154%2021.5809%2028.3714C20.5639%2028.2439%2020.0554%2027.3484%2020.4169%2026.4064C20.7619%2025.5289%2021.2209%2024.635%2021.8119%2023.9C23.0899%2022.3025%2024.5329%2020.849%2025.8289%2019.268C26.6203%2018.2991%2027.3335%2017.2689%2027.9618%2016.187C28.4208%2015.4205%2028.2078%2014.4935%2027.4038%2014.111C26.0584%2013.4556%2024.6154%2012.9936%2023.1889%2012.4986C23.0239%2012.4341%2022.7779%2012.6096%2022.4509%2012.7221C22.8604%2013.0881%2023.1559%2013.3596%2023.5654%2013.727C19.3339%2014.447%2015.3305%2015.467%2011.4455%2016.874C11.4275%2016.9535%2011.396%2017.0165%2011.411%2017.0495C11.9855%2017.927%2011.723%2018.5975%2010.886%2019.1405C10.5611%2019.3531%2010.2732%2019.6176%2010.034%2019.9235C12.593%2020.6735%2014.873%2020.243%2017.0539%2018.821C16.9234%2018.6305%2016.7914%2018.455%2016.6609%2018.263C17.4799%2018.407%2017.9719%2018.854%2018.0379%2019.556C18.0544%2019.7165%2017.9569%2019.8755%2017.9074%2020.036C17.7919%2019.907%2017.6449%2019.781%2017.5474%2019.6355C17.4799%2019.5395%2017.4634%2019.4285%2017.4154%2019.268C14.8235%2020.993%2012.035%2021.425%208.96751%2020.531C8.96751%2021.137%208.93451%2021.6485%208.98401%2022.1435C9.01701%2022.574%208.83701%2022.766%208.44401%2022.9895C7.55752%2023.5325%206.63803%2024.092%205.90003%2024.8105C5.01504%2025.6879%205.34354%2026.7589%206.54053%2027.2059C7.90102%2027.7159%209.329%2027.7309%2010.7555%2027.5569C12.4445%2027.3484%2014.1005%2027.0769%2015.9394%2026.8219C13.79%2027.8269%2011.6735%2028.5319%209.4445%2028.8169C7.88452%2029.0269%206.32753%2029.1379%204.78554%2028.6909C2.57156%2028.0684%201.58607%2026.4394%202.16057%2024.251C2.70206%2022.2065%204.01455%2020.5775%205.42454%2019.076C10.133%2014.078%2016.0864%2011.5401%2022.9744%2011.0286C24.5824%2010.9176%2026.2069%2011.1246%2027.7143%2011.7951C29.8308%2012.7536%2030.7173%2014.78%2029.6838%2016.826C29.0118%2018.1835%2028.0758%2019.4285%2027.1413%2020.6585C26.2234%2021.872%2025.1899%2022.9895%2024.2224%2024.155C23.9434%2024.506%2023.6809%2024.875%2023.4679%2025.2724C23.0569%2026.0224%2023.3359%2026.5174%2024.2059%2026.4394C26.0254%2026.2624%2027.8808%2026.1199%2029.6358%2025.6729C32.2098%2025.0174%2034.7193%2024.092%2037.2618%2023.2775C37.5243%2023.213%2037.7703%2023.117%2037.9998%2023.0225V23.021Z'%20fill='currentColor'/%3e%3c/svg%3e",Ij="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eCursor%3c/title%3e%3cg%20transform='translate(12%2012)%20scale(0.88)%20translate(-12%20-12)'%3e%3cpath%20d='M22.106%205.68L12.5.135a.998.998%200%2000-.998%200L1.893%205.68a.84.84%200%2000-.419.726v11.186c0%20.3.16.577.42.727l9.607%205.547a.999.999%200%2000.998%200l9.608-5.547a.84.84%200%2000.42-.727V6.407a.84.84%200%2000-.42-.726zm-.603%201.176L12.228%2022.92c-.063.108-.228.064-.228-.061V12.34a.59.59%200%2000-.295-.51l-9.11-5.26c-.107-.062-.063-.228.062-.228h18.55c.264%200%20.428.286.296.514z'%3e%3c/path%3e%3c/g%3e%3c/svg%3e",Tj="data:image/svg+xml,%3csvg%20fill='%23000000'%20viewBox='0%200%2033%2025'%20role='img'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M79.01%205.863c-4.066%200-6.511%202.92-6.511%206.535%200%203.635%202.445%206.555%206.511%206.555%204.046%200%206.512-2.92%206.512-6.555s-2.466-6.535-6.512-6.535Zm0%2010.968c-2.633%200-4.172-1.933-4.172-4.433s1.539-4.455%204.172-4.455c2.635%200%204.151%201.933%204.151%204.434%200%202.521-1.516%204.454-4.15%204.454Zm14.393%202.096c3.393%200%205.542-1.808%205.837-4.539h-2.36c-.316%201.555-1.517%202.437-3.477%202.437-2.423%200-3.878-1.68-3.878-4.433%200-2.774%201.476-4.434%203.878-4.434%201.96%200%203.14.862%203.477%202.5h2.36c-.295-2.773-2.444-4.622-5.837-4.622-3.856%200-6.217%202.669-6.217%206.535%200%203.887%202.36%206.556%206.217%206.556Zm-29.543-.311h2.36v-6.01c0-2.752%201.348-4.244%203.772-4.244h2.276V6.177h-2.255c-2.128%200-3.288.735-3.898%202.605l-.443-.063.527-2.542h-2.36v12.439h.02Zm-24.445-7.332c.106-2.101%201.517-3.53%203.793-3.53%202.276%200%203.646%201.345%203.646%203.53h-7.439Zm9.778.4c0-3.426-2.381-5.821-5.943-5.821-3.73%200-6.174%202.563-6.174%206.535%200%204.013%202.423%206.555%206.28%206.555%202.929%200%205.247-1.597%205.669-3.887h-2.36c-.507%201.156-1.666%201.828-3.31%201.828-2.38%200-3.877-1.408-3.94-3.803h9.694c.042-.588.084-.861.084-1.408Zm5.69%206.932h1.939l5.5-12.44h-2.529L56%2015.99l-.316.021-3.793-9.833h-2.508l5.5%2012.439ZM32.23%2012.35c0-.882-.359-1.701-.99-2.437a8.594%208.594%200%200%201-1.497%201.093c.337.42.527.861.527%201.345%200%202.731-5.837%204.811-14.14%204.811-8.281.021-14.118-2.059-14.118-4.811%200-.463.168-.925.505-1.345a8.13%208.13%200%200%201-1.475-1.093c-.632.736-.99%201.555-.99%202.438%200%204.034%207.207%206.534%2016.1%206.534%208.87.021%2016.078-2.5%2016.078-6.535Zm-3.351%201.534c-.906-.462-1.96-.861-3.16-1.197-1.37.378-2.909.672-4.553.861%202.318.294%204.341.778%205.9%201.408.76-.336%201.37-.693%201.813-1.072Zm-17.849-.357a31.902%2031.902%200%200%201-4.467-.84c-1.18.336-2.255.735-3.16%201.197.42.379%201.01.715%201.748%201.05%201.539-.63%203.52-1.113%205.88-1.407Zm21.2-6.808c0-4.013-7.207-6.534-16.079-6.534C7.26.185.051%202.706.051%206.719c0%204.035%207.208%206.535%2016.1%206.535%208.872.021%2016.079-2.5%2016.079-6.535Zm-1.94%200c0%202.732-5.836%204.812-14.139%204.812-8.302.021-14.14-2.06-14.14-4.812%200-2.731%205.838-4.811%2014.14-4.811%207.86%200%2014.14%202.08%2014.14%204.811Zm-3.223%202.564c.758-.336%201.37-.694%201.812-1.072-2.95-1.513-7.544-2.353-12.728-2.353s-9.799.84-12.728%202.353c.422.378%201.012.715%201.75%201.05%202.507-1.05%206.363-1.68%2010.978-1.68%204.404%200%208.324.651%2010.916%201.702ZM1.042%2015.628c-.632.736-.99%201.534-.99%202.438%200%204.034%207.207%206.534%2016.1%206.534%208.892%200%2016.099-2.521%2016.099-6.534%200-.883-.359-1.702-.99-2.438-.422.4-.907.757-1.497%201.093.337.42.527.861.527%201.345%200%202.731-5.837%204.811-14.14%204.811-8.302%200-14.14-2.08-14.14-4.811%200-.463.17-.925.506-1.345a10.73%2010.73%200%200%201-1.475-1.093Z'/%3e%3c/svg%3e",jj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M35.3993%2026.4544C34.2871%2028.3855%2027.8314%2032.9425%2020%2032.9425C12.1686%2032.9425%205.71288%2028.3855%204.60075%2026.4544C4.5427%2026.3532%204.50826%2026.2401%204.5%2026.1237V22.418C4.51199%2022.3209%204.53496%2022.2256%204.56846%2022.1338C5.04896%2020.9261%206.30833%2019.1733%207.93325%2018.7031C8.14896%2018.149%208.468%2017.3404%208.76508%2016.7437C8.71727%2016.2776%208.69485%2015.8094%208.69792%2015.3409C8.69792%2013.6217%209.06217%2012.113%2010.1601%2010.9906C10.6729%2010.4662%2011.3097%2010.0644%2012.064%209.76091C13.871%208.29357%2016.4453%207.05745%2019.9716%207.05745C23.4978%207.05745%2026.129%208.29357%2027.936%209.76091C28.6903%2010.0644%2029.3271%2010.4662%2029.8399%2010.9906C30.9378%2012.113%2031.3021%2013.6217%2031.3021%2015.3409C31.3021%2015.8162%2031.284%2016.2877%2031.2349%2016.7437C31.532%2017.3404%2031.851%2018.149%2032.0667%2018.7031C33.6917%2019.1733%2034.951%2020.9261%2035.4315%2022.1338C35.4677%2022.2248%2035.4908%2022.3205%2035.5%2022.418V26.1237C35.4917%2026.2401%2035.4573%2026.3532%2035.3993%2026.4544ZM20.2222%2018.7147H19.7778C19.6422%2018.945%2019.4889%2019.1644%2019.3193%2019.3709C18.3247%2020.5941%2016.8419%2021.2981%2014.7881%2021.2981C12.56%2021.2981%2010.9273%2020.8344%209.90304%2019.6719C9.86495%2019.6283%209.82833%2019.5835%209.79325%2019.5375L9.66667%2019.6719V28.1775C11.5202%2029.1837%2015.4972%2030.992%2020%2030.992C24.5028%2030.992%2028.4798%2029.1837%2030.3333%2028.1775V19.6719L30.2067%2019.5375C30.2067%2019.5375%2030.1641%2019.5957%2030.097%2019.6719C29.0727%2020.8344%2027.44%2021.2981%2025.2119%2021.2981C23.1581%2021.2981%2021.6753%2020.5941%2020.6807%2019.3709C20.5111%2019.1644%2020.3578%2018.945%2020.2222%2018.7147ZM23.2292%2022.9127C23.9383%2022.9127%2024.5208%2023.4952%2024.5208%2024.2043V26.7877C24.5208%2027.4968%2023.9383%2028.0793%2023.2292%2028.0793C22.52%2028.0793%2021.9375%2027.4968%2021.9375%2026.7877V24.2043C21.9375%2023.4952%2022.52%2022.9127%2023.2292%2022.9127ZM16.7708%2022.9127C17.48%2022.9127%2018.0625%2023.4952%2018.0625%2024.2043V26.7877C18.0625%2027.4968%2017.48%2028.0793%2016.7708%2028.0793C16.0617%2028.0793%2015.4792%2027.4968%2015.4792%2026.7877V24.2043C15.4792%2023.4952%2016.0617%2022.9127%2016.7708%2022.9127ZM21.0501%2014.9237C21.2258%2016.289%2021.5707%2017.3947%2022.1842%2018.149C22.7551%2018.8517%2023.649%2019.3606%2025.2119%2019.3606C27.2437%2019.3606%2028.1724%2018.9253%2028.6438%2018.3905C29.1398%2017.8287%2029.3646%2016.9051%2029.3646%2015.3409C29.3646%2013.8684%2029.0507%2012.9552%2028.454%2012.3455C27.8378%2011.7152%2026.7502%2011.2321%2024.8063%2011.0216C22.8856%2010.8136%2021.975%2011.1998%2021.5345%2011.7049C21.187%2012.1014%2020.97%2012.7485%2020.9688%2013.7431V13.7702C20.9688%2014.1121%2020.9959%2014.4966%2021.0501%2014.9237ZM18.9499%2014.9237C19.0041%2014.4966%2019.0312%2014.1117%2019.0312%2013.7689V13.7431C19.03%2012.7485%2018.813%2012.1014%2018.4655%2011.7049C18.025%2011.1998%2017.1144%2010.8136%2015.1937%2011.0216C13.2498%2011.2321%2012.1622%2011.7152%2011.546%2012.3455C10.9493%2012.9552%2010.6354%2013.8684%2010.6354%2015.3409C10.6354%2016.9051%2010.8615%2017.8287%2011.3562%2018.3905C11.8276%2018.9253%2012.7563%2019.3606%2014.7881%2019.3606C16.351%2019.3606%2017.2449%2018.8517%2017.8158%2018.149C18.4293%2017.3947%2018.7742%2016.289%2018.9499%2014.9237Z'%20fill='currentColor'/%3e%3c/svg%3e",Hj="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='utf-8'?%3e%3c!--%20Uploaded%20to:%20SVG%20Repo,%20www.svgrepo.com,%20Generator:%20SVG%20Repo%20Mixer%20Tools%20--%3e%3csvg%20fill='%23000000'%20width='800px'%20height='800px'%20viewBox='0%200%2024%2024'%20role='img'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.702%202.29c-2.494-1.554-5.778-1.187-8.706.654C9.076%201.104%205.79.736%203.3%202.29c-3.941%202.463-4.42%208.806-1.07%2014.167%202.47%203.954%206.333%206.269%209.77%206.226%203.439.043%207.301-2.273%209.771-6.226%203.347-5.361%202.872-11.704-1.069-14.167zM4.042%2015.328a12.838%2012.838%200%200%201-1.546-3.541%2010.12%2010.12%200%200%201-.336-3.338c.15-1.98.956-3.524%202.27-4.345%201.315-.822%203.052-.87%204.903-.137.281.113.556.24.825.382A15.11%2015.11%200%200%200%207.5%207.54c-2.035%203.255-2.655%206.878-1.945%209.765a13.247%2013.247%200%200%201-1.514-1.98zm17.465-3.541a12.866%2012.866%200%200%201-1.547%203.54%2013.25%2013.25%200%200%201-1.513%201.984c.635-2.589.203-5.76-1.353-8.734a.39.39%200%200%200-.563-.153l-4.852%203.032a.397.397%200%200%200-.126.546l.712%201.139a.395.395%200%200%200%20.547.126l3.145-1.965c.101.306.203.606.28.916.296%201.086.41%202.214.335%203.337-.15%201.982-.956%203.525-2.27%204.347a4.437%204.437%200%200%201-2.25.65h-.101a4.432%204.432%200%200%201-2.25-.65c-1.314-.822-2.121-2.365-2.27-4.347a10.153%2010.153%200%200%201%20.335-3.337%2013.212%2013.212%200%200%201%204.05-6.482%2010.148%2010.148%200%200%201%202.849-1.765c1.845-.733%203.586-.685%204.9.137%201.316.822%202.122%202.365%202.271%204.345a10.146%2010.146%200%200%201-.33%203.334z'/%3e%3c/svg%3e",Lj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M37%2020.034C27.8809%2020.5837%2020.5808%2027.8809%2020.0326%2037H19.966C19.4163%2027.8809%2012.1177%2020.5837%203%2020.034V19.9674C12.1191%2019.4163%2019.4163%2012.1191%2019.966%203H20.0326C20.5822%2012.1191%2027.8809%2019.4163%2037%2019.9674V20.034Z'%20fill='currentColor'/%3e%3c/svg%3e",Nj="/assets/kimi-for-coding-eVEHug_h.svg",Vj="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eLM%20Studio%3c/title%3e%3cpath%20d='M2.84%202a1.273%201.273%200%20100%202.547h14.107a1.273%201.273%200%20100-2.547H2.84zM7.935%205.33a1.273%201.273%200%20000%202.548H22.04a1.274%201.274%200%20000-2.547H7.935zM3.624%209.935c0-.704.57-1.274%201.274-1.274h14.106a1.274%201.274%200%20010%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM1.273%2012.188a1.273%201.273%200%20100%202.547H15.38a1.274%201.274%200%20000-2.547H1.273zM3.624%2016.792c0-.704.57-1.274%201.274-1.274h14.106a1.273%201.273%200%20110%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM13.029%2018.849a1.273%201.273%200%20100%202.547h9.698a1.273%201.273%200%20100-2.547h-9.698z'%20fill-opacity='.3'%3e%3c/path%3e%3cpath%20d='M2.84%202a1.273%201.273%200%20100%202.547h10.287a1.274%201.274%200%20000-2.547H2.84zM7.935%205.33a1.273%201.273%200%20000%202.548H18.22a1.274%201.274%200%20000-2.547H7.935zM3.624%209.935c0-.704.57-1.274%201.274-1.274h10.286a1.273%201.273%200%20010%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM1.273%2012.188a1.273%201.273%200%20100%202.547H11.56a1.274%201.274%200%20000-2.547H1.273zM3.624%2016.792c0-.704.57-1.274%201.274-1.274h10.286a1.273%201.273%200%20110%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM13.029%2018.849a1.273%201.273%200%20100%202.547h5.78a1.273%201.273%200%20100-2.547h-5.78z'%3e%3c/path%3e%3c/svg%3e",Rj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M17.8758%209.20865C17.8758%208.59461%2017.3777%208.09634%2016.7663%208.09634C16.155%208.09634%2015.6567%208.59575%2015.6567%209.20865V27.6446C15.6567%2029.0714%2014.4985%2030.2324%2013.0755%2030.2324C11.6523%2030.2324%2010.4941%2029.0714%2010.4941%2027.6446V15.8167C10.4941%2015.2027%209.99591%2014.7044%209.38453%2014.7044C8.77316%2014.7044%208.275%2015.2038%208.275%2015.8167V20.8301C8.275%2022.2567%207.11678%2023.4179%205.69364%2023.4179C4.2705%2023.4179%203.1123%2022.2567%203.1123%2020.8301V19.0129C3.1123%2018.6054%203.44177%2018.2752%203.84822%2018.2752C4.25467%2018.2752%204.58413%2018.6054%204.58413%2019.0129V20.8301C4.58413%2021.4441%205.08227%2021.9424%205.69364%2021.9424C6.30502%2021.9424%206.80317%2021.443%206.80317%2020.8301V15.8167C6.80317%2014.39%207.96139%2013.2289%209.38453%2013.2289C10.8077%2013.2289%2011.9659%2014.39%2011.9659%2015.8167V27.6446C11.9659%2028.2587%2012.4641%2028.7569%2013.0755%2028.7569C13.6868%2028.7569%2014.1849%2028.2575%2014.1849%2027.6446V20.4123V9.20865C14.1849%207.78194%2015.3431%206.62082%2016.7663%206.62082C18.1894%206.62082%2019.3476%207.78194%2019.3476%209.20865V24.4746C19.3476%2024.8821%2019.0182%2025.2123%2018.6117%2025.2123C18.2053%2025.2123%2017.8758%2024.8821%2017.8758%2024.4746V9.20865ZM31.531%2013.2289C30.1079%2013.2289%2028.9496%2014.39%2028.9496%2015.8167V25.6969C28.9496%2026.311%2028.4515%2026.8093%2027.8401%2026.8093C27.2287%2026.8093%2026.7306%2026.3099%2026.7306%2025.6969V9.20865C26.7306%207.78194%2025.5723%206.62082%2024.1492%206.62082C22.7261%206.62082%2021.5679%207.78194%2021.5679%209.20865V30.1383C21.5679%2030.7523%2021.0697%2031.2506%2020.4583%2031.2506C19.8469%2031.2506%2019.3488%2030.7511%2019.3488%2030.1383V27.5471C19.3488%2027.1396%2019.0194%2026.8093%2018.6129%2026.8093C18.2065%2026.8093%2017.877%2027.1396%2017.877%2027.5471V30.1383C17.877%2031.565%2019.0352%2032.7261%2020.4583%2032.7261C21.8815%2032.7261%2023.0397%2031.565%2023.0397%2030.1383V9.20865C23.0397%208.59461%2023.5378%208.09634%2024.1492%208.09634C24.7605%208.09634%2025.2587%208.59575%2025.2587%209.20865V25.6969C25.2587%2027.1237%2026.417%2028.2848%2027.8401%2028.2848C29.2632%2028.2848%2030.4215%2027.1237%2030.4215%2025.6969V15.8167C30.4215%2015.2027%2030.9196%2014.7044%2031.531%2014.7044C32.1424%2014.7044%2032.6405%2015.2038%2032.6405%2015.8167V24.4746C32.6405%2024.8821%2032.97%2025.2123%2033.3764%2025.2123C33.7829%2025.2123%2034.1123%2024.8821%2034.1123%2024.4746V15.8167C34.1123%2014.39%2032.9541%2013.2289%2031.531%2013.2289Z'%20fill='currentColor'/%3e%3c/svg%3e",zj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M17.8758%209.20865C17.8758%208.59461%2017.3777%208.09634%2016.7663%208.09634C16.155%208.09634%2015.6567%208.59575%2015.6567%209.20865V27.6446C15.6567%2029.0714%2014.4985%2030.2324%2013.0755%2030.2324C11.6523%2030.2324%2010.4941%2029.0714%2010.4941%2027.6446V15.8167C10.4941%2015.2027%209.99591%2014.7044%209.38453%2014.7044C8.77316%2014.7044%208.275%2015.2038%208.275%2015.8167V20.8301C8.275%2022.2567%207.11678%2023.4179%205.69364%2023.4179C4.2705%2023.4179%203.1123%2022.2567%203.1123%2020.8301V19.0129C3.1123%2018.6054%203.44177%2018.2752%203.84822%2018.2752C4.25467%2018.2752%204.58413%2018.6054%204.58413%2019.0129V20.8301C4.58413%2021.4441%205.08227%2021.9424%205.69364%2021.9424C6.30502%2021.9424%206.80317%2021.443%206.80317%2020.8301V15.8167C6.80317%2014.39%207.96139%2013.2289%209.38453%2013.2289C10.8077%2013.2289%2011.9659%2014.39%2011.9659%2015.8167V27.6446C11.9659%2028.2587%2012.4641%2028.7569%2013.0755%2028.7569C13.6868%2028.7569%2014.1849%2028.2575%2014.1849%2027.6446V20.4123V9.20865C14.1849%207.78194%2015.3431%206.62082%2016.7663%206.62082C18.1894%206.62082%2019.3476%207.78194%2019.3476%209.20865V24.4746C19.3476%2024.8821%2019.0182%2025.2123%2018.6117%2025.2123C18.2053%2025.2123%2017.8758%2024.8821%2017.8758%2024.4746V9.20865ZM31.531%2013.2289C30.1079%2013.2289%2028.9496%2014.39%2028.9496%2015.8167V25.6969C28.9496%2026.311%2028.4515%2026.8093%2027.8401%2026.8093C27.2287%2026.8093%2026.7306%2026.3099%2026.7306%2025.6969V9.20865C26.7306%207.78194%2025.5723%206.62082%2024.1492%206.62082C22.7261%206.62082%2021.5679%207.78194%2021.5679%209.20865V30.1383C21.5679%2030.7523%2021.0697%2031.2506%2020.4583%2031.2506C19.8469%2031.2506%2019.3488%2030.7511%2019.3488%2030.1383V27.5471C19.3488%2027.1396%2019.0194%2026.8093%2018.6129%2026.8093C18.2065%2026.8093%2017.877%2027.1396%2017.877%2027.5471V30.1383C17.877%2031.565%2019.0352%2032.7261%2020.4583%2032.7261C21.8815%2032.7261%2023.0397%2031.565%2023.0397%2030.1383V9.20865C23.0397%208.59461%2023.5378%208.09634%2024.1492%208.09634C24.7605%208.09634%2025.2587%208.59575%2025.2587%209.20865V25.6969C25.2587%2027.1237%2026.417%2028.2848%2027.8401%2028.2848C29.2632%2028.2848%2030.4215%2027.1237%2030.4215%2025.6969V15.8167C30.4215%2015.2027%2030.9196%2014.7044%2031.531%2014.7044C32.1424%2014.7044%2032.6405%2015.2038%2032.6405%2015.8167V24.4746C32.6405%2024.8821%2032.97%2025.2123%2033.3764%2025.2123C33.7829%2025.2123%2034.1123%2024.8821%2034.1123%2024.4746V15.8167C34.1123%2014.39%2032.9541%2013.2289%2031.531%2013.2289Z'%20fill='currentColor'/%3e%3c/svg%3e",Oj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M26.7,5.25l2.14-1.53,10.49,13.29-16.23,19.43-2.65,3L0.42,16.83l6.87-8.64,5.78,2.21,1.79-4.46L23.3,0.1l3.42,5.15ZM31.13,13.98L22.91,1.78l-7.1,4.95-5.45,13.53,20.77-6.28ZM36.74,15.57l-8.03-10.1-0.14-0.1-1.14,0.89,5.03,7.58,4.28,1.73ZM9.06,20.35l3.53-8.84-4.89-1.92-5.62,7.1,6.98,3.66ZM37.62,17.19l-5.3-2.14-9.22,19.52,14.52-17.38ZM30.95,15.24l-20.63,6.22,10.1,15.93,10.53-22.15ZM15.79,32.41l-6.86-10.82c-1.61-0.84-3.2-1.73-4.81-2.57-0.1-0.05-0.21-0.12-0.32-0.13l11.99,13.52Z'%20fill='currentColor'/%3e%3c/svg%3e",$j="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eOllama%3c/title%3e%3cpath%20d='M7.905%201.09c.216.085.411.225.588.41.295.306.544.744.734%201.263.191.522.315%201.1.362%201.68a5.054%205.054%200%20012.049-.636l.051-.004c.87-.07%201.73.087%202.48.474.101.053.2.11.297.17.05-.569.172-1.134.36-1.644.19-.52.439-.957.733-1.264a1.67%201.67%200%2001.589-.41c.257-.1.53-.118.796-.042.401.114.745.368%201.016.737.248.337.434.769.561%201.287.23.934.27%202.163.115%203.645l.053.04.026.019c.757.576%201.284%201.397%201.563%202.35.435%201.487.216%203.155-.534%204.088l-.018.021.002.003c.417.762.67%201.567.724%202.4l.002.03c.064%201.065-.2%202.137-.814%203.19l-.007.01.01.024c.472%201.157.62%202.322.438%203.486l-.006.039a.651.651%200%2001-.747.536.648.648%200%2001-.54-.742c.167-1.033.01-2.069-.48-3.123a.643.643%200%2001.04-.617l.004-.006c.604-.924.854-1.83.8-2.72-.046-.779-.325-1.544-.8-2.273a.644.644%200%2001.18-.886l.009-.006c.243-.159.467-.565.58-1.12a4.229%204.229%200%2000-.095-1.974c-.205-.7-.58-1.284-1.105-1.683-.595-.454-1.383-.673-2.38-.61a.653.653%200%2001-.632-.371c-.314-.665-.772-1.141-1.343-1.436a3.288%203.288%200%2000-1.772-.332c-1.245.099-2.343.801-2.67%201.686a.652.652%200%2001-.61.425c-1.067.002-1.893.252-2.497.703-.522.39-.878.935-1.066%201.588a4.07%204.07%200%2000-.068%201.886c.112.558.331%201.02.582%201.269l.008.007c.212.207.257.53.109.785-.36.622-.629%201.549-.673%202.44-.05%201.018.186%201.902.719%202.536l.016.019a.643.643%200%2001.095.69c-.576%201.236-.753%202.252-.562%203.052a.652.652%200%2001-1.269.298c-.243-1.018-.078-2.184.473-3.498l.014-.035-.008-.012a4.339%204.339%200%2001-.598-1.309l-.005-.019a5.764%205.764%200%2001-.177-1.785c.044-.91.278-1.842.622-2.59l.012-.026-.002-.002c-.293-.418-.51-.953-.63-1.545l-.005-.024a5.352%205.352%200%2001.093-2.49c.262-.915.777-1.701%201.536-2.269.06-.045.123-.09.186-.132-.159-1.493-.119-2.73.112-3.67.127-.518.314-.95.562-1.287.27-.368.614-.622%201.015-.737.266-.076.54-.059.797.042zm4.116%209.09c.936%200%201.8.313%202.446.855.63.527%201.005%201.235%201.005%201.94%200%20.888-.406%201.58-1.133%202.022-.62.375-1.451.557-2.403.557-1.009%200-1.871-.259-2.493-.734-.617-.47-.963-1.13-.963-1.845%200-.707.398-1.417%201.056-1.946.668-.537%201.55-.849%202.485-.849zm0%20.896a3.07%203.07%200%2000-1.916.65c-.461.37-.722.835-.722%201.25%200%20.428.21.829.61%201.134.455.347%201.124.548%201.943.548.799%200%201.473-.147%201.932-.426.463-.28.7-.686.7-1.257%200-.423-.246-.89-.683-1.256-.484-.405-1.14-.643-1.864-.643zm.662%201.21l.004.004c.12.151.095.37-.056.49l-.292.23v.446a.375.375%200%2001-.376.373.375.375%200%2001-.376-.373v-.46l-.271-.218a.347.347%200%2001-.052-.49.353.353%200%2001.494-.051l.215.172.22-.174a.353.353%200%2001.49.051zm-5.04-1.919c.478%200%20.867.39.867.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zm8.706%200c.48%200%20.868.39.868.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zM7.44%202.3l-.003.002a.659.659%200%2000-.285.238l-.005.006c-.138.189-.258.467-.348.832-.17.692-.216%201.631-.124%202.782.43-.128.899-.208%201.404-.237l.01-.001.019-.034c.046-.082.095-.161.148-.239.123-.771.022-1.692-.253-2.444-.134-.364-.297-.65-.453-.813a.628.628%200%2000-.107-.09L7.44%202.3zm9.174.04l-.002.001a.628.628%200%2000-.107.09c-.156.163-.32.45-.453.814-.29.794-.387%201.776-.23%202.572l.058.097.008.014h.03a5.184%205.184%200%20011.466.212c.086-1.124.038-2.043-.128-2.722-.09-.365-.21-.643-.349-.832l-.004-.006a.659.659%200%2000-.285-.239h-.004z'%3e%3c/path%3e%3c/svg%3e",Zj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M32.8377%2017.282C33.2127%2016.25%2033.3072%2015.218%2033.2127%2014.1875C33.1197%2013.1571%2032.7447%2012.1251%2032.2752%2011.1876C31.4322%209.78209%2030.2127%208.6571%2028.8072%208.0001C27.3072%207.34461%2025.7127%207.15711%2024.1197%207.53211C23.3698%206.78212%2022.5253%206.12512%2021.5878%205.65713C20.6503%205.18913%2019.5253%205.00013%2018.4948%205.00013C16.8851%204.99074%2015.3125%205.48246%2013.9948%206.40712C12.6824%207.34311%2011.7449%208.6571%2011.2754%2010.1571C10.1504%2010.4376%209.21289%2010.9071%208.27539%2011.4696C7.4324%2012.1251%206.77541%2012.9696%206.21291%2013.8126C5.36992%2015.2195%205.08792%2016.8125%205.27542%2018.407C5.46399%2019.9968%206.11605%2021.496%207.1504%2022.718C6.79608%2023.7086%206.66795%2024.7659%206.77541%2025.8124C6.86991%2026.8444%207.2449%2027.8749%207.7129%2028.8124C8.55739%2030.2194%209.77538%2031.3444%2011.1824%2031.9999C12.6824%2032.6569%2014.2753%2032.8444%2015.8698%2032.4694C16.6198%2033.2194%2017.4628%2033.8749%2018.4003%2034.3444C19.3378%2034.8139%2020.4628%2034.9999%2021.4948%2034.9999C23.1043%2035.0097%2024.6769%2034.5185%2025.9947%2033.5944C27.3072%2032.6569%2028.2447%2031.3444%2028.7127%2029.8444C29.7719%2029.6432%2030.7682%2029.1934%2031.6197%2028.5319C32.4627%2027.8749%2033.2127%2027.1249%2033.6822%2026.1874C34.5251%2024.7819%2034.8071%2023.1875%2034.6196%2021.5945C34.4322%2020%2033.8697%2018.5015%2032.8377%2017.282ZM21.5878%2033.0304C20.0878%2033.0304%2018.9628%2032.5609%2017.9323%2031.7179C17.9323%2031.7179%2018.0253%2031.6234%2018.1198%2031.6234L24.1197%2028.1554C24.2862%2028.0803%2024.4196%2027.9469%2024.4947%2027.7804C24.5698%2027.636%2024.6021%2027.4731%2024.5877%2027.3109V18.875L27.1197%2020.375V27.3124C27.1455%2028.0547%2027.0215%2028.7945%2026.755%2029.4878C26.4885%2030.181%2026.085%2030.8134%2025.5687%2031.3473C25.0523%2031.8811%2024.4337%2032.3054%2023.7497%2032.5949C23.0658%2032.8843%2022.3305%2033.0314%2021.5878%2033.0304ZM9.49488%2027.8749C8.83789%2026.7499%208.55739%2025.4374%208.83789%2024.125C8.83789%2024.125%208.93239%2024.2195%209.02539%2024.2195L15.0253%2027.6874C15.1693%2027.7638%2015.3325%2027.7966%2015.4948%2027.7819C15.6823%2027.7819%2015.8698%2027.7819%2015.9628%2027.6874L23.2753%2023.4695V26.3749L17.1823%2029.9374C16.5506%2030.3042%2015.8527%2030.5427%2015.1287%2030.6393C14.4046%2030.7358%2013.6686%2030.6884%2012.9629%2030.4999C11.4629%2030.1249%2010.2449%2029.1874%209.49488%2027.8749ZM7.9004%2014.8445C8.56239%2013.7234%209.58826%2012.8627%2010.8074%2012.4056V19.532C10.8074%2019.718%2010.8074%2019.907%2010.9004%2020C10.9755%2020.1665%2011.1089%2020.2998%2011.2754%2020.375L18.5878%2024.5944L16.0573%2026.0944L10.0574%2022.625C9.41842%2022.2639%208.85742%2021.7797%208.40684%2021.2004C7.95627%2020.6211%207.62506%2019.9582%207.4324%2019.25C7.05741%2017.8445%207.1504%2016.157%207.9004%2014.8445ZM28.6197%2019.625L21.3073%2015.407L23.8377%2013.9071L29.8377%2017.375C30.7752%2017.9375%2031.5252%2018.6875%2031.9947%2019.625C32.4642%2020.5625%2032.7447%2021.5945%2032.6502%2022.7195C32.5603%2023.7755%2032.1699%2024.7837%2031.5252%2025.6249C30.8697%2026.4694%2030.0252%2027.1249%2028.9947%2027.4999V20.375C28.9947%2020.1875%2028.9947%2020%2028.9002%2019.907C28.9002%2019.907%2028.8072%2019.718%2028.6197%2019.625ZM31.1502%2015.875C31.1502%2015.875%2031.0572%2015.782%2030.9627%2015.782L24.9627%2012.3126C24.7752%2012.2196%2024.6822%2012.2196%2024.4947%2012.2196C24.3072%2012.2196%2024.1197%2012.2196%2024.0252%2012.3126L16.7128%2016.532V13.6251L22.8073%2010.0626C23.7448%209.50009%2024.7752%209.31259%2025.9002%209.31259C26.9322%209.31259%2027.9627%209.68759%2028.9002%2010.3446C29.7447%2011.0001%2030.4947%2011.8446%2030.8697%2012.7821C31.2447%2013.7196%2031.3377%2014.8445%2031.1502%2015.875ZM15.4003%2021.125L12.8699%2019.625V12.5946C12.8699%2011.5626%2013.1503%2010.4376%2013.7128%209.59459C14.2753%208.6571%2015.1198%208.0001%2016.0573%207.53211C17.0127%207.05249%2018.0956%206.88812%2019.1503%207.06261C20.1823%207.15711%2021.2128%207.62511%2022.0573%208.2821C22.0573%208.2821%2021.9628%208.3751%2021.8698%208.3751L15.8698%2011.8446C15.7033%2011.9197%2015.57%2012.0531%2015.4948%2012.2196C15.4003%2012.4071%2015.4003%2012.5001%2015.4003%2012.6876V21.125ZM16.7128%2018.125L19.9948%2016.25L23.2753%2018.125V21.875L19.9948%2023.75L16.7128%2021.875V18.125Z'%20fill='currentColor'/%3e%3c/svg%3e",qj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M3.10913%2012.07C3.65512%2012.07%205.76627%2011.5988%206.85825%2010.98C7.95023%2010.3612%207.95023%2010.3612%2010.207%208.75965C13.0642%206.73196%2015.0845%207.41088%2018.3968%207.41088'%20fill='currentColor'/%3e%3cpath%20d='M3.10913%2012.07C3.65512%2012.07%205.76627%2011.5988%206.85825%2010.98C7.95023%2010.3612%207.95023%2010.3612%2010.207%208.75965C13.0642%206.73196%2015.0845%207.41088%2018.3968%207.41088'%20stroke='currentColor'%20stroke-width='3.27593'/%3e%3cpath%20d='M21.6%207.43108L16.0037%2010.6622V4.20001L21.6%207.43108Z'%20fill='currentColor'%20stroke='currentColor'%20stroke-width='0.0363992'/%3e%3cpath%20d='M3%2012.072C3.54599%2012.072%205.65714%2012.5432%206.74912%2013.162C7.8411%2013.7808%207.8411%2013.7808%2010.0978%2015.3823C12.9551%2017.41%2014.9753%2016.7311%2018.2877%2016.7311'%20fill='currentColor'/%3e%3cpath%20d='M3%2012.072C3.54599%2012.072%205.65714%2012.5432%206.74912%2013.162C7.8411%2013.7808%207.8411%2013.7808%2010.0978%2015.3823C12.9551%2017.41%2014.9753%2016.7311%2018.2877%2016.7311'%20stroke='currentColor'%20stroke-width='3.27593'/%3e%3cpath%20d='M21.4909%2016.7109L15.8945%2013.4798V19.942L21.4909%2016.7109Z'%20fill='currentColor'%20stroke='currentColor'%20stroke-width='0.0363992'/%3e%3c/svg%3e",Uj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3cimage%20width='24'%20height='24'%20xlink:href='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF0AAABcCAYAAAAMLblmAAAACXBIWXMAAAAAAAAAAQCEeRdzAAAHhklEQVR4nO1d21HjSBRtjJhvMhgtxlX8DRsBJgIggjERwESAiWAgAjwRYCJAGwHMH1U8VhvBst+89hxzRRkwuG+rJet1qlwSM1KrdXR1+nb37as5UzCEYbi4sLAQPj4+rs7NzX17enpaxI/7i8khs6xfWuA+1oNZV4IkB0Gwit0NEN1FpVaxHf0fyB5t8W8zrKF/zIT0hGiQuoc/uR1ZcdXI/Qi5kk6yW63WDsjdTYiuI3IhfXl5uQuSd7C7mcf1io5MSYdlh/Pz83sgvJfldcqGTEgflxH8WVsZ+QjeSRcpOTIld+2yhFfSl5aWfoLwXZ9lVhFeSKd2Q06O6WP7KG8CbvlD+TEeavz2P/HvIbfsRJkSyFlq0kVOjo3HmwWJEcr8jd0IvdPzi4uL2Pbcsc7WqMOFcrq+6uULqUiHnOzgpg58VESI/vXw8DCM4/jWtRw5N5LfqG7tdpuuKn/fPVQ1NZxJB+F7IKqf8vqUjMP7+/uDNERPw/X19RCbId6CPlzYLvbZEw6zut40OJHugfBcyH4LXCvGZsAfrL9nZkS+mnQPhA+h0z80Op0FYP0DWP4Q+r8rY0C5QUU6NTwF4THO3b66uoocz/cOecv6IH8A2Tk1OVm9Nenipbg2modoIPt5SokGIjt/4B77eVi9Fen0w6WXqQW1ex/W7cXDyRqoZ7/T6QwfHx/pAodZXceKdMdXL0aHaevy8vJcXasZgvWFja1nKTdTSWfD6XDxGI3l+qwbS1dQbkh8Vr3sT0kXHe8ryyw14QnGiD/1TfynpDvoeCUIT8CGH8Rv+ZaaD0l3kJVbanhVCE+QWDyIPzOexpcmkk5vReuP00spW6NpCxIPqd3Cm3/qo7yJpHOKTVnOYVncQlewU9dutw+xu5O2rHek08qx6SnKiNGlrsXEBe8TsruWtmF9R7rWytlwpqlA2QB+ttF5OktTxivSHax8ULWGcxrYbqWVmVekK62c7uG+64XLDI4jgStOiDh5M2/lxToYCLr2q25WnoD+O7yZQ9fBsRfSZVDf9snFQRAMXC5YFXACBtZOiVFb+7ila+YPo7paeYI01j4inTPo2HRtT6qrlr+Fq7WPSJfJWitw1r7uVp6A1g5ZPjHKKINEXjZsT2CYhOYCVQeMcABO9KSzh5WsepgGSEukr1p1IcMDnIa0lpiAei7haFOB41TRVjWCSmICWYZidTDeiL9ca1VlgJdzjcRQXjSDN5G6RjWAhARaHx/g4ND24FarFTvUqfKQ8RhrXQ/wlL7aPqWqTlL4gIRxW6lGYLvKjY1oumpVGxLabUe6sZwHhbQUMjqrQLDmh6TbWvp/ztWpASAvt7YybU068K9zjeoBlaU38ABYeUN6kdGQ7glMjaLRdNVgTYMPYT/gZSxJT9ZqNpgMTVaPwNbV0QwX1BGanj0tPTZ2PanQvUq1QGh7IIcB/rE9eGVlJWzG0yfDdtyFCGSgxurgh4eHrnleh9lgDJ1O5yXvmA0oL9YDWcwg51KpqkPLS3B/f38+Pz9vdTDeiDWnWlUcUIsN1SSGhBHExqIh4AQ251SLuh50VtBm2kh6pJxYtYpCDYKgZyS7RIOXxXD6YCOj0HVcgDEyDekCbcwLMSKdOVag67Yr6bqNxDzDIZ5/hBHpouuRsYxnZOYIbPrai1UNmnDEcbyMMqKRPLFtEJjYEg8511wtBUW6+HS4jgNZiWHTKCzW3dolnj90OfeFdJEYBodaeTF1tnbRcucUJa8mMSAxQ8mJawNmGeWFf7hevKwQRQhdz39FukSgRsayQWVaV/ipJ0XKVpQ1XD2WcbybruNyc00Pi0kbUI8/6yIzkpwhFd6RrrV2IKyLzDjmvnmHiRPTWmunzOBBnV9fX1d2lYZj7puJmEi6Y/KBg06n87uKQaYpcphNxIchGA6rgheZcGxlZaUySXYIDnnklmRH/PZt7B4rygvv7u5Oq0K8JN/3nkDt02Aj5qiVDpNmJK0SxCeE5544jYDM7OL14oxRqCi31MRnnQ9+KumUGTSQW9BrvmaawXoSf0aJkqzOpYB8PCXTFLBWsYyypoZ+uLYF50M6hn/bv7m5KfzSdtwjZZQTNJmGGVoHkDILM3zV0CUBAZOwgfjNL1++FDKbneg37yuXtFiqqF3mogXxxpH4VcjN30WzevmKwE+TYwSbOlQ6DfEErV7Govf59riU4QPSw+Q9dPO+tlN8elrizbNVHYF8nr/PfAN5yY5Y9s4sP1DivCjAA/FEiN8RZIdkDLB/koWnQ6s2z1+C6ZkCxOKnWolB4jnQZfxoYo8/lMf9SPIQRIxA0wwbj39yByR/w3azaF+ETL38hZaJGz337Nt25fXfY8gfl4Dzo1KMpTfPod1vwaUnoSxcsF6GMit4WXOUw+cNFqf1Dsv0AVmvC71E56Pmg4Gfw/vqOpkvze2jHmVEZksaafXyKZu+Kcjny4qCTNeRitb35PNlfdOQP0Iui3cnkK8dKq4Ucl0xnZDPffYM4XF8F9ewUH501pjZMvXky4ncl3EQPoQ1zSq1sqIQuQHE44mSv6Xbviodnq9GOj/m+Y0o/VvxPy8IndI+RM9sAAAAAElFTkSuQmCC'/%3e%3c/svg%3e",Wj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.1312%207.50002L17.4088%2011.1913H5.81625L8.5375%207.50002H20.1325H20.1312ZM34.0675%2028.81L31.3475%2032.5H19.795L22.5125%2028.81H34.0675ZM35%207.50002L16.58%2032.5H5L23.42%207.50002H35Z'%20fill='currentColor'/%3e%3c/svg%3e",Gj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.1312%207.5L17.4088%2011.1912H5.81625L8.5375%207.5H20.1325H20.1312ZM34.0675%2028.81L31.3475%2032.5H19.795L22.5125%2028.81H34.0675ZM35%207.5L16.58%2032.5H5L23.42%207.5H35Z'%20fill='currentColor'/%3e%3c/svg%3e",Kj=Object.assign({"../assets/provider-logos/anthropic.svg":Pj,"../assets/provider-logos/bailian-coding-plan.svg":Ej,"../assets/provider-logos/cursor.svg":Ij,"../assets/provider-logos/evroc.svg":Tj,"../assets/provider-logos/github-copilot.svg":jj,"../assets/provider-logos/gocode.svg":Hj,"../assets/provider-logos/google.svg":Lj,"../assets/provider-logos/kimi-for-coding.svg":Nj,"../assets/provider-logos/lmstudio.svg":Vj,"../assets/provider-logos/minimax-cn-coding-plan.svg":Rj,"../assets/provider-logos/minimax-coding-plan.svg":zj,"../assets/provider-logos/nano-gpt.svg":Oj,"../assets/provider-logos/ollama.svg":$j,"../assets/provider-logos/openai.svg":Zj,"../assets/provider-logos/openrouter.svg":qj,"../assets/provider-logos/wafer.ai.svg":Uj,"../assets/provider-logos/zai-coding-plan.svg":Wj,"../assets/provider-logos/zhipuai-coding-plan.svg":Gj}),O1=new Map,Xc=new Set,c7=new Map([["codex","openai"],["chatgpt","openai"],["claude","anthropic"],["gemini","google"],["evroc-ai","evroc"],["evrocai","evroc"],["ollama-cloud","ollama"],["wafer-ai","wafer.ai"],["wafer","wafer.ai"]]),Yj=t=>(t??"").toLowerCase().trim().replace(/^models\./,"").replace(/^provider\./,"").replace(/\s+/g,"-"),Ap=t=>{const e=Yj(t);if(!e)return[];const n=e.replace(/[^a-z0-9_\-./:]/g,""),s=n.split(/[/:]/)[0]||n,o=[c7.get(n),c7.get(s),n,s].filter(r=>!!(r&&r.length>0));return[...new Set(o)]},Jj=t=>{const e=Ap(t),n=e.find(r=>O1.has(r))??null,s=n?O1.get(n)??null:null;if(s)return s;const o=e[0]??null;return o?`https://models.dev/logos/${o}.svg`:null},Qj=t=>{if(typeof Image>"u")return;const e=Jj(t);if(!e||Xc.has(e))return;Xc.add(e);const n=new Image;n.decoding="async",n.onerror=()=>{Xc.delete(e)},n.src=e,n.decode?.().catch(()=>{})},WX=t=>{for(const e of t)Qj(e)};for(const[t,e]of Object.entries(Kj)){const n=t.match(/provider-logos\/([^/]+)\.svg$/i);n?.[1]&&e&&O1.set(n[1].toLowerCase(),e)}function Fp(t){const e=de.c(23);let n,s,o,r;if(e[0]!==t){const p=Ap(t);s=p.find(Xj)??null,o=p[0]??null,n=!!s,r=s?O1.get(s)??null:null,e[0]=t,e[1]=n,e[2]=s,e[3]=o,e[4]=r}else n=e[1],s=e[2],o=e[3],r=e[4];const i=r,[l,c]=ae.useState(n?"local":"remote");let d;e[5]!==n?(d=()=>{c(n?"local":"remote")},e[5]=n,e[6]=d):d=e[6];let u;e[7]!==n||e[8]!==s||e[9]!==o?(u=[n,s,o],e[7]=n,e[8]=s,e[9]=o,e[10]=u):u=e[10],ae.useEffect(d,u);let f;e[11]!==n?(f=()=>{c(p=>p==="local"&&n?"remote":"none")},e[11]=n,e[12]=f):f=e[12];const m=f;if(!s&&!o){let p;return e[13]!==m?(p={src:null,onError:m,hasLogo:!1},e[13]=m,e[14]=p):p=e[14],p}if(l==="local"&&i){let p;return e[15]!==m||e[16]!==i?(p={src:i,onError:m,hasLogo:!0},e[15]=m,e[16]=i,e[17]=p):p=e[17],p}if(l==="remote"&&o){const p=`https://models.dev/logos/${o}.svg`;let b;return e[18]!==m||e[19]!==p?(b={src:p,onError:m,hasLogo:!0},e[18]=m,e[19]=p,e[20]=b):b=e[20],b}let h;return e[21]!==m?(h={src:null,onError:m,hasLogo:!1},e[21]=m,e[22]=h):h=e[22],h}function Xj(t){return O1.has(t)}const Ar=t=>{const e=de.c(10),{providerId:n,alt:s,className:o,onError:r}=t,{src:i,onError:l,hasLogo:c}=Fp(n);let d;e[0]!==r||e[1]!==l?(d=()=>{l(),r?.()},e[0]=r,e[1]=l,e[2]=d):d=e[2];const u=d;if(!c||!i)return null;const f=s||`${n} logo`;let m;e[3]!==o?(m=z("dark:invert object-contain",o),e[3]=o,e[4]=m):m=e[4];let h;return e[5]!==u||e[6]!==i||e[7]!==f||e[8]!==m?(h=a.jsx("img",{src:i,alt:f,className:m,loading:"eager",decoding:"async",fetchPriority:"high",draggable:!1,onError:u}),e[5]=u,e[6]=i,e[7]=f,e[8]=m,e[9]=h):h=e[9],h};function eH(t){const e=de.c(4),{onResizeStart:n,ariaLabel:s}=t;let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o=a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:a.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})}),e[0]=o):o=e[0];let r;return e[1]!==s||e[2]!==n?(r=a.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":s,onPointerDown:n,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:o}),e[1]=s,e[2]=n,e[3]=r):r=e[3],r}const s5=ae.forwardRef((t,e)=>{const n=de.c(60);let s,o,r,i,l,c,d,u,f,m,h,p,b;n[0]!==t?({className:s,outerClassName:d,scrollbarClassName:m,fillContainer:p,useScrollShadow:b,scrollShadowSize:f,hasError:l,resizedHeight:o,onResizeHeightChange:c,disabled:r,simple:h,endSlot:i,...u}=t,n[0]=t,n[1]=s,n[2]=o,n[3]=r,n[4]=i,n[5]=l,n[6]=c,n[7]=d,n[8]=u,n[9]=f,n[10]=m,n[11]=h,n[12]=p,n[13]=b):(s=n[1],o=n[2],r=n[3],i=n[4],l=n[5],c=n[6],d=n[7],u=n[8],f=n[9],m=n[10],h=n[11],p=n[12],b=n[13]);const w=p===void 0?!1:p,v=b===void 0?!1:b,{t:x}=Ye(),y=ae.useRef(null),k=ae.useRef(null),[C,S]=ae.useState(null),M=o??C;let A;n[14]!==c?(A=$=>{const U=y.current;if(!U)return;k.current={startY:$.clientY,startHeight:U.getBoundingClientRect().height};const L=$.currentTarget;L.setPointerCapture($.pointerId);const Z=fe=>{const Q=k.current;if(!Q)return;const pe=Q.startHeight+(fe.clientY-Q.startY),ne=Math.max(82,pe);c?c(ne):S(ne)},Y=()=>{k.current=null,L.removeEventListener("pointermove",Z),L.removeEventListener("pointerup",Y),L.removeEventListener("pointercancel",Y)};L.addEventListener("pointermove",Z),L.addEventListener("pointerup",Y),L.addEventListener("pointercancel",Y),$.preventDefault()},n[14]=c,n[15]=A):A=n[15];const B=A;let F;n[16]===Symbol.for("react.memo_cache_sentinel")?(F=$=>{if($.target.closest('textarea, button, [role="separator"]'))return;const L=y.current?.querySelector("textarea");L&&document.activeElement!==L&&($.preventDefault(),L.focus())},n[16]=F):F=n[16];const _=F;if(h){const $=e,U=w?"[field-sizing:fixed]":"field-sizing-content";let L;n[17]!==s||n[18]!==U?(L=z("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",U,s),n[17]=s,n[18]=U,n[19]=L):L=n[19];let Z;return n[20]!==r||n[21]!==w||n[22]!==d||n[23]!==u||n[24]!==f||n[25]!==m||n[26]!==$||n[27]!==L||n[28]!==v?(Z=a.jsx(Zn,{as:"textarea",ref:$,disableHorizontal:!0,fillContainer:w,useScrollShadow:v,scrollShadowSize:f,outerClassName:d,scrollbarClassName:m,className:L,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:r,...u}),n[20]=r,n[21]=w,n[22]=d,n[23]=u,n[24]=f,n[25]=m,n[26]=$,n[27]=L,n[28]=v,n[29]=Z):Z=n[29],Z}let D;n[30]!==M?(D=M!==null?{height:`${M}px`}:void 0,n[30]=M,n[31]=D):D=n[31];let E;if(n[32]!==l||n[33]!==d){let $;n[35]!==l?($=l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],n[35]=l,n[36]=$):$=n[36],E=z("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],$,d),n[32]=l,n[33]=d,n[34]=E}else E=n[34];let I;n[37]!==s||n[38]!==r?(I=z("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!r&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],r&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",s),n[37]=s,n[38]=r,n[39]=I):I=n[39];let T;n[40]!==r||n[41]!==u||n[42]!==e||n[43]!==I?(T=a.jsx("textarea",{ref:e,className:I,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:r,...u}),n[40]=r,n[41]=u,n[42]=e,n[43]=I,n[44]=T):T=n[44];let j;n[45]!==x?(j=x("textarea.resizeHandleAria"),n[45]=x,n[46]=j):j=n[46];let V;n[47]!==B||n[48]!==j?(V=a.jsx(eH,{onResizeStart:B,ariaLabel:j}),n[47]=B,n[48]=j,n[49]=V):V=n[49];let H;n[50]!==i||n[51]!==V?(H=a.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[i,V]}),n[50]=i,n[51]=V,n[52]=H):H=n[52];let N;n[53]!==H||n[54]!==T?(N=a.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[T,H]}),n[53]=H,n[54]=T,n[55]=N):N=n[55];let R;return n[56]!==N||n[57]!==D||n[58]!==E?(R=a.jsx("div",{ref:y,onPointerDown:_,style:D,className:E,children:N}),n[56]=N,n[57]=D,n[58]=E,n[59]=R):R=n[59],R});s5.displayName="Textarea";function tH(){const t=de.c(11),e=Ie(nH),n=V_(e??""),s=Z3(e??""),o=ae.useRef(0);let r,i;t[0]!==e||t[1]!==n?(r=()=>{!e||!n||n.length},i=[e,n],t[0]=e,t[1]=n,t[2]=r,t[3]=i):(r=t[2],i=t[3]),ae.useEffect(r,i);let l,c;t[4]!==e||t[5]!==s?(l=()=>{!e||!s||s.length},c=[e,s],t[4]=e,t[5]=s,t[6]=l,t[7]=c):(l=t[6],c=t[7]),ae.useEffect(l,c);let d;t[8]===Symbol.for("react.memo_cache_sentinel")?(d=()=>{o.current=0},t[8]=d):d=t[8];let u;t[9]!==e?(u=[e],t[9]=e,t[10]=u):u=t[10],ae.useEffect(d,u)}function nH(t){return t.currentSessionId}const sH=g.memo(function(){return tH(),null});function GX(t){const e=de.c(5),{children:n}=t,s=Pe(oH);let o;e[0]!==s?(o=s?a.jsx(sH,{}):null,e[0]=s,e[1]=o):o=e[1];let r;return e[2]!==n||e[3]!==o?(r=a.jsxs(a.Fragment,{children:[o,n]}),e[2]=n,e[3]=o,e[4]=r):r=e[4],r}function oH(t){return t.voiceModeEnabled}class rH{recognition=null;isListening=!1;currentLang="en-US";onResultCallback=null;onErrorCallback=null;restartOnEnd=!1;conversationMode=!1;isSpeaking=!1;audioContext=null;audioUnlockRequired=!1;isSupported(){const e="SpeechRecognition"in window||"webkitSpeechRecognition"in window,n="speechSynthesis"in window;return e&&n}getSupportDetails(){return{recognition:"SpeechRecognition"in window||"webkitSpeechRecognition"in window,synthesis:"speechSynthesis"in window,prefixed:!("SpeechRecognition"in window)&&"webkitSpeechRecognition"in window,secureContext:window.isSecureContext}}setConversationMode(e){this.conversationMode=e,e||(this.restartOnEnd=!1)}isConversationMode(){return this.conversationMode}pauseListening(){if(this.restartOnEnd=!1,this.recognition)try{this.recognition.stop()}catch{}this.isListening=!1}resumeListening(){if(console.log("[BrowserVoiceService] resumeListening called:",{conversationMode:this.conversationMode,hasCallback:!!this.onResultCallback,isSpeaking:this.isSpeaking,currentLang:this.currentLang}),this.conversationMode&&this.onResultCallback&&!this.isSpeaking)try{console.log("[BrowserVoiceService] Resuming listening..."),this.startListeningSync(this.currentLang,this.onResultCallback,this.onErrorCallback||void 0)}catch(e){console.error("[BrowserVoiceService] Failed to resume listening:",e)}else console.log("[BrowserVoiceService] Not resuming - conditions not met")}async checkMicrophonePermission(){try{return"permissions"in navigator?(await navigator.permissions.query({name:"microphone"})).state==="granted":!1}catch{return!1}}async prepareListening(){if(!this.isSupported())throw new Error("Web Speech API not supported in this browser");if(typeof navigator>"u"||typeof navigator.mediaDevices?.getUserMedia!="function")return!0;try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(n=>n.stop()),!0}catch(e){const n=typeof e=="object"&&e&&"name"in e?String(e.name):"";if(n==="NotAllowedError")throw new Error("Microphone permission denied");if(n==="NotFoundError")throw new Error("No microphone found");const s=e instanceof Error?e.message:"Unable to access microphone";throw new Error(s)}}startListeningSync(e,n,s){if(!this.isSupported()){const r="Web Speech API not supported in this browser";throw s?.(r),new Error(r)}this.stopListening();const o=window.SpeechRecognition||window.webkitSpeechRecognition;this.recognition=new o,this.currentLang=e,this.onResultCallback=n,this.onErrorCallback=s||null,this.recognition.continuous=!0,this.recognition.interimResults=!0,this.recognition.lang=e,this.recognition.onstart=()=>{console.log("[BrowserVoiceService] Recognition started"),this.isListening=!0,this.restartOnEnd=!0},this.recognition.onaudiostart=()=>{console.log("[BrowserVoiceService] Audio recording started")},this.recognition.onsoundstart=()=>{console.log("[BrowserVoiceService] Sound detected")},this.recognition.onresult=r=>{console.log("[BrowserVoiceService] Got result:",r.results.length,"results");let i="",l="";for(let c=r.resultIndex;c<r.results.length;c++){const d=r.results[c];d.isFinal?i+=d[0].transcript:l+=d[0].transcript}console.log("[BrowserVoiceService] Transcripts - interim:",l,"final:",i),l&&(console.log("[BrowserVoiceService] Calling onResultCallback with interim"),this.onResultCallback?.(l,!1)),i&&(console.log("[BrowserVoiceService] Calling onResultCallback with final"),this.onResultCallback?.(i,!0))},this.recognition.onerror=r=>{if(r.error==="aborted")return;const i=this.getErrorMessage(r.error);this.onErrorCallback?.(i),(r.error==="not-allowed"||r.error==="service-not-allowed"||r.error==="network")&&(this.restartOnEnd=!1,this.isListening=!1)},this.recognition.onend=()=>{if(this.isListening=!1,this.restartOnEnd&&this.recognition&&!this.isSpeaking)try{this.recognition.start()}catch{}};try{this.recognition.start()}catch(r){const i=r instanceof Error?r.message:"Failed to start speech recognition";throw s?.(i),new Error(i)}}async startListening(e,n,s){this.startListeningSync(e,n,s)}stopListening(){if(this.restartOnEnd=!1,this.recognition){try{this.recognition.stop()}catch{}this.recognition=null}this.isListening=!1}getIsListening(){return this.isListening}getCurrentLang(){return this.currentLang}async resumeAudioContext(){this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioContext.state==="suspended"&&await this.audioContext.resume()}isAudioUnlockRequired(){return this.audioUnlockRequired}async unlockAudio(){try{const e=new Audio;if(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA",e.volume=.01,await e.play(),await this.resumeAudioContext(),this.isMobileDevice()&&"speechSynthesis"in window){const n=new SpeechSynthesisUtterance("");n.volume=0,window.speechSynthesis.speak(n),window.speechSynthesis.cancel(),console.log("[BrowserVoiceService] Speech synthesis unlocked for mobile")}return this.audioUnlockRequired=!1,console.log("[BrowserVoiceService] Audio unlocked successfully"),!0}catch(e){return console.error("[BrowserVoiceService] Failed to unlock audio:",e),!1}}async speakText(e,n,s,o){if(!("speechSynthesis"in window))throw new Error("Speech synthesis not supported");await this.resumeAudioContext();const r=await this.waitForVoices();await new Promise(c=>setTimeout(c,50)),this.isSpeaking=!0,this.pauseListening(),window.speechSynthesis.cancel();const i=new SpeechSynthesisUtterance(e);i.lang=n,i.rate=o?.rate??1,i.pitch=o?.pitch??1,i.volume=o?.volume??1;let l=null;return o?.voiceName&&(l=r.find(c=>c.name===o.voiceName)||null,l?console.log(`[BrowserVoiceService] Using selected voice: ${l.name} (${l.lang})`):console.warn(`[BrowserVoiceService] Selected voice "${o.voiceName}" not found, falling back to language match`)),l||(l=this.findBestVoice(r,n),l?console.log(`[BrowserVoiceService] Using language-matched voice: ${l.name} (${l.lang})`):console.warn(`[BrowserVoiceService] No voice found for language: ${n}, using default`)),l&&(i.voice=l),console.log(`[BrowserVoiceService] Speaking text (${e.length} chars) in ${n}`),new Promise((c,d)=>{let u=!1;i.onstart=()=>{u=!0,console.log("[BrowserVoiceService] Speech started"),c()},i.onend=()=>{this.isSpeaking=!1,console.log("[BrowserVoiceService] Speech ended"),s?.()},i.onerror=f=>{this.isSpeaking=!1,console.error("[BrowserVoiceService] Speech synthesis error:",f.error),(f.error==="not-allowed"||f.error==="interrupted")&&(this.audioUnlockRequired=!0);let m=`Speech synthesis error: ${f.error||"unknown"}`;f.error==="not-allowed"?m="Audio blocked by browser autoplay policy. Please interact with the page first.":f.error==="interrupted"&&(m="Speech was interrupted. Please try again."),d(new Error(m))},setTimeout(()=>{u||(console.warn("[BrowserVoiceService] Speech start timeout - audio may be blocked"),this.audioUnlockRequired=!0)},2e3),window.speechSynthesis.speak(i)})}cancelSpeech(){"speechSynthesis"in window&&window.speechSynthesis.cancel()}getVoices(){return"speechSynthesis"in window?window.speechSynthesis.getVoices():[]}async waitForVoices(){if(!("speechSynthesis"in window))return[];const e=window.speechSynthesis.getVoices();return e.length>0?e:new Promise(n=>{const s=()=>{n(window.speechSynthesis.getVoices()),window.speechSynthesis.onvoiceschanged=null};window.speechSynthesis.onvoiceschanged=s,setTimeout(()=>{n(window.speechSynthesis.getVoices()),window.speechSynthesis.onvoiceschanged=null},1e3)})}findBestVoice(e,n){let s=e.find(o=>o.lang===n);if(!s){const o=n.split("-")[0];s=e.find(r=>r.lang.startsWith(o))}return s||(s=e.find(o=>o.lang.startsWith(n.split("-")[0])&&o.localService)),s||null}isMobileDevice(){if(typeof navigator>"u")return!1;const e=navigator.userAgent.toLowerCase();return/iphone|ipad|ipod|android|mobile|webos|blackberry|iemobile|opera mini/i.test(e)}isIOSSafari(){if(typeof navigator>"u")return!1;const e=navigator.userAgent.toLowerCase(),n=/iphone|ipad|ipod/i.test(e),s=/safari/i.test(e)&&!/chrome|crios|crmo/i.test(e);return n&&s}getErrorMessage(e){const n=this.isMobileDevice(),s=this.isIOSSafari();return{"no-speech":"No speech detected",aborted:"Speech recognition aborted","audio-capture":"No microphone found",network:"Network error - check connection","not-allowed":n?"Microphone permission denied. Check Settings > Safari > Microphone":"Microphone permission denied","service-not-allowed":s?"Speech recognition requires a user gesture. Please tap the microphone button again.":"Speech recognition service not allowed","bad-grammar":"Grammar error","language-not-supported":"Language not supported"}[e]||`Speech recognition error: ${e}`}}const ln=new rH,iH=80,aH=300;class lH{stream=null;mediaRecorder=null;audioContext=null;analyser=null;vadTimer=null;chunks=[];recordingStartMs=0;isActive=!1;isSpeaking=!1;silenceSince=null;onResult=null;onError=null;finishResolver=null;lang="en";cfg={baseURL:"",model:"deepdml/faster-whisper-large-v3-turbo-ct2",language:"",silenceThresholdDb:-45,silenceHoldMs:1500,apiKey:""};configure(e){this.cfg={silenceThresholdDb:-45,silenceHoldMs:1500,language:"",apiKey:"",...e},this.cfg.apiKey=e.apiKey??""}isSupported(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof window.MediaRecorder<"u"&&typeof window.AudioContext<"u"}async startListening(e,n,s){this.isActive&&this.stopListening(),this.lang=e,this.onResult=n,this.onError=s??null,this.isActive=!0;try{this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(o){this.isActive=!1;const r=o instanceof Error?o.message:"Microphone access denied";s?.(r);return}this._setupAudioContext(),this._startRecorder(),this._startVAD()}stopListening(){this._stopVAD(),this._stopRecorder(),this._cleanupAfterStop(!0)}async finishListening(){if(this.isActive){if(this._stopVAD(),this.isSpeaking=!1,this.silenceSince=null,!this.mediaRecorder||this.mediaRecorder.state==="inactive"){this._cleanupAfterStop(!0);return}await new Promise(e=>{this.finishResolver=e,this._finaliseUtterance(!1)}),this._cleanupAfterStop(!0)}}getIsListening(){return this.isActive}_setupAudioContext(){if(!this.stream)return;const e=window.AudioContext??window.webkitAudioContext;this.audioContext=new e;const n=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=512,n.connect(this.analyser)}_teardownAudioContext(){try{this.audioContext?.close()}catch{}this.audioContext=null,this.analyser=null}_startRecorder(){if(!this.stream)return;const e=this._pickMimeType(),n={};e&&MediaRecorder.isTypeSupported(e)&&(n.mimeType=e),this.mediaRecorder=new MediaRecorder(this.stream,n),this.chunks=[],this.recordingStartMs=Date.now(),this.mediaRecorder.ondataavailable=s=>{s.data&&s.data.size>0&&this.chunks.push(s.data)},this.mediaRecorder.onstop=()=>{const s=this.chunks.splice(0),o=Date.now()-this.recordingStartMs;if(s.length===0||o<aH){this.finishResolver?.(),this.finishResolver=null;return}const r=s[0].type||e||"audio/webm",i=new Blob(s,{type:r});this._upload(i,r).finally(()=>{this.finishResolver?.(),this.finishResolver=null})},this.mediaRecorder.start(250)}_stopRecorder(){if(this.mediaRecorder&&this.mediaRecorder.state!=="inactive")try{this.mediaRecorder.stop()}catch{this.finishResolver?.(),this.finishResolver=null}this.mediaRecorder=null}_releaseStream(){this.stream&&(this.stream.getTracks().forEach(e=>e.stop()),this.stream=null)}_startVAD(){this._stopVAD(),this.silenceSince=null,this.isSpeaking=!1,this.vadTimer=setInterval(()=>{if(!this.isActive||!this.analyser)return;this._getRmsDb()<this.cfg.silenceThresholdDb?this.isSpeaking&&(this.silenceSince===null?this.silenceSince=Date.now():Date.now()-this.silenceSince>=this.cfg.silenceHoldMs&&(this.isSpeaking=!1,this.silenceSince=null,this._finaliseUtterance(!0))):(this.silenceSince=null,this.isSpeaking||(this.isSpeaking=!0,this.mediaRecorder?.state==="recording"&&(this.recordingStartMs=Date.now())))},iH)}_stopVAD(){this.vadTimer!==null&&(clearInterval(this.vadTimer),this.vadTimer=null)}_cleanupAfterStop(e){const n=this.finishResolver;this.isActive=!1,this.finishResolver=null,this.mediaRecorder=null,this._teardownAudioContext(),this._releaseStream(),e&&(this.chunks=[]),this.isSpeaking=!1,this.silenceSince=null,this.onResult=null,this.onError=null,n?.()}_finaliseUtterance(e){this.isActive&&(this.mediaRecorder&&this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),e&&setTimeout(()=>{this.isActive&&this.stream&&this._startRecorder()},100))}_getRmsDb(){if(!this.analyser)return-1/0;const e=new Float32Array(this.analyser.fftSize);this.analyser.getFloatTimeDomainData(e);let n=0;for(const o of e)n+=o*o;const s=Math.sqrt(n/e.length);return s===0?-1/0:20*Math.log10(s)}async _upload(e,n){if(this.onResult)try{const s={"Content-Type":n,"X-Base-URL":this.cfg.baseURL,"X-Model":this.cfg.model};if(this.cfg.apiKey&&(s.Authorization=`Bearer ${this.cfg.apiKey}`),this.cfg.language)s["X-Language"]=this.cfg.language;else if(this.lang&&this.lang!=="auto"){const l=this.lang.split("-")[0];s["X-Language"]=l}const o=await nt("/api/stt/transcribe",{method:"POST",headers:s,body:e});if(!o.ok){const l=await o.json().catch(()=>({error:"Unknown error"}));throw new Error(l.error??`HTTP ${o.status}`)}const i=((await o.json()).transcript??"").trim();i&&this.onResult(i,!0)}catch(s){if(!this.isActive)return;const o=s instanceof Error?s.message:"Transcription upload failed";console.error("[AudioStreamService] Upload error:",o),this.onError?.(o)}}_pickMimeType(){const e=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/ogg","audio/mp4"];return typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported?e.find(n=>MediaRecorder.isTypeSupported(n))??"":""}}const mo=new lH,KX=[{id:"Xenova/whisper-tiny.en",name:"Whisper Tiny (EN)",size:"~39 MB",languages:"English",description:"Fastest, lowest accuracy. Good for quick dictation."},{id:"Xenova/whisper-base.en",name:"Whisper Base (EN)",size:"~73 MB",languages:"English",description:"Balanced speed and accuracy. Default for English."},{id:"Xenova/whisper-small.en",name:"Whisper Small (EN)",size:"~166 MB",languages:"English",description:"Higher accuracy, slower. Best for noisy environments."}],cH=80,dH=300,uH=16e3;class fH{transcriber=null;worker=null;modelStatus={state:"unloaded"};currentModelId=null;stream=null;mediaRecorder=null;audioContext=null;analyser=null;vadTimer=null;chunks=[];recordingStartMs=0;isActive=!1;isSpeaking=!1;silenceSince=null;onResult=null;onError=null;finishResolver=null;lang="en";cfg={silenceThresholdDb:-45,silenceHoldMs:1500};onModelStatusChange=null;configure(e){this.cfg={...this.cfg,...e}}isSupported(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof window.MediaRecorder<"u"&&typeof window.AudioContext<"u"}getModelStatus(){return this.modelStatus}getCurrentModelId(){return this.currentModelId}setModelStatus(e){this.modelStatus=e,this.onModelStatusChange?.(e)}async loadModel(e){if(!(this.currentModelId===e&&this.modelStatus.state==="ready")&&!(this.modelStatus.state==="downloading"||this.modelStatus.state==="loading")){this._terminateWorker(),this.transcriber=null,this.setModelStatus({state:"downloading",progress:0}),this.currentModelId=e;try{const s=(await rn(()=>import("./wasmSttWorker-k0YUxAR6.js"),[])).default;this.worker=new s,await new Promise((o,r)=>{const i=setTimeout(()=>r(new Error("Worker init timed out")),1e4);this.worker.onmessage=l=>{const c=l.data;c.type==="progress"?this.setModelStatus({state:"downloading",progress:c.progress??0}):c.type==="loaded"?(clearTimeout(i),o()):c.type==="error"&&(clearTimeout(i),r(new Error(c.error??"Worker load failed")))},this.worker.onerror=l=>{clearTimeout(i),r(new Error(l.message||"Worker error"))},this.worker.postMessage({type:"load",modelId:e})}),this.setModelStatus({state:"ready"});return}catch(n){console.warn("[WasmStt] Worker failed, using main-thread:",n instanceof Error?n.message:n),this._terminateWorker()}try{const{pipeline:n,env:s}=await rn(async()=>{const{pipeline:l,env:c}=await import("./vendor-.bun-By2L9XvG.js").then(d=>d.co);return{pipeline:l,env:c}},__vite__mapDeps([0,1]));s.backends.onnx.wasm.numThreads=1,s.allowLocalModels=!1;const o=new Map;let r=0,i=0;this.transcriber=await n("automatic-speech-recognition",e,{progress_callback:l=>{if(l.status==="progress"&&l.file){const c=o.get(l.file)??0,d=l.loaded??0,u=Math.max(0,d-c);o.set(l.file,d),r+=u,l.total&&l.total>i&&(i=l.total);const f=Math.max(i,r),m=f>0?Math.min(100,Math.round(r/f*100)):0;this.setModelStatus({state:"downloading",progress:m})}}}),this.setModelStatus({state:"ready"})}catch(n){const s=n instanceof Error?n.message:"Unknown error loading model";throw this.setModelStatus({state:"error",error:s}),this.transcriber=null,this.currentModelId=null,n}}}_terminateWorker(){this.worker&&(this.worker.terminate(),this.worker=null)}async unloadModel(){this._terminateWorker(),this.transcriber=null,this.currentModelId=null,this.setModelStatus({state:"unloaded"})}async startListening(e,n,s){if(this.isActive&&this.stopListening(),!this.transcriber&&!this.worker){s?.("Whisper model not loaded. Select a model in Voice Settings first.");return}this.lang=e,this.onResult=n,this.onError=s??null,this.isActive=!0;try{this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(o){this.isActive=!1;const r=o instanceof Error?o.message:"Microphone access denied";s?.(r);return}this._setupAudioContext(),this._startRecorder(),this._startVAD()}stopListening(){if(this._stopVAD(),this.mediaRecorder&&this.mediaRecorder.state==="recording")try{this.mediaRecorder.stop()}catch{}this._cleanupAfterStop(!0)}async finishListening(){if(this.isActive){if(this._stopVAD(),this.isSpeaking=!1,this.silenceSince=null,!this.mediaRecorder||this.mediaRecorder.state==="inactive"){this._cleanupAfterStop(!0);return}await new Promise(e=>{this.finishResolver=e,this._finaliseUtterance(!1)}),this._cleanupAfterStop(!0)}}getIsListening(){return this.isActive}_setupAudioContext(){if(!this.stream)return;const e=window.AudioContext??window.webkitAudioContext;this.audioContext=new e;const n=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=512,n.connect(this.analyser)}_teardownAudioContext(){try{this.audioContext?.close()}catch{}this.audioContext=null,this.analyser=null}_startRecorder(){if(!this.stream)return;const e=this._pickMimeType(),n={};e&&MediaRecorder.isTypeSupported(e)&&(n.mimeType=e),this.mediaRecorder=new MediaRecorder(this.stream,n),this.chunks=[],this.recordingStartMs=Date.now(),this.mediaRecorder.ondataavailable=s=>{s.data&&s.data.size>0&&this.chunks.push(s.data)},this.mediaRecorder.onstop=()=>{const s=this.chunks.splice(0),o=Date.now()-this.recordingStartMs;if(s.length===0||o<dH){this.finishResolver?.(),this.finishResolver=null;return}const r=s[0].type||e||"audio/webm",i=new Blob(s,{type:r});this._transcribe(i).finally(()=>{this.finishResolver?.(),this.finishResolver=null})},this.mediaRecorder.start(250)}_releaseStream(){this.stream&&(this.stream.getTracks().forEach(e=>e.stop()),this.stream=null)}_startVAD(){this._stopVAD(),this.silenceSince=null,this.isSpeaking=!1,this.vadTimer=setInterval(()=>{if(!this.isActive||!this.analyser)return;this._getRmsDb()<this.cfg.silenceThresholdDb?this.isSpeaking&&(this.silenceSince===null?this.silenceSince=Date.now():Date.now()-this.silenceSince>=this.cfg.silenceHoldMs&&(this.isSpeaking=!1,this.silenceSince=null,this._finaliseUtterance(!0))):(this.silenceSince=null,this.isSpeaking||(this.isSpeaking=!0,this.mediaRecorder?.state==="recording"&&(this.recordingStartMs=Date.now())))},cH)}_stopVAD(){this.vadTimer!==null&&(clearInterval(this.vadTimer),this.vadTimer=null)}_cleanupAfterStop(e){const n=this.finishResolver;this.isActive=!1,this.finishResolver=null,this.mediaRecorder=null,this._teardownAudioContext(),this._releaseStream(),e&&(this.chunks=[]),this.isSpeaking=!1,this.silenceSince=null,this.onResult=null,this.onError=null,n?.()}_finaliseUtterance(e){this.isActive&&(this.mediaRecorder&&this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),e&&setTimeout(()=>{this.isActive&&this.stream&&this._startRecorder()},100))}_getRmsDb(){if(!this.analyser)return-1/0;const e=new Float32Array(this.analyser.fftSize);this.analyser.getFloatTimeDomainData(e);let n=0;for(const o of e)n+=o*o;const s=Math.sqrt(n/e.length);return s===0?-1/0:20*Math.log10(s)}async _transcribe(e){if(this.onResult){if(!this.transcriber&&!this.worker){this.onError?.("Model not loaded");return}try{const n=await this._decodeToFloat32(e);if(!n||n.length===0){this.onError?.(`Failed to decode audio (${e.size} bytes)`);return}const s=this._resolveLanguageHint(),o=this.worker?await this._transcribeViaWorker(n,s):await this._transcribeMainThread(n,s);o&&this.onResult(o,!0)}catch(n){if(!this.isActive)return;const s=n instanceof Error?n.message:"Local transcription failed";this.onError?.(s)}}}_transcribeViaWorker(e,n){return new Promise((s,o)=>{if(!this.worker)return o(new Error("Worker gone"));const r=i=>{const l=i.data;l.type==="result"?(this.worker.removeEventListener("message",r),s(l.transcript??"")):l.type==="log"?console.log("[WasmStt Worker]",l.text):l.type==="error"&&(this.worker.removeEventListener("message",r),o(new Error(l.error??"Transcription failed")))};this.worker.addEventListener("message",r),this.worker.postMessage({type:"transcribe",audio:e.buffer,language:n},[e.buffer]),setTimeout(()=>{this.worker?.removeEventListener("message",r),o(new Error("Transcription timed out"))},3e4)})}async _transcribeMainThread(e,n){const s=this.transcriber;return((await s(e,{task:"transcribe",...n?{language:n}:{}}))?.text??"").trim()}async _decodeToFloat32(e){if(!this.audioContext)return null;const n=await e.arrayBuffer();let s;try{s=await this.audioContext.decodeAudioData(n)}catch{return null}const o=s.sampleRate,r=s.getChannelData(0),i=uH;if(o===i)return new Float32Array(r);const l=o/i,c=Math.ceil(r.length/l),d=new Float32Array(c);for(let u=0;u<c;u++){const f=u*l,m=Math.floor(f),h=Math.min(m+1,r.length-1),p=f-m;d[u]=r[m]*(1-p)+r[h]*p}return d}_resolveLanguageHint(){if(this.lang&&this.lang!=="auto")return this.lang.split("-")[0]}_pickMimeType(){const e=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/ogg","audio/mp4"];return typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported?e.find(n=>MediaRecorder.isTypeSupported(n))??"":""}}const To=new fH,mH=3e4;let Ti=null,Oa=null;async function hH(){const t=Date.now();return Ti&&t-Ti.checkedAt<mH?Ti.available:Oa||(Oa=(async()=>{try{const e=await nt("/api/tts/status");if(!e.ok)return Ti={available:!1,checkedAt:Date.now()},!1;const s=!!(await e.json()).available;return Ti={available:s,checkedAt:Date.now()},s}catch{return Ti={available:!1,checkedAt:Date.now()},!1}finally{Oa=null}})(),Oa)}let ed=null;function d7(){return ed||(ed=new(window.AudioContext||window.webkitAudioContext)),ed}function _p(t={}){const e=t.enabled??!0,n=t.availabilityMode??"auto",[s,o]=ae.useState(!1),[r,i]=ae.useState(!1),[l,c]=ae.useState(null),d=ae.useRef(null),u=ae.useRef(null),f=Pe(k=>k.currentProviderId),m=Pe(k=>k.currentModelId),h=Pe(k=>k.openaiApiKey),p=Pe(k=>k.openaiCompatibleUrl),b=Pe(k=>k.openaiCompatibleApiKey),w=ae.useCallback(async()=>{if(!e)return i(!1),!1;const k=!!(h&&h.trim().length>0),C=!!(p&&p.trim().length>0);if(n==="openai-compatible")return i(C),C;if(k||n==="auto"&&C)return i(!0),!0;try{const S=await hH();return i(S),S}catch{return i(!1),!1}},[n,e,h,p]);ae.useEffect(()=>{w()},[w]);const v=ae.useCallback(()=>{if(d.current){try{d.current.stop()}catch{}d.current=null}u.current&&(u.current.abort(),u.current=null),o(!1)},[]),x=ae.useCallback(async()=>{try{const k=d7();k.state==="suspended"&&(await k.resume(),console.log("[useServerTTS] AudioContext resumed"));const C=k.createBuffer(1,1,22050),S=k.createBufferSource();S.buffer=C,S.connect(k.destination),S.start(0),console.log("[useServerTTS] Audio unlocked for mobile playback")}catch(k){console.error("[useServerTTS] Failed to unlock audio:",k)}},[]),y=ae.useCallback(async(k,C)=>{if(v(),!k.trim()){c("No text to speak"),C?.onError?.("No text to speak");return}c(null);try{const S=d7();S.state==="suspended"&&(await S.resume(),console.log("[useServerTTS] AudioContext resumed"));const M=S.createBuffer(1,1,22050),A=S.createBufferSource();A.buffer=M,A.connect(S.destination),A.start(0),u.current=new AbortController;const B=C?.voice||"nova";console.log("[useServerTTS] Speaking with voice:",B,"options:",C);const F=await nt("/api/tts/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:k.trim(),voice:B,model:C?.model||void 0,speed:C?.speed||.9,instructions:C?.instructions,summarize:!1,providerId:C?.providerId||f||void 0,modelId:C?.modelId||m||void 0,apiKey:C?.baseURL?b||void 0:h||void 0,baseURL:C?.baseURL||void 0}),signal:u.current.signal});if(!F.ok){const H=await F.json().catch(()=>({error:"Unknown error"}));throw new Error(H.error||`HTTP ${F.status}`)}const D=await(await F.blob()).arrayBuffer();console.log("[useServerTTS] Decoding audio data...");const E=await S.decodeAudioData(D),I=S.createBufferSource();I.buffer=E;const T=C?.pitch??1;T!==1&&(I.detune.value=(T-1)*1200);const j=C?.volume??1,V=S.createGain();V.gain.value=j,I.connect(V),V.connect(S.destination),d.current=I,I.onended=()=>{console.log("[useServerTTS] Audio playback ended"),o(!1),d.current=null,C?.onEnd?.()},console.log("[useServerTTS] Starting audio playback via Web Audio API..."),o(!0),C?.onStart?.(),I.start(0)}catch(S){if(S.name==="AbortError")return;const M=S instanceof Error?S.message:"Failed to speak";console.error("[useServerTTS] Error:",M),c(M),C?.onError?.(M),o(!1)}},[v,f,m,h,b]);return ae.useEffect(()=>()=>{v()},[v]),{isPlaying:s,isAvailable:r,error:l,speak:y,stop:v,checkAvailability:w,unlockAudio:x}}const pH=3e4;let ji=null,$a=null;async function gH(){const t=Date.now();return ji&&t-ji.checkedAt<pH?ji:$a||($a=(async()=>{try{const e=await nt("/api/tts/say/status");if(!e.ok){const o={available:!1,voices:[],checkedAt:Date.now()};return ji=o,o}const n=await e.json(),s={available:!!n.available,voices:Array.isArray(n.voices)?n.voices:[],checkedAt:Date.now()};return ji=s,s}catch{const e={available:!1,voices:[],checkedAt:Date.now()};return ji=e,e}finally{$a=null}})(),$a)}let td=null;function u7(){return td||(td=new(window.AudioContext||window.webkitAudioContext)),td}function Bp(t={}){const e=t.enabled??!0,[n,s]=ae.useState(!1),[o,r]=ae.useState(!1),[i,l]=ae.useState([]),[c,d]=ae.useState(null),u=ae.useRef(null),f=ae.useRef(null),m=ae.useCallback(async()=>{try{const w=u7();w.state==="suspended"&&(await w.resume(),console.log("[useSayTTS] AudioContext resumed"));const v=w.createBuffer(1,1,22050),x=w.createBufferSource();x.buffer=v,x.connect(w.destination),x.start(0),console.log("[useSayTTS] Audio unlocked for mobile playback")}catch(w){console.error("[useSayTTS] Failed to unlock audio:",w)}},[]),h=ae.useCallback(async()=>{if(!e)return r(!1),l([]),!1;try{const w=await gH();return r(w.available),l(w.voices),w.available}catch{return r(!1),l([]),!1}},[e]);ae.useEffect(()=>{h()},[h]);const p=ae.useCallback(()=>{if(u.current){try{u.current.stop()}catch{}u.current=null}f.current&&(f.current.abort(),f.current=null),s(!1)},[]),b=ae.useCallback(async(w,v)=>{if(p(),!w.trim()){d("No text to speak"),v?.onError?.("No text to speak");return}d(null);try{f.current=new AbortController;const x=await nt("/api/tts/say/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:w.trim(),voice:v?.voice||"Samantha",rate:v?.rate||200}),signal:f.current.signal});if(!x.ok){const A=await x.json().catch(()=>({error:"Unknown error"}));throw new Error(A.error||`HTTP ${x.status}`)}const y=await x.blob(),k=await y.arrayBuffer();console.log("[useSayTTS] Received audio:",y.size,"bytes");const C=u7();C.state==="suspended"&&(await C.resume(),console.log("[useSayTTS] AudioContext resumed before playback")),console.log("[useSayTTS] Decoding audio data...");const S=await C.decodeAudioData(k),M=C.createBufferSource();M.buffer=S,M.connect(C.destination),u.current=M,M.onended=()=>{console.log("[useSayTTS] Audio playback ended"),s(!1),u.current=null,v?.onEnd?.()},console.log("[useSayTTS] Starting audio playback via Web Audio API..."),s(!0),v?.onStart?.(),M.start(0)}catch(x){if(x.name==="AbortError")return;const y=x instanceof Error?x.message:"Failed to speak";console.error("[useSayTTS] Error:",y),d(y),v?.onError?.(y),s(!1)}},[p]);return ae.useEffect(()=>()=>{p()},[p]),{isPlaying:n,isAvailable:o,voices:i,error:c,speak:b,stop:p,checkAvailability:h,unlockAudio:m}}function Dp(t){return t?t.replace(/```[\s\S]*?```/g,"").replace(/`[^`]*`/g,"").replace(/[*_~#]/g,"").replace(/https?:\/\/[^\s]+/g,"").replace(/\/[\w\-./]+/g,"").replace(/^\s*[$#>]\s*/gm,"").replace(/[[\]{}()<>|&;]/g," ").replace(/\\/g,"").replace(/\s+/g," ").trim():""}const V2="browserVoiceLanguage",nd="browserVoiceConversationMode",sd="openchamber:voice-language-changed",od="openchamber:voice-conversation-mode-changed",R2=1200,bH=700,f7=new Set(["ru","ru-RU"]),Za=t=>{const e=(t||"").trim();if(!e)return"en-US";const n=e.split("-")[0].toLowerCase();return f7.has(e)||f7.has(n)?"en-US":e};function vH(){const[t,e]=ae.useState("idle"),[n,s]=ae.useState(null),[o,r]=ae.useState(()=>{if(typeof window<"u"){const ce=localStorage.getItem(V2);if(ce)return Za(ce)}return Za(navigator.language||"en-US")}),[i,l]=ae.useState(()=>typeof window<"u"?localStorage.getItem(nd)==="true":!1),c=ae.useMemo(()=>{if(typeof navigator>"u")return!1;const ce=navigator.userAgent.toLowerCase();return/iphone|ipad|ipod|android|mobile|webos|blackberry|iemobile|opera mini/i.test(ce)},[]),d=ae.useRef(!1),u=ae.useRef(!1),f=ae.useRef(""),m=ae.useRef(!1),h=ae.useRef(""),p=ae.useRef(null),b=ae.useRef(null),w=ae.useRef(0),v=ae.useRef(null),x=ae.useRef(!1),y=Ie(ce=>ce.currentSessionId),k=Ie(ce=>ce.sendMessage),C=zt(ce=>ce.setPendingInputText),S=Ie(ce=>ce.createSession),M=Pe(ce=>ce.currentProviderId),A=Pe(ce=>ce.currentModelId),B=Pe(ce=>ce.currentAgentName),F=Pe(ce=>ce.currentVariant),_=Pe(ce=>ce.voiceModeEnabled),D=Pe(ce=>ce.voiceProvider),E=Pe(ce=>ce.speechRate),I=Pe(ce=>ce.speechPitch),T=Pe(ce=>ce.speechVolume),j=Pe(ce=>ce.sayVoice),V=Pe(ce=>ce.browserVoice),H=Pe(ce=>ce.openaiVoice),N=Pe(ce=>ce.openaiCompatibleVoice),R=Pe(ce=>ce.openaiCompatibleUrl),$=Pe(ce=>ce.openaiCompatibleTtsModel),U=Pe(ce=>ce.sttApiKey),L=_&&(D==="openai"||D==="openai-compatible"),Z=_&&D==="say",Y=Pe(ce=>ce.sttProvider),fe=Pe(ce=>ce.sttServerUrl),Q=Pe(ce=>ce.sttModel),pe=Pe(ce=>ce.wasmSttModel),ne=Pe(ce=>ce.sttLanguage),re=Pe(ce=>ce.sttSilenceThresholdDb),se=Pe(ce=>ce.sttSilenceHoldMs),te=Y==="server"?mo.isSupported():Y==="wasm"?To.isSupported():ln.isSupported(),{speak:ke,stop:be,isAvailable:X,unlockAudio:ee}=_p({enabled:L,availabilityMode:D==="openai-compatible"?"openai-compatible":"openai"}),{speak:G,stop:O,isAvailable:ie,unlockAudio:oe}=Bp({enabled:Z}),Ce=ae.useRef(null);ae.useEffect(()=>{Ce.current!==null&&Ce.current!==y&&d.current&&(console.log("[useBrowserVoice] Session changed, stopping voice"),d.current=!1,u.current=!1,ln.stopListening(),mo.stopListening(),ln.cancelSpeech(),e("idle"),s(null)),Ce.current=y},[y]);const ue=ae.useCallback(ce=>{const Ae=Za(ce);r(Ae),typeof window<"u"&&(localStorage.setItem(V2,Ae),window.dispatchEvent(new CustomEvent(sd,{detail:Ae})))},[]);ae.useEffect(()=>{if(typeof window>"u")return;const ce=He=>{const Ee=Za(He.detail||localStorage.getItem(V2)||"en-US");r(Le=>Le===Ee?Le:Ee)},Ae=He=>{if(He.key!==V2||!He.newValue)return;const he=Za(He.newValue);r(Ee=>Ee===he?Ee:he)};return window.addEventListener(sd,ce),window.addEventListener("storage",Ae),()=>{window.removeEventListener(sd,ce),window.removeEventListener("storage",Ae)}},[]);const Me=ae.useCallback(()=>{l(ce=>{const Ae=!ce;return ln.setConversationMode(Ae),typeof window<"u"&&(localStorage.setItem(nd,String(Ae)),window.dispatchEvent(new CustomEvent(od,{detail:Ae}))),Ae})},[]);ae.useEffect(()=>{if(typeof window>"u")return;const ce=He=>{const Ee=He.detail;typeof Ee=="boolean"&&l(Le=>Le===Ee?Le:Ee)},Ae=He=>{if(He.key!==nd||He.newValue==null)return;const he=He.newValue==="true";l(Ee=>Ee===he?Ee:he)};return window.addEventListener(od,ce),window.addEventListener("storage",Ae),()=>{window.removeEventListener(od,ce),window.removeEventListener("storage",Ae)}},[]),ae.useEffect(()=>{ln.setConversationMode(i)},[i]);const ye=ae.useRef(null),K=ae.useRef(null),W=ae.useCallback(ce=>{Y==="server"?mo.startListening(ce,K.current,ye.current):Y==="wasm"?To.startListening(ce,K.current,ye.current):c?ln.startListeningSync(ce,K.current,ye.current):ln.startListening(ce,K.current,ye.current)},[Y,c]),le=ae.useCallback(ce=>{if(!d.current){console.log("[useBrowserVoice] Ignoring error after voice stopped:",ce);return}const Ae=ce.toLowerCase();if(Ae.includes("aborted")){console.log("[useBrowserVoice] Ignoring non-fatal aborted error"),s(null),e("listening");return}const He=typeof document<"u"&&document.visibilityState!=="visible",he=Ae.includes("permission")||Ae.includes("not allowed")||Ae.includes("service not allowed");if(He&&he&&i){console.log("[useBrowserVoice] Suppressing permission error while app hidden; will resume on visibility"),m.current=!0,s(null),e("idle");return}if(Ae.includes("network")||Ae.includes("connection")||Ae.includes("check connection")){console.error("[useBrowserVoice] Network error — staying in error state:",ce),s(ce),e("error"),w.current=0,v.current!==null&&(clearTimeout(v.current),v.current=null);return}if(console.error("[useBrowserVoice] Recognition error:",ce),s(ce),e("error"),he||x.current){w.current=0;return}const Le=w.current+1;w.current=Le;const Ve=3;if(Le<=Ve){const Ue=Math.min(1e3*Math.pow(2,Le-1),8e3);console.log(`[useBrowserVoice] Scheduling recovery retry ${Le}/${Ve} in ${Ue}ms`),v.current!==null&&clearTimeout(v.current),v.current=setTimeout(()=>{v.current=null,d.current&&(e("listening"),s(null),W(o))},Ue)}else console.log("[useBrowserVoice] Max recovery retries reached — staying in error state")},[o,i,W]);ae.useEffect(()=>{ye.current=le},[le]);const xe=ae.useCallback(async ce=>{if(!(!ce.trim()||!d.current)&&ce.trim()!==f.current){if(f.current=ce.trim(),!M||!A){s("No provider or model configured. Please configure them in settings."),e("error");return}if(ln.stopListening(),mo.stopListening(),!i){C(ce.trim(),"append-inline"),u.current=!1,d.current=!1,e("idle");return}e("processing"),u.current=!0;try{let Ae=y;if(!Ae){console.log("[useBrowserVoice] No active session, creating new session...");const he=await S();if(!he){s("Failed to create session"),e("error"),u.current=!1;return}Ae=he.id,console.log("[useBrowserVoice] Created new session:",Ae)}await k(ce.trim(),M,A,B??void 0,void 0,void 0,void 0,F??void 0);const He=async()=>{if(!d.current||!Ae)return;const Ee=us(Ae).filter(Le=>Le.role==="assistant").sort((Le,Ve)=>{const Ue=Le.time?.created??0;return(Ve.time?.created??0)-Ue});if(Ee.length>0){const Le=Ee[0],Ue=Es(Le.id).filter(qe=>qe.type==="text").map(qe=>qe.text??"").join(" ");if(Ue.trim()){e("speaking");try{const qe=Dp(Ue),Ge=()=>{if(d.current&&i){if(typeof document<"u"&&document.visibilityState!=="visible"){m.current=!0,e("idle");return}e("listening"),W(o)}else d.current=!1,e("idle")};if((D==="openai"||D==="openai-compatible")&&X){const vt=D==="openai-compatible"?N:H,St=D==="openai-compatible"?R:void 0,Pt=D==="openai-compatible"?$:void 0;console.log("[useBrowserVoice] Using server TTS with voice:",vt,"provider:",D),await ke(qe,{voice:vt,model:Pt,speed:E,pitch:I,volume:T,baseURL:St,onStart:()=>console.log("[useBrowserVoice] Server TTS started"),onEnd:()=>{console.log("[useBrowserVoice] Server TTS ended"),Ge()},onError:yt=>{console.error("[useBrowserVoice] Server TTS error:",yt),s(`Voice TTS failed: ${yt}. Please check your settings or switch to Browser voice.`),e("error"),Ge()}})}else if(D==="say"&&ie){console.log("[useBrowserVoice] Using macOS Say TTS with voice:",j);const vt=Math.round(100+(E-.5)*200);await G(qe,{voice:j,rate:vt,onStart:()=>console.log("[useBrowserVoice] Say TTS started"),onEnd:()=>{console.log("[useBrowserVoice] Say TTS ended"),Ge()},onError:St=>{console.error("[useBrowserVoice] Say TTS error:",St),Ge()}})}else console.log("[useBrowserVoice] Using browser TTS"),D==="openai"&&!X&&(console.warn("[useBrowserVoice] OpenAI voice selected but unavailable, falling back to browser voice"),s("OpenAI voice unavailable (API key not configured). Using browser voice instead.")),await ln.waitForVoices(),await ln.resumeAudioContext(),await ln.speakText(qe,o,()=>{Ge()},{rate:E,pitch:I,volume:T,voiceName:V||void 0})}catch(qe){const Ge=qe instanceof Error?qe.message:"Speech failed";if(!d.current){console.log("[useBrowserVoice] Ignoring speech error after voice stopped:",Ge);return}console.error("[useBrowserVoice] Speech error:",Ge),(Ge.includes("not-allowed")||Ge.includes("autoplay"))&&s("Audio blocked by browser. Please click the voice button again to enable audio."),i?(e("listening"),W(o)):(d.current=!1,e("idle"))}return}}setTimeout(He,500)};setTimeout(He,1e3)}catch(Ae){console.error("[useBrowserVoice] Send message error:",Ae),s(Ae instanceof Error?Ae.message:"Failed to send message"),e("error"),u.current=!1}}},[y,M,A,B,F,o,k,C,S,E,I,T,X,ke,ie,G,D,j,V,H,N,R,$,i,W]),Se=ae.useCallback(async(ce,Ae)=>{if(!d.current)return;const He=ce.trim();!Ae||!He||(console.log("[useBrowserVoice] Speech result:",He),h.current=He,p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{p.current=null;const he=h.current.trim();h.current="",he&&xe(he)},R2))},[xe]);ae.useEffect(()=>{if(typeof document>"u")return;const ce=()=>{if(document.visibilityState==="visible"&&m.current){if(!d.current||!i){m.current=!1;return}m.current=!1,e("listening");try{W(o)}catch(Ae){const He=Ae instanceof Error?Ae.message:"Failed to resume voice";s(He),e("error")}}};return document.addEventListener("visibilitychange",ce),()=>{document.removeEventListener("visibilitychange",ce)}},[i,c,o,Y,W]),ae.useEffect(()=>{if(typeof navigator>"u")return;const ce=navigator.mediaDevices;if(!ce||typeof ce.addEventListener!="function")return;const Ae=()=>{!d.current||t!=="listening"||(b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{if(b.current=null,!d.current||t!=="listening")return;if(typeof document<"u"&&document.visibilityState!=="visible"){m.current=!0,e("idle");return}try{ln.stopListening(),mo.stopListening(),To.stopListening(),W(o)}catch(he){const Ee=he instanceof Error?he.message:"Microphone source changed. Tap mic to continue.";s(Ee),e("error"),d.current=!1}},bH))};return ce.addEventListener("devicechange",Ae),()=>{ce.removeEventListener("devicechange",Ae),b.current&&(clearTimeout(b.current),b.current=null)}},[c,o,t,Y,W]),ae.useEffect(()=>{K.current=Se},[Se]);const we=ae.useCallback(async()=>{if(!te)return!1;if(Y==="server"||Y==="wasm")return!0;try{return await ln.prepareListening(),!0}catch(ce){const Ae=ce instanceof Error?ce.message:"Microphone permission denied";return s(Ae),!1}},[te,Y]),me=ae.useCallback(async()=>{if(!te){s("Voice input not supported in this browser"),e("error");return}if(!y){s("No active session"),e("error");return}if(d.current=!0,f.current="",w.current=0,x.current=!1,v.current!==null&&(clearTimeout(v.current),v.current=null),s(null),e("listening"),Y==="server"){mo.configure({baseURL:fe,model:Q,language:ne||void 0,silenceThresholdDb:re,silenceHoldMs:se,apiKey:U||void 0});try{await mo.startListening(o,Se,le)}catch(ce){const Ae=ce instanceof Error?ce.message:"Failed to start voice";console.error("[useBrowserVoice] Server STT start error:",Ae),s(Ae),e("error"),d.current=!1}return}if(Y==="wasm"){const ce=To.getModelStatus();if(console.log("[useBrowserVoice] WASM model status:",ce.state),ce.state!=="ready")try{e("processing"),await To.loadModel(pe)}catch(Ae){const He=Ae instanceof Error?Ae.message:"Failed to load Whisper model";console.error("[useBrowserVoice] WASM model load error:",He),s(He),e("error"),d.current=!1;return}To.configure({silenceThresholdDb:re,silenceHoldMs:se});try{await To.startListening(o,Se,le),console.log("[useBrowserVoice] WASM listening started")}catch(Ae){const He=Ae instanceof Error?Ae.message:"Failed to start voice";console.error("[useBrowserVoice] WASM STT start error:",He),s(He),e("error"),d.current=!1}return}if(c)try{ln.unlockAudio().catch(()=>{}),ee().catch(()=>{}),oe().catch(()=>{}),ln.startListeningSync(o,Se,le)}catch(ce){const Ae=ce instanceof Error?ce.message:"Failed to start voice";console.error("[useBrowserVoice] Mobile voice start error:",Ae),s(Ae),e("error"),d.current=!1}else try{await ln.startListening(o,Se,le)}catch(ce){const Ae=ce instanceof Error?ce.message:"Failed to start voice";console.error("[useBrowserVoice] Desktop voice start error:",Ae),s(Ae),e("error"),d.current=!1}},[te,y,o,Se,le,c,ee,oe,Y,fe,Q,U,pe,ne,re,se]),_e=ae.useCallback(()=>{d.current=!1,u.current=!1,m.current=!1,w.current=0,x.current=!1,b.current&&(clearTimeout(b.current),b.current=null),v.current!==null&&(clearTimeout(v.current),v.current=null),h.current="",p.current&&(clearTimeout(p.current),p.current=null),ln.stopListening(),mo.stopListening(),To.stopListening(),ln.cancelSpeech(),be(),O(),e("idle"),s(null)},[be,O]),ge=ae.useCallback(()=>{if(d.current){if(x.current=!0,m.current=!1,b.current&&(clearTimeout(b.current),b.current=null),e("processing"),Y==="server"){mo.finishListening().then(()=>{window.setTimeout(()=>{d.current&&(h.current||p.current||u.current||(d.current=!1,u.current=!1,e("idle")))},R2+200)});return}if(Y==="wasm"){To.finishListening().then(()=>{window.setTimeout(()=>{d.current&&(h.current||p.current||u.current||(d.current=!1,u.current=!1,e("idle"),x.current=!1))},R2+200)});return}ln.stopListening(),window.setTimeout(()=>{d.current&&(h.current||p.current||u.current||(d.current=!1,u.current=!1,e("idle")))},R2+300)}},[Y]);return ae.useEffect(()=>()=>{d.current=!1,b.current&&(clearTimeout(b.current),b.current=null),h.current="",p.current&&(clearTimeout(p.current),p.current=null),ln.setConversationMode(!1),ln.stopListening(),mo.stopListening(),ln.cancelSpeech()},[]),{status:t,isSupported:te,error:n,language:o,setLanguage:ue,startVoice:me,stopVoice:_e,finishVoiceInput:ge,conversationMode:i,toggleConversationMode:Me,prepareVoice:we,isMobile:c,voiceProvider:D}}const yH={sm:{icon:"w-4 h-4",container:"gap-1.5"},md:{icon:"w-5 h-5",container:"gap-2"},lg:{icon:"w-6 h-6",container:"gap-2.5"}},wH={idle:{icon:"mic-off",color:"text-muted-foreground",labelKey:"voice.status.idle"},listening:{icon:"mic",color:"text-primary",labelKey:"voice.status.listening",animation:"animate-pulse"},processing:{icon:"loader-4",color:"text-primary",labelKey:"voice.status.processing",animation:"animate-spin"},speaking:{icon:"volume-up",color:"text-green-500",labelKey:"voice.status.speaking"},error:{icon:"alert",color:"text-destructive",labelKey:"voice.status.error"}};function m7(t){const e=de.c(19),{status:n,showLabel:s,size:o,className:r,conversationMode:i}=t,l=s===void 0?!1:s,c=o===void 0?"md":o,d=r===void 0?"":r,u=i===void 0?!1:i,{t:f}=Ye(),m=wH[n],h=m.icon,p=yH[c],w=`flex items-center ${l?p.container:""} ${d}`,v=`
471
+ ${t.stack??""}`;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}function i7(t){const e=kp(t);return xj.some(n=>n.test(e))}function Cj(t){return`1.13.5:${kp(t).slice(0,500)}`}function kj(t){if(typeof window>"u")return;const e=Date.now(),n=Cj(t);let s=null;try{const r=window.sessionStorage.getItem(r7);if(r)try{s=JSON.parse(r)}catch{s=null}}catch{return}const o=typeof s?.timestamp=="number"?s.timestamp:0;if(!(s?.signature===n&&e-o<wj)){try{window.sessionStorage.setItem(r7,JSON.stringify({signature:n,timestamp:e}))}catch{return}window.setTimeout(()=>{window.location.reload()},0)}}async function Sj(t,e={}){const n=e.retries??1;let s;for(let o=0;o<=n;o+=1)try{return await t()}catch(r){if(s=r,!i7(r)||o>=n)break;await new Promise(i=>setTimeout(i,yj*(o+1)))}throw i7(s)&&kj(s),s}const n5=t=>ae.lazy(()=>Sj(t)),Mj=n5(()=>rn(()=>import("./MarkdownRendererImpl-BNr_9Jsb.js"),__vite__mapDeps([2,0,1,3,4])).then(t=>({default:t.MarkdownRenderer}))),Aj=n5(()=>rn(()=>import("./MarkdownRendererImpl-BNr_9Jsb.js"),__vite__mapDeps([2,0,1,3,4])).then(t=>({default:t.SimpleMarkdownRenderer}))),Sp=a.jsx("div",{className:"break-words w-full min-w-0"}),Mp=t=>{const e=de.c(2);let n;return e[0]!==t?(n=a.jsx(g.Suspense,{fallback:Sp,children:a.jsx(Mj,{...t})}),e[0]=t,e[1]=n):n=e[1],n},yi=t=>{const e=de.c(2);let n;return e[0]!==t?(n=a.jsx(g.Suspense,{fallback:Sp,children:a.jsx(Aj,{...t})}),e[0]=t,e[1]=n):n=e[1],n},zl=t=>{try{return new URL(t)}catch{return null}},UX=t=>{const e=zl(t.trim());return e?e.protocol==="http:"||e.protocol==="https:":!1},Fj=t=>{const e=zl(t.trim());return!e||e.protocol!=="http:"&&e.protocol!=="https:"?null:`https://icons.duckduckgo.com/ip3/${e.hostname.toLowerCase()}.ico`},_j=new Set(["localhost","127.0.0.1","0.0.0.0","::1"]),Bj=t=>{const e=zl(t.trim());return!e||e.protocol!=="http:"&&e.protocol!=="https:"?!1:_j.has(e.hostname.toLowerCase())},Dj=/\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::\d{2,5})?(?:\/[^\s<>"'`\u0000-\u001f]*)?/gi,a7=t=>{if(!t)return[];const e=t.match(Dj);if(!e||e.length===0)return[];const n=new Set,s=[];for(const o of e){const r=o.replace(/[),.;:!?'"`]+$/g,"");!r||!Bj(r)||n.has(r)||(n.add(r),s.push(r))}return s},l7=async t=>{if(typeof window>"u")return!1;const e=t.trim();if(!e)return!1;const n=zl(e);if(!n||n.protocol!=="http:"&&n.protocol!=="https:")return!1;const s=n.toString(),o=Ao();if(o?.runtime?.isVSCode&&o.vscode?.openExternalUrl)try{return await o.vscode.openExternalUrl(s),!0}catch{return!1}const r=window.__OPENCHAMBER_DESKTOP__;if(r?.openExternal)try{return await r.openExternal(s),!0}catch{}try{return window.open(s,"_blank","noopener,noreferrer"),!0}catch{return!1}},Pj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M26.9568%209.88184H22.1265L30.7753%2031.7848H35.4917L26.9568%209.88184ZM13.028%209.88184L4.4917%2031.7848H9.32203L11.2305%2027.1793H20.2166L22.0126%2031.6724H26.8444L18.0832%209.88184H13.028ZM12.5783%2023.1361L15.4987%2015.3853L18.5315%2023.1361H12.5783Z'%20fill='currentColor'/%3e%3c/svg%3e",Ej="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M37.9998%2023.021C33.7998%2025.2889%2029.5698%2027.3649%2024.8614%2028.3069C23.8114%2028.5154%2022.6474%2028.5154%2021.5809%2028.3714C20.5639%2028.2439%2020.0554%2027.3484%2020.4169%2026.4064C20.7619%2025.5289%2021.2209%2024.635%2021.8119%2023.9C23.0899%2022.3025%2024.5329%2020.849%2025.8289%2019.268C26.6203%2018.2991%2027.3335%2017.2689%2027.9618%2016.187C28.4208%2015.4205%2028.2078%2014.4935%2027.4038%2014.111C26.0584%2013.4556%2024.6154%2012.9936%2023.1889%2012.4986C23.0239%2012.4341%2022.7779%2012.6096%2022.4509%2012.7221C22.8604%2013.0881%2023.1559%2013.3596%2023.5654%2013.727C19.3339%2014.447%2015.3305%2015.467%2011.4455%2016.874C11.4275%2016.9535%2011.396%2017.0165%2011.411%2017.0495C11.9855%2017.927%2011.723%2018.5975%2010.886%2019.1405C10.5611%2019.3531%2010.2732%2019.6176%2010.034%2019.9235C12.593%2020.6735%2014.873%2020.243%2017.0539%2018.821C16.9234%2018.6305%2016.7914%2018.455%2016.6609%2018.263C17.4799%2018.407%2017.9719%2018.854%2018.0379%2019.556C18.0544%2019.7165%2017.9569%2019.8755%2017.9074%2020.036C17.7919%2019.907%2017.6449%2019.781%2017.5474%2019.6355C17.4799%2019.5395%2017.4634%2019.4285%2017.4154%2019.268C14.8235%2020.993%2012.035%2021.425%208.96751%2020.531C8.96751%2021.137%208.93451%2021.6485%208.98401%2022.1435C9.01701%2022.574%208.83701%2022.766%208.44401%2022.9895C7.55752%2023.5325%206.63803%2024.092%205.90003%2024.8105C5.01504%2025.6879%205.34354%2026.7589%206.54053%2027.2059C7.90102%2027.7159%209.329%2027.7309%2010.7555%2027.5569C12.4445%2027.3484%2014.1005%2027.0769%2015.9394%2026.8219C13.79%2027.8269%2011.6735%2028.5319%209.4445%2028.8169C7.88452%2029.0269%206.32753%2029.1379%204.78554%2028.6909C2.57156%2028.0684%201.58607%2026.4394%202.16057%2024.251C2.70206%2022.2065%204.01455%2020.5775%205.42454%2019.076C10.133%2014.078%2016.0864%2011.5401%2022.9744%2011.0286C24.5824%2010.9176%2026.2069%2011.1246%2027.7143%2011.7951C29.8308%2012.7536%2030.7173%2014.78%2029.6838%2016.826C29.0118%2018.1835%2028.0758%2019.4285%2027.1413%2020.6585C26.2234%2021.872%2025.1899%2022.9895%2024.2224%2024.155C23.9434%2024.506%2023.6809%2024.875%2023.4679%2025.2724C23.0569%2026.0224%2023.3359%2026.5174%2024.2059%2026.4394C26.0254%2026.2624%2027.8808%2026.1199%2029.6358%2025.6729C32.2098%2025.0174%2034.7193%2024.092%2037.2618%2023.2775C37.5243%2023.213%2037.7703%2023.117%2037.9998%2023.0225V23.021Z'%20fill='currentColor'/%3e%3c/svg%3e",Ij="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eCursor%3c/title%3e%3cg%20transform='translate(12%2012)%20scale(0.88)%20translate(-12%20-12)'%3e%3cpath%20d='M22.106%205.68L12.5.135a.998.998%200%2000-.998%200L1.893%205.68a.84.84%200%2000-.419.726v11.186c0%20.3.16.577.42.727l9.607%205.547a.999.999%200%2000.998%200l9.608-5.547a.84.84%200%2000.42-.727V6.407a.84.84%200%2000-.42-.726zm-.603%201.176L12.228%2022.92c-.063.108-.228.064-.228-.061V12.34a.59.59%200%2000-.295-.51l-9.11-5.26c-.107-.062-.063-.228.062-.228h18.55c.264%200%20.428.286.296.514z'%3e%3c/path%3e%3c/g%3e%3c/svg%3e",Tj="data:image/svg+xml,%3csvg%20fill='%23000000'%20viewBox='0%200%2033%2025'%20role='img'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M79.01%205.863c-4.066%200-6.511%202.92-6.511%206.535%200%203.635%202.445%206.555%206.511%206.555%204.046%200%206.512-2.92%206.512-6.555s-2.466-6.535-6.512-6.535Zm0%2010.968c-2.633%200-4.172-1.933-4.172-4.433s1.539-4.455%204.172-4.455c2.635%200%204.151%201.933%204.151%204.434%200%202.521-1.516%204.454-4.15%204.454Zm14.393%202.096c3.393%200%205.542-1.808%205.837-4.539h-2.36c-.316%201.555-1.517%202.437-3.477%202.437-2.423%200-3.878-1.68-3.878-4.433%200-2.774%201.476-4.434%203.878-4.434%201.96%200%203.14.862%203.477%202.5h2.36c-.295-2.773-2.444-4.622-5.837-4.622-3.856%200-6.217%202.669-6.217%206.535%200%203.887%202.36%206.556%206.217%206.556Zm-29.543-.311h2.36v-6.01c0-2.752%201.348-4.244%203.772-4.244h2.276V6.177h-2.255c-2.128%200-3.288.735-3.898%202.605l-.443-.063.527-2.542h-2.36v12.439h.02Zm-24.445-7.332c.106-2.101%201.517-3.53%203.793-3.53%202.276%200%203.646%201.345%203.646%203.53h-7.439Zm9.778.4c0-3.426-2.381-5.821-5.943-5.821-3.73%200-6.174%202.563-6.174%206.535%200%204.013%202.423%206.555%206.28%206.555%202.929%200%205.247-1.597%205.669-3.887h-2.36c-.507%201.156-1.666%201.828-3.31%201.828-2.38%200-3.877-1.408-3.94-3.803h9.694c.042-.588.084-.861.084-1.408Zm5.69%206.932h1.939l5.5-12.44h-2.529L56%2015.99l-.316.021-3.793-9.833h-2.508l5.5%2012.439ZM32.23%2012.35c0-.882-.359-1.701-.99-2.437a8.594%208.594%200%200%201-1.497%201.093c.337.42.527.861.527%201.345%200%202.731-5.837%204.811-14.14%204.811-8.281.021-14.118-2.059-14.118-4.811%200-.463.168-.925.505-1.345a8.13%208.13%200%200%201-1.475-1.093c-.632.736-.99%201.555-.99%202.438%200%204.034%207.207%206.534%2016.1%206.534%208.87.021%2016.078-2.5%2016.078-6.535Zm-3.351%201.534c-.906-.462-1.96-.861-3.16-1.197-1.37.378-2.909.672-4.553.861%202.318.294%204.341.778%205.9%201.408.76-.336%201.37-.693%201.813-1.072Zm-17.849-.357a31.902%2031.902%200%200%201-4.467-.84c-1.18.336-2.255.735-3.16%201.197.42.379%201.01.715%201.748%201.05%201.539-.63%203.52-1.113%205.88-1.407Zm21.2-6.808c0-4.013-7.207-6.534-16.079-6.534C7.26.185.051%202.706.051%206.719c0%204.035%207.208%206.535%2016.1%206.535%208.872.021%2016.079-2.5%2016.079-6.535Zm-1.94%200c0%202.732-5.836%204.812-14.139%204.812-8.302.021-14.14-2.06-14.14-4.812%200-2.731%205.838-4.811%2014.14-4.811%207.86%200%2014.14%202.08%2014.14%204.811Zm-3.223%202.564c.758-.336%201.37-.694%201.812-1.072-2.95-1.513-7.544-2.353-12.728-2.353s-9.799.84-12.728%202.353c.422.378%201.012.715%201.75%201.05%202.507-1.05%206.363-1.68%2010.978-1.68%204.404%200%208.324.651%2010.916%201.702ZM1.042%2015.628c-.632.736-.99%201.534-.99%202.438%200%204.034%207.207%206.534%2016.1%206.534%208.892%200%2016.099-2.521%2016.099-6.534%200-.883-.359-1.702-.99-2.438-.422.4-.907.757-1.497%201.093.337.42.527.861.527%201.345%200%202.731-5.837%204.811-14.14%204.811-8.302%200-14.14-2.08-14.14-4.811%200-.463.17-.925.506-1.345a10.73%2010.73%200%200%201-1.475-1.093Z'/%3e%3c/svg%3e",jj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M35.3993%2026.4544C34.2871%2028.3855%2027.8314%2032.9425%2020%2032.9425C12.1686%2032.9425%205.71288%2028.3855%204.60075%2026.4544C4.5427%2026.3532%204.50826%2026.2401%204.5%2026.1237V22.418C4.51199%2022.3209%204.53496%2022.2256%204.56846%2022.1338C5.04896%2020.9261%206.30833%2019.1733%207.93325%2018.7031C8.14896%2018.149%208.468%2017.3404%208.76508%2016.7437C8.71727%2016.2776%208.69485%2015.8094%208.69792%2015.3409C8.69792%2013.6217%209.06217%2012.113%2010.1601%2010.9906C10.6729%2010.4662%2011.3097%2010.0644%2012.064%209.76091C13.871%208.29357%2016.4453%207.05745%2019.9716%207.05745C23.4978%207.05745%2026.129%208.29357%2027.936%209.76091C28.6903%2010.0644%2029.3271%2010.4662%2029.8399%2010.9906C30.9378%2012.113%2031.3021%2013.6217%2031.3021%2015.3409C31.3021%2015.8162%2031.284%2016.2877%2031.2349%2016.7437C31.532%2017.3404%2031.851%2018.149%2032.0667%2018.7031C33.6917%2019.1733%2034.951%2020.9261%2035.4315%2022.1338C35.4677%2022.2248%2035.4908%2022.3205%2035.5%2022.418V26.1237C35.4917%2026.2401%2035.4573%2026.3532%2035.3993%2026.4544ZM20.2222%2018.7147H19.7778C19.6422%2018.945%2019.4889%2019.1644%2019.3193%2019.3709C18.3247%2020.5941%2016.8419%2021.2981%2014.7881%2021.2981C12.56%2021.2981%2010.9273%2020.8344%209.90304%2019.6719C9.86495%2019.6283%209.82833%2019.5835%209.79325%2019.5375L9.66667%2019.6719V28.1775C11.5202%2029.1837%2015.4972%2030.992%2020%2030.992C24.5028%2030.992%2028.4798%2029.1837%2030.3333%2028.1775V19.6719L30.2067%2019.5375C30.2067%2019.5375%2030.1641%2019.5957%2030.097%2019.6719C29.0727%2020.8344%2027.44%2021.2981%2025.2119%2021.2981C23.1581%2021.2981%2021.6753%2020.5941%2020.6807%2019.3709C20.5111%2019.1644%2020.3578%2018.945%2020.2222%2018.7147ZM23.2292%2022.9127C23.9383%2022.9127%2024.5208%2023.4952%2024.5208%2024.2043V26.7877C24.5208%2027.4968%2023.9383%2028.0793%2023.2292%2028.0793C22.52%2028.0793%2021.9375%2027.4968%2021.9375%2026.7877V24.2043C21.9375%2023.4952%2022.52%2022.9127%2023.2292%2022.9127ZM16.7708%2022.9127C17.48%2022.9127%2018.0625%2023.4952%2018.0625%2024.2043V26.7877C18.0625%2027.4968%2017.48%2028.0793%2016.7708%2028.0793C16.0617%2028.0793%2015.4792%2027.4968%2015.4792%2026.7877V24.2043C15.4792%2023.4952%2016.0617%2022.9127%2016.7708%2022.9127ZM21.0501%2014.9237C21.2258%2016.289%2021.5707%2017.3947%2022.1842%2018.149C22.7551%2018.8517%2023.649%2019.3606%2025.2119%2019.3606C27.2437%2019.3606%2028.1724%2018.9253%2028.6438%2018.3905C29.1398%2017.8287%2029.3646%2016.9051%2029.3646%2015.3409C29.3646%2013.8684%2029.0507%2012.9552%2028.454%2012.3455C27.8378%2011.7152%2026.7502%2011.2321%2024.8063%2011.0216C22.8856%2010.8136%2021.975%2011.1998%2021.5345%2011.7049C21.187%2012.1014%2020.97%2012.7485%2020.9688%2013.7431V13.7702C20.9688%2014.1121%2020.9959%2014.4966%2021.0501%2014.9237ZM18.9499%2014.9237C19.0041%2014.4966%2019.0312%2014.1117%2019.0312%2013.7689V13.7431C19.03%2012.7485%2018.813%2012.1014%2018.4655%2011.7049C18.025%2011.1998%2017.1144%2010.8136%2015.1937%2011.0216C13.2498%2011.2321%2012.1622%2011.7152%2011.546%2012.3455C10.9493%2012.9552%2010.6354%2013.8684%2010.6354%2015.3409C10.6354%2016.9051%2010.8615%2017.8287%2011.3562%2018.3905C11.8276%2018.9253%2012.7563%2019.3606%2014.7881%2019.3606C16.351%2019.3606%2017.2449%2018.8517%2017.8158%2018.149C18.4293%2017.3947%2018.7742%2016.289%2018.9499%2014.9237Z'%20fill='currentColor'/%3e%3c/svg%3e",Hj="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='utf-8'?%3e%3c!--%20Uploaded%20to:%20SVG%20Repo,%20www.svgrepo.com,%20Generator:%20SVG%20Repo%20Mixer%20Tools%20--%3e%3csvg%20fill='%23000000'%20width='800px'%20height='800px'%20viewBox='0%200%2024%2024'%20role='img'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.702%202.29c-2.494-1.554-5.778-1.187-8.706.654C9.076%201.104%205.79.736%203.3%202.29c-3.941%202.463-4.42%208.806-1.07%2014.167%202.47%203.954%206.333%206.269%209.77%206.226%203.439.043%207.301-2.273%209.771-6.226%203.347-5.361%202.872-11.704-1.069-14.167zM4.042%2015.328a12.838%2012.838%200%200%201-1.546-3.541%2010.12%2010.12%200%200%201-.336-3.338c.15-1.98.956-3.524%202.27-4.345%201.315-.822%203.052-.87%204.903-.137.281.113.556.24.825.382A15.11%2015.11%200%200%200%207.5%207.54c-2.035%203.255-2.655%206.878-1.945%209.765a13.247%2013.247%200%200%201-1.514-1.98zm17.465-3.541a12.866%2012.866%200%200%201-1.547%203.54%2013.25%2013.25%200%200%201-1.513%201.984c.635-2.589.203-5.76-1.353-8.734a.39.39%200%200%200-.563-.153l-4.852%203.032a.397.397%200%200%200-.126.546l.712%201.139a.395.395%200%200%200%20.547.126l3.145-1.965c.101.306.203.606.28.916.296%201.086.41%202.214.335%203.337-.15%201.982-.956%203.525-2.27%204.347a4.437%204.437%200%200%201-2.25.65h-.101a4.432%204.432%200%200%201-2.25-.65c-1.314-.822-2.121-2.365-2.27-4.347a10.153%2010.153%200%200%201%20.335-3.337%2013.212%2013.212%200%200%201%204.05-6.482%2010.148%2010.148%200%200%201%202.849-1.765c1.845-.733%203.586-.685%204.9.137%201.316.822%202.122%202.365%202.271%204.345a10.146%2010.146%200%200%201-.33%203.334z'/%3e%3c/svg%3e",Lj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M37%2020.034C27.8809%2020.5837%2020.5808%2027.8809%2020.0326%2037H19.966C19.4163%2027.8809%2012.1177%2020.5837%203%2020.034V19.9674C12.1191%2019.4163%2019.4163%2012.1191%2019.966%203H20.0326C20.5822%2012.1191%2027.8809%2019.4163%2037%2019.9674V20.034Z'%20fill='currentColor'/%3e%3c/svg%3e",Nj="/assets/kimi-for-coding-eVEHug_h.svg",Vj="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eLM%20Studio%3c/title%3e%3cpath%20d='M2.84%202a1.273%201.273%200%20100%202.547h14.107a1.273%201.273%200%20100-2.547H2.84zM7.935%205.33a1.273%201.273%200%20000%202.548H22.04a1.274%201.274%200%20000-2.547H7.935zM3.624%209.935c0-.704.57-1.274%201.274-1.274h14.106a1.274%201.274%200%20010%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM1.273%2012.188a1.273%201.273%200%20100%202.547H15.38a1.274%201.274%200%20000-2.547H1.273zM3.624%2016.792c0-.704.57-1.274%201.274-1.274h14.106a1.273%201.273%200%20110%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM13.029%2018.849a1.273%201.273%200%20100%202.547h9.698a1.273%201.273%200%20100-2.547h-9.698z'%20fill-opacity='.3'%3e%3c/path%3e%3cpath%20d='M2.84%202a1.273%201.273%200%20100%202.547h10.287a1.274%201.274%200%20000-2.547H2.84zM7.935%205.33a1.273%201.273%200%20000%202.548H18.22a1.274%201.274%200%20000-2.547H7.935zM3.624%209.935c0-.704.57-1.274%201.274-1.274h10.286a1.273%201.273%200%20010%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM1.273%2012.188a1.273%201.273%200%20100%202.547H11.56a1.274%201.274%200%20000-2.547H1.273zM3.624%2016.792c0-.704.57-1.274%201.274-1.274h10.286a1.273%201.273%200%20110%202.547H4.898c-.703%200-1.274-.57-1.274-1.273zM13.029%2018.849a1.273%201.273%200%20100%202.547h5.78a1.273%201.273%200%20100-2.547h-5.78z'%3e%3c/path%3e%3c/svg%3e",Rj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M17.8758%209.20865C17.8758%208.59461%2017.3777%208.09634%2016.7663%208.09634C16.155%208.09634%2015.6567%208.59575%2015.6567%209.20865V27.6446C15.6567%2029.0714%2014.4985%2030.2324%2013.0755%2030.2324C11.6523%2030.2324%2010.4941%2029.0714%2010.4941%2027.6446V15.8167C10.4941%2015.2027%209.99591%2014.7044%209.38453%2014.7044C8.77316%2014.7044%208.275%2015.2038%208.275%2015.8167V20.8301C8.275%2022.2567%207.11678%2023.4179%205.69364%2023.4179C4.2705%2023.4179%203.1123%2022.2567%203.1123%2020.8301V19.0129C3.1123%2018.6054%203.44177%2018.2752%203.84822%2018.2752C4.25467%2018.2752%204.58413%2018.6054%204.58413%2019.0129V20.8301C4.58413%2021.4441%205.08227%2021.9424%205.69364%2021.9424C6.30502%2021.9424%206.80317%2021.443%206.80317%2020.8301V15.8167C6.80317%2014.39%207.96139%2013.2289%209.38453%2013.2289C10.8077%2013.2289%2011.9659%2014.39%2011.9659%2015.8167V27.6446C11.9659%2028.2587%2012.4641%2028.7569%2013.0755%2028.7569C13.6868%2028.7569%2014.1849%2028.2575%2014.1849%2027.6446V20.4123V9.20865C14.1849%207.78194%2015.3431%206.62082%2016.7663%206.62082C18.1894%206.62082%2019.3476%207.78194%2019.3476%209.20865V24.4746C19.3476%2024.8821%2019.0182%2025.2123%2018.6117%2025.2123C18.2053%2025.2123%2017.8758%2024.8821%2017.8758%2024.4746V9.20865ZM31.531%2013.2289C30.1079%2013.2289%2028.9496%2014.39%2028.9496%2015.8167V25.6969C28.9496%2026.311%2028.4515%2026.8093%2027.8401%2026.8093C27.2287%2026.8093%2026.7306%2026.3099%2026.7306%2025.6969V9.20865C26.7306%207.78194%2025.5723%206.62082%2024.1492%206.62082C22.7261%206.62082%2021.5679%207.78194%2021.5679%209.20865V30.1383C21.5679%2030.7523%2021.0697%2031.2506%2020.4583%2031.2506C19.8469%2031.2506%2019.3488%2030.7511%2019.3488%2030.1383V27.5471C19.3488%2027.1396%2019.0194%2026.8093%2018.6129%2026.8093C18.2065%2026.8093%2017.877%2027.1396%2017.877%2027.5471V30.1383C17.877%2031.565%2019.0352%2032.7261%2020.4583%2032.7261C21.8815%2032.7261%2023.0397%2031.565%2023.0397%2030.1383V9.20865C23.0397%208.59461%2023.5378%208.09634%2024.1492%208.09634C24.7605%208.09634%2025.2587%208.59575%2025.2587%209.20865V25.6969C25.2587%2027.1237%2026.417%2028.2848%2027.8401%2028.2848C29.2632%2028.2848%2030.4215%2027.1237%2030.4215%2025.6969V15.8167C30.4215%2015.2027%2030.9196%2014.7044%2031.531%2014.7044C32.1424%2014.7044%2032.6405%2015.2038%2032.6405%2015.8167V24.4746C32.6405%2024.8821%2032.97%2025.2123%2033.3764%2025.2123C33.7829%2025.2123%2034.1123%2024.8821%2034.1123%2024.4746V15.8167C34.1123%2014.39%2032.9541%2013.2289%2031.531%2013.2289Z'%20fill='currentColor'/%3e%3c/svg%3e",zj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M17.8758%209.20865C17.8758%208.59461%2017.3777%208.09634%2016.7663%208.09634C16.155%208.09634%2015.6567%208.59575%2015.6567%209.20865V27.6446C15.6567%2029.0714%2014.4985%2030.2324%2013.0755%2030.2324C11.6523%2030.2324%2010.4941%2029.0714%2010.4941%2027.6446V15.8167C10.4941%2015.2027%209.99591%2014.7044%209.38453%2014.7044C8.77316%2014.7044%208.275%2015.2038%208.275%2015.8167V20.8301C8.275%2022.2567%207.11678%2023.4179%205.69364%2023.4179C4.2705%2023.4179%203.1123%2022.2567%203.1123%2020.8301V19.0129C3.1123%2018.6054%203.44177%2018.2752%203.84822%2018.2752C4.25467%2018.2752%204.58413%2018.6054%204.58413%2019.0129V20.8301C4.58413%2021.4441%205.08227%2021.9424%205.69364%2021.9424C6.30502%2021.9424%206.80317%2021.443%206.80317%2020.8301V15.8167C6.80317%2014.39%207.96139%2013.2289%209.38453%2013.2289C10.8077%2013.2289%2011.9659%2014.39%2011.9659%2015.8167V27.6446C11.9659%2028.2587%2012.4641%2028.7569%2013.0755%2028.7569C13.6868%2028.7569%2014.1849%2028.2575%2014.1849%2027.6446V20.4123V9.20865C14.1849%207.78194%2015.3431%206.62082%2016.7663%206.62082C18.1894%206.62082%2019.3476%207.78194%2019.3476%209.20865V24.4746C19.3476%2024.8821%2019.0182%2025.2123%2018.6117%2025.2123C18.2053%2025.2123%2017.8758%2024.8821%2017.8758%2024.4746V9.20865ZM31.531%2013.2289C30.1079%2013.2289%2028.9496%2014.39%2028.9496%2015.8167V25.6969C28.9496%2026.311%2028.4515%2026.8093%2027.8401%2026.8093C27.2287%2026.8093%2026.7306%2026.3099%2026.7306%2025.6969V9.20865C26.7306%207.78194%2025.5723%206.62082%2024.1492%206.62082C22.7261%206.62082%2021.5679%207.78194%2021.5679%209.20865V30.1383C21.5679%2030.7523%2021.0697%2031.2506%2020.4583%2031.2506C19.8469%2031.2506%2019.3488%2030.7511%2019.3488%2030.1383V27.5471C19.3488%2027.1396%2019.0194%2026.8093%2018.6129%2026.8093C18.2065%2026.8093%2017.877%2027.1396%2017.877%2027.5471V30.1383C17.877%2031.565%2019.0352%2032.7261%2020.4583%2032.7261C21.8815%2032.7261%2023.0397%2031.565%2023.0397%2030.1383V9.20865C23.0397%208.59461%2023.5378%208.09634%2024.1492%208.09634C24.7605%208.09634%2025.2587%208.59575%2025.2587%209.20865V25.6969C25.2587%2027.1237%2026.417%2028.2848%2027.8401%2028.2848C29.2632%2028.2848%2030.4215%2027.1237%2030.4215%2025.6969V15.8167C30.4215%2015.2027%2030.9196%2014.7044%2031.531%2014.7044C32.1424%2014.7044%2032.6405%2015.2038%2032.6405%2015.8167V24.4746C32.6405%2024.8821%2032.97%2025.2123%2033.3764%2025.2123C33.7829%2025.2123%2034.1123%2024.8821%2034.1123%2024.4746V15.8167C34.1123%2014.39%2032.9541%2013.2289%2031.531%2013.2289Z'%20fill='currentColor'/%3e%3c/svg%3e",Oj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M26.7,5.25l2.14-1.53,10.49,13.29-16.23,19.43-2.65,3L0.42,16.83l6.87-8.64,5.78,2.21,1.79-4.46L23.3,0.1l3.42,5.15ZM31.13,13.98L22.91,1.78l-7.1,4.95-5.45,13.53,20.77-6.28ZM36.74,15.57l-8.03-10.1-0.14-0.1-1.14,0.89,5.03,7.58,4.28,1.73ZM9.06,20.35l3.53-8.84-4.89-1.92-5.62,7.1,6.98,3.66ZM37.62,17.19l-5.3-2.14-9.22,19.52,14.52-17.38ZM30.95,15.24l-20.63,6.22,10.1,15.93,10.53-22.15ZM15.79,32.41l-6.86-10.82c-1.61-0.84-3.2-1.73-4.81-2.57-0.1-0.05-0.21-0.12-0.32-0.13l11.99,13.52Z'%20fill='currentColor'/%3e%3c/svg%3e",$j="data:image/svg+xml,%3csvg%20fill='currentColor'%20fill-rule='evenodd'%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eOllama%3c/title%3e%3cpath%20d='M7.905%201.09c.216.085.411.225.588.41.295.306.544.744.734%201.263.191.522.315%201.1.362%201.68a5.054%205.054%200%20012.049-.636l.051-.004c.87-.07%201.73.087%202.48.474.101.053.2.11.297.17.05-.569.172-1.134.36-1.644.19-.52.439-.957.733-1.264a1.67%201.67%200%2001.589-.41c.257-.1.53-.118.796-.042.401.114.745.368%201.016.737.248.337.434.769.561%201.287.23.934.27%202.163.115%203.645l.053.04.026.019c.757.576%201.284%201.397%201.563%202.35.435%201.487.216%203.155-.534%204.088l-.018.021.002.003c.417.762.67%201.567.724%202.4l.002.03c.064%201.065-.2%202.137-.814%203.19l-.007.01.01.024c.472%201.157.62%202.322.438%203.486l-.006.039a.651.651%200%2001-.747.536.648.648%200%2001-.54-.742c.167-1.033.01-2.069-.48-3.123a.643.643%200%2001.04-.617l.004-.006c.604-.924.854-1.83.8-2.72-.046-.779-.325-1.544-.8-2.273a.644.644%200%2001.18-.886l.009-.006c.243-.159.467-.565.58-1.12a4.229%204.229%200%2000-.095-1.974c-.205-.7-.58-1.284-1.105-1.683-.595-.454-1.383-.673-2.38-.61a.653.653%200%2001-.632-.371c-.314-.665-.772-1.141-1.343-1.436a3.288%203.288%200%2000-1.772-.332c-1.245.099-2.343.801-2.67%201.686a.652.652%200%2001-.61.425c-1.067.002-1.893.252-2.497.703-.522.39-.878.935-1.066%201.588a4.07%204.07%200%2000-.068%201.886c.112.558.331%201.02.582%201.269l.008.007c.212.207.257.53.109.785-.36.622-.629%201.549-.673%202.44-.05%201.018.186%201.902.719%202.536l.016.019a.643.643%200%2001.095.69c-.576%201.236-.753%202.252-.562%203.052a.652.652%200%2001-1.269.298c-.243-1.018-.078-2.184.473-3.498l.014-.035-.008-.012a4.339%204.339%200%2001-.598-1.309l-.005-.019a5.764%205.764%200%2001-.177-1.785c.044-.91.278-1.842.622-2.59l.012-.026-.002-.002c-.293-.418-.51-.953-.63-1.545l-.005-.024a5.352%205.352%200%2001.093-2.49c.262-.915.777-1.701%201.536-2.269.06-.045.123-.09.186-.132-.159-1.493-.119-2.73.112-3.67.127-.518.314-.95.562-1.287.27-.368.614-.622%201.015-.737.266-.076.54-.059.797.042zm4.116%209.09c.936%200%201.8.313%202.446.855.63.527%201.005%201.235%201.005%201.94%200%20.888-.406%201.58-1.133%202.022-.62.375-1.451.557-2.403.557-1.009%200-1.871-.259-2.493-.734-.617-.47-.963-1.13-.963-1.845%200-.707.398-1.417%201.056-1.946.668-.537%201.55-.849%202.485-.849zm0%20.896a3.07%203.07%200%2000-1.916.65c-.461.37-.722.835-.722%201.25%200%20.428.21.829.61%201.134.455.347%201.124.548%201.943.548.799%200%201.473-.147%201.932-.426.463-.28.7-.686.7-1.257%200-.423-.246-.89-.683-1.256-.484-.405-1.14-.643-1.864-.643zm.662%201.21l.004.004c.12.151.095.37-.056.49l-.292.23v.446a.375.375%200%2001-.376.373.375.375%200%2001-.376-.373v-.46l-.271-.218a.347.347%200%2001-.052-.49.353.353%200%2001.494-.051l.215.172.22-.174a.353.353%200%2001.49.051zm-5.04-1.919c.478%200%20.867.39.867.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zm8.706%200c.48%200%20.868.39.868.871a.87.87%200%2001-.868.871.87.87%200%2001-.867-.87.87.87%200%2001.867-.872zM7.44%202.3l-.003.002a.659.659%200%2000-.285.238l-.005.006c-.138.189-.258.467-.348.832-.17.692-.216%201.631-.124%202.782.43-.128.899-.208%201.404-.237l.01-.001.019-.034c.046-.082.095-.161.148-.239.123-.771.022-1.692-.253-2.444-.134-.364-.297-.65-.453-.813a.628.628%200%2000-.107-.09L7.44%202.3zm9.174.04l-.002.001a.628.628%200%2000-.107.09c-.156.163-.32.45-.453.814-.29.794-.387%201.776-.23%202.572l.058.097.008.014h.03a5.184%205.184%200%20011.466.212c.086-1.124.038-2.043-.128-2.722-.09-.365-.21-.643-.349-.832l-.004-.006a.659.659%200%2000-.285-.239h-.004z'%3e%3c/path%3e%3c/svg%3e",Zj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M32.8377%2017.282C33.2127%2016.25%2033.3072%2015.218%2033.2127%2014.1875C33.1197%2013.1571%2032.7447%2012.1251%2032.2752%2011.1876C31.4322%209.78209%2030.2127%208.6571%2028.8072%208.0001C27.3072%207.34461%2025.7127%207.15711%2024.1197%207.53211C23.3698%206.78212%2022.5253%206.12512%2021.5878%205.65713C20.6503%205.18913%2019.5253%205.00013%2018.4948%205.00013C16.8851%204.99074%2015.3125%205.48246%2013.9948%206.40712C12.6824%207.34311%2011.7449%208.6571%2011.2754%2010.1571C10.1504%2010.4376%209.21289%2010.9071%208.27539%2011.4696C7.4324%2012.1251%206.77541%2012.9696%206.21291%2013.8126C5.36992%2015.2195%205.08792%2016.8125%205.27542%2018.407C5.46399%2019.9968%206.11605%2021.496%207.1504%2022.718C6.79608%2023.7086%206.66795%2024.7659%206.77541%2025.8124C6.86991%2026.8444%207.2449%2027.8749%207.7129%2028.8124C8.55739%2030.2194%209.77538%2031.3444%2011.1824%2031.9999C12.6824%2032.6569%2014.2753%2032.8444%2015.8698%2032.4694C16.6198%2033.2194%2017.4628%2033.8749%2018.4003%2034.3444C19.3378%2034.8139%2020.4628%2034.9999%2021.4948%2034.9999C23.1043%2035.0097%2024.6769%2034.5185%2025.9947%2033.5944C27.3072%2032.6569%2028.2447%2031.3444%2028.7127%2029.8444C29.7719%2029.6432%2030.7682%2029.1934%2031.6197%2028.5319C32.4627%2027.8749%2033.2127%2027.1249%2033.6822%2026.1874C34.5251%2024.7819%2034.8071%2023.1875%2034.6196%2021.5945C34.4322%2020%2033.8697%2018.5015%2032.8377%2017.282ZM21.5878%2033.0304C20.0878%2033.0304%2018.9628%2032.5609%2017.9323%2031.7179C17.9323%2031.7179%2018.0253%2031.6234%2018.1198%2031.6234L24.1197%2028.1554C24.2862%2028.0803%2024.4196%2027.9469%2024.4947%2027.7804C24.5698%2027.636%2024.6021%2027.4731%2024.5877%2027.3109V18.875L27.1197%2020.375V27.3124C27.1455%2028.0547%2027.0215%2028.7945%2026.755%2029.4878C26.4885%2030.181%2026.085%2030.8134%2025.5687%2031.3473C25.0523%2031.8811%2024.4337%2032.3054%2023.7497%2032.5949C23.0658%2032.8843%2022.3305%2033.0314%2021.5878%2033.0304ZM9.49488%2027.8749C8.83789%2026.7499%208.55739%2025.4374%208.83789%2024.125C8.83789%2024.125%208.93239%2024.2195%209.02539%2024.2195L15.0253%2027.6874C15.1693%2027.7638%2015.3325%2027.7966%2015.4948%2027.7819C15.6823%2027.7819%2015.8698%2027.7819%2015.9628%2027.6874L23.2753%2023.4695V26.3749L17.1823%2029.9374C16.5506%2030.3042%2015.8527%2030.5427%2015.1287%2030.6393C14.4046%2030.7358%2013.6686%2030.6884%2012.9629%2030.4999C11.4629%2030.1249%2010.2449%2029.1874%209.49488%2027.8749ZM7.9004%2014.8445C8.56239%2013.7234%209.58826%2012.8627%2010.8074%2012.4056V19.532C10.8074%2019.718%2010.8074%2019.907%2010.9004%2020C10.9755%2020.1665%2011.1089%2020.2998%2011.2754%2020.375L18.5878%2024.5944L16.0573%2026.0944L10.0574%2022.625C9.41842%2022.2639%208.85742%2021.7797%208.40684%2021.2004C7.95627%2020.6211%207.62506%2019.9582%207.4324%2019.25C7.05741%2017.8445%207.1504%2016.157%207.9004%2014.8445ZM28.6197%2019.625L21.3073%2015.407L23.8377%2013.9071L29.8377%2017.375C30.7752%2017.9375%2031.5252%2018.6875%2031.9947%2019.625C32.4642%2020.5625%2032.7447%2021.5945%2032.6502%2022.7195C32.5603%2023.7755%2032.1699%2024.7837%2031.5252%2025.6249C30.8697%2026.4694%2030.0252%2027.1249%2028.9947%2027.4999V20.375C28.9947%2020.1875%2028.9947%2020%2028.9002%2019.907C28.9002%2019.907%2028.8072%2019.718%2028.6197%2019.625ZM31.1502%2015.875C31.1502%2015.875%2031.0572%2015.782%2030.9627%2015.782L24.9627%2012.3126C24.7752%2012.2196%2024.6822%2012.2196%2024.4947%2012.2196C24.3072%2012.2196%2024.1197%2012.2196%2024.0252%2012.3126L16.7128%2016.532V13.6251L22.8073%2010.0626C23.7448%209.50009%2024.7752%209.31259%2025.9002%209.31259C26.9322%209.31259%2027.9627%209.68759%2028.9002%2010.3446C29.7447%2011.0001%2030.4947%2011.8446%2030.8697%2012.7821C31.2447%2013.7196%2031.3377%2014.8445%2031.1502%2015.875ZM15.4003%2021.125L12.8699%2019.625V12.5946C12.8699%2011.5626%2013.1503%2010.4376%2013.7128%209.59459C14.2753%208.6571%2015.1198%208.0001%2016.0573%207.53211C17.0127%207.05249%2018.0956%206.88812%2019.1503%207.06261C20.1823%207.15711%2021.2128%207.62511%2022.0573%208.2821C22.0573%208.2821%2021.9628%208.3751%2021.8698%208.3751L15.8698%2011.8446C15.7033%2011.9197%2015.57%2012.0531%2015.4948%2012.2196C15.4003%2012.4071%2015.4003%2012.5001%2015.4003%2012.6876V21.125ZM16.7128%2018.125L19.9948%2016.25L23.2753%2018.125V21.875L19.9948%2023.75L16.7128%2021.875V18.125Z'%20fill='currentColor'/%3e%3c/svg%3e",qj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M3.10913%2012.07C3.65512%2012.07%205.76627%2011.5988%206.85825%2010.98C7.95023%2010.3612%207.95023%2010.3612%2010.207%208.75965C13.0642%206.73196%2015.0845%207.41088%2018.3968%207.41088'%20fill='currentColor'/%3e%3cpath%20d='M3.10913%2012.07C3.65512%2012.07%205.76627%2011.5988%206.85825%2010.98C7.95023%2010.3612%207.95023%2010.3612%2010.207%208.75965C13.0642%206.73196%2015.0845%207.41088%2018.3968%207.41088'%20stroke='currentColor'%20stroke-width='3.27593'/%3e%3cpath%20d='M21.6%207.43108L16.0037%2010.6622V4.20001L21.6%207.43108Z'%20fill='currentColor'%20stroke='currentColor'%20stroke-width='0.0363992'/%3e%3cpath%20d='M3%2012.072C3.54599%2012.072%205.65714%2012.5432%206.74912%2013.162C7.8411%2013.7808%207.8411%2013.7808%2010.0978%2015.3823C12.9551%2017.41%2014.9753%2016.7311%2018.2877%2016.7311'%20fill='currentColor'/%3e%3cpath%20d='M3%2012.072C3.54599%2012.072%205.65714%2012.5432%206.74912%2013.162C7.8411%2013.7808%207.8411%2013.7808%2010.0978%2015.3823C12.9551%2017.41%2014.9753%2016.7311%2018.2877%2016.7311'%20stroke='currentColor'%20stroke-width='3.27593'/%3e%3cpath%20d='M21.4909%2016.7109L15.8945%2013.4798V19.942L21.4909%2016.7109Z'%20fill='currentColor'%20stroke='currentColor'%20stroke-width='0.0363992'/%3e%3c/svg%3e",Uj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3cimage%20width='24'%20height='24'%20xlink:href='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAF0AAABcCAYAAAAMLblmAAAACXBIWXMAAAAAAAAAAQCEeRdzAAAHhklEQVR4nO1d21HjSBRtjJhvMhgtxlX8DRsBJgIggjERwESAiWAgAjwRYCJAGwHMH1U8VhvBst+89hxzRRkwuG+rJet1qlwSM1KrdXR1+nb37as5UzCEYbi4sLAQPj4+rs7NzX17enpaxI/7i8khs6xfWuA+1oNZV4IkB0Gwit0NEN1FpVaxHf0fyB5t8W8zrKF/zIT0hGiQuoc/uR1ZcdXI/Qi5kk6yW63WDsjdTYiuI3IhfXl5uQuSd7C7mcf1io5MSYdlh/Pz83sgvJfldcqGTEgflxH8WVsZ+QjeSRcpOTIld+2yhFfSl5aWfoLwXZ9lVhFeSKd2Q06O6WP7KG8CbvlD+TEeavz2P/HvIbfsRJkSyFlq0kVOjo3HmwWJEcr8jd0IvdPzi4uL2Pbcsc7WqMOFcrq+6uULqUiHnOzgpg58VESI/vXw8DCM4/jWtRw5N5LfqG7tdpuuKn/fPVQ1NZxJB+F7IKqf8vqUjMP7+/uDNERPw/X19RCbId6CPlzYLvbZEw6zut40OJHugfBcyH4LXCvGZsAfrL9nZkS+mnQPhA+h0z80Op0FYP0DWP4Q+r8rY0C5QUU6NTwF4THO3b66uoocz/cOecv6IH8A2Tk1OVm9Nenipbg2modoIPt5SokGIjt/4B77eVi9Fen0w6WXqQW1ex/W7cXDyRqoZ7/T6QwfHx/pAodZXceKdMdXL0aHaevy8vJcXasZgvWFja1nKTdTSWfD6XDxGI3l+qwbS1dQbkh8Vr3sT0kXHe8ryyw14QnGiD/1TfynpDvoeCUIT8CGH8Rv+ZaaD0l3kJVbanhVCE+QWDyIPzOexpcmkk5vReuP00spW6NpCxIPqd3Cm3/qo7yJpHOKTVnOYVncQlewU9dutw+xu5O2rHek08qx6SnKiNGlrsXEBe8TsruWtmF9R7rWytlwpqlA2QB+ttF5OktTxivSHax8ULWGcxrYbqWVmVekK62c7uG+64XLDI4jgStOiDh5M2/lxToYCLr2q25WnoD+O7yZQ9fBsRfSZVDf9snFQRAMXC5YFXACBtZOiVFb+7ila+YPo7paeYI01j4inTPo2HRtT6qrlr+Fq7WPSJfJWitw1r7uVp6A1g5ZPjHKKINEXjZsT2CYhOYCVQeMcABO9KSzh5WsepgGSEukr1p1IcMDnIa0lpiAei7haFOB41TRVjWCSmICWYZidTDeiL9ca1VlgJdzjcRQXjSDN5G6RjWAhARaHx/g4ND24FarFTvUqfKQ8RhrXQ/wlL7aPqWqTlL4gIRxW6lGYLvKjY1oumpVGxLabUe6sZwHhbQUMjqrQLDmh6TbWvp/ztWpASAvt7YybU068K9zjeoBlaU38ABYeUN6kdGQ7glMjaLRdNVgTYMPYT/gZSxJT9ZqNpgMTVaPwNbV0QwX1BGanj0tPTZ2PanQvUq1QGh7IIcB/rE9eGVlJWzG0yfDdtyFCGSgxurgh4eHrnleh9lgDJ1O5yXvmA0oL9YDWcwg51KpqkPLS3B/f38+Pz9vdTDeiDWnWlUcUIsN1SSGhBHExqIh4AQ251SLuh50VtBm2kh6pJxYtYpCDYKgZyS7RIOXxXD6YCOj0HVcgDEyDekCbcwLMSKdOVag67Yr6bqNxDzDIZ5/hBHpouuRsYxnZOYIbPrai1UNmnDEcbyMMqKRPLFtEJjYEg8511wtBUW6+HS4jgNZiWHTKCzW3dolnj90OfeFdJEYBodaeTF1tnbRcucUJa8mMSAxQ8mJawNmGeWFf7hevKwQRQhdz39FukSgRsayQWVaV/ipJ0XKVpQ1XD2WcbybruNyc00Pi0kbUI8/6yIzkpwhFd6RrrV2IKyLzDjmvnmHiRPTWmunzOBBnV9fX1d2lYZj7puJmEi6Y/KBg06n87uKQaYpcphNxIchGA6rgheZcGxlZaUySXYIDnnklmRH/PZt7B4rygvv7u5Oq0K8JN/3nkDt02Aj5qiVDpNmJK0SxCeE5544jYDM7OL14oxRqCi31MRnnQ9+KumUGTSQW9BrvmaawXoSf0aJkqzOpYB8PCXTFLBWsYyypoZ+uLYF50M6hn/bv7m5KfzSdtwjZZQTNJmGGVoHkDILM3zV0CUBAZOwgfjNL1++FDKbneg37yuXtFiqqF3mogXxxpH4VcjN30WzevmKwE+TYwSbOlQ6DfEErV7Govf59riU4QPSw+Q9dPO+tlN8elrizbNVHYF8nr/PfAN5yY5Y9s4sP1DivCjAA/FEiN8RZIdkDLB/koWnQ6s2z1+C6ZkCxOKnWolB4jnQZfxoYo8/lMf9SPIQRIxA0wwbj39yByR/w3azaF+ETL38hZaJGz337Nt25fXfY8gfl4Dzo1KMpTfPod1vwaUnoSxcsF6GMit4WXOUw+cNFqf1Dsv0AVmvC71E56Pmg4Gfw/vqOpkvze2jHmVEZksaafXyKZu+Kcjny4qCTNeRitb35PNlfdOQP0Iui3cnkK8dKq4Ucl0xnZDPffYM4XF8F9ewUH501pjZMvXky4ncl3EQPoQ1zSq1sqIQuQHE44mSv6Xbviodnq9GOj/m+Y0o/VvxPy8IndI+RM9sAAAAAElFTkSuQmCC'/%3e%3c/svg%3e",Wj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.1312%207.50002L17.4088%2011.1913H5.81625L8.5375%207.50002H20.1325H20.1312ZM34.0675%2028.81L31.3475%2032.5H19.795L22.5125%2028.81H34.0675ZM35%207.50002L16.58%2032.5H5L23.42%207.50002H35Z'%20fill='currentColor'/%3e%3c/svg%3e",Gj="data:image/svg+xml,%3csvg%20width='24'%20height='24'%20viewBox='0%200%2040%2040'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.1312%207.5L17.4088%2011.1912H5.81625L8.5375%207.5H20.1325H20.1312ZM34.0675%2028.81L31.3475%2032.5H19.795L22.5125%2028.81H34.0675ZM35%207.5L16.58%2032.5H5L23.42%207.5H35Z'%20fill='currentColor'/%3e%3c/svg%3e",Kj=Object.assign({"../assets/provider-logos/anthropic.svg":Pj,"../assets/provider-logos/bailian-coding-plan.svg":Ej,"../assets/provider-logos/cursor.svg":Ij,"../assets/provider-logos/evroc.svg":Tj,"../assets/provider-logos/github-copilot.svg":jj,"../assets/provider-logos/gocode.svg":Hj,"../assets/provider-logos/google.svg":Lj,"../assets/provider-logos/kimi-for-coding.svg":Nj,"../assets/provider-logos/lmstudio.svg":Vj,"../assets/provider-logos/minimax-cn-coding-plan.svg":Rj,"../assets/provider-logos/minimax-coding-plan.svg":zj,"../assets/provider-logos/nano-gpt.svg":Oj,"../assets/provider-logos/ollama.svg":$j,"../assets/provider-logos/openai.svg":Zj,"../assets/provider-logos/openrouter.svg":qj,"../assets/provider-logos/wafer.ai.svg":Uj,"../assets/provider-logos/zai-coding-plan.svg":Wj,"../assets/provider-logos/zhipuai-coding-plan.svg":Gj}),O1=new Map,Xc=new Set,c7=new Map([["codex","openai"],["chatgpt","openai"],["claude","anthropic"],["gemini","google"],["evroc-ai","evroc"],["evrocai","evroc"],["ollama-cloud","ollama"],["wafer-ai","wafer.ai"],["wafer","wafer.ai"]]),Yj=t=>(t??"").toLowerCase().trim().replace(/^models\./,"").replace(/^provider\./,"").replace(/\s+/g,"-"),Ap=t=>{const e=Yj(t);if(!e)return[];const n=e.replace(/[^a-z0-9_\-./:]/g,""),s=n.split(/[/:]/)[0]||n,o=[c7.get(n),c7.get(s),n,s].filter(r=>!!(r&&r.length>0));return[...new Set(o)]},Jj=t=>{const e=Ap(t),n=e.find(r=>O1.has(r))??null,s=n?O1.get(n)??null:null;if(s)return s;const o=e[0]??null;return o?`https://models.dev/logos/${o}.svg`:null},Qj=t=>{if(typeof Image>"u")return;const e=Jj(t);if(!e||Xc.has(e))return;Xc.add(e);const n=new Image;n.decoding="async",n.onerror=()=>{Xc.delete(e)},n.src=e,n.decode?.().catch(()=>{})},WX=t=>{for(const e of t)Qj(e)};for(const[t,e]of Object.entries(Kj)){const n=t.match(/provider-logos\/([^/]+)\.svg$/i);n?.[1]&&e&&O1.set(n[1].toLowerCase(),e)}function Fp(t){const e=de.c(23);let n,s,o,r;if(e[0]!==t){const p=Ap(t);s=p.find(Xj)??null,o=p[0]??null,n=!!s,r=s?O1.get(s)??null:null,e[0]=t,e[1]=n,e[2]=s,e[3]=o,e[4]=r}else n=e[1],s=e[2],o=e[3],r=e[4];const i=r,[l,c]=ae.useState(n?"local":"remote");let d;e[5]!==n?(d=()=>{c(n?"local":"remote")},e[5]=n,e[6]=d):d=e[6];let u;e[7]!==n||e[8]!==s||e[9]!==o?(u=[n,s,o],e[7]=n,e[8]=s,e[9]=o,e[10]=u):u=e[10],ae.useEffect(d,u);let f;e[11]!==n?(f=()=>{c(p=>p==="local"&&n?"remote":"none")},e[11]=n,e[12]=f):f=e[12];const m=f;if(!s&&!o){let p;return e[13]!==m?(p={src:null,onError:m,hasLogo:!1},e[13]=m,e[14]=p):p=e[14],p}if(l==="local"&&i){let p;return e[15]!==m||e[16]!==i?(p={src:i,onError:m,hasLogo:!0},e[15]=m,e[16]=i,e[17]=p):p=e[17],p}if(l==="remote"&&o){const p=`https://models.dev/logos/${o}.svg`;let b;return e[18]!==m||e[19]!==p?(b={src:p,onError:m,hasLogo:!0},e[18]=m,e[19]=p,e[20]=b):b=e[20],b}let h;return e[21]!==m?(h={src:null,onError:m,hasLogo:!1},e[21]=m,e[22]=h):h=e[22],h}function Xj(t){return O1.has(t)}const Ar=t=>{const e=de.c(10),{providerId:n,alt:s,className:o,onError:r}=t,{src:i,onError:l,hasLogo:c}=Fp(n);let d;e[0]!==r||e[1]!==l?(d=()=>{l(),r?.()},e[0]=r,e[1]=l,e[2]=d):d=e[2];const u=d;if(!c||!i)return null;const f=s||`${n} logo`;let m;e[3]!==o?(m=z("dark:invert object-contain",o),e[3]=o,e[4]=m):m=e[4];let h;return e[5]!==u||e[6]!==i||e[7]!==f||e[8]!==m?(h=a.jsx("img",{src:i,alt:f,className:m,loading:"eager",decoding:"async",fetchPriority:"high",draggable:!1,onError:u}),e[5]=u,e[6]=i,e[7]=f,e[8]=m,e[9]=h):h=e[9],h};function eH(t){const e=de.c(4),{onResizeStart:n,ariaLabel:s}=t;let o;e[0]===Symbol.for("react.memo_cache_sentinel")?(o=a.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:a.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})}),e[0]=o):o=e[0];let r;return e[1]!==s||e[2]!==n?(r=a.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":s,onPointerDown:n,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:o}),e[1]=s,e[2]=n,e[3]=r):r=e[3],r}const s5=ae.forwardRef((t,e)=>{const n=de.c(60);let s,o,r,i,l,c,d,u,f,m,h,p,b;n[0]!==t?({className:s,outerClassName:d,scrollbarClassName:m,fillContainer:p,useScrollShadow:b,scrollShadowSize:f,hasError:l,resizedHeight:o,onResizeHeightChange:c,disabled:r,simple:h,endSlot:i,...u}=t,n[0]=t,n[1]=s,n[2]=o,n[3]=r,n[4]=i,n[5]=l,n[6]=c,n[7]=d,n[8]=u,n[9]=f,n[10]=m,n[11]=h,n[12]=p,n[13]=b):(s=n[1],o=n[2],r=n[3],i=n[4],l=n[5],c=n[6],d=n[7],u=n[8],f=n[9],m=n[10],h=n[11],p=n[12],b=n[13]);const w=p===void 0?!1:p,v=b===void 0?!1:b,{t:x}=Ye(),y=ae.useRef(null),k=ae.useRef(null),[C,S]=ae.useState(null),M=o??C;let A;n[14]!==c?(A=$=>{const U=y.current;if(!U)return;k.current={startY:$.clientY,startHeight:U.getBoundingClientRect().height};const L=$.currentTarget;L.setPointerCapture($.pointerId);const Z=fe=>{const Q=k.current;if(!Q)return;const pe=Q.startHeight+(fe.clientY-Q.startY),ne=Math.max(82,pe);c?c(ne):S(ne)},Y=()=>{k.current=null,L.removeEventListener("pointermove",Z),L.removeEventListener("pointerup",Y),L.removeEventListener("pointercancel",Y)};L.addEventListener("pointermove",Z),L.addEventListener("pointerup",Y),L.addEventListener("pointercancel",Y),$.preventDefault()},n[14]=c,n[15]=A):A=n[15];const B=A;let F;n[16]===Symbol.for("react.memo_cache_sentinel")?(F=$=>{if($.target.closest('textarea, button, [role="separator"]'))return;const L=y.current?.querySelector("textarea");L&&document.activeElement!==L&&($.preventDefault(),L.focus())},n[16]=F):F=n[16];const _=F;if(h){const $=e,U=w?"[field-sizing:fixed]":"field-sizing-content";let L;n[17]!==s||n[18]!==U?(L=z("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",U,s),n[17]=s,n[18]=U,n[19]=L):L=n[19];let Z;return n[20]!==r||n[21]!==w||n[22]!==d||n[23]!==u||n[24]!==f||n[25]!==m||n[26]!==$||n[27]!==L||n[28]!==v?(Z=a.jsx(Zn,{as:"textarea",ref:$,disableHorizontal:!0,fillContainer:w,useScrollShadow:v,scrollShadowSize:f,outerClassName:d,scrollbarClassName:m,className:L,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:r,...u}),n[20]=r,n[21]=w,n[22]=d,n[23]=u,n[24]=f,n[25]=m,n[26]=$,n[27]=L,n[28]=v,n[29]=Z):Z=n[29],Z}let D;n[30]!==M?(D=M!==null?{height:`${M}px`}:void 0,n[30]=M,n[31]=D):D=n[31];let E;if(n[32]!==l||n[33]!==d){let $;n[35]!==l?($=l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],n[35]=l,n[36]=$):$=n[36],E=z("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],$,d),n[32]=l,n[33]=d,n[34]=E}else E=n[34];let I;n[37]!==s||n[38]!==r?(I=z("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!r&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],r&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",s),n[37]=s,n[38]=r,n[39]=I):I=n[39];let T;n[40]!==r||n[41]!==u||n[42]!==e||n[43]!==I?(T=a.jsx("textarea",{ref:e,className:I,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:r,...u}),n[40]=r,n[41]=u,n[42]=e,n[43]=I,n[44]=T):T=n[44];let j;n[45]!==x?(j=x("textarea.resizeHandleAria"),n[45]=x,n[46]=j):j=n[46];let V;n[47]!==B||n[48]!==j?(V=a.jsx(eH,{onResizeStart:B,ariaLabel:j}),n[47]=B,n[48]=j,n[49]=V):V=n[49];let H;n[50]!==i||n[51]!==V?(H=a.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[i,V]}),n[50]=i,n[51]=V,n[52]=H):H=n[52];let N;n[53]!==H||n[54]!==T?(N=a.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[T,H]}),n[53]=H,n[54]=T,n[55]=N):N=n[55];let R;return n[56]!==N||n[57]!==D||n[58]!==E?(R=a.jsx("div",{ref:y,onPointerDown:_,style:D,className:E,children:N}),n[56]=N,n[57]=D,n[58]=E,n[59]=R):R=n[59],R});s5.displayName="Textarea";function tH(){const t=de.c(11),e=Ie(nH),n=V_(e??""),s=Z3(e??""),o=ae.useRef(0);let r,i;t[0]!==e||t[1]!==n?(r=()=>{!e||!n||n.length},i=[e,n],t[0]=e,t[1]=n,t[2]=r,t[3]=i):(r=t[2],i=t[3]),ae.useEffect(r,i);let l,c;t[4]!==e||t[5]!==s?(l=()=>{!e||!s||s.length},c=[e,s],t[4]=e,t[5]=s,t[6]=l,t[7]=c):(l=t[6],c=t[7]),ae.useEffect(l,c);let d;t[8]===Symbol.for("react.memo_cache_sentinel")?(d=()=>{o.current=0},t[8]=d):d=t[8];let u;t[9]!==e?(u=[e],t[9]=e,t[10]=u):u=t[10],ae.useEffect(d,u)}function nH(t){return t.currentSessionId}const sH=g.memo(function(){return tH(),null});function GX(t){const e=de.c(5),{children:n}=t,s=Pe(oH);let o;e[0]!==s?(o=s?a.jsx(sH,{}):null,e[0]=s,e[1]=o):o=e[1];let r;return e[2]!==n||e[3]!==o?(r=a.jsxs(a.Fragment,{children:[o,n]}),e[2]=n,e[3]=o,e[4]=r):r=e[4],r}function oH(t){return t.voiceModeEnabled}class rH{recognition=null;isListening=!1;currentLang="en-US";onResultCallback=null;onErrorCallback=null;restartOnEnd=!1;conversationMode=!1;isSpeaking=!1;audioContext=null;audioUnlockRequired=!1;isSupported(){const e="SpeechRecognition"in window||"webkitSpeechRecognition"in window,n="speechSynthesis"in window;return e&&n}getSupportDetails(){return{recognition:"SpeechRecognition"in window||"webkitSpeechRecognition"in window,synthesis:"speechSynthesis"in window,prefixed:!("SpeechRecognition"in window)&&"webkitSpeechRecognition"in window,secureContext:window.isSecureContext}}setConversationMode(e){this.conversationMode=e,e||(this.restartOnEnd=!1)}isConversationMode(){return this.conversationMode}pauseListening(){if(this.restartOnEnd=!1,this.recognition)try{this.recognition.stop()}catch{}this.isListening=!1}resumeListening(){if(console.log("[BrowserVoiceService] resumeListening called:",{conversationMode:this.conversationMode,hasCallback:!!this.onResultCallback,isSpeaking:this.isSpeaking,currentLang:this.currentLang}),this.conversationMode&&this.onResultCallback&&!this.isSpeaking)try{console.log("[BrowserVoiceService] Resuming listening..."),this.startListeningSync(this.currentLang,this.onResultCallback,this.onErrorCallback||void 0)}catch(e){console.error("[BrowserVoiceService] Failed to resume listening:",e)}else console.log("[BrowserVoiceService] Not resuming - conditions not met")}async checkMicrophonePermission(){try{return"permissions"in navigator?(await navigator.permissions.query({name:"microphone"})).state==="granted":!1}catch{return!1}}async prepareListening(){if(!this.isSupported())throw new Error("Web Speech API not supported in this browser");if(typeof navigator>"u"||typeof navigator.mediaDevices?.getUserMedia!="function")return!0;try{return(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(n=>n.stop()),!0}catch(e){const n=typeof e=="object"&&e&&"name"in e?String(e.name):"";if(n==="NotAllowedError")throw new Error("Microphone permission denied");if(n==="NotFoundError")throw new Error("No microphone found");const s=e instanceof Error?e.message:"Unable to access microphone";throw new Error(s)}}startListeningSync(e,n,s){if(!this.isSupported()){const r="Web Speech API not supported in this browser";throw s?.(r),new Error(r)}this.stopListening();const o=window.SpeechRecognition||window.webkitSpeechRecognition;this.recognition=new o,this.currentLang=e,this.onResultCallback=n,this.onErrorCallback=s||null,this.recognition.continuous=!0,this.recognition.interimResults=!0,this.recognition.lang=e,this.recognition.onstart=()=>{console.log("[BrowserVoiceService] Recognition started"),this.isListening=!0,this.restartOnEnd=!0},this.recognition.onaudiostart=()=>{console.log("[BrowserVoiceService] Audio recording started")},this.recognition.onsoundstart=()=>{console.log("[BrowserVoiceService] Sound detected")},this.recognition.onresult=r=>{console.log("[BrowserVoiceService] Got result:",r.results.length,"results");let i="",l="";for(let c=r.resultIndex;c<r.results.length;c++){const d=r.results[c];d.isFinal?i+=d[0].transcript:l+=d[0].transcript}console.log("[BrowserVoiceService] Transcripts - interim:",l,"final:",i),l&&(console.log("[BrowserVoiceService] Calling onResultCallback with interim"),this.onResultCallback?.(l,!1)),i&&(console.log("[BrowserVoiceService] Calling onResultCallback with final"),this.onResultCallback?.(i,!0))},this.recognition.onerror=r=>{if(r.error==="aborted")return;const i=this.getErrorMessage(r.error);this.onErrorCallback?.(i),(r.error==="not-allowed"||r.error==="service-not-allowed"||r.error==="network")&&(this.restartOnEnd=!1,this.isListening=!1)},this.recognition.onend=()=>{if(this.isListening=!1,this.restartOnEnd&&this.recognition&&!this.isSpeaking)try{this.recognition.start()}catch{}};try{this.recognition.start()}catch(r){const i=r instanceof Error?r.message:"Failed to start speech recognition";throw s?.(i),new Error(i)}}async startListening(e,n,s){this.startListeningSync(e,n,s)}stopListening(){if(this.restartOnEnd=!1,this.recognition){try{this.recognition.stop()}catch{}this.recognition=null}this.isListening=!1}getIsListening(){return this.isListening}getCurrentLang(){return this.currentLang}async resumeAudioContext(){this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioContext.state==="suspended"&&await this.audioContext.resume()}isAudioUnlockRequired(){return this.audioUnlockRequired}async unlockAudio(){try{const e=new Audio;if(e.src="data:audio/wav;base64,UklGRigAAABXQVZFZm10IBIAAAABAAEARKwAAIhYAQACABAAAABkYXRhAgAAAAEA",e.volume=.01,await e.play(),await this.resumeAudioContext(),this.isMobileDevice()&&"speechSynthesis"in window){const n=new SpeechSynthesisUtterance("");n.volume=0,window.speechSynthesis.speak(n),window.speechSynthesis.cancel(),console.log("[BrowserVoiceService] Speech synthesis unlocked for mobile")}return this.audioUnlockRequired=!1,console.log("[BrowserVoiceService] Audio unlocked successfully"),!0}catch(e){return console.error("[BrowserVoiceService] Failed to unlock audio:",e),!1}}async speakText(e,n,s,o){if(!("speechSynthesis"in window))throw new Error("Speech synthesis not supported");await this.resumeAudioContext();const r=await this.waitForVoices();await new Promise(c=>setTimeout(c,50)),this.isSpeaking=!0,this.pauseListening(),window.speechSynthesis.cancel();const i=new SpeechSynthesisUtterance(e);i.lang=n,i.rate=o?.rate??1,i.pitch=o?.pitch??1,i.volume=o?.volume??1;let l=null;return o?.voiceName&&(l=r.find(c=>c.name===o.voiceName)||null,l?console.log(`[BrowserVoiceService] Using selected voice: ${l.name} (${l.lang})`):console.warn(`[BrowserVoiceService] Selected voice "${o.voiceName}" not found, falling back to language match`)),l||(l=this.findBestVoice(r,n),l?console.log(`[BrowserVoiceService] Using language-matched voice: ${l.name} (${l.lang})`):console.warn(`[BrowserVoiceService] No voice found for language: ${n}, using default`)),l&&(i.voice=l),console.log(`[BrowserVoiceService] Speaking text (${e.length} chars) in ${n}`),new Promise((c,d)=>{let u=!1;i.onstart=()=>{u=!0,console.log("[BrowserVoiceService] Speech started"),c()},i.onend=()=>{this.isSpeaking=!1,console.log("[BrowserVoiceService] Speech ended"),s?.()},i.onerror=f=>{this.isSpeaking=!1,console.error("[BrowserVoiceService] Speech synthesis error:",f.error),(f.error==="not-allowed"||f.error==="interrupted")&&(this.audioUnlockRequired=!0);let m=`Speech synthesis error: ${f.error||"unknown"}`;f.error==="not-allowed"?m="Audio blocked by browser autoplay policy. Please interact with the page first.":f.error==="interrupted"&&(m="Speech was interrupted. Please try again."),d(new Error(m))},setTimeout(()=>{u||(console.warn("[BrowserVoiceService] Speech start timeout - audio may be blocked"),this.audioUnlockRequired=!0)},2e3),window.speechSynthesis.speak(i)})}cancelSpeech(){"speechSynthesis"in window&&window.speechSynthesis.cancel()}getVoices(){return"speechSynthesis"in window?window.speechSynthesis.getVoices():[]}async waitForVoices(){if(!("speechSynthesis"in window))return[];const e=window.speechSynthesis.getVoices();return e.length>0?e:new Promise(n=>{const s=()=>{n(window.speechSynthesis.getVoices()),window.speechSynthesis.onvoiceschanged=null};window.speechSynthesis.onvoiceschanged=s,setTimeout(()=>{n(window.speechSynthesis.getVoices()),window.speechSynthesis.onvoiceschanged=null},1e3)})}findBestVoice(e,n){let s=e.find(o=>o.lang===n);if(!s){const o=n.split("-")[0];s=e.find(r=>r.lang.startsWith(o))}return s||(s=e.find(o=>o.lang.startsWith(n.split("-")[0])&&o.localService)),s||null}isMobileDevice(){if(typeof navigator>"u")return!1;const e=navigator.userAgent.toLowerCase();return/iphone|ipad|ipod|android|mobile|webos|blackberry|iemobile|opera mini/i.test(e)}isIOSSafari(){if(typeof navigator>"u")return!1;const e=navigator.userAgent.toLowerCase(),n=/iphone|ipad|ipod/i.test(e),s=/safari/i.test(e)&&!/chrome|crios|crmo/i.test(e);return n&&s}getErrorMessage(e){const n=this.isMobileDevice(),s=this.isIOSSafari();return{"no-speech":"No speech detected",aborted:"Speech recognition aborted","audio-capture":"No microphone found",network:"Network error - check connection","not-allowed":n?"Microphone permission denied. Check Settings > Safari > Microphone":"Microphone permission denied","service-not-allowed":s?"Speech recognition requires a user gesture. Please tap the microphone button again.":"Speech recognition service not allowed","bad-grammar":"Grammar error","language-not-supported":"Language not supported"}[e]||`Speech recognition error: ${e}`}}const ln=new rH,iH=80,aH=300;class lH{stream=null;mediaRecorder=null;audioContext=null;analyser=null;vadTimer=null;chunks=[];recordingStartMs=0;isActive=!1;isSpeaking=!1;silenceSince=null;onResult=null;onError=null;finishResolver=null;lang="en";cfg={baseURL:"",model:"deepdml/faster-whisper-large-v3-turbo-ct2",language:"",silenceThresholdDb:-45,silenceHoldMs:1500,apiKey:""};configure(e){this.cfg={silenceThresholdDb:-45,silenceHoldMs:1500,language:"",apiKey:"",...e},this.cfg.apiKey=e.apiKey??""}isSupported(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof window.MediaRecorder<"u"&&typeof window.AudioContext<"u"}async startListening(e,n,s){this.isActive&&this.stopListening(),this.lang=e,this.onResult=n,this.onError=s??null,this.isActive=!0;try{this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(o){this.isActive=!1;const r=o instanceof Error?o.message:"Microphone access denied";s?.(r);return}this._setupAudioContext(),this._startRecorder(),this._startVAD()}stopListening(){this._stopVAD(),this._stopRecorder(),this._cleanupAfterStop(!0)}async finishListening(){if(this.isActive){if(this._stopVAD(),this.isSpeaking=!1,this.silenceSince=null,!this.mediaRecorder||this.mediaRecorder.state==="inactive"){this._cleanupAfterStop(!0);return}await new Promise(e=>{this.finishResolver=e,this._finaliseUtterance(!1)}),this._cleanupAfterStop(!0)}}getIsListening(){return this.isActive}_setupAudioContext(){if(!this.stream)return;const e=window.AudioContext??window.webkitAudioContext;this.audioContext=new e;const n=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=512,n.connect(this.analyser)}_teardownAudioContext(){try{this.audioContext?.close()}catch{}this.audioContext=null,this.analyser=null}_startRecorder(){if(!this.stream)return;const e=this._pickMimeType(),n={};e&&MediaRecorder.isTypeSupported(e)&&(n.mimeType=e),this.mediaRecorder=new MediaRecorder(this.stream,n),this.chunks=[],this.recordingStartMs=Date.now(),this.mediaRecorder.ondataavailable=s=>{s.data&&s.data.size>0&&this.chunks.push(s.data)},this.mediaRecorder.onstop=()=>{const s=this.chunks.splice(0),o=Date.now()-this.recordingStartMs;if(s.length===0||o<aH){this.finishResolver?.(),this.finishResolver=null;return}const r=s[0].type||e||"audio/webm",i=new Blob(s,{type:r});this._upload(i,r).finally(()=>{this.finishResolver?.(),this.finishResolver=null})},this.mediaRecorder.start(250)}_stopRecorder(){if(this.mediaRecorder&&this.mediaRecorder.state!=="inactive")try{this.mediaRecorder.stop()}catch{this.finishResolver?.(),this.finishResolver=null}this.mediaRecorder=null}_releaseStream(){this.stream&&(this.stream.getTracks().forEach(e=>e.stop()),this.stream=null)}_startVAD(){this._stopVAD(),this.silenceSince=null,this.isSpeaking=!1,this.vadTimer=setInterval(()=>{if(!this.isActive||!this.analyser)return;this._getRmsDb()<this.cfg.silenceThresholdDb?this.isSpeaking&&(this.silenceSince===null?this.silenceSince=Date.now():Date.now()-this.silenceSince>=this.cfg.silenceHoldMs&&(this.isSpeaking=!1,this.silenceSince=null,this._finaliseUtterance(!0))):(this.silenceSince=null,this.isSpeaking||(this.isSpeaking=!0,this.mediaRecorder?.state==="recording"&&(this.recordingStartMs=Date.now())))},iH)}_stopVAD(){this.vadTimer!==null&&(clearInterval(this.vadTimer),this.vadTimer=null)}_cleanupAfterStop(e){const n=this.finishResolver;this.isActive=!1,this.finishResolver=null,this.mediaRecorder=null,this._teardownAudioContext(),this._releaseStream(),e&&(this.chunks=[]),this.isSpeaking=!1,this.silenceSince=null,this.onResult=null,this.onError=null,n?.()}_finaliseUtterance(e){this.isActive&&(this.mediaRecorder&&this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),e&&setTimeout(()=>{this.isActive&&this.stream&&this._startRecorder()},100))}_getRmsDb(){if(!this.analyser)return-1/0;const e=new Float32Array(this.analyser.fftSize);this.analyser.getFloatTimeDomainData(e);let n=0;for(const o of e)n+=o*o;const s=Math.sqrt(n/e.length);return s===0?-1/0:20*Math.log10(s)}async _upload(e,n){if(this.onResult)try{const s={"Content-Type":n,"X-Base-URL":this.cfg.baseURL,"X-Model":this.cfg.model};if(this.cfg.apiKey&&(s.Authorization=`Bearer ${this.cfg.apiKey}`),this.cfg.language)s["X-Language"]=this.cfg.language;else if(this.lang&&this.lang!=="auto"){const l=this.lang.split("-")[0];s["X-Language"]=l}const o=await nt("/api/stt/transcribe",{method:"POST",headers:s,body:e});if(!o.ok){const l=await o.json().catch(()=>({error:"Unknown error"}));throw new Error(l.error??`HTTP ${o.status}`)}const i=((await o.json()).transcript??"").trim();i&&this.onResult(i,!0)}catch(s){if(!this.isActive)return;const o=s instanceof Error?s.message:"Transcription upload failed";console.error("[AudioStreamService] Upload error:",o),this.onError?.(o)}}_pickMimeType(){const e=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/ogg","audio/mp4"];return typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported?e.find(n=>MediaRecorder.isTypeSupported(n))??"":""}}const mo=new lH,KX=[{id:"Xenova/whisper-tiny.en",name:"Whisper Tiny (EN)",size:"~39 MB",languages:"English",description:"Fastest, lowest accuracy. Good for quick dictation."},{id:"Xenova/whisper-base.en",name:"Whisper Base (EN)",size:"~73 MB",languages:"English",description:"Balanced speed and accuracy. Default for English."},{id:"Xenova/whisper-small.en",name:"Whisper Small (EN)",size:"~166 MB",languages:"English",description:"Higher accuracy, slower. Best for noisy environments."}],cH=80,dH=300,uH=16e3;class fH{transcriber=null;worker=null;modelStatus={state:"unloaded"};currentModelId=null;stream=null;mediaRecorder=null;audioContext=null;analyser=null;vadTimer=null;chunks=[];recordingStartMs=0;isActive=!1;isSpeaking=!1;silenceSince=null;onResult=null;onError=null;finishResolver=null;lang="en";cfg={silenceThresholdDb:-45,silenceHoldMs:1500};onModelStatusChange=null;configure(e){this.cfg={...this.cfg,...e}}isSupported(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"&&typeof window.MediaRecorder<"u"&&typeof window.AudioContext<"u"}getModelStatus(){return this.modelStatus}getCurrentModelId(){return this.currentModelId}setModelStatus(e){this.modelStatus=e,this.onModelStatusChange?.(e)}async loadModel(e){if(!(this.currentModelId===e&&this.modelStatus.state==="ready")&&!(this.modelStatus.state==="downloading"||this.modelStatus.state==="loading")){this._terminateWorker(),this.transcriber=null,this.setModelStatus({state:"downloading",progress:0}),this.currentModelId=e;try{const s=(await rn(()=>import("./wasmSttWorker-k0YUxAR6.js"),[])).default;this.worker=new s,await new Promise((o,r)=>{const i=setTimeout(()=>r(new Error("Worker init timed out")),1e4);this.worker.onmessage=l=>{const c=l.data;c.type==="progress"?this.setModelStatus({state:"downloading",progress:c.progress??0}):c.type==="loaded"?(clearTimeout(i),o()):c.type==="error"&&(clearTimeout(i),r(new Error(c.error??"Worker load failed")))},this.worker.onerror=l=>{clearTimeout(i),r(new Error(l.message||"Worker error"))},this.worker.postMessage({type:"load",modelId:e})}),this.setModelStatus({state:"ready"});return}catch(n){console.warn("[WasmStt] Worker failed, using main-thread:",n instanceof Error?n.message:n),this._terminateWorker()}try{const{pipeline:n,env:s}=await rn(async()=>{const{pipeline:l,env:c}=await import("./vendor-.bun-By2L9XvG.js").then(d=>d.co);return{pipeline:l,env:c}},__vite__mapDeps([0,1]));s.backends.onnx.wasm.numThreads=1,s.allowLocalModels=!1;const o=new Map;let r=0,i=0;this.transcriber=await n("automatic-speech-recognition",e,{progress_callback:l=>{if(l.status==="progress"&&l.file){const c=o.get(l.file)??0,d=l.loaded??0,u=Math.max(0,d-c);o.set(l.file,d),r+=u,l.total&&l.total>i&&(i=l.total);const f=Math.max(i,r),m=f>0?Math.min(100,Math.round(r/f*100)):0;this.setModelStatus({state:"downloading",progress:m})}}}),this.setModelStatus({state:"ready"})}catch(n){const s=n instanceof Error?n.message:"Unknown error loading model";throw this.setModelStatus({state:"error",error:s}),this.transcriber=null,this.currentModelId=null,n}}}_terminateWorker(){this.worker&&(this.worker.terminate(),this.worker=null)}async unloadModel(){this._terminateWorker(),this.transcriber=null,this.currentModelId=null,this.setModelStatus({state:"unloaded"})}async startListening(e,n,s){if(this.isActive&&this.stopListening(),!this.transcriber&&!this.worker){s?.("Whisper model not loaded. Select a model in Voice Settings first.");return}this.lang=e,this.onResult=n,this.onError=s??null,this.isActive=!0;try{this.stream=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1})}catch(o){this.isActive=!1;const r=o instanceof Error?o.message:"Microphone access denied";s?.(r);return}this._setupAudioContext(),this._startRecorder(),this._startVAD()}stopListening(){if(this._stopVAD(),this.mediaRecorder&&this.mediaRecorder.state==="recording")try{this.mediaRecorder.stop()}catch{}this._cleanupAfterStop(!0)}async finishListening(){if(this.isActive){if(this._stopVAD(),this.isSpeaking=!1,this.silenceSince=null,!this.mediaRecorder||this.mediaRecorder.state==="inactive"){this._cleanupAfterStop(!0);return}await new Promise(e=>{this.finishResolver=e,this._finaliseUtterance(!1)}),this._cleanupAfterStop(!0)}}getIsListening(){return this.isActive}_setupAudioContext(){if(!this.stream)return;const e=window.AudioContext??window.webkitAudioContext;this.audioContext=new e;const n=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=512,n.connect(this.analyser)}_teardownAudioContext(){try{this.audioContext?.close()}catch{}this.audioContext=null,this.analyser=null}_startRecorder(){if(!this.stream)return;const e=this._pickMimeType(),n={};e&&MediaRecorder.isTypeSupported(e)&&(n.mimeType=e),this.mediaRecorder=new MediaRecorder(this.stream,n),this.chunks=[],this.recordingStartMs=Date.now(),this.mediaRecorder.ondataavailable=s=>{s.data&&s.data.size>0&&this.chunks.push(s.data)},this.mediaRecorder.onstop=()=>{const s=this.chunks.splice(0),o=Date.now()-this.recordingStartMs;if(s.length===0||o<dH){this.finishResolver?.(),this.finishResolver=null;return}const r=s[0].type||e||"audio/webm",i=new Blob(s,{type:r});this._transcribe(i).finally(()=>{this.finishResolver?.(),this.finishResolver=null})},this.mediaRecorder.start(250)}_releaseStream(){this.stream&&(this.stream.getTracks().forEach(e=>e.stop()),this.stream=null)}_startVAD(){this._stopVAD(),this.silenceSince=null,this.isSpeaking=!1,this.vadTimer=setInterval(()=>{if(!this.isActive||!this.analyser)return;this._getRmsDb()<this.cfg.silenceThresholdDb?this.isSpeaking&&(this.silenceSince===null?this.silenceSince=Date.now():Date.now()-this.silenceSince>=this.cfg.silenceHoldMs&&(this.isSpeaking=!1,this.silenceSince=null,this._finaliseUtterance(!0))):(this.silenceSince=null,this.isSpeaking||(this.isSpeaking=!0,this.mediaRecorder?.state==="recording"&&(this.recordingStartMs=Date.now())))},cH)}_stopVAD(){this.vadTimer!==null&&(clearInterval(this.vadTimer),this.vadTimer=null)}_cleanupAfterStop(e){const n=this.finishResolver;this.isActive=!1,this.finishResolver=null,this.mediaRecorder=null,this._teardownAudioContext(),this._releaseStream(),e&&(this.chunks=[]),this.isSpeaking=!1,this.silenceSince=null,this.onResult=null,this.onError=null,n?.()}_finaliseUtterance(e){this.isActive&&(this.mediaRecorder&&this.mediaRecorder.state==="recording"&&this.mediaRecorder.stop(),e&&setTimeout(()=>{this.isActive&&this.stream&&this._startRecorder()},100))}_getRmsDb(){if(!this.analyser)return-1/0;const e=new Float32Array(this.analyser.fftSize);this.analyser.getFloatTimeDomainData(e);let n=0;for(const o of e)n+=o*o;const s=Math.sqrt(n/e.length);return s===0?-1/0:20*Math.log10(s)}async _transcribe(e){if(this.onResult){if(!this.transcriber&&!this.worker){this.onError?.("Model not loaded");return}try{const n=await this._decodeToFloat32(e);if(!n||n.length===0){this.onError?.(`Failed to decode audio (${e.size} bytes)`);return}const s=this._resolveLanguageHint(),o=this.worker?await this._transcribeViaWorker(n,s):await this._transcribeMainThread(n,s);o&&this.onResult(o,!0)}catch(n){if(!this.isActive)return;const s=n instanceof Error?n.message:"Local transcription failed";this.onError?.(s)}}}_transcribeViaWorker(e,n){return new Promise((s,o)=>{if(!this.worker)return o(new Error("Worker gone"));const r=i=>{const l=i.data;l.type==="result"?(this.worker.removeEventListener("message",r),s(l.transcript??"")):l.type==="log"?console.log("[WasmStt Worker]",l.text):l.type==="error"&&(this.worker.removeEventListener("message",r),o(new Error(l.error??"Transcription failed")))};this.worker.addEventListener("message",r),this.worker.postMessage({type:"transcribe",audio:e.buffer,language:n},[e.buffer]),setTimeout(()=>{this.worker?.removeEventListener("message",r),o(new Error("Transcription timed out"))},3e4)})}async _transcribeMainThread(e,n){const s=this.transcriber;return((await s(e,{task:"transcribe",...n?{language:n}:{}}))?.text??"").trim()}async _decodeToFloat32(e){if(!this.audioContext)return null;const n=await e.arrayBuffer();let s;try{s=await this.audioContext.decodeAudioData(n)}catch{return null}const o=s.sampleRate,r=s.getChannelData(0),i=uH;if(o===i)return new Float32Array(r);const l=o/i,c=Math.ceil(r.length/l),d=new Float32Array(c);for(let u=0;u<c;u++){const f=u*l,m=Math.floor(f),h=Math.min(m+1,r.length-1),p=f-m;d[u]=r[m]*(1-p)+r[h]*p}return d}_resolveLanguageHint(){if(this.lang&&this.lang!=="auto")return this.lang.split("-")[0]}_pickMimeType(){const e=["audio/webm;codecs=opus","audio/webm","audio/ogg;codecs=opus","audio/ogg","audio/mp4"];return typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported?e.find(n=>MediaRecorder.isTypeSupported(n))??"":""}}const To=new fH,mH=3e4;let Ti=null,Oa=null;async function hH(){const t=Date.now();return Ti&&t-Ti.checkedAt<mH?Ti.available:Oa||(Oa=(async()=>{try{const e=await nt("/api/tts/status");if(!e.ok)return Ti={available:!1,checkedAt:Date.now()},!1;const s=!!(await e.json()).available;return Ti={available:s,checkedAt:Date.now()},s}catch{return Ti={available:!1,checkedAt:Date.now()},!1}finally{Oa=null}})(),Oa)}let ed=null;function d7(){return ed||(ed=new(window.AudioContext||window.webkitAudioContext)),ed}function _p(t={}){const e=t.enabled??!0,n=t.availabilityMode??"auto",[s,o]=ae.useState(!1),[r,i]=ae.useState(!1),[l,c]=ae.useState(null),d=ae.useRef(null),u=ae.useRef(null),f=Pe(k=>k.currentProviderId),m=Pe(k=>k.currentModelId),h=Pe(k=>k.openaiApiKey),p=Pe(k=>k.openaiCompatibleUrl),b=Pe(k=>k.openaiCompatibleApiKey),w=ae.useCallback(async()=>{if(!e)return i(!1),!1;const k=!!(h&&h.trim().length>0),C=!!(p&&p.trim().length>0);if(n==="openai-compatible")return i(C),C;if(k||n==="auto"&&C)return i(!0),!0;try{const S=await hH();return i(S),S}catch{return i(!1),!1}},[n,e,h,p]);ae.useEffect(()=>{w()},[w]);const v=ae.useCallback(()=>{if(d.current){try{d.current.stop()}catch{}d.current=null}u.current&&(u.current.abort(),u.current=null),o(!1)},[]),x=ae.useCallback(async()=>{try{const k=d7();k.state==="suspended"&&(await k.resume(),console.log("[useServerTTS] AudioContext resumed"));const C=k.createBuffer(1,1,22050),S=k.createBufferSource();S.buffer=C,S.connect(k.destination),S.start(0),console.log("[useServerTTS] Audio unlocked for mobile playback")}catch(k){console.error("[useServerTTS] Failed to unlock audio:",k)}},[]),y=ae.useCallback(async(k,C)=>{if(v(),!k.trim()){c("No text to speak"),C?.onError?.("No text to speak");return}c(null);try{const S=d7();S.state==="suspended"&&(await S.resume(),console.log("[useServerTTS] AudioContext resumed"));const M=S.createBuffer(1,1,22050),A=S.createBufferSource();A.buffer=M,A.connect(S.destination),A.start(0),u.current=new AbortController;const B=C?.voice||"nova";console.log("[useServerTTS] Speaking with voice:",B,"options:",C);const F=await nt("/api/tts/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:k.trim(),voice:B,model:C?.model||void 0,speed:C?.speed||.9,instructions:C?.instructions,summarize:!1,providerId:C?.providerId||f||void 0,modelId:C?.modelId||m||void 0,apiKey:C?.baseURL?b||void 0:h||void 0,baseURL:C?.baseURL||void 0}),signal:u.current.signal});if(!F.ok){const H=await F.json().catch(()=>({error:"Unknown error"}));throw new Error(H.error||`HTTP ${F.status}`)}const D=await(await F.blob()).arrayBuffer();console.log("[useServerTTS] Decoding audio data...");const E=await S.decodeAudioData(D),I=S.createBufferSource();I.buffer=E;const T=C?.pitch??1;T!==1&&(I.detune.value=(T-1)*1200);const j=C?.volume??1,V=S.createGain();V.gain.value=j,I.connect(V),V.connect(S.destination),d.current=I,I.onended=()=>{console.log("[useServerTTS] Audio playback ended"),o(!1),d.current=null,C?.onEnd?.()},console.log("[useServerTTS] Starting audio playback via Web Audio API..."),o(!0),C?.onStart?.(),I.start(0)}catch(S){if(S.name==="AbortError")return;const M=S instanceof Error?S.message:"Failed to speak";console.error("[useServerTTS] Error:",M),c(M),C?.onError?.(M),o(!1)}},[v,f,m,h,b]);return ae.useEffect(()=>()=>{v()},[v]),{isPlaying:s,isAvailable:r,error:l,speak:y,stop:v,checkAvailability:w,unlockAudio:x}}const pH=3e4;let ji=null,$a=null;async function gH(){const t=Date.now();return ji&&t-ji.checkedAt<pH?ji:$a||($a=(async()=>{try{const e=await nt("/api/tts/say/status");if(!e.ok){const o={available:!1,voices:[],checkedAt:Date.now()};return ji=o,o}const n=await e.json(),s={available:!!n.available,voices:Array.isArray(n.voices)?n.voices:[],checkedAt:Date.now()};return ji=s,s}catch{const e={available:!1,voices:[],checkedAt:Date.now()};return ji=e,e}finally{$a=null}})(),$a)}let td=null;function u7(){return td||(td=new(window.AudioContext||window.webkitAudioContext)),td}function Bp(t={}){const e=t.enabled??!0,[n,s]=ae.useState(!1),[o,r]=ae.useState(!1),[i,l]=ae.useState([]),[c,d]=ae.useState(null),u=ae.useRef(null),f=ae.useRef(null),m=ae.useCallback(async()=>{try{const w=u7();w.state==="suspended"&&(await w.resume(),console.log("[useSayTTS] AudioContext resumed"));const v=w.createBuffer(1,1,22050),x=w.createBufferSource();x.buffer=v,x.connect(w.destination),x.start(0),console.log("[useSayTTS] Audio unlocked for mobile playback")}catch(w){console.error("[useSayTTS] Failed to unlock audio:",w)}},[]),h=ae.useCallback(async()=>{if(!e)return r(!1),l([]),!1;try{const w=await gH();return r(w.available),l(w.voices),w.available}catch{return r(!1),l([]),!1}},[e]);ae.useEffect(()=>{h()},[h]);const p=ae.useCallback(()=>{if(u.current){try{u.current.stop()}catch{}u.current=null}f.current&&(f.current.abort(),f.current=null),s(!1)},[]),b=ae.useCallback(async(w,v)=>{if(p(),!w.trim()){d("No text to speak"),v?.onError?.("No text to speak");return}d(null);try{f.current=new AbortController;const x=await nt("/api/tts/say/speak",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:w.trim(),voice:v?.voice||"Samantha",rate:v?.rate||200}),signal:f.current.signal});if(!x.ok){const A=await x.json().catch(()=>({error:"Unknown error"}));throw new Error(A.error||`HTTP ${x.status}`)}const y=await x.blob(),k=await y.arrayBuffer();console.log("[useSayTTS] Received audio:",y.size,"bytes");const C=u7();C.state==="suspended"&&(await C.resume(),console.log("[useSayTTS] AudioContext resumed before playback")),console.log("[useSayTTS] Decoding audio data...");const S=await C.decodeAudioData(k),M=C.createBufferSource();M.buffer=S,M.connect(C.destination),u.current=M,M.onended=()=>{console.log("[useSayTTS] Audio playback ended"),s(!1),u.current=null,v?.onEnd?.()},console.log("[useSayTTS] Starting audio playback via Web Audio API..."),s(!0),v?.onStart?.(),M.start(0)}catch(x){if(x.name==="AbortError")return;const y=x instanceof Error?x.message:"Failed to speak";console.error("[useSayTTS] Error:",y),d(y),v?.onError?.(y),s(!1)}},[p]);return ae.useEffect(()=>()=>{p()},[p]),{isPlaying:n,isAvailable:o,voices:i,error:c,speak:b,stop:p,checkAvailability:h,unlockAudio:m}}function Dp(t){return t?t.replace(/```[\s\S]*?```/g,"").replace(/`[^`]*`/g,"").replace(/[*_~#]/g,"").replace(/https?:\/\/[^\s]+/g,"").replace(/\/[\w\-./]+/g,"").replace(/^\s*[$#>]\s*/gm,"").replace(/[[\]{}()<>|&;]/g," ").replace(/\\/g,"").replace(/\s+/g," ").trim():""}const V2="browserVoiceLanguage",nd="browserVoiceConversationMode",sd="openchamber:voice-language-changed",od="openchamber:voice-conversation-mode-changed",R2=1200,bH=700,f7=new Set(["ru","ru-RU"]),Za=t=>{const e=(t||"").trim();if(!e)return"en-US";const n=e.split("-")[0].toLowerCase();return f7.has(e)||f7.has(n)?"en-US":e};function vH(){const[t,e]=ae.useState("idle"),[n,s]=ae.useState(null),[o,r]=ae.useState(()=>{if(typeof window<"u"){const ce=localStorage.getItem(V2);if(ce)return Za(ce)}return Za(navigator.language||"en-US")}),[i,l]=ae.useState(()=>typeof window<"u"?localStorage.getItem(nd)==="true":!1),c=ae.useMemo(()=>{if(typeof navigator>"u")return!1;const ce=navigator.userAgent.toLowerCase();return/iphone|ipad|ipod|android|mobile|webos|blackberry|iemobile|opera mini/i.test(ce)},[]),d=ae.useRef(!1),u=ae.useRef(!1),f=ae.useRef(""),m=ae.useRef(!1),h=ae.useRef(""),p=ae.useRef(null),b=ae.useRef(null),w=ae.useRef(0),v=ae.useRef(null),x=ae.useRef(!1),y=Ie(ce=>ce.currentSessionId),k=Ie(ce=>ce.sendMessage),C=zt(ce=>ce.setPendingInputText),S=Ie(ce=>ce.createSession),M=Pe(ce=>ce.currentProviderId),A=Pe(ce=>ce.currentModelId),B=Pe(ce=>ce.currentAgentName),F=Pe(ce=>ce.currentVariant),_=Pe(ce=>ce.voiceModeEnabled),D=Pe(ce=>ce.voiceProvider),E=Pe(ce=>ce.speechRate),I=Pe(ce=>ce.speechPitch),T=Pe(ce=>ce.speechVolume),j=Pe(ce=>ce.sayVoice),V=Pe(ce=>ce.browserVoice),H=Pe(ce=>ce.openaiVoice),N=Pe(ce=>ce.openaiCompatibleVoice),R=Pe(ce=>ce.openaiCompatibleUrl),$=Pe(ce=>ce.openaiCompatibleTtsModel),U=Pe(ce=>ce.sttApiKey),L=_&&(D==="openai"||D==="openai-compatible"),Z=_&&D==="say",Y=Pe(ce=>ce.sttProvider),fe=Pe(ce=>ce.sttServerUrl),Q=Pe(ce=>ce.sttModel),pe=Pe(ce=>ce.wasmSttModel),ne=Pe(ce=>ce.sttLanguage),re=Pe(ce=>ce.sttSilenceThresholdDb),se=Pe(ce=>ce.sttSilenceHoldMs),te=Y==="server"?mo.isSupported():Y==="wasm"?To.isSupported():ln.isSupported(),{speak:ke,stop:be,isAvailable:X,unlockAudio:ee}=_p({enabled:L,availabilityMode:D==="openai-compatible"?"openai-compatible":"openai"}),{speak:G,stop:O,isAvailable:ie,unlockAudio:oe}=Bp({enabled:Z}),Ce=ae.useRef(null);ae.useEffect(()=>{Ce.current!==null&&Ce.current!==y&&d.current&&(console.log("[useBrowserVoice] Session changed, stopping voice"),d.current=!1,u.current=!1,ln.stopListening(),mo.stopListening(),ln.cancelSpeech(),e("idle"),s(null)),Ce.current=y},[y]);const ue=ae.useCallback(ce=>{const Ae=Za(ce);r(Ae),typeof window<"u"&&(localStorage.setItem(V2,Ae),window.dispatchEvent(new CustomEvent(sd,{detail:Ae})))},[]);ae.useEffect(()=>{if(typeof window>"u")return;const ce=He=>{const Ee=Za(He.detail||localStorage.getItem(V2)||"en-US");r(Le=>Le===Ee?Le:Ee)},Ae=He=>{if(He.key!==V2||!He.newValue)return;const he=Za(He.newValue);r(Ee=>Ee===he?Ee:he)};return window.addEventListener(sd,ce),window.addEventListener("storage",Ae),()=>{window.removeEventListener(sd,ce),window.removeEventListener("storage",Ae)}},[]);const Me=ae.useCallback(()=>{l(ce=>{const Ae=!ce;return ln.setConversationMode(Ae),typeof window<"u"&&(localStorage.setItem(nd,String(Ae)),window.dispatchEvent(new CustomEvent(od,{detail:Ae}))),Ae})},[]);ae.useEffect(()=>{if(typeof window>"u")return;const ce=He=>{const Ee=He.detail;typeof Ee=="boolean"&&l(Le=>Le===Ee?Le:Ee)},Ae=He=>{if(He.key!==nd||He.newValue==null)return;const he=He.newValue==="true";l(Ee=>Ee===he?Ee:he)};return window.addEventListener(od,ce),window.addEventListener("storage",Ae),()=>{window.removeEventListener(od,ce),window.removeEventListener("storage",Ae)}},[]),ae.useEffect(()=>{ln.setConversationMode(i)},[i]);const ye=ae.useRef(null),K=ae.useRef(null),W=ae.useCallback(ce=>{Y==="server"?mo.startListening(ce,K.current,ye.current):Y==="wasm"?To.startListening(ce,K.current,ye.current):c?ln.startListeningSync(ce,K.current,ye.current):ln.startListening(ce,K.current,ye.current)},[Y,c]),le=ae.useCallback(ce=>{if(!d.current){console.log("[useBrowserVoice] Ignoring error after voice stopped:",ce);return}const Ae=ce.toLowerCase();if(Ae.includes("aborted")){console.log("[useBrowserVoice] Ignoring non-fatal aborted error"),s(null),e("listening");return}const He=typeof document<"u"&&document.visibilityState!=="visible",he=Ae.includes("permission")||Ae.includes("not allowed")||Ae.includes("service not allowed");if(He&&he&&i){console.log("[useBrowserVoice] Suppressing permission error while app hidden; will resume on visibility"),m.current=!0,s(null),e("idle");return}if(Ae.includes("network")||Ae.includes("connection")||Ae.includes("check connection")){console.error("[useBrowserVoice] Network error — staying in error state:",ce),s(ce),e("error"),w.current=0,v.current!==null&&(clearTimeout(v.current),v.current=null);return}if(console.error("[useBrowserVoice] Recognition error:",ce),s(ce),e("error"),he||x.current){w.current=0;return}const Le=w.current+1;w.current=Le;const Ve=3;if(Le<=Ve){const Ue=Math.min(1e3*Math.pow(2,Le-1),8e3);console.log(`[useBrowserVoice] Scheduling recovery retry ${Le}/${Ve} in ${Ue}ms`),v.current!==null&&clearTimeout(v.current),v.current=setTimeout(()=>{v.current=null,d.current&&(e("listening"),s(null),W(o))},Ue)}else console.log("[useBrowserVoice] Max recovery retries reached — staying in error state")},[o,i,W]);ae.useEffect(()=>{ye.current=le},[le]);const xe=ae.useCallback(async ce=>{if(!(!ce.trim()||!d.current)&&ce.trim()!==f.current){if(f.current=ce.trim(),!M||!A){s("No provider or model configured. Please configure them in settings."),e("error");return}if(ln.stopListening(),mo.stopListening(),!i){C(ce.trim(),"append-inline"),u.current=!1,d.current=!1,e("idle");return}e("processing"),u.current=!0;try{let Ae=y;if(!Ae){console.log("[useBrowserVoice] No active session, creating new session...");const he=await S();if(!he){s("Failed to create session"),e("error"),u.current=!1;return}Ae=he.id,console.log("[useBrowserVoice] Created new session:",Ae)}await k(ce.trim(),M,A,B??void 0,void 0,void 0,void 0,F??void 0);const He=async()=>{if(!d.current||!Ae)return;const Ee=us(Ae).filter(Le=>Le.role==="assistant").sort((Le,Ve)=>{const Ue=Le.time?.created??0;return(Ve.time?.created??0)-Ue});if(Ee.length>0){const Le=Ee[0],Ue=Es(Le.id).filter(qe=>qe.type==="text").map(qe=>qe.text??"").join(" ");if(Ue.trim()){e("speaking");try{const qe=Dp(Ue),Ge=()=>{if(d.current&&i){if(typeof document<"u"&&document.visibilityState!=="visible"){m.current=!0,e("idle");return}e("listening"),W(o)}else d.current=!1,e("idle")};if((D==="openai"||D==="openai-compatible")&&X){const vt=D==="openai-compatible"?N:H,St=D==="openai-compatible"?R:void 0,Pt=D==="openai-compatible"?$:void 0;console.log("[useBrowserVoice] Using server TTS with voice:",vt,"provider:",D),await ke(qe,{voice:vt,model:Pt,speed:E,pitch:I,volume:T,baseURL:St,onStart:()=>console.log("[useBrowserVoice] Server TTS started"),onEnd:()=>{console.log("[useBrowserVoice] Server TTS ended"),Ge()},onError:yt=>{console.error("[useBrowserVoice] Server TTS error:",yt),s(`Voice TTS failed: ${yt}. Please check your settings or switch to Browser voice.`),e("error"),Ge()}})}else if(D==="say"&&ie){console.log("[useBrowserVoice] Using macOS Say TTS with voice:",j);const vt=Math.round(100+(E-.5)*200);await G(qe,{voice:j,rate:vt,onStart:()=>console.log("[useBrowserVoice] Say TTS started"),onEnd:()=>{console.log("[useBrowserVoice] Say TTS ended"),Ge()},onError:St=>{console.error("[useBrowserVoice] Say TTS error:",St),Ge()}})}else console.log("[useBrowserVoice] Using browser TTS"),D==="openai"&&!X&&(console.warn("[useBrowserVoice] OpenAI voice selected but unavailable, falling back to browser voice"),s("OpenAI voice unavailable (API key not configured). Using browser voice instead.")),await ln.waitForVoices(),await ln.resumeAudioContext(),await ln.speakText(qe,o,()=>{Ge()},{rate:E,pitch:I,volume:T,voiceName:V||void 0})}catch(qe){const Ge=qe instanceof Error?qe.message:"Speech failed";if(!d.current){console.log("[useBrowserVoice] Ignoring speech error after voice stopped:",Ge);return}console.error("[useBrowserVoice] Speech error:",Ge),(Ge.includes("not-allowed")||Ge.includes("autoplay"))&&s("Audio blocked by browser. Please click the voice button again to enable audio."),i?(e("listening"),W(o)):(d.current=!1,e("idle"))}return}}setTimeout(He,500)};setTimeout(He,1e3)}catch(Ae){console.error("[useBrowserVoice] Send message error:",Ae),s(Ae instanceof Error?Ae.message:"Failed to send message"),e("error"),u.current=!1}}},[y,M,A,B,F,o,k,C,S,E,I,T,X,ke,ie,G,D,j,V,H,N,R,$,i,W]),Se=ae.useCallback(async(ce,Ae)=>{if(!d.current)return;const He=ce.trim();!Ae||!He||(console.log("[useBrowserVoice] Speech result:",He),h.current=He,p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{p.current=null;const he=h.current.trim();h.current="",he&&xe(he)},R2))},[xe]);ae.useEffect(()=>{if(typeof document>"u")return;const ce=()=>{if(document.visibilityState==="visible"&&m.current){if(!d.current||!i){m.current=!1;return}m.current=!1,e("listening");try{W(o)}catch(Ae){const He=Ae instanceof Error?Ae.message:"Failed to resume voice";s(He),e("error")}}};return document.addEventListener("visibilitychange",ce),()=>{document.removeEventListener("visibilitychange",ce)}},[i,c,o,Y,W]),ae.useEffect(()=>{if(typeof navigator>"u")return;const ce=navigator.mediaDevices;if(!ce||typeof ce.addEventListener!="function")return;const Ae=()=>{!d.current||t!=="listening"||(b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{if(b.current=null,!d.current||t!=="listening")return;if(typeof document<"u"&&document.visibilityState!=="visible"){m.current=!0,e("idle");return}try{ln.stopListening(),mo.stopListening(),To.stopListening(),W(o)}catch(he){const Ee=he instanceof Error?he.message:"Microphone source changed. Tap mic to continue.";s(Ee),e("error"),d.current=!1}},bH))};return ce.addEventListener("devicechange",Ae),()=>{ce.removeEventListener("devicechange",Ae),b.current&&(clearTimeout(b.current),b.current=null)}},[c,o,t,Y,W]),ae.useEffect(()=>{K.current=Se},[Se]);const we=ae.useCallback(async()=>{if(!te)return!1;if(Y==="server"||Y==="wasm")return!0;try{return await ln.prepareListening(),!0}catch(ce){const Ae=ce instanceof Error?ce.message:"Microphone permission denied";return s(Ae),!1}},[te,Y]),me=ae.useCallback(async()=>{if(!te){s("Voice input not supported in this browser"),e("error");return}if(!y){s("No active session"),e("error");return}if(d.current=!0,f.current="",w.current=0,x.current=!1,v.current!==null&&(clearTimeout(v.current),v.current=null),s(null),e("listening"),Y==="server"){mo.configure({baseURL:fe,model:Q,language:ne||void 0,silenceThresholdDb:re,silenceHoldMs:se,apiKey:U||void 0});try{await mo.startListening(o,Se,le)}catch(ce){const Ae=ce instanceof Error?ce.message:"Failed to start voice";console.error("[useBrowserVoice] Server STT start error:",Ae),s(Ae),e("error"),d.current=!1}return}if(Y==="wasm"){const ce=To.getModelStatus();if(console.log("[useBrowserVoice] WASM model status:",ce.state),ce.state!=="ready")try{e("processing"),await To.loadModel(pe)}catch(Ae){const He=Ae instanceof Error?Ae.message:"Failed to load Whisper model";console.error("[useBrowserVoice] WASM model load error:",He),s(He),e("error"),d.current=!1;return}To.configure({silenceThresholdDb:re,silenceHoldMs:se});try{await To.startListening(o,Se,le),console.log("[useBrowserVoice] WASM listening started")}catch(Ae){const He=Ae instanceof Error?Ae.message:"Failed to start voice";console.error("[useBrowserVoice] WASM STT start error:",He),s(He),e("error"),d.current=!1}return}if(c)try{ln.unlockAudio().catch(()=>{}),ee().catch(()=>{}),oe().catch(()=>{}),ln.startListeningSync(o,Se,le)}catch(ce){const Ae=ce instanceof Error?ce.message:"Failed to start voice";console.error("[useBrowserVoice] Mobile voice start error:",Ae),s(Ae),e("error"),d.current=!1}else try{await ln.startListening(o,Se,le)}catch(ce){const Ae=ce instanceof Error?ce.message:"Failed to start voice";console.error("[useBrowserVoice] Desktop voice start error:",Ae),s(Ae),e("error"),d.current=!1}},[te,y,o,Se,le,c,ee,oe,Y,fe,Q,U,pe,ne,re,se]),_e=ae.useCallback(()=>{d.current=!1,u.current=!1,m.current=!1,w.current=0,x.current=!1,b.current&&(clearTimeout(b.current),b.current=null),v.current!==null&&(clearTimeout(v.current),v.current=null),h.current="",p.current&&(clearTimeout(p.current),p.current=null),ln.stopListening(),mo.stopListening(),To.stopListening(),ln.cancelSpeech(),be(),O(),e("idle"),s(null)},[be,O]),ge=ae.useCallback(()=>{if(d.current){if(x.current=!0,m.current=!1,b.current&&(clearTimeout(b.current),b.current=null),e("processing"),Y==="server"){mo.finishListening().then(()=>{window.setTimeout(()=>{d.current&&(h.current||p.current||u.current||(d.current=!1,u.current=!1,e("idle")))},R2+200)});return}if(Y==="wasm"){To.finishListening().then(()=>{window.setTimeout(()=>{d.current&&(h.current||p.current||u.current||(d.current=!1,u.current=!1,e("idle"),x.current=!1))},R2+200)});return}ln.stopListening(),window.setTimeout(()=>{d.current&&(h.current||p.current||u.current||(d.current=!1,u.current=!1,e("idle")))},R2+300)}},[Y]);return ae.useEffect(()=>()=>{d.current=!1,b.current&&(clearTimeout(b.current),b.current=null),h.current="",p.current&&(clearTimeout(p.current),p.current=null),ln.setConversationMode(!1),ln.stopListening(),mo.stopListening(),ln.cancelSpeech()},[]),{status:t,isSupported:te,error:n,language:o,setLanguage:ue,startVoice:me,stopVoice:_e,finishVoiceInput:ge,conversationMode:i,toggleConversationMode:Me,prepareVoice:we,isMobile:c,voiceProvider:D}}const yH={sm:{icon:"w-4 h-4",container:"gap-1.5"},md:{icon:"w-5 h-5",container:"gap-2"},lg:{icon:"w-6 h-6",container:"gap-2.5"}},wH={idle:{icon:"mic-off",color:"text-muted-foreground",labelKey:"voice.status.idle"},listening:{icon:"mic",color:"text-primary",labelKey:"voice.status.listening",animation:"animate-pulse"},processing:{icon:"loader-4",color:"text-primary",labelKey:"voice.status.processing",animation:"animate-spin"},speaking:{icon:"volume-up",color:"text-green-500",labelKey:"voice.status.speaking"},error:{icon:"alert",color:"text-destructive",labelKey:"voice.status.error"}};function m7(t){const e=de.c(19),{status:n,showLabel:s,size:o,className:r,conversationMode:i}=t,l=s===void 0?!1:s,c=o===void 0?"md":o,d=r===void 0?"":r,u=i===void 0?!1:i,{t:f}=Ye(),m=wH[n],h=m.icon,p=yH[c],w=`flex items-center ${l?p.container:""} ${d}`,v=`
472
472
  ${p.icon}
473
473
  ${m.color}
474
474
  ${m.animation||""}
@@ -7143,5 +7143,5 @@ ${this.state.error.stack}`:"",o=this.state.errorInfo?.componentStack?`
7143
7143
 
7144
7144
  ${e.componentStackLabel}${this.state.errorInfo.componentStack}`:"",r=`${n}${s}${o}`;(await $s(r)).ok&&(this.setState({copied:!0}),window.setTimeout(()=>{this.setState(l=>l.copied?{copied:!1}:null)},1500))};render(){const{strings:e}=this.props;return this.state.hasError?this.props.fallback?this.props.fallback:a.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:a.jsxs(iJ,{className:"w-full max-w-md",children:[a.jsx(aJ,{className:"text-center",children:a.jsxs(lJ,{className:"flex items-center justify-center gap-2 text-destructive",children:[a.jsx(q,{name:"error-warning",className:"h-5 w-5"}),e.title]})}),a.jsxs(cJ,{className:"space-y-4",children:[a.jsx("p",{className:"text-sm text-muted-foreground text-center",children:e.description}),this.state.error&&a.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[a.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:e.detailsSummary}),a.jsxs("pre",{className:"mt-2 max-h-48 overflow-auto",children:[this.state.error.toString(),this.state.errorInfo?.componentStack?`
7145
7145
 
7146
- ${e.componentStackLabel}${this.state.errorInfo.componentStack}`:""]})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(bt,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[a.jsx(q,{name:"restart",className:"h-4 w-4 mr-2"}),e.tryAgain]}),a.jsx(bt,{onClick:this.handleCopy,variant:"outline",className:"flex-1",children:this.state.copied?e.copied:e.copy})]})]})]})}):this.props.children}}const See=t=>{const e=de.c(29),{children:n,fallback:s}=t,{t:o}=Ye();let r;e[0]!==o?(r=o("errorBoundary.state.unknownError"),e[0]=o,e[1]=r):r=e[1];let i;e[2]!==o?(i=o("errorBoundary.title"),e[2]=o,e[3]=i):i=e[3];let l;e[4]!==o?(l=o("errorBoundary.description"),e[4]=o,e[5]=l):l=e[5];let c;e[6]!==o?(c=o("errorBoundary.actions.errorDetails"),e[6]=o,e[7]=c):c=e[7];let d;e[8]!==o?(d=o("errorBoundary.state.componentStackLabel"),e[8]=o,e[9]=d):d=e[9];let u;e[10]!==o?(u=o("errorBoundary.actions.tryAgain"),e[10]=o,e[11]=u):u=e[11];let f;e[12]!==o?(f=o("errorBoundary.actions.copied"),e[12]=o,e[13]=f):f=e[13];let m;e[14]!==o?(m=o("errorBoundary.actions.copy"),e[14]=o,e[15]=m):m=e[15];let h;e[16]!==r||e[17]!==i||e[18]!==l||e[19]!==c||e[20]!==d||e[21]!==u||e[22]!==f||e[23]!==m?(h={unknownError:r,title:i,description:l,detailsSummary:c,componentStackLabel:d,tryAgain:u,copied:f,copy:m},e[16]=r,e[17]=i,e[18]=l,e[19]=c,e[20]=d,e[21]=u,e[22]=f,e[23]=m,e[24]=h):h=e[24];const p=h;let b;return e[25]!==n||e[26]!==s||e[27]!==p?(b=a.jsx(dJ,{fallback:s,strings:p,children:n}),e[25]=n,e[26]=s,e[27]=p,e[28]=b):b=e[28],b},Ln=t=>Q1(Go.getState().dictionary,t),Mee=t=>typeof t!="number"||!Number.isFinite(t)?null:Math.max(0,Math.min(100,Math.round(t))),uJ=t=>typeof t!="number"||!Number.isFinite(t)?"-":`${Math.round(t)}%`,Aee=(t,e)=>t??uJ(e),Fee=(t,e,n="auto")=>{if(!t)return e??"";try{const s=new Date(t);if(!Number.isFinite(s.getTime()))return e??"";const o=new Date;return s.toDateString()===o.toDateString()?Bb(s,n,{fallback:e??""}):lW(s,n,{month:"short",day:"numeric",weekday:"short",hour:"numeric",minute:"2-digit"})}catch{return e??""}},_ee=t=>t===null?"safe":t>=80?"critical":t>=50?"warn":"safe",Bee=t=>t==="5h"?Ln("quota.window.5h"):t==="7d"?Ln("quota.window.7d"):t==="7d-sonnet"?Ln("quota.window.7dSonnet"):t==="7d-opus"?Ln("quota.window.7dOpus"):t==="weekly"?Ln("quota.window.weekly"):t==="daily"?Ln("quota.window.daily"):t==="monthly"?Ln("quota.window.monthly"):t==="credits"?Ln("quota.window.credits"):t==="credits_balance"?Ln("quota.window.creditsBalance"):t==="billing_cycle"?Ln("quota.window.billingCycle"):t==="auto"?Ln("quota.window.auto"):t==="api"?Ln("quota.window.api"):t==="plan_limit"?Ln("quota.window.planLimit"):t==="on_demand"?Ln("quota.window.onDemand"):t==="session"?Ln("quota.window.session"):t==="premium"?Ln("quota.window.premium"):t==="chat"?Ln("quota.window.chat"):t==="completions"?Ln("quota.window.completions"):t==="premium_interactions"?Ln("quota.window.premiumInteractions"):t,fJ=t=>{const e=t.toLowerCase().trim();if(e==="5h")return 5*3600;if(e==="7d"||e==="weekly"||e==="7d-sonnet"||e==="7d-opus")return 7*86400;if(e==="monthly")return 30*86400;if(e==="24h"||e==="daily")return 86400;if(e==="1h")return 3600;const n=e.match(/^(\d+)h$/);if(n)return parseInt(n[1],10)*3600;const s=e.match(/^(\d+)d$/);return s?parseInt(s[1],10)*86400:null},Dee=(t,e,n,s)=>{let o=n;if(o===null&&s&&(o=fJ(s)),t===null||e===null||o===null||o<=0)return null;const r=Date.now(),i=Math.max(0,(e-r)/1e3),l=Math.max(0,Math.min(o,o-i)),c=Math.max(0,Math.min(1,l/o)),d=t/100,u=t>=100&&i>0;let f;c>.01?f=Math.min(999,d/c*100):f=t;let m;u?m="exhausted":d<=c?m="on-track":f<=130?m="slightly-fast":m="too-fast";const h=o>=120*3600,p=h?86400:3600,b=h?"d":"h",w=o/p,v=Math.max(l/p,w*.01),x=t/v,y=Number.isFinite(x)?`${Math.min(999.9,Math.max(0,x)).toFixed(1)}%/${b}`:"-",k=f>100?`+${Math.round(f)}%`:`${Math.round(f)}%`;let C=null;const S=o/86400;return S>=7&&(C=100/S),{elapsedRatio:c,usageRatio:d,predictedFinalPercent:f,remainingSeconds:i,isExhausted:u,elapsedSeconds:l,totalSeconds:o,status:m,paceRateText:y,predictText:k,dailyAllocationPercent:C}},Pee=t=>{switch(t){case"exhausted":case"too-fast":return"var(--status-error)";case"slightly-fast":return"var(--status-warning)";case"on-track":return"var(--status-success)"}},Eee=t=>{const e=Math.max(0,Math.floor(t)),n=Math.floor(e/60),s=Math.floor(n/60),o=Math.floor(s/24),r=s%24,i=n%60;return o>0?`${o}d ${r}h`:s>0?`${s}h`:n===0?"<1m":`${i}m`},Iee=t=>Math.min(100,Math.max(0,t*100)),mJ=["standalone","minimal-ui","fullscreen","window-controls-overlay"],Jf="openchamber.pwaRecentSessions",hJ=t=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(`(display-mode: ${t})`).matches,Tee=()=>typeof window>"u"?"browser":typeof document<"u"&&document.referrer.startsWith("android-app://")?"twa":window.navigator.standalone?"standalone":mJ.find(n=>hJ(n))??"browser",pJ=1440*60*1e3,lv=5,Qf=1440*60*1e3,Ad=t=>t.time?.updated??t.time?.created??0,Xf=({sessions:t,currentSessionId:e,cutoffDays:n,keepRecent:s=lv,now:o=Date.now()})=>{if(!Array.isArray(t)||n<=0)return[];const r=o-n*pJ,i=[...t].sort((c,d)=>Ad(d)-Ad(c)),l=new Set(i.slice(0,s).map(c=>c.id));return i.filter(c=>{if(!c?.id||l.has(c.id)||c.id===e||c.share)return!1;const d=Ad(c);return d?d<r:!1}).map(c=>c.id)},gJ=t=>{const e=typeof t=="object"?t:void 0,n=e?.autoRun!==!1,s=typeof t=="boolean"?t:e?.enabled??!0,o=Ie(x=>x.currentSessionId),r=Ie(x=>x.isLoading),i=vn(x=>x.activeSessions),l=vn(x=>x.hasLoaded),c=Fe(x=>x.autoDeleteEnabled),d=Fe(x=>x.autoDeleteAfterDays),u=Fe(x=>x.sessionRetentionAction),f=Fe(x=>x.autoDeleteLastRunAt),m=Fe(x=>x.setAutoDeleteLastRunAt),[h,p]=g.useState(!1),b=g.useRef(!1);g.useEffect(()=>{o4(Er())},[]);const w=g.useMemo(()=>d<=0?[]:Xf({sessions:i,currentSessionId:o,cutoffDays:d}),[d,o,i]),v=g.useCallback(async({force:x=!1}={})=>{if(b.current)return{completedIds:[],failedIds:[],action:u,skippedReason:"running"};if((!c||d<=0)&&!x)return{completedIds:[],failedIds:[],action:u,skippedReason:"disabled"};if(r)return{completedIds:[],failedIds:[],action:u,skippedReason:"loading"};const y=Date.now();if(!x&&f&&y-f<Qf)return{completedIds:[],failedIds:[],action:u,skippedReason:"cooldown"};const{activeSessions:k}=await o4(Er());if(k.length===0)return{completedIds:[],failedIds:[],action:u,skippedReason:"no-candidates"};const C=Xf({sessions:k,currentSessionId:o,cutoffDays:d,now:y});if(C.length===0)return m(y),{completedIds:[],failedIds:[],action:u,skippedReason:"no-candidates"};b.current=!0,p(!0);try{const S=new Map(k.map(B=>[B.id,B])),M=[],A=[];for(const B of C){const F=S.get(B),_=F?J1(F):null;if(!_){A.push(B);continue}try{u==="archive"?await We.updateSession(B,{time:{archived:Date.now()}},_):await We.deleteSession(B,_),M.push(B)}catch{A.push(B)}}return u==="archive"?vn.getState().archiveSessions(M):vn.getState().removeSessions(M),{completedIds:M,failedIds:A,action:u}}finally{b.current=!1,p(!1),m(Date.now())}},[d,c,f,o,r,u,m]);return g.useEffect(()=>{if(!s||!n||!c||d<=0||r||!l||i.length===0)return;const x=Date.now();f&&x-f<Qf||v()},[d,c,f,n,s,l,i.length,r,v]),{candidates:w,isRunning:h,runCleanup:v,keepRecentCount:lv,action:u}},bJ=40,vJ=20*1024*1024,Yo=new Map;let pl=0;function yJ(t){return t.length*2}function cv(t,e){const n=Yo.get(t);n!==void 0&&(pl-=n),Yo.delete(t),Yo.set(t,e),pl+=e}function dv(t,e){const n=Yo.get(t);n===void 0&&e===void 0||cv(t,n??0)}function uv(t){const e=Yo.get(t);e!==void 0&&(Yo.delete(t),pl-=e)}function wJ(t,e){const n=t??new Set;for(;Yo.size>bJ||pl>vJ;){const s=Yo.keys().next().value;if(!s)return;if(n.has(s)){if(dv(s),Yo.size<=n.size)return;continue}uv(s),e(s)}}function xJ(t,e){cv(t,e)}function CJ(t){uv(t)}function kJ(t,e){dv(t,e)}function SJ(t){const e=new Map,n=f=>{e.delete(f),CJ(f)},s=f=>{const m=f.endsWith("/")?f:`${f}/`;for(const h of e.keys())(h===f||h.startsWith(m))&&n(h)},o=(f,m)=>m.isFile?f.mtimeMs!==void 0&&m.mtimeMs!==void 0?f.mtimeMs===m.mtimeMs&&f.size===m.size:f.size===m.size:!1,r=(f,m,h)=>{const p=yJ(m.content);return e.set(f,{...m,size:h?.isFile?h.size:void 0,mtimeMs:h?.isFile?h.mtimeMs:void 0}),xJ(f,p),wJ(new Set,w=>{e.delete(w)}),m},i=async(f,m)=>{const h=await t.statFile?.(f,m).catch(()=>null),p=await t.readFile(f,m),b=await t.statFile?.(f,m).catch(()=>null);if(h&&b&&h.isFile&&b.isFile){if(h.size===b.size&&h.mtimeMs===b.mtimeMs)return r(f,p,b);const w=await t.statFile?.(f,m).catch(()=>null),v=await t.readFile(f,m),x=await t.statFile?.(f,m).catch(()=>null);return w&&x&&w.isFile&&x.isFile&&w.size===x.size&&w.mtimeMs===x.mtimeMs,r(f,v,x)}return r(f,p,b??h)},l=t.readFile?async(f,m)=>{if(m?.allowOutsideWorkspace)return i(f,m);const h=e.get(f);if(h){if(t.statFile){const p=await t.statFile(f,m).catch(()=>(n(f),null));if(!p||!o(h,p))return n(f),i(f,m)}return kJ(f),{content:h.content,path:h.path}}return i(f,m)}:void 0,c=t.writeFile?async(f,m)=>(n(f),t.writeFile(f,m)):void 0,d=t.delete?async f=>(s(f),t.delete(f)):void 0,u=t.rename?async(f,m)=>(s(f),s(m),t.rename(f,m)):void 0;return{...t,readFile:l,writeFile:c,delete:d,rename:u}}function jee(t){const e=de.c(8),{apis:n,children:s}=t;let o;e[0]!==n.files?(o=SJ(n.files),e[0]=n.files,e[1]=o):o=e[1];let r;e[2]!==n||e[3]!==o?(r={...n,files:o},e[2]=n,e[3]=o,e[4]=r):r=e[4];const i=r;let l;return e[5]!==i||e[6]!==s?(l=a.jsx(wi.Provider,{value:i,children:s}),e[5]=i,e[6]=s,e[7]=l):l=e[7],l}const MJ="inset 0 1px 0 0 rgba(255,255,255,0.12), inset 0 0 0 1px rgba(255,255,255,0.08), 0 0 0 1px rgba(0,0,0,0.36), 0 1px 1px -0.5px rgba(0,0,0,0.22), 0 3px 3px -1.5px rgba(0,0,0,0.20), 0 6px 6px -3px rgba(0,0,0,0.16)",AJ="inset 0 1px 0 0 rgba(255,255,255,0.8), inset 0 0 0 1px rgba(0,0,0,0.04), 0 0 0 1px rgba(0,0,0,0.10), 0 1px 2px -0.5px rgba(0,0,0,0.08), 0 4px 8px -2px rgba(0,0,0,0.08), 0 12px 20px -4px rgba(0,0,0,0.08)";function FJ(){const t=de.c(2),e=_J,[n,s]=ae.useState(e);let o,r;return t[0]===Symbol.for("react.memo_cache_sentinel")?(o=()=>{const i=()=>s(e()),l=new MutationObserver(i);return l.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),i(),()=>l.disconnect()},r=[],t[0]=o,t[1]=r):(o=t[0],r=t[1]),ae.useEffect(o,r),n}function _J(){return typeof document<"u"&&document.documentElement.classList.contains("dark")}function BJ(t){const e=de.c(3);let n,s;e[0]!==t?(n=()=>{if(typeof document>"u")return;const o=l=>{l.style.setProperty("box-shadow",t,"important"),l.style.setProperty("outline","none","important"),l.getAttribute("tabindex")==="0"&&l.setAttribute("tabindex","-1")},r=()=>{document.querySelectorAll("[data-sonner-toast]").forEach(o)};r();const i=new MutationObserver(l=>{for(const c of l)c.addedNodes.forEach(d=>{d instanceof HTMLElement&&(d.matches?.("[data-sonner-toast]")&&o(d),d.querySelectorAll?.("[data-sonner-toast]").forEach(o))});r()});return i.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","tabindex","data-expanded","data-swiping"]}),()=>i.disconnect()},s=[t],e[0]=t,e[1]=n,e[2]=s):(n=e[1],s=e[2]),ae.useEffect(n,s)}const Hee=t=>{const e=de.c(7);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];const s=FJ();BJ(s?MJ:AJ);const r=s?"dark":"light";let i,l;e[2]===Symbol.for("react.memo_cache_sentinel")?(i={classNames:{toast:"group/toast toast !rounded-[var(--radius-xl)] !border-0 !px-3.5 !py-3 !gap-2.5 !text-foreground",title:"typography-ui-label !font-medium !text-foreground",description:"typography-meta !text-muted-foreground !mt-0.5",actionButton:"!rounded-[var(--radius-md)] !bg-[var(--primary-base)] !text-[var(--primary-foreground)] hover:!opacity-85 !px-2 !py-1 typography-meta !font-medium transition-opacity",cancelButton:"!rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-foreground hover:!bg-[var(--interactive-active)] !px-2 !py-1 typography-meta !font-medium transition-colors",closeButton:"!rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-foreground hover:!bg-[var(--interactive-active)]",icon:"!text-muted-foreground",success:"[&_[data-icon]]:!text-[var(--status-success)]",error:"[&_[data-icon]]:!text-[var(--status-error)]",warning:"[&_[data-icon]]:!text-[var(--status-warning)]",info:"[&_[data-icon]]:!text-[var(--status-info)]"},style:{borderRadius:"var(--radius-xl)",backgroundColor:"var(--surface-elevated)"}},l={"--normal-bg":"var(--surface-elevated)","--normal-text":"var(--foreground)","--normal-border":"transparent","--error-bg":"var(--surface-elevated)","--error-text":"var(--foreground)","--error-border":"transparent","--success-bg":"var(--surface-elevated)","--success-text":"var(--foreground)","--success-border":"transparent","--warning-bg":"var(--surface-elevated)","--warning-text":"var(--foreground)","--warning-border":"transparent","--info-bg":"var(--surface-elevated)","--info-text":"var(--foreground)","--info-border":"transparent"},e[2]=i,e[3]=l):(i=e[2],l=e[3]);let c;return e[4]!==n||e[5]!==r?(c=a.jsx(Wy,{theme:r,className:"toaster group",closeButton:!1,toastOptions:i,style:l,...n}),e[4]=n,e[5]=r,e[6]=c):c=e[6],c},DJ=2e4,fv=()=>typeof document>"u"||document.visibilityState==="visible"&&document.hasFocus()?"visible":"hidden",T5=t=>{if(!xl())return;const e=Ao();e?.push?.setVisibility&&e.push.setVisibility({visible:t})},Lee=t=>{const e=de.c(3),n=t?.enabled??!0;let s,o;e[0]!==n?(s=()=>{if(!n||!xl()||typeof document>"u")return;const r=PJ,i=EJ,l=IJ;r();const c=window.setInterval(i,DJ);return document.addEventListener("visibilitychange",r),window.addEventListener("pagehide",l),window.addEventListener("pageshow",r),window.addEventListener("focus",r),window.addEventListener("blur",r),()=>{window.clearInterval(c),document.removeEventListener("visibilitychange",r),window.removeEventListener("pagehide",l),window.removeEventListener("pageshow",r),window.removeEventListener("focus",r),window.removeEventListener("blur",r)}},o=[n],e[0]=n,e[1]=s,e[2]=o):(s=e[1],o=e[2]),g.useEffect(s,o)};function PJ(){T5(fv()==="visible")}function EJ(){fv()==="visible"&&T5(!0)}function IJ(){T5(!1)}const TJ="OpenChamber",em=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase()),jJ=t=>{const n=t.replace(/\\/g,"/").replace(/\/+$/,"").split("/").filter(Boolean);return n[n.length-1]??""},HJ=(t,e)=>[t,e,TJ].filter(s=>typeof s=="string"&&s.trim().length>0).join(" | "),Nee=()=>{const t=$t(r=>r.activeProjectId?r.projects.find(i=>i.id===r.activeProjectId)??null:null),e=g.useMemo(()=>{if(!t)return null;const r=t.label?.trim();if(r)return em(r);const i=jJ(t.path);return i?em(i):null},[t]),[n,s]=g.useState(null);g.useEffect(()=>{if(typeof window>"u"||!qt()){s(null);return}let r=!1;const i=async()=>{try{if(km()){r||s(null);return}const c=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,d=bi();if(d&&Ji(d,c)){r||s(null);return}const f=(await K3()).hosts.find(h=>d?Ji(d,Br(h)):!1),m=f?.label?.trim()?cs(f.label.trim()):"Instance";r||s(m)}catch{r||s("Instance")}};i();const l=()=>{i()};return window.addEventListener("focus",l),()=>{r=!0,window.removeEventListener("focus",l)}},[]);const o=g.useMemo(()=>HJ(e,n),[e,n]);g.useEffect(()=>{if(typeof document<"u"&&(document.title=o),!qt())return;(async()=>{try{if(typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""))return;await IT(o)}catch{return}})()},[o])},LJ=()=>{const e=Ie.getState().currentSessionId;if(!e)return"";const s=Ki().find(o=>o.id===e);return typeof s?.directory=="string"?s.directory:""},NJ=async(t,e=6e3)=>{const n=new AbortController,s=setTimeout(()=>n.abort(),e),o=Date.now();try{const r=await nt(t,{method:"GET",headers:{Accept:"application/json"},signal:n.signal}),i=Date.now()-o,l=r.headers.get("content-type")||"",c=l.toLowerCase(),d=c.includes("json")&&!c.includes("text/html");let u="";if(d){const f=await r.json().catch(()=>null);if(Array.isArray(f))u=`json[array] len=${f.length}`;else if(f&&typeof f=="object"){const m=Object.keys(f).slice(0,8);u=`json[object] keys=${m.join(",")}${Object.keys(f).length>m.length?",…":""}`}else u=`json[${typeof f}]`}else u=l?`content-type=${l}`:"no content-type";return{ok:r.ok&&d,status:r.status,elapsedMs:i,summary:u}}catch(r){const i=Date.now()-o,c=n.signal.aborted||r instanceof Error&&(r.name==="AbortError"||r.message.toLowerCase().includes("aborted"))?`timeout after ${e}ms`:r instanceof Error?r.message:String(r);return{ok:!1,status:0,elapsedMs:i,summary:`error=${c}`}}finally{clearTimeout(s)}},VJ=t=>{if(!t||!Number.isFinite(t))return"(n/a)";try{return new Date(t).toISOString()}catch{return"(invalid)"}},RJ=t=>{if(typeof t=="number"&&Number.isFinite(t)&&t>0)return Math.trunc(t);if(typeof t=="string"){const e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return null},zJ=t=>!!t&&typeof t=="object"&&!Array.isArray(t),br=(t,e="(n/a)")=>typeof t=="string"?t.trim()||e:typeof t=="number"&&Number.isFinite(t)?String(t):typeof t=="boolean"?t?"true":"false":e,tm=(t,e,n)=>t==="node-shebang"||t==="node-launcher"?e?`node (${e})`:"node":t==="bun-shebang"?n?`bun (${n})`:"bun":t||"direct executable",OJ=async()=>{const t=new Date,e="1.13.4",n=typeof navigator<"u"?navigator.userAgent:"(no navigator)",s=LJ(),o=Fe.getState().eventStreamStatus,r=typeof window<"u"?window.location.origin:"",i=wm(),l=i.health(),c=i.api("/api/"),d=await(async()=>{if(!l)return null;const v=new AbortController,x=setTimeout(()=>v.abort(),5e3);try{const y=await nt(l,{method:"GET",headers:{Accept:"application/json"},signal:v.signal});if(!y.ok)return null;const k=await y.json().catch(()=>null);return!k||typeof k!="object"||Array.isArray(k)?null:k}catch{return null}finally{clearTimeout(x)}})(),u=await(async()=>{if(!c)return null;const v=new AbortController,x=setTimeout(()=>v.abort(),7e3);try{const y=await nt(i.api("/api/config/opencode-resolution"),{method:"GET",headers:{Accept:"application/json"},signal:v.signal}),k=y.headers.get("content-type")||"(none)";if(!y.ok)return{data:null,status:y.status,error:`http ${y.status} content-type=${k}`};const C=await y.text();let S=null;try{S=JSON.parse(C)}catch{const M=C.replace(/\s+/g," ").slice(0,120);return{data:null,status:y.status,error:`invalid json content-type=${k} body=${M||"(empty)"}`}}return!S||typeof S!="object"||Array.isArray(S)?{data:null,status:y.status,error:`invalid json-shape content-type=${k}`}:{data:S,status:y.status,error:null}}catch(y){return{data:null,status:null,error:y instanceof Error?y.message:String(y)}}finally{clearTimeout(x)}})()||{data:null,error:null},f=(v,x=!0)=>{if(!c)return null;const y=new URL(v.replace(/^\/+/,""),c);return x&&s&&y.searchParams.set("directory",s),y.toString()},m=[{label:"health",path:"/health",includeDirectory:!1},{label:"config",path:"/config",includeDirectory:!0},{label:"providers",path:"/config/providers",includeDirectory:!0},{label:"agents",path:"/agent",includeDirectory:!0,timeoutMs:12e3},{label:"commands",path:"/command",includeDirectory:!0,timeoutMs:1e4},{label:"project",path:"/project/current",includeDirectory:!0},{label:"path",path:"/path",includeDirectory:!0},{label:"sessions",path:"/session",includeDirectory:!0,timeoutMs:12e3},{label:"sessionStatus",path:"/session/status",includeDirectory:!0}],h=c?await Promise.all(m.map(async v=>{const x=f(v.path,v.includeDirectory!==!1);if(!x)return{label:v.label,url:"(none)",result:null};const y=await NJ(x,typeof v.timeoutMs=="number"?v.timeoutMs:void 0);return{label:v.label,url:x,result:y}})):[],p=[];p.push(`Time: ${t.toISOString()}`),p.push(`OpenChamber version: ${e}`),p.push(`Runtime: ${r||"(unknown)"} (api=${c||"(unknown)"})`),p.push(`OpenCode SDK base: ${We.getBaseUrl()}`),p.push(`Event stream: ${o}`),p.push(`Directory: ${s||"(none)"}`),p.push(`Platform: ${n}`);const b=RJ(d?.openCodePort);if(p.push(`OpenCode runtime port: ${b??"(unknown)"}`),typeof d?.openCodeRunning=="boolean"&&p.push(`OpenCode runtime running: ${d.openCodeRunning?"yes":"no"}`),typeof d?.openCodeSecureConnection=="boolean"&&p.push(`Secure OpenCode connection: ${d.openCodeSecureConnection?"true":"false"}`),typeof d?.openCodeAuthSource=="string"&&d.openCodeAuthSource.trim()&&p.push(`OpenCode auth source: ${d.openCodeAuthSource}`),typeof window<"u"){const v=window.__OPENCHAMBER_MACOS_MAJOR__;typeof v=="number"&&Number.isFinite(v)&&v>0&&p.push(`macOS major: ${v}`)}if(/Mac OS X|Macintosh/.test(n)){p.push(""),p.push("OpenCode CLI resolution:");const v=zJ(d?.lastOpenCodeLaunchDiagnostics)?d.lastOpenCodeLaunchDiagnostics:null,x=v&&Array.isArray(v.args)?v.args.filter(T=>typeof T=="string"):[],y=u.data,k=y&&typeof y.configured=="string"?y.configured:null,C=y&&typeof y.resolved=="string"?y.resolved:d&&typeof d.opencodeBinaryResolved=="string"?d.opencodeBinaryResolved:"",S=y&&typeof y.resolvedDir=="string"?y.resolvedDir:"",M=y&&typeof y.source=="string"?y.source:d&&typeof d.opencodeBinarySource=="string"?d.opencodeBinarySource:"",A=y&&typeof y.launchBinary=="string"?y.launchBinary:d&&typeof d.opencodeLaunchBinary=="string"?d.opencodeLaunchBinary:"",B=y&&typeof y.launchWrapperType=="string"?y.launchWrapperType:d&&typeof d.opencodeLaunchWrapperType=="string"?d.opencodeLaunchWrapperType:"",F=y&&Array.isArray(y.launchArgs)?y.launchArgs.filter(T=>typeof T=="string"):d&&Array.isArray(d.opencodeLaunchArgs)?d.opencodeLaunchArgs.filter(T=>typeof T=="string"):[],_=y&&typeof y.node=="string"?y.node:d&&typeof d.nodeBinaryResolved=="string"?d.nodeBinaryResolved:"",D=y&&typeof y.bun=="string"?y.bun:d&&typeof d.bunBinaryResolved=="string"?d.bunBinaryResolved:"",E=y&&typeof y.detectedNow=="string"?y.detectedNow:"",I=y&&typeof y.detectedSourceNow=="string"?y.detectedSourceNow:"";if(k!==null&&p.push(`- configured: ${k.trim().length===0?"(cleared)":k}`),C){const T=S||(C.includes("/")?C.split("/").slice(0,-1).join("/")||"/":"");p.push(`- opencode: ${C}${T?` (dir=${T})`:""}`)}else p.push("- opencode: (n/a)");p.push(`- source: ${M||"(n/a)"}`),E&&(p.push(`- detected-now: ${E}`),p.push(`- detected-source: ${I||"(n/a)"}`)),v?(p.push(`- launched-at: ${br(v.launchedAt)}`),p.push(`- launch: ${br(v.binary)} ${x.join(" ")}`.trim()),p.push(`- cwd: ${br(v.cwd)}`),p.push(`- wrapper: ${br(v.wrapperType)}`),p.push(`- runtime: ${tm(br(v.wrapperType,""),_,D)}`),p.push(`- PATH entries: ${br(v.pathEntryCount,"(unknown)")}`),p.push(`- shell env: ${br(v.hasShellEnv,"(unknown)")} (${br(v.shellEnvKeysCount,"?")} keys)`)):(p.push(`- launch-binary: ${A||"(n/a)"}`),p.push(`- launch-wrapper: ${B||"(n/a)"}`),p.push(`- launch-args: ${F.length?F.join(" "):"(none)"}`),p.push(`- runtime: ${tm(B||"",_,D)}`)),!y&&u.error&&p.push(`- resolution-endpoint: ${u.error}`)}if(p.push(""),h.length){p.push("OpenCode API probes:");for(const v of h){if(!v.result){p.push(`- ${v.label}: (no url)`);continue}const{ok:x,status:y,elapsedMs:k,summary:C}=v.result,S=x?"":` url=${v.url}`;p.push(`- ${v.label}: ${x?"ok":"fail"} status=${y} time=${k}ms ${C}${S}`)}}else p.push("OpenCode API probes: (skipped)");return p.push(""),p.push(`Generated: ${VJ(Date.now())}`),p.join(`
7146
+ ${e.componentStackLabel}${this.state.errorInfo.componentStack}`:""]})]}),a.jsxs("div",{className:"flex gap-2",children:[a.jsxs(bt,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[a.jsx(q,{name:"restart",className:"h-4 w-4 mr-2"}),e.tryAgain]}),a.jsx(bt,{onClick:this.handleCopy,variant:"outline",className:"flex-1",children:this.state.copied?e.copied:e.copy})]})]})]})}):this.props.children}}const See=t=>{const e=de.c(29),{children:n,fallback:s}=t,{t:o}=Ye();let r;e[0]!==o?(r=o("errorBoundary.state.unknownError"),e[0]=o,e[1]=r):r=e[1];let i;e[2]!==o?(i=o("errorBoundary.title"),e[2]=o,e[3]=i):i=e[3];let l;e[4]!==o?(l=o("errorBoundary.description"),e[4]=o,e[5]=l):l=e[5];let c;e[6]!==o?(c=o("errorBoundary.actions.errorDetails"),e[6]=o,e[7]=c):c=e[7];let d;e[8]!==o?(d=o("errorBoundary.state.componentStackLabel"),e[8]=o,e[9]=d):d=e[9];let u;e[10]!==o?(u=o("errorBoundary.actions.tryAgain"),e[10]=o,e[11]=u):u=e[11];let f;e[12]!==o?(f=o("errorBoundary.actions.copied"),e[12]=o,e[13]=f):f=e[13];let m;e[14]!==o?(m=o("errorBoundary.actions.copy"),e[14]=o,e[15]=m):m=e[15];let h;e[16]!==r||e[17]!==i||e[18]!==l||e[19]!==c||e[20]!==d||e[21]!==u||e[22]!==f||e[23]!==m?(h={unknownError:r,title:i,description:l,detailsSummary:c,componentStackLabel:d,tryAgain:u,copied:f,copy:m},e[16]=r,e[17]=i,e[18]=l,e[19]=c,e[20]=d,e[21]=u,e[22]=f,e[23]=m,e[24]=h):h=e[24];const p=h;let b;return e[25]!==n||e[26]!==s||e[27]!==p?(b=a.jsx(dJ,{fallback:s,strings:p,children:n}),e[25]=n,e[26]=s,e[27]=p,e[28]=b):b=e[28],b},Ln=t=>Q1(Go.getState().dictionary,t),Mee=t=>typeof t!="number"||!Number.isFinite(t)?null:Math.max(0,Math.min(100,Math.round(t))),uJ=t=>typeof t!="number"||!Number.isFinite(t)?"-":`${Math.round(t)}%`,Aee=(t,e)=>t??uJ(e),Fee=(t,e,n="auto")=>{if(!t)return e??"";try{const s=new Date(t);if(!Number.isFinite(s.getTime()))return e??"";const o=new Date;return s.toDateString()===o.toDateString()?Bb(s,n,{fallback:e??""}):lW(s,n,{month:"short",day:"numeric",weekday:"short",hour:"numeric",minute:"2-digit"})}catch{return e??""}},_ee=t=>t===null?"safe":t>=80?"critical":t>=50?"warn":"safe",Bee=t=>t==="5h"?Ln("quota.window.5h"):t==="7d"?Ln("quota.window.7d"):t==="7d-sonnet"?Ln("quota.window.7dSonnet"):t==="7d-opus"?Ln("quota.window.7dOpus"):t==="weekly"?Ln("quota.window.weekly"):t==="daily"?Ln("quota.window.daily"):t==="monthly"?Ln("quota.window.monthly"):t==="credits"?Ln("quota.window.credits"):t==="credits_balance"?Ln("quota.window.creditsBalance"):t==="billing_cycle"?Ln("quota.window.billingCycle"):t==="auto"?Ln("quota.window.auto"):t==="api"?Ln("quota.window.api"):t==="plan_limit"?Ln("quota.window.planLimit"):t==="on_demand"?Ln("quota.window.onDemand"):t==="session"?Ln("quota.window.session"):t==="premium"?Ln("quota.window.premium"):t==="chat"?Ln("quota.window.chat"):t==="completions"?Ln("quota.window.completions"):t==="premium_interactions"?Ln("quota.window.premiumInteractions"):t,fJ=t=>{const e=t.toLowerCase().trim();if(e==="5h")return 5*3600;if(e==="7d"||e==="weekly"||e==="7d-sonnet"||e==="7d-opus")return 7*86400;if(e==="monthly")return 30*86400;if(e==="24h"||e==="daily")return 86400;if(e==="1h")return 3600;const n=e.match(/^(\d+)h$/);if(n)return parseInt(n[1],10)*3600;const s=e.match(/^(\d+)d$/);return s?parseInt(s[1],10)*86400:null},Dee=(t,e,n,s)=>{let o=n;if(o===null&&s&&(o=fJ(s)),t===null||e===null||o===null||o<=0)return null;const r=Date.now(),i=Math.max(0,(e-r)/1e3),l=Math.max(0,Math.min(o,o-i)),c=Math.max(0,Math.min(1,l/o)),d=t/100,u=t>=100&&i>0;let f;c>.01?f=Math.min(999,d/c*100):f=t;let m;u?m="exhausted":d<=c?m="on-track":f<=130?m="slightly-fast":m="too-fast";const h=o>=120*3600,p=h?86400:3600,b=h?"d":"h",w=o/p,v=Math.max(l/p,w*.01),x=t/v,y=Number.isFinite(x)?`${Math.min(999.9,Math.max(0,x)).toFixed(1)}%/${b}`:"-",k=f>100?`+${Math.round(f)}%`:`${Math.round(f)}%`;let C=null;const S=o/86400;return S>=7&&(C=100/S),{elapsedRatio:c,usageRatio:d,predictedFinalPercent:f,remainingSeconds:i,isExhausted:u,elapsedSeconds:l,totalSeconds:o,status:m,paceRateText:y,predictText:k,dailyAllocationPercent:C}},Pee=t=>{switch(t){case"exhausted":case"too-fast":return"var(--status-error)";case"slightly-fast":return"var(--status-warning)";case"on-track":return"var(--status-success)"}},Eee=t=>{const e=Math.max(0,Math.floor(t)),n=Math.floor(e/60),s=Math.floor(n/60),o=Math.floor(s/24),r=s%24,i=n%60;return o>0?`${o}d ${r}h`:s>0?`${s}h`:n===0?"<1m":`${i}m`},Iee=t=>Math.min(100,Math.max(0,t*100)),mJ=["standalone","minimal-ui","fullscreen","window-controls-overlay"],Jf="openchamber.pwaRecentSessions",hJ=t=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(`(display-mode: ${t})`).matches,Tee=()=>typeof window>"u"?"browser":typeof document<"u"&&document.referrer.startsWith("android-app://")?"twa":window.navigator.standalone?"standalone":mJ.find(n=>hJ(n))??"browser",pJ=1440*60*1e3,lv=5,Qf=1440*60*1e3,Ad=t=>t.time?.updated??t.time?.created??0,Xf=({sessions:t,currentSessionId:e,cutoffDays:n,keepRecent:s=lv,now:o=Date.now()})=>{if(!Array.isArray(t)||n<=0)return[];const r=o-n*pJ,i=[...t].sort((c,d)=>Ad(d)-Ad(c)),l=new Set(i.slice(0,s).map(c=>c.id));return i.filter(c=>{if(!c?.id||l.has(c.id)||c.id===e||c.share)return!1;const d=Ad(c);return d?d<r:!1}).map(c=>c.id)},gJ=t=>{const e=typeof t=="object"?t:void 0,n=e?.autoRun!==!1,s=typeof t=="boolean"?t:e?.enabled??!0,o=Ie(x=>x.currentSessionId),r=Ie(x=>x.isLoading),i=vn(x=>x.activeSessions),l=vn(x=>x.hasLoaded),c=Fe(x=>x.autoDeleteEnabled),d=Fe(x=>x.autoDeleteAfterDays),u=Fe(x=>x.sessionRetentionAction),f=Fe(x=>x.autoDeleteLastRunAt),m=Fe(x=>x.setAutoDeleteLastRunAt),[h,p]=g.useState(!1),b=g.useRef(!1);g.useEffect(()=>{o4(Er())},[]);const w=g.useMemo(()=>d<=0?[]:Xf({sessions:i,currentSessionId:o,cutoffDays:d}),[d,o,i]),v=g.useCallback(async({force:x=!1}={})=>{if(b.current)return{completedIds:[],failedIds:[],action:u,skippedReason:"running"};if((!c||d<=0)&&!x)return{completedIds:[],failedIds:[],action:u,skippedReason:"disabled"};if(r)return{completedIds:[],failedIds:[],action:u,skippedReason:"loading"};const y=Date.now();if(!x&&f&&y-f<Qf)return{completedIds:[],failedIds:[],action:u,skippedReason:"cooldown"};const{activeSessions:k}=await o4(Er());if(k.length===0)return{completedIds:[],failedIds:[],action:u,skippedReason:"no-candidates"};const C=Xf({sessions:k,currentSessionId:o,cutoffDays:d,now:y});if(C.length===0)return m(y),{completedIds:[],failedIds:[],action:u,skippedReason:"no-candidates"};b.current=!0,p(!0);try{const S=new Map(k.map(B=>[B.id,B])),M=[],A=[];for(const B of C){const F=S.get(B),_=F?J1(F):null;if(!_){A.push(B);continue}try{u==="archive"?await We.updateSession(B,{time:{archived:Date.now()}},_):await We.deleteSession(B,_),M.push(B)}catch{A.push(B)}}return u==="archive"?vn.getState().archiveSessions(M):vn.getState().removeSessions(M),{completedIds:M,failedIds:A,action:u}}finally{b.current=!1,p(!1),m(Date.now())}},[d,c,f,o,r,u,m]);return g.useEffect(()=>{if(!s||!n||!c||d<=0||r||!l||i.length===0)return;const x=Date.now();f&&x-f<Qf||v()},[d,c,f,n,s,l,i.length,r,v]),{candidates:w,isRunning:h,runCleanup:v,keepRecentCount:lv,action:u}},bJ=40,vJ=20*1024*1024,Yo=new Map;let pl=0;function yJ(t){return t.length*2}function cv(t,e){const n=Yo.get(t);n!==void 0&&(pl-=n),Yo.delete(t),Yo.set(t,e),pl+=e}function dv(t,e){const n=Yo.get(t);n===void 0&&e===void 0||cv(t,n??0)}function uv(t){const e=Yo.get(t);e!==void 0&&(Yo.delete(t),pl-=e)}function wJ(t,e){const n=t??new Set;for(;Yo.size>bJ||pl>vJ;){const s=Yo.keys().next().value;if(!s)return;if(n.has(s)){if(dv(s),Yo.size<=n.size)return;continue}uv(s),e(s)}}function xJ(t,e){cv(t,e)}function CJ(t){uv(t)}function kJ(t,e){dv(t,e)}function SJ(t){const e=new Map,n=f=>{e.delete(f),CJ(f)},s=f=>{const m=f.endsWith("/")?f:`${f}/`;for(const h of e.keys())(h===f||h.startsWith(m))&&n(h)},o=(f,m)=>m.isFile?f.mtimeMs!==void 0&&m.mtimeMs!==void 0?f.mtimeMs===m.mtimeMs&&f.size===m.size:f.size===m.size:!1,r=(f,m,h)=>{const p=yJ(m.content);return e.set(f,{...m,size:h?.isFile?h.size:void 0,mtimeMs:h?.isFile?h.mtimeMs:void 0}),xJ(f,p),wJ(new Set,w=>{e.delete(w)}),m},i=async(f,m)=>{const h=await t.statFile?.(f,m).catch(()=>null),p=await t.readFile(f,m),b=await t.statFile?.(f,m).catch(()=>null);if(h&&b&&h.isFile&&b.isFile){if(h.size===b.size&&h.mtimeMs===b.mtimeMs)return r(f,p,b);const w=await t.statFile?.(f,m).catch(()=>null),v=await t.readFile(f,m),x=await t.statFile?.(f,m).catch(()=>null);return w&&x&&w.isFile&&x.isFile&&w.size===x.size&&w.mtimeMs===x.mtimeMs,r(f,v,x)}return r(f,p,b??h)},l=t.readFile?async(f,m)=>{if(m?.allowOutsideWorkspace)return i(f,m);const h=e.get(f);if(h){if(t.statFile){const p=await t.statFile(f,m).catch(()=>(n(f),null));if(!p||!o(h,p))return n(f),i(f,m)}return kJ(f),{content:h.content,path:h.path}}return i(f,m)}:void 0,c=t.writeFile?async(f,m)=>(n(f),t.writeFile(f,m)):void 0,d=t.delete?async f=>(s(f),t.delete(f)):void 0,u=t.rename?async(f,m)=>(s(f),s(m),t.rename(f,m)):void 0;return{...t,readFile:l,writeFile:c,delete:d,rename:u}}function jee(t){const e=de.c(8),{apis:n,children:s}=t;let o;e[0]!==n.files?(o=SJ(n.files),e[0]=n.files,e[1]=o):o=e[1];let r;e[2]!==n||e[3]!==o?(r={...n,files:o},e[2]=n,e[3]=o,e[4]=r):r=e[4];const i=r;let l;return e[5]!==i||e[6]!==s?(l=a.jsx(wi.Provider,{value:i,children:s}),e[5]=i,e[6]=s,e[7]=l):l=e[7],l}const MJ="inset 0 1px 0 0 rgba(255,255,255,0.12), inset 0 0 0 1px rgba(255,255,255,0.08), 0 0 0 1px rgba(0,0,0,0.36), 0 1px 1px -0.5px rgba(0,0,0,0.22), 0 3px 3px -1.5px rgba(0,0,0,0.20), 0 6px 6px -3px rgba(0,0,0,0.16)",AJ="inset 0 1px 0 0 rgba(255,255,255,0.8), inset 0 0 0 1px rgba(0,0,0,0.04), 0 0 0 1px rgba(0,0,0,0.10), 0 1px 2px -0.5px rgba(0,0,0,0.08), 0 4px 8px -2px rgba(0,0,0,0.08), 0 12px 20px -4px rgba(0,0,0,0.08)";function FJ(){const t=de.c(2),e=_J,[n,s]=ae.useState(e);let o,r;return t[0]===Symbol.for("react.memo_cache_sentinel")?(o=()=>{const i=()=>s(e()),l=new MutationObserver(i);return l.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),i(),()=>l.disconnect()},r=[],t[0]=o,t[1]=r):(o=t[0],r=t[1]),ae.useEffect(o,r),n}function _J(){return typeof document<"u"&&document.documentElement.classList.contains("dark")}function BJ(t){const e=de.c(3);let n,s;e[0]!==t?(n=()=>{if(typeof document>"u")return;const o=l=>{l.style.setProperty("box-shadow",t,"important"),l.style.setProperty("outline","none","important"),l.getAttribute("tabindex")==="0"&&l.setAttribute("tabindex","-1")},r=()=>{document.querySelectorAll("[data-sonner-toast]").forEach(o)};r();const i=new MutationObserver(l=>{for(const c of l)c.addedNodes.forEach(d=>{d instanceof HTMLElement&&(d.matches?.("[data-sonner-toast]")&&o(d),d.querySelectorAll?.("[data-sonner-toast]").forEach(o))});r()});return i.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","tabindex","data-expanded","data-swiping"]}),()=>i.disconnect()},s=[t],e[0]=t,e[1]=n,e[2]=s):(n=e[1],s=e[2]),ae.useEffect(n,s)}const Hee=t=>{const e=de.c(7);let n;e[0]!==t?({...n}=t,e[0]=t,e[1]=n):n=e[1];const s=FJ();BJ(s?MJ:AJ);const r=s?"dark":"light";let i,l;e[2]===Symbol.for("react.memo_cache_sentinel")?(i={classNames:{toast:"group/toast toast !rounded-[var(--radius-xl)] !border-0 !px-3.5 !py-3 !gap-2.5 !text-foreground",title:"typography-ui-label !font-medium !text-foreground",description:"typography-meta !text-muted-foreground !mt-0.5",actionButton:"!rounded-[var(--radius-md)] !bg-[var(--primary-base)] !text-[var(--primary-foreground)] hover:!opacity-85 !px-2 !py-1 typography-meta !font-medium transition-opacity",cancelButton:"!rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-foreground hover:!bg-[var(--interactive-active)] !px-2 !py-1 typography-meta !font-medium transition-colors",closeButton:"!rounded-[var(--radius-md)] !bg-[var(--interactive-hover)] !text-foreground hover:!bg-[var(--interactive-active)]",icon:"!text-muted-foreground",success:"[&_[data-icon]]:!text-[var(--status-success)]",error:"[&_[data-icon]]:!text-[var(--status-error)]",warning:"[&_[data-icon]]:!text-[var(--status-warning)]",info:"[&_[data-icon]]:!text-[var(--status-info)]"},style:{borderRadius:"var(--radius-xl)",backgroundColor:"var(--surface-elevated)"}},l={"--normal-bg":"var(--surface-elevated)","--normal-text":"var(--foreground)","--normal-border":"transparent","--error-bg":"var(--surface-elevated)","--error-text":"var(--foreground)","--error-border":"transparent","--success-bg":"var(--surface-elevated)","--success-text":"var(--foreground)","--success-border":"transparent","--warning-bg":"var(--surface-elevated)","--warning-text":"var(--foreground)","--warning-border":"transparent","--info-bg":"var(--surface-elevated)","--info-text":"var(--foreground)","--info-border":"transparent"},e[2]=i,e[3]=l):(i=e[2],l=e[3]);let c;return e[4]!==n||e[5]!==r?(c=a.jsx(Wy,{theme:r,className:"toaster group",closeButton:!1,toastOptions:i,style:l,...n}),e[4]=n,e[5]=r,e[6]=c):c=e[6],c},DJ=2e4,fv=()=>typeof document>"u"||document.visibilityState==="visible"&&document.hasFocus()?"visible":"hidden",T5=t=>{if(!xl())return;const e=Ao();e?.push?.setVisibility&&e.push.setVisibility({visible:t})},Lee=t=>{const e=de.c(3),n=t?.enabled??!0;let s,o;e[0]!==n?(s=()=>{if(!n||!xl()||typeof document>"u")return;const r=PJ,i=EJ,l=IJ;r();const c=window.setInterval(i,DJ);return document.addEventListener("visibilitychange",r),window.addEventListener("pagehide",l),window.addEventListener("pageshow",r),window.addEventListener("focus",r),window.addEventListener("blur",r),()=>{window.clearInterval(c),document.removeEventListener("visibilitychange",r),window.removeEventListener("pagehide",l),window.removeEventListener("pageshow",r),window.removeEventListener("focus",r),window.removeEventListener("blur",r)}},o=[n],e[0]=n,e[1]=s,e[2]=o):(s=e[1],o=e[2]),g.useEffect(s,o)};function PJ(){T5(fv()==="visible")}function EJ(){fv()==="visible"&&T5(!0)}function IJ(){T5(!1)}const TJ="OpenChamber",em=t=>t.replace(/[-_]/g," ").replace(/\b\w/g,e=>e.toUpperCase()),jJ=t=>{const n=t.replace(/\\/g,"/").replace(/\/+$/,"").split("/").filter(Boolean);return n[n.length-1]??""},HJ=(t,e)=>[t,e,TJ].filter(s=>typeof s=="string"&&s.trim().length>0).join(" | "),Nee=()=>{const t=$t(r=>r.activeProjectId?r.projects.find(i=>i.id===r.activeProjectId)??null:null),e=g.useMemo(()=>{if(!t)return null;const r=t.label?.trim();if(r)return em(r);const i=jJ(t.path);return i?em(i):null},[t]),[n,s]=g.useState(null);g.useEffect(()=>{if(typeof window>"u"||!qt()){s(null);return}let r=!1;const i=async()=>{try{if(km()){r||s(null);return}const c=window.__OPENCHAMBER_LOCAL_ORIGIN__||window.location.origin,d=bi();if(d&&Ji(d,c)){r||s(null);return}const f=(await K3()).hosts.find(h=>d?Ji(d,Br(h)):!1),m=f?.label?.trim()?cs(f.label.trim()):"Instance";r||s(m)}catch{r||s("Instance")}};i();const l=()=>{i()};return window.addEventListener("focus",l),()=>{r=!0,window.removeEventListener("focus",l)}},[]);const o=g.useMemo(()=>HJ(e,n),[e,n]);g.useEffect(()=>{if(typeof document<"u"&&(document.title=o),!qt())return;(async()=>{try{if(typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""))return;await IT(o)}catch{return}})()},[o])},LJ=()=>{const e=Ie.getState().currentSessionId;if(!e)return"";const s=Ki().find(o=>o.id===e);return typeof s?.directory=="string"?s.directory:""},NJ=async(t,e=6e3)=>{const n=new AbortController,s=setTimeout(()=>n.abort(),e),o=Date.now();try{const r=await nt(t,{method:"GET",headers:{Accept:"application/json"},signal:n.signal}),i=Date.now()-o,l=r.headers.get("content-type")||"",c=l.toLowerCase(),d=c.includes("json")&&!c.includes("text/html");let u="";if(d){const f=await r.json().catch(()=>null);if(Array.isArray(f))u=`json[array] len=${f.length}`;else if(f&&typeof f=="object"){const m=Object.keys(f).slice(0,8);u=`json[object] keys=${m.join(",")}${Object.keys(f).length>m.length?",…":""}`}else u=`json[${typeof f}]`}else u=l?`content-type=${l}`:"no content-type";return{ok:r.ok&&d,status:r.status,elapsedMs:i,summary:u}}catch(r){const i=Date.now()-o,c=n.signal.aborted||r instanceof Error&&(r.name==="AbortError"||r.message.toLowerCase().includes("aborted"))?`timeout after ${e}ms`:r instanceof Error?r.message:String(r);return{ok:!1,status:0,elapsedMs:i,summary:`error=${c}`}}finally{clearTimeout(s)}},VJ=t=>{if(!t||!Number.isFinite(t))return"(n/a)";try{return new Date(t).toISOString()}catch{return"(invalid)"}},RJ=t=>{if(typeof t=="number"&&Number.isFinite(t)&&t>0)return Math.trunc(t);if(typeof t=="string"){const e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return null},zJ=t=>!!t&&typeof t=="object"&&!Array.isArray(t),br=(t,e="(n/a)")=>typeof t=="string"?t.trim()||e:typeof t=="number"&&Number.isFinite(t)?String(t):typeof t=="boolean"?t?"true":"false":e,tm=(t,e,n)=>t==="node-shebang"||t==="node-launcher"?e?`node (${e})`:"node":t==="bun-shebang"?n?`bun (${n})`:"bun":t||"direct executable",OJ=async()=>{const t=new Date,e="1.13.5",n=typeof navigator<"u"?navigator.userAgent:"(no navigator)",s=LJ(),o=Fe.getState().eventStreamStatus,r=typeof window<"u"?window.location.origin:"",i=wm(),l=i.health(),c=i.api("/api/"),d=await(async()=>{if(!l)return null;const v=new AbortController,x=setTimeout(()=>v.abort(),5e3);try{const y=await nt(l,{method:"GET",headers:{Accept:"application/json"},signal:v.signal});if(!y.ok)return null;const k=await y.json().catch(()=>null);return!k||typeof k!="object"||Array.isArray(k)?null:k}catch{return null}finally{clearTimeout(x)}})(),u=await(async()=>{if(!c)return null;const v=new AbortController,x=setTimeout(()=>v.abort(),7e3);try{const y=await nt(i.api("/api/config/opencode-resolution"),{method:"GET",headers:{Accept:"application/json"},signal:v.signal}),k=y.headers.get("content-type")||"(none)";if(!y.ok)return{data:null,status:y.status,error:`http ${y.status} content-type=${k}`};const C=await y.text();let S=null;try{S=JSON.parse(C)}catch{const M=C.replace(/\s+/g," ").slice(0,120);return{data:null,status:y.status,error:`invalid json content-type=${k} body=${M||"(empty)"}`}}return!S||typeof S!="object"||Array.isArray(S)?{data:null,status:y.status,error:`invalid json-shape content-type=${k}`}:{data:S,status:y.status,error:null}}catch(y){return{data:null,status:null,error:y instanceof Error?y.message:String(y)}}finally{clearTimeout(x)}})()||{data:null,error:null},f=(v,x=!0)=>{if(!c)return null;const y=new URL(v.replace(/^\/+/,""),c);return x&&s&&y.searchParams.set("directory",s),y.toString()},m=[{label:"health",path:"/health",includeDirectory:!1},{label:"config",path:"/config",includeDirectory:!0},{label:"providers",path:"/config/providers",includeDirectory:!0},{label:"agents",path:"/agent",includeDirectory:!0,timeoutMs:12e3},{label:"commands",path:"/command",includeDirectory:!0,timeoutMs:1e4},{label:"project",path:"/project/current",includeDirectory:!0},{label:"path",path:"/path",includeDirectory:!0},{label:"sessions",path:"/session",includeDirectory:!0,timeoutMs:12e3},{label:"sessionStatus",path:"/session/status",includeDirectory:!0}],h=c?await Promise.all(m.map(async v=>{const x=f(v.path,v.includeDirectory!==!1);if(!x)return{label:v.label,url:"(none)",result:null};const y=await NJ(x,typeof v.timeoutMs=="number"?v.timeoutMs:void 0);return{label:v.label,url:x,result:y}})):[],p=[];p.push(`Time: ${t.toISOString()}`),p.push(`OpenChamber version: ${e}`),p.push(`Runtime: ${r||"(unknown)"} (api=${c||"(unknown)"})`),p.push(`OpenCode SDK base: ${We.getBaseUrl()}`),p.push(`Event stream: ${o}`),p.push(`Directory: ${s||"(none)"}`),p.push(`Platform: ${n}`);const b=RJ(d?.openCodePort);if(p.push(`OpenCode runtime port: ${b??"(unknown)"}`),typeof d?.openCodeRunning=="boolean"&&p.push(`OpenCode runtime running: ${d.openCodeRunning?"yes":"no"}`),typeof d?.openCodeSecureConnection=="boolean"&&p.push(`Secure OpenCode connection: ${d.openCodeSecureConnection?"true":"false"}`),typeof d?.openCodeAuthSource=="string"&&d.openCodeAuthSource.trim()&&p.push(`OpenCode auth source: ${d.openCodeAuthSource}`),typeof window<"u"){const v=window.__OPENCHAMBER_MACOS_MAJOR__;typeof v=="number"&&Number.isFinite(v)&&v>0&&p.push(`macOS major: ${v}`)}if(/Mac OS X|Macintosh/.test(n)){p.push(""),p.push("OpenCode CLI resolution:");const v=zJ(d?.lastOpenCodeLaunchDiagnostics)?d.lastOpenCodeLaunchDiagnostics:null,x=v&&Array.isArray(v.args)?v.args.filter(T=>typeof T=="string"):[],y=u.data,k=y&&typeof y.configured=="string"?y.configured:null,C=y&&typeof y.resolved=="string"?y.resolved:d&&typeof d.opencodeBinaryResolved=="string"?d.opencodeBinaryResolved:"",S=y&&typeof y.resolvedDir=="string"?y.resolvedDir:"",M=y&&typeof y.source=="string"?y.source:d&&typeof d.opencodeBinarySource=="string"?d.opencodeBinarySource:"",A=y&&typeof y.launchBinary=="string"?y.launchBinary:d&&typeof d.opencodeLaunchBinary=="string"?d.opencodeLaunchBinary:"",B=y&&typeof y.launchWrapperType=="string"?y.launchWrapperType:d&&typeof d.opencodeLaunchWrapperType=="string"?d.opencodeLaunchWrapperType:"",F=y&&Array.isArray(y.launchArgs)?y.launchArgs.filter(T=>typeof T=="string"):d&&Array.isArray(d.opencodeLaunchArgs)?d.opencodeLaunchArgs.filter(T=>typeof T=="string"):[],_=y&&typeof y.node=="string"?y.node:d&&typeof d.nodeBinaryResolved=="string"?d.nodeBinaryResolved:"",D=y&&typeof y.bun=="string"?y.bun:d&&typeof d.bunBinaryResolved=="string"?d.bunBinaryResolved:"",E=y&&typeof y.detectedNow=="string"?y.detectedNow:"",I=y&&typeof y.detectedSourceNow=="string"?y.detectedSourceNow:"";if(k!==null&&p.push(`- configured: ${k.trim().length===0?"(cleared)":k}`),C){const T=S||(C.includes("/")?C.split("/").slice(0,-1).join("/")||"/":"");p.push(`- opencode: ${C}${T?` (dir=${T})`:""}`)}else p.push("- opencode: (n/a)");p.push(`- source: ${M||"(n/a)"}`),E&&(p.push(`- detected-now: ${E}`),p.push(`- detected-source: ${I||"(n/a)"}`)),v?(p.push(`- launched-at: ${br(v.launchedAt)}`),p.push(`- launch: ${br(v.binary)} ${x.join(" ")}`.trim()),p.push(`- cwd: ${br(v.cwd)}`),p.push(`- wrapper: ${br(v.wrapperType)}`),p.push(`- runtime: ${tm(br(v.wrapperType,""),_,D)}`),p.push(`- PATH entries: ${br(v.pathEntryCount,"(unknown)")}`),p.push(`- shell env: ${br(v.hasShellEnv,"(unknown)")} (${br(v.shellEnvKeysCount,"?")} keys)`)):(p.push(`- launch-binary: ${A||"(n/a)"}`),p.push(`- launch-wrapper: ${B||"(n/a)"}`),p.push(`- launch-args: ${F.length?F.join(" "):"(none)"}`),p.push(`- runtime: ${tm(B||"",_,D)}`)),!y&&u.error&&p.push(`- resolution-endpoint: ${u.error}`)}if(p.push(""),h.length){p.push("OpenCode API probes:");for(const v of h){if(!v.result){p.push(`- ${v.label}: (no url)`);continue}const{ok:x,status:y,elapsedMs:k,summary:C}=v.result,S=x?"":` url=${v.url}`;p.push(`- ${v.label}: ${x?"ok":"fail"} status=${y} time=${k}ms ${C}${S}`)}}else p.push("OpenCode API probes: (skipped)");return p.push(""),p.push(`Generated: ${VJ(Date.now())}`),p.join(`
7147
7147
  `)},$J=async()=>{const t=await OJ(),e=Fe.getState();e.setOpenCodeStatusText(t),e.setOpenCodeStatusDialogOpen(!0)},ZJ=()=>{const t=de.c(60),e=Ie(qJ),n=Ie(UJ),s=Ie(WJ),o=Ie(GJ),r=C3,i=Fe(KJ),l=Fe(YJ),c=Fe(JJ),d=Fe(QJ),u=Fe(XJ),f=Fe(eQ),m=Fe(tQ),h=Fe(nQ),p=Fe(sQ),b=Fe(oQ),w=Fe(rQ),v=Fe(iQ),x=Fe(aQ),y=Fe(lQ),k=Fe(cQ),C=Fe(dQ),S=Zt(uQ),M=$t(fQ),{themeMode:A,setThemeMode:B}=Us(),{working:F}=nv(),_=g.useRef(null),D=g.useRef(null),E=g.useRef(A);let I,T;t[0]!==A?(I=()=>{E.current=A},T=[A],t[0]=A,t[1]=I,t[2]=T):(I=t[1],T=t[2]),g.useEffect(I,T);let j;t[3]!==s?(j=()=>{D.current&&(clearTimeout(D.current),D.current=null),_.current=null,s()},t[3]=s,t[4]=j):j=t[4];const V=j;let H;t[5]!==M?.id||t[6]!==M?.path||t[7]!==n||t[8]!==S||t[9]!==o||t[10]!==p||t[11]!==e||t[12]!==V||t[13]!==w||t[14]!==h||t[15]!==x||t[16]!==u||t[17]!==f||t[18]!==b||t[19]!==v||t[20]!==B||t[21]!==y||t[22]!==C||t[23]!==m||t[24]!==i||t[25]!==k||t[26]!==l||t[27]!==d||t[28]!==c||t[29]!==F?(H=()=>{const Z=se=>h5(se,C),Y=mQ,fe=['[data-slot="dropdown-menu-content"]','[data-slot="select-content"]','[role="combobox"]','[role="listbox"]','[role="menu"]','[role="menuitem"]','[role="option"]',"[data-radix-popper-content-wrapper]"].join(","),Q=se=>se instanceof Element&&!!se.closest(fe),pe=pQ,ne=se=>{if(Y(se.target)){if(tn(se,Z("toggle_terminal"))){const{isMobile:te}=Fe.getState();if(te)return;se.preventDefault(),se.stopPropagation(),m();return}if(tn(se,Z("toggle_terminal_expanded"))){const{isMobile:te,isBottomTerminalExpanded:ke}=Fe.getState();if(te)return;se.preventDefault(),se.stopPropagation(),h(!ke);return}}},re=se=>{if(Y(se.target))return;const te=gQ;if(tn(se,Z("open_command_palette"))){se.preventDefault(),i();return}if(tn(se,Z("open_timeline_dialog"))){se.preventDefault(),y(!0);return}if(tn(se,Z("open_status"))){se.preventDefault(),$J();return}if(tn(se,Z("open_help"))){se.preventDefault(),l();return}if(yx()&&tn(se,Z("new_mini_chat"))){se.preventDefault(),U1("desktop_open_draft_mini_chat_window",{directory:S||M?.path||"",projectId:M?.id??null}).catch(bQ);return}const ke=tn(se,Z("new_chat")),be=tn(se,Z("new_chat_worktree"));if(ke||be){if(se.preventDefault(),w("chat"),b(!1),!Lt()&&be){s$();return}e();return}if(tn(se,Z("cycle_theme"))){if(se.preventDefault(),i2()!==null&&window.parent&&window.parent!==window){window.parent.postMessage({type:"openchamber:cycle-theme-request"},window.location.origin);return}const O=["light","dark","system"],ie=document.activeElement,Ce=(O.indexOf(E.current)+1)%O.length;B(O[Ce]),requestAnimationFrame(()=>{typeof document>"u"||typeof window>"u"||(document.hasFocus()||window.focus(),ie&&document.contains(ie)&&ie.focus({preventScroll:!0}))});return}if(tn(se,Z("open_settings"))){se.preventDefault();const{isSettingsDialogOpen:O}=Fe.getState();v(!O);return}if(tn(se,Z("toggle_sidebar"))){se.preventDefault();const{isMobile:O,isSessionSwitcherOpen:ie}=Fe.getState();O?b(!ie):c();return}if(tn(se,Z("focus_input"))){se.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}const X=Z("cycle_agent"),ee=X&&!X.includes("shift")?l2(`shift+${X}`):"",G=ee&&tn(se,ee)?-1:tn(se,X)?1:0;if(G!==0){const{isSettingsDialogOpen:O,isCommandPaletteOpen:ie,isHelpDialogOpen:oe,isSessionSwitcherOpen:Ce,isAboutDialogOpen:ue,activeMainTab:Me}=Fe.getState();if(O||ie||oe||Ce||ue||Me!=="chat"||!te(se.target))return;const K=Pe.getState(),W=i3(K.getVisibleAgents(),K.currentAgentName,G);if(!W)return;se.preventDefault(),K.setAgent(W),Fe.getState().addRecentAgent(W);const le=Ie.getState().currentSessionId;le&&Ht.getState().saveSessionAgentSelection(le,W);return}if(tn(se,Z("toggle_right_sidebar"))){const{isMobile:O}=Fe.getState();if(O)return;se.preventDefault(),d();return}if(tn(se,Z("open_right_sidebar_git"))){const{isMobile:O}=Fe.getState();if(O)return;se.preventDefault(),u(!0),f("git");return}if(tn(se,Z("open_right_sidebar_files"))){const{isMobile:O}=Fe.getState();if(O)return;se.preventDefault(),u(!0),f("files");return}if(tn(se,Z("cycle_right_sidebar_tab"))){const{isMobile:O,rightSidebarTab:ie}=Fe.getState();if(O)return;const oe=["git","files","context"],Ce=oe.indexOf(ie),ue=oe[(Ce+1)%oe.length];se.preventDefault(),u(!0),f(ue);return}if(tn(se,Z("toggle_terminal"))){const{isMobile:O}=Fe.getState();if(O)return;se.preventDefault(),m();return}if(tn(se,Z("toggle_terminal_expanded"))){const{isMobile:O,isBottomTerminalExpanded:ie}=Fe.getState();if(O)return;se.preventDefault(),h(!ie);return}if(tn(se,Z("open_model_selector"))){const{isSettingsDialogOpen:O,isCommandPaletteOpen:ie,isHelpDialogOpen:oe,isSessionSwitcherOpen:Ce,isAboutDialogOpen:ue,activeMainTab:Me,isModelSelectorOpen:ye}=Fe.getState();if(O||ie||oe||Ce||ue||!(Me==="chat"))return;se.preventDefault(),x(!ye);return}if(tn(se,Z("cycle_thinking_variant"))){const{isSettingsDialogOpen:O,isCommandPaletteOpen:ie,isHelpDialogOpen:oe,isSessionSwitcherOpen:Ce,isAboutDialogOpen:ue,activeMainTab:Me}=Fe.getState();if(O||ie||oe||Ce||ue||!(Me==="chat"))return;const W=Pe.getState();if(W.getCurrentModelVariants().length===0)return;se.preventDefault(),W.cycleCurrentVariant();const xe=Pe.getState().currentVariant,Se=Ie.getState().currentSessionId,we=Pe.getState().currentAgentName,me=Pe.getState().currentProviderId,_e=Pe.getState().currentModelId;Se&&we&&me&&_e&&Ht.getState().saveAgentModelVariantForSession(Se,we,me,_e,xe);return}if(tn(se,Z("cycle_favorite_model_forward"))||tn(se,Z("cycle_favorite_model_backward"))){const{isSettingsDialogOpen:O,isCommandPaletteOpen:ie,isHelpDialogOpen:oe,isSessionSwitcherOpen:Ce,isAboutDialogOpen:ue,activeMainTab:Me,favoriteModels:ye,addRecentModel:K}=Fe.getState();if(O||ie||oe||Ce||ue||!(Me==="chat")||ye.length===0)return;se.preventDefault();const{currentProviderId:xe,currentModelId:Se,setProvider:we,setModel:me}=Pe.getState(),_e=ye.length,ge=ye.findIndex(He=>He.providerID===xe&&He.modelID===Se),ce=tn(se,Z("cycle_favorite_model_forward"))?1:-1,Ae=ye[(ge+ce+_e)%_e];we(Ae.providerID),me(Ae.modelID),K(Ae.providerID,Ae.modelID);return}if(tn(se,Z("expand_input"))){if(p)return;se.preventDefault(),k();return}if(se.key==="Escape"){const O=se.target,ie=!!O?.closest('[role="dialog"]'),oe=!!document.querySelector('[data-settings-view="true"]'),Ce=!!(O?.closest(".terminal-viewport-container")||O?.getAttribute("data-terminal-hidden-input")==="true"),ue=Q(O)||pe(),{isSettingsDialogOpen:Me,isCommandPaletteOpen:ye,isHelpDialogOpen:K,isSessionSwitcherOpen:W,isAboutDialogOpen:le,isMultiRunLauncherOpen:xe,isImagePreviewOpen:Se,activeMainTab:we}=Fe.getState();if(ie||Ce||ue){V();return}if(Me){se.preventDefault(),v(!1),V();return}if(oe){V();return}if(ye||K||W||le||xe||Se||!(we==="chat")){V();return}const ge=o;if(!(F.canAbort&&!!ge)){V();return}const Ae=Date.now(),He=_.current;if(He&&Ae<He){se.preventDefault(),V(),r(ge??"");return}se.preventDefault();const he=n(3e3)??Ae+3e3;_.current=he,D.current&&clearTimeout(D.current);const Ee=Math.max(he-Ae,0);D.current=setTimeout(()=>{_.current&&Date.now()>=_.current&&V()},Ee||0);return}};return window.addEventListener("keydown",ne,!0),window.addEventListener("keydown",re),()=>{window.removeEventListener("keydown",ne,!0),window.removeEventListener("keydown",re)}},t[5]=M?.id,t[6]=M?.path,t[7]=n,t[8]=S,t[9]=o,t[10]=p,t[11]=e,t[12]=V,t[13]=w,t[14]=h,t[15]=x,t[16]=u,t[17]=f,t[18]=b,t[19]=v,t[20]=B,t[21]=y,t[22]=C,t[23]=m,t[24]=i,t[25]=k,t[26]=l,t[27]=d,t[28]=c,t[29]=F,t[30]=H):H=t[30];const N=M?.id,R=M?.path;let $;t[31]!==n||t[32]!==S||t[33]!==o||t[34]!==p||t[35]!==e||t[36]!==V||t[37]!==w||t[38]!==h||t[39]!==x||t[40]!==u||t[41]!==f||t[42]!==b||t[43]!==v||t[44]!==B||t[45]!==y||t[46]!==C||t[47]!==N||t[48]!==R||t[49]!==m||t[50]!==i||t[51]!==k||t[52]!==l||t[53]!==d||t[54]!==c||t[55]!==F?($=[e,r,i,l,c,d,u,f,m,h,p,b,w,v,x,y,k,B,F,n,V,o,S,N,R,C],t[31]=n,t[32]=S,t[33]=o,t[34]=p,t[35]=e,t[36]=V,t[37]=w,t[38]=h,t[39]=x,t[40]=u,t[41]=f,t[42]=b,t[43]=v,t[44]=B,t[45]=y,t[46]=C,t[47]=N,t[48]=R,t[49]=m,t[50]=i,t[51]=k,t[52]=l,t[53]=d,t[54]=c,t[55]=F,t[56]=$):$=t[56],g.useEffect(H,$);let U,L;t[57]!==V?(U=()=>()=>{V()},L=[V],t[57]=V,t[58]=U,t[59]=L):(U=t[58],L=t[59]),g.useEffect(U,L)};function qJ(t){return t.openNewSessionDraft}function UJ(t){return t.armAbortPrompt}function WJ(t){return t.clearAbortPrompt}function GJ(t){return t.currentSessionId}function KJ(t){return t.toggleCommandPalette}function YJ(t){return t.toggleHelpDialog}function JJ(t){return t.toggleSidebar}function QJ(t){return t.toggleRightSidebar}function XJ(t){return t.setRightSidebarOpen}function eQ(t){return t.setRightSidebarTab}function tQ(t){return t.toggleBottomTerminal}function nQ(t){return t.setBottomTerminalExpanded}function sQ(t){return t.isMobile}function oQ(t){return t.setSessionSwitcherOpen}function rQ(t){return t.setActiveMainTab}function iQ(t){return t.setSettingsDialogOpen}function aQ(t){return t.setModelSelectorOpen}function lQ(t){return t.setTimelineDialogOpen}function cQ(t){return t.toggleExpandedInput}function dQ(t){return t.shortcutOverrides}function uQ(t){return t.currentDirectory}function fQ(t){return t.getActiveProject()}function mQ(t){return t instanceof Element?!!(t.closest(".terminal-viewport-container")||t.getAttribute("data-terminal-hidden-input")==="true"):!1}function hQ(t){return t.getClientRects().length>0}function pQ(){const t=document.querySelectorAll('[data-slot="dropdown-menu-content"], [data-slot="select-content"], [role="listbox"], [role="menu"], [data-radix-popper-content-wrapper]');return Array.from(t).some(hQ)}function gQ(t){return t instanceof HTMLTextAreaElement&&t.getAttribute("data-chat-input")==="true"}function bQ(t){console.warn("[keyboard-shortcuts] failed to open draft mini chat window",t)}const vQ=3,yQ=(t,e)=>{if(typeof t!="string")return e;const n=t.trim().replace(/\s+/g," ");return n?n.slice(0,48):e},wQ=(t,e)=>{const n=e?[...t.filter(r=>r.id===e),...t.filter(r=>r.id!==e)]:t,s=[],o=new Set;for(const r of n){const i=typeof r.id=="string"?r.id.trim():"";if(!(!i||o.has(i))&&(o.add(i),s.push({sessionId:i,title:yQ(r.title,`Session ${s.length+1}`)}),s.length>=vQ))break}return s},xQ=()=>{const t=de.c(9),e=n2(),n=Ie(CQ);let s;t[0]!==n||t[1]!==e?(s=wQ(e,n),t[0]=n,t[1]=e,t[2]=s):s=t[2];const o=s;let r;t[3]!==o?(r=JSON.stringify(o),t[3]=o,t[4]=r):r=t[4];const i=r;let l,c;t[5]!==o||t[6]!==i?(l=()=>{if(typeof window>"u"||!xl())return;try{o.length===0?localStorage.removeItem(Jf):localStorage.setItem(Jf,i)}catch{return}window.__OPENCHAMBER_UPDATE_PWA_MANIFEST__?.()},c=[o,i],t[5]=o,t[6]=i,t[7]=l,t[8]=c):(l=t[7],c=t[8]),g.useEffect(l,c)};function CQ(t){return t.currentSessionId}const kQ=2e3,SQ=t=>{const e=Ie.getState().sessionAbortFlags.get(t);return e?Date.now()-e.timestamp<kQ:!1},MQ=t=>{const e=t[0];if(!e)return null;const n=Pe.getState().getVisibleAgents(),{sanitizedText:s,mention:o}=T4(e.content,n);return{queuedMessageId:e.id,primaryText:s,primaryAttachments:e.attachments??[],agentMentionName:o?.name,sendConfig:e.sendConfig}},AQ=(t,e,n)=>Ie.getState().sendMessage(e.primaryText,n.providerID,n.modelID,n.agent,e.primaryAttachments,e.agentMentionName,void 0,n.variant,"normal",{sessionId:t}),FQ=t=>{const e=ei.getState(),n=Pe.getState(),s=Ht.getState(),o=e.getSessionAgentSelection(t)??e.getCurrentAgent(t)??n.currentAgentName??void 0,r=e.getSessionModelSelection(t),i=o?e.getAgentModelForSession(t,o):null,l=i?.providerId??r?.providerId??n.currentProviderId??s.lastUsedProvider?.providerID,c=i?.modelId??r?.modelId??n.currentModelId??s.lastUsedProvider?.modelID,d=o&&l&&c?s.getAgentModelVariantForSession(t,o,l,c)??e.getAgentModelVariantForSession(t,o,l,c):void 0;return{providerID:l,modelID:c,agent:o,variant:d}},_Q=(t,e)=>(t==="busy"||t==="retry")&&e==="idle";function BQ(t){const e=typeof t=="boolean"?t:t?.enabled??!0,n=Ys(c=>c.queuedMessages),s=fs(c=>c.runsByOriginalSessionID),o=hs(c=>c.session_status),r=g.useRef(new Set),i=g.useRef(new Map),l=g.useRef(new Set);g.useEffect(()=>{if(!e)return;const c=async(m,h)=>{if(h.length===0||r.current.has(m)||SQ(m))return;if(fs.getState().isRunningForSession(m)){l.current.add(m);return}if((Km(m)?.type??"idle")!=="idle")return;const b=MQ(h);if(!b||!b.primaryText&&b.primaryAttachments.length===0)return;const w=b.sendConfig,v=w?.providerID&&w?.modelID?w:FQ(m);if(!(!v.providerID||!v.modelID)){r.current.add(m);try{await AQ(m,b,{providerID:v.providerID,modelID:v.modelID,agent:v.agent,variant:v.variant});const x=Ys.getState().removeFromQueue;x(m,b.queuedMessageId)}catch(x){console.warn("[queue] queued auto-send failed:",x)}finally{r.current.delete(m)}}},d=o??{},u=new Map(i.current);for(const[m,h]of Object.entries(d))h&&u.set(m,h.type);Object.entries(n).forEach(([m,h])=>{const p=d[m]?.type??"idle",b=i.current.get(m),w=l.current.has(m),v=fs.getState().isRunningForSession(m);v?l.current.add(m):w&&l.current.delete(m),h.length>0&&(_Q(b,p)||w&&!v&&p==="idle")&&c(m,h),u.set(m,p)}),i.current=u},[e,n,o,s])}const Fd=t=>Number.isFinite(t)?`${Math.max(0,Math.round(t))}px`:"0px",_d=(t,e,n,s)=>{t.style.setProperty("--oc-wco-left-inset",Fd(e)),t.style.setProperty("--oc-wco-right-inset",Fd(n)),t.style.setProperty("--oc-wco-titlebar-height",Fd(s))},DQ=()=>{const t=de.c(1);let e;t[0]===Symbol.for("react.memo_cache_sentinel")?(e=[],t[0]=e):e=t[0],g.useEffect(PQ,e)};function PQ(){if(typeof window>"u"||!xl())return;const t=document.documentElement,e=typeof window.matchMedia=="function"?window.matchMedia("(display-mode: window-controls-overlay)"):null,s=window.navigator.windowControlsOverlay,o=()=>{if(!s||!e?.matches||!s.visible){_d(t,0,0,0);return}const i=s.getTitlebarAreaRect(),l=Math.max(0,Number(i.x)||0),c=Math.max(0,Number(i.width)||0),d=Math.max(0,Number(i.height)||0),u=Math.max(0,window.innerWidth-(l+c));_d(t,l,u,d)},r=()=>{o()};return o(),window.addEventListener("resize",o),window.addEventListener("focus",o),e&&(typeof e.addEventListener=="function"?e.addEventListener("change",r):typeof e.addListener=="function"&&e.addListener(r)),s&&typeof s.addEventListener=="function"&&s.addEventListener("geometrychange",o),()=>{window.removeEventListener("resize",o),window.removeEventListener("focus",o),e&&(typeof e.removeEventListener=="function"?e.removeEventListener("change",r):typeof e.removeListener=="function"&&e.removeListener(r)),s&&typeof s.removeEventListener=="function"&&s.removeEventListener("geometrychange",o),_d(t,0,0,0)}}const EQ="openchamber:mini-chat-presence",IQ=()=>{const t=m5(),e=g.useRef(t.optimistic.add),n=g.useRef(t.optimistic.remove);return e.current=t.optimistic.add,n.current=t.optimistic.remove,g.useEffect(()=>{rh(s=>e.current(s),s=>n.current(s))},[]),null},TQ=()=>{const t=de.c(1);let e;return t[0]===Symbol.for("react.memo_cache_sentinel")?(e=[],t[0]=e):e=t[0],g.useEffect(LQ,e),null};function jQ(t){const e=de.c(1),{embeddedBackgroundWorkEnabled:n}=t;gJ(n),BQ(n);let s;return e[0]===Symbol.for("react.memo_cache_sentinel")?(s=a.jsx(IQ,{}),e[0]=s):s=e[0],s}function Vee(t){const e=de.c(5),{embeddedBackgroundWorkEnabled:n}=t;xQ(),DQ(),ZJ();let s;e[0]!==n?(s=a.jsx(jQ,{embeddedBackgroundWorkEnabled:n}),e[0]=n,e[1]=s):s=e[1];let o;e[2]===Symbol.for("react.memo_cache_sentinel")?(o=a.jsx(TQ,{}),e[2]=o):o=e[2];let r;return e[3]!==s?(r=a.jsxs(a.Fragment,{children:[s,o]}),e[3]=s,e[4]=r):r=e[4],r}function HQ(t){const e=t.data;if(e?.type!=="mini-chat-session-presence"||!e.sessionId||!e.directory)return;const n=e.viewed!==!1;qF(e.directory,e.sessionId,n),n&&Xh(e.sessionId)}function LQ(){if(typeof BroadcastChannel>"u")return;const t=new BroadcastChannel(EQ);return t.onmessage=HQ,()=>t.close()}const NQ=()=>{const t=de.c(3),e=Fe(VQ),n=Fe(RQ);let s;return t[0]!==n||t[1]!==e?(s={uiFont:e,monoFont:n},t[0]=n,t[1]=e,t[2]=s):s=t[2],s};function VQ(t){return t.uiFont}function RQ(t){return t.monoFont}const nm=new Set,Bd=new Map,zQ=(t,e)=>`https://cdn.jsdelivr.net/npm/${encodeURIComponent(t.packageName).replace("%40","@").replace("%2F","/")}/files/${t.filePrefix}-latin-${e}-normal.woff2`,OQ=(t,e)=>{const n=`${t.family}:${e}`;if(nm.has(n))return Promise.resolve();const s=Bd.get(n);if(s)return s;if(typeof document>"u"||typeof FontFace>"u"||!document.fonts)return Promise.resolve();const o=new FontFace(t.family,`url(${zQ(t,e)}) format('woff2')`,{style:"normal",weight:String(e),display:"swap"});document.fonts.add(o);const r=o.load().then(()=>{nm.add(n)}).catch(i=>{document.fonts.delete(o),console.warn(`Failed to load font: ${t.family} ${e}`,i)}).finally(()=>{Bd.delete(n)});return Bd.set(n,r),r},mv=t=>t?Promise.all(t.weights.map(e=>OQ(t,e))).then(()=>{}):Promise.resolve(),$Q=t=>mv(Td[t]?.source),ZQ=t=>mv(jd[t]?.source);function Ree(){const t=de.c(4),{uiFont:e,monoFont:n}=NQ();let s,o;t[0]!==n||t[1]!==e?(s=()=>{if(typeof document>"u")return;const r=document.documentElement,i=Td[e]?.stack??Td[wx].stack,l=jd[n]?.stack??jd[xx].stack;$Q(e),ZQ(n),r.style.setProperty("--font-sans",i),r.style.setProperty("--font-heading",i),r.style.setProperty("--font-family-sans",i),r.style.setProperty("--font-mono",l),r.style.setProperty("--font-family-mono",l),r.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=i)},o=[e,n],t[0]=n,t[1]=e,t[2]=s,t[3]=o):(s=t[2],o=t[3]),g.useEffect(s,o)}export{Vee as $,gee as A,bt as B,Hg as C,$t as D,Sm as E,Zs as F,Fm as G,Mm as H,q as I,JN as J,kx as K,NS as L,bo as M,jS as N,WO as O,Am as P,Pe as Q,cl as R,Rl as S,Xg as T,Ree as U,Lee as V,Nee as W,See as X,dX as Y,jee as Z,w4 as _,xi as a,zt as a$,Hee as a0,O3 as a1,Ht as a2,m3 as a3,WX as a4,Bee as a5,pee as a6,y_ as a7,$m as a8,Uo as a9,Dee as aA,Iee as aB,Bb as aC,ej as aD,uX as aE,qX as aF,K3 as aG,Ji as aH,Br as aI,cs as aJ,Er as aK,N1 as aL,fX as aM,cee as aN,nee as aO,h5 as aP,yX as aQ,tn as aR,ii as aS,Tp as aT,jp as aU,Pp as aV,ai as aW,er as aX,tr as aY,Mo as aZ,So as a_,Mee as aa,_ee as ab,Ar as ac,Aee as ad,Fee as ae,rX as af,jX as ag,EX as ah,PX as ai,fM as aj,vD as ak,HX as al,LX as am,NX as an,eo as ao,oi as ap,X8 as aq,ri as ar,si as as,oo as at,l7 as au,JM as av,Ut as aw,Wt as ax,Ot as ay,WD as az,Nr as b,IS as b$,Kh as b0,UM as b1,Nh as b2,cn as b3,r$ as b4,_g as b5,KM as b6,YM as b7,_3 as b8,s5 as b9,KB as bA,GB as bB,Zn as bC,lu as bD,uu as bE,du as bF,fu as bG,t0 as bH,gB as bI,sD as bJ,ep as bK,bee as bL,mX as bM,kz as bN,aee as bO,lee as bP,mee as bQ,Pg as bR,vB as bS,hX as bT,Q1 as bU,Go as bV,vX as bW,u5 as bX,TV as bY,V1 as bZ,qp as b_,ui as ba,Fo as bb,WM as bc,R9 as bd,tB as be,nB as bf,u$ as bg,Rg as bh,f$ as bi,m$ as bj,h$ as bk,p$ as bl,kB as bm,SB as bn,fi as bo,MB as bp,AB as bq,FB as br,_B as bs,EB as bt,lW as bu,DB as bv,JB as bw,qB as bx,WB as by,YB as bz,iee as c,Lg as c$,pL as c0,g5 as c1,RX as c2,VX as c3,gW as c4,eW as c5,DL as c6,JX as c7,yee as c8,wee as c9,cu as cA,Ep as cB,Ip as cC,us as cD,K1 as cE,Es as cF,wi as cG,Hr as cH,m5 as cI,k1 as cJ,W3 as cK,cX as cL,Z3 as cM,iX as cN,L_ as cO,bp as cP,YT as cQ,QT as cR,JT as cS,zX as cT,OX as cU,$X as cV,oX as cW,uee as cX,jl as cY,Jd as cZ,Qd as c_,MP as ca,wX as cb,n2 as cc,I3 as cd,Il as ce,tee as cf,Y4 as cg,$o as ch,Hi as ci,Nl as cj,op as ck,dee as cl,gX as cm,vee as cn,J1 as co,qc as cp,s$ as cq,ree as cr,_R as cs,eX as ct,rg as cu,zV as cv,ag as cw,xX as cx,Eh as cy,XU as cz,al as d,eee as d$,x5 as d0,j3 as d1,F3 as d2,ZM as d3,Qi as d4,M8 as d5,d3 as d6,ZC as d7,hee as d8,DO as d9,xs as dA,t5 as dB,XQ as dC,YQ as dD,KQ as dE,aJ as dF,lJ as dG,cJ as dH,kee as dI,mC as dJ,QQ as dK,ZX as dL,a3 as dM,A$ as dN,M$ as dO,F$ as dP,xo as dQ,ns as dR,JQ as dS,TK as dT,HB as dU,jB as dV,TB as dW,RB as dX,zB as dY,IB as dZ,lC as d_,PO as da,IX as db,T3 as dc,n5 as dd,hs as de,Cee as df,MY as dg,iJ as dh,Ki as di,$J as dj,ka as dk,r9 as dl,o4 as dm,lX as dn,Y1 as dp,Vo as dq,TX as dr,fs as ds,aX as dt,_S as du,GX as dv,Xh as dw,Ll as dx,no as dy,f1 as dz,fee as e,Ko as e$,qM as e0,ND as e1,I8 as e2,kX as e3,Y3 as e4,SX as e5,LD as e6,FX as e7,CX as e8,QM as e9,mo as eA,KX as eB,To as eC,see as eD,l2 as eE,z7 as eF,oee as eG,oa as eH,wp as eI,bX as eJ,GO as eK,v5 as eL,Ng as eM,jg as eN,w3 as eO,x3 as eP,Nz as eQ,jQ as eR,xee as eS,zZ as eT,NZ as eU,yN as eV,UX as eW,Fj as eX,Bj as eY,Ol as eZ,XX as e_,x4 as ea,FD as eb,Vn as ec,MX as ed,AX as ee,Pee as ef,Eee as eg,Hk as eh,nX as ei,tX as ej,sX as ek,jk as el,Tk as em,Tee as en,gJ as eo,a1 as ep,ip as eq,_X as er,rP as es,nP as et,sP as eu,Kc as ev,BX as ew,DX as ex,vH as ey,ln as ez,Kn as f,ql as f0,bW as f1,_0 as f2,Pz as f3,ts as f4,Wc as f5,NQ as f6,pX as f7,iB as g,cB as h,lB as i,pB as j,Ma as k,YX as l,z as m,ko as n,QX as o,$s as p,Us as q,z1 as r,aB as s,$e as t,Ye as u,nl as v,yi as w,DF as x,vn as y,Ie as z};