@av-pi-studio/web-client 0.0.49 → 0.0.51

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 (43) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/web/assets/{BinaryFallbackViewer-BqWD5myp.js → BinaryFallbackViewer-BCheCWlj.js} +2 -2
  3. package/dist/web/assets/{BinaryFallbackViewer-BqWD5myp.js.map → BinaryFallbackViewer-BCheCWlj.js.map} +1 -1
  4. package/dist/web/assets/{ChatPanel-Cghr4FA9.js → ChatPanel-K1uSkIOF.js} +3 -3
  5. package/dist/web/assets/{ChatPanel-Cghr4FA9.js.map → ChatPanel-K1uSkIOF.js.map} +1 -1
  6. package/dist/web/assets/{CodeView-Cr7QCw_g.js → CodeView-wz9a-TBl.js} +2 -2
  7. package/dist/web/assets/{CodeView-Cr7QCw_g.js.map → CodeView-wz9a-TBl.js.map} +1 -1
  8. package/dist/web/assets/FilePanel-B88cfGeN.js +2 -0
  9. package/dist/web/assets/{FilePanel-D10heC-L.js.map → FilePanel-B88cfGeN.js.map} +1 -1
  10. package/dist/web/assets/{ImageViewer-5clHM3Nh.js → ImageViewer-DMuVw1TC.js} +2 -2
  11. package/dist/web/assets/{ImageViewer-5clHM3Nh.js.map → ImageViewer-DMuVw1TC.js.map} +1 -1
  12. package/dist/web/assets/MarkdownFileViewer-D9pKcm5W.js +2 -0
  13. package/dist/web/assets/{MarkdownFileViewer-Dd70piQk.js.map → MarkdownFileViewer-D9pKcm5W.js.map} +1 -1
  14. package/dist/web/assets/{MoleculeViewerPanel-DFx9LSN6.js → MoleculeViewerPanel-DWiCnr-2.js} +2 -2
  15. package/dist/web/assets/{MoleculeViewerPanel-DFx9LSN6.js.map → MoleculeViewerPanel-DWiCnr-2.js.map} +1 -1
  16. package/dist/web/assets/{TerminalPanel-L9DJMwB6.js → TerminalPanel-DgCqvB_u.js} +2 -2
  17. package/dist/web/assets/{TerminalPanel-L9DJMwB6.js.map → TerminalPanel-DgCqvB_u.js.map} +1 -1
  18. package/dist/web/assets/{TextViewer-BDXrL58w.js → TextViewer-CCNwnC6m.js} +2 -2
  19. package/dist/web/assets/{TextViewer-BDXrL58w.js.map → TextViewer-CCNwnC6m.js.map} +1 -1
  20. package/dist/web/assets/{VideoViewer-DfNnw1AJ.js → VideoViewer-F211X3SB.js} +2 -2
  21. package/dist/web/assets/{VideoViewer-DfNnw1AJ.js.map → VideoViewer-F211X3SB.js.map} +1 -1
  22. package/dist/web/assets/index-BLc00KUW.css +1 -0
  23. package/dist/web/assets/index-CqmgQdsG.js +3 -0
  24. package/dist/web/assets/index-CqmgQdsG.js.map +1 -0
  25. package/dist/web/assets/markdown-CTYolZ3e.js +2 -0
  26. package/dist/web/assets/{markdown-0OCAeyJh.js.map → markdown-CTYolZ3e.js.map} +1 -1
  27. package/dist/web/assets/{use-file-download-C5ZdZp1T.js → use-file-download-BoIvv6b7.js} +2 -2
  28. package/dist/web/assets/{use-file-download-C5ZdZp1T.js.map → use-file-download-BoIvv6b7.js.map} +1 -1
  29. package/dist/web/assets/{use-file-watch-2C2o-DDo.js → use-file-watch-BY4_Mzyt.js} +2 -2
  30. package/dist/web/assets/{use-file-watch-2C2o-DDo.js.map → use-file-watch-BY4_Mzyt.js.map} +1 -1
  31. package/dist/web/assets/{vendor-icons-CAhpOZSZ.js → vendor-icons-CctYQ66i.js} +72 -47
  32. package/dist/web/assets/vendor-icons-CctYQ66i.js.map +1 -0
  33. package/dist/web/index.html +3 -3
  34. package/package.json +3 -3
  35. package/dist/web/assets/FilePanel-D10heC-L.js +0 -2
  36. package/dist/web/assets/MarkdownFileViewer-Dd70piQk.js +0 -2
  37. package/dist/web/assets/index-Bu36Yj2q.css +0 -1
  38. package/dist/web/assets/index-Ds0VVcbZ.js +0 -3
  39. package/dist/web/assets/index-Ds0VVcbZ.js.map +0 -1
  40. package/dist/web/assets/markdown-0OCAeyJh.js +0 -2
  41. package/dist/web/assets/paths--dEDMUm1.js +0 -2
  42. package/dist/web/assets/paths--dEDMUm1.js.map +0 -1
  43. package/dist/web/assets/vendor-icons-CAhpOZSZ.js.map +0 -1
@@ -0,0 +1,3 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ChatPanel-K1uSkIOF.js","assets/vendor-react-p-LLqNcx.js","assets/vendor-query-chxBrUuj.js","assets/vendor-icons-CctYQ66i.js","assets/markdown-CTYolZ3e.js","assets/vendor-highlight-Cry4x-mr.js","assets/vendor-markdown-ePgMI45n.js","assets/vendor-B2Vnrid8.js","assets/markdown-JJHL50c6.css","assets/StatusBadge-D5M084rB.js","assets/StatusBadge-BgIink5J.css","assets/DiffView-CUxhzW_O.js","assets/DiffView-CRbeRztO.css","assets/vendor-overlays-DWi-xJna.js","assets/vendor-dnd-CjSU1Kqk.js","assets/ChatPanel-CG6o6nFc.css","assets/FilePanel-B88cfGeN.js","assets/use-file-watch-BY4_Mzyt.js","assets/FilePanel.module-DoDNR5C2.js","assets/FilePanel-DIInFr3h.css","assets/TerminalPanel-DgCqvB_u.js","assets/vendor-terminal-BhzX2_ts.js","assets/vendor-terminal-DYP7pi_n.css","assets/TerminalPanel-BQj62G6N.css","assets/MoleculeViewerPanel-DWiCnr-2.js","assets/vendor-molviewer-PwwY6jQU.js","assets/vendor-molviewer-CtvG6b9Z.css","assets/use-file-download-BoIvv6b7.js","assets/MoleculeViewerPanel-CTZU0_lX.css","assets/TextViewer-CCNwnC6m.js","assets/CodeView-wz9a-TBl.js","assets/CodeView-CLRODhB8.css","assets/TextViewer-B9IV5fXQ.css","assets/MarkdownFileViewer-D9pKcm5W.js","assets/MarkdownFileViewer-BD5Ri_Fb.css","assets/ImageViewer-DMuVw1TC.js","assets/ImageViewer-ijzMsq8H.css","assets/VideoViewer-F211X3SB.js","assets/VideoViewer-BBuZ4wou.css","assets/BinaryFallbackViewer-BCheCWlj.js","assets/BinaryFallbackViewer-CLiNWU_S.css"])))=>i.map(i=>d[i]);
2
+ var Kn=Object.defineProperty;var Vn=(e,t,n)=>t in e?Kn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var C=(e,t,n)=>Vn(e,typeof t!="symbol"?t+"":t,n);import{r as y,j as a,c as Gn}from"./vendor-react-p-LLqNcx.js";import{Q as Xn,a as Jn,u as Qt,b as Yn,c as Ie,d as Qn}from"./vendor-query-chxBrUuj.js";import{A as l,B as u,C as F,D as Zt,E as B,F as ye,G as ie,H as $,I as b,J as W,K as H,L as rt,M as ve,N as be}from"./vendor-B2Vnrid8.js";import{L as Zn,P as es,a as ts,b as ns,c as ss,E as vt,d as os,S as rs,A as as,T as kt,C as It,e as en,F as is,f as tn,g as nn,h as sn,i as on,G as rn,j as cs,M as an,X as ht,k as ke,l as cn,m as mt,n as st,o as Ge,p as ls,D as ds,U as us,R as ps,q as ln,r as fs,s as hs,t as ms,u as gs,v as _s,w as ys}from"./vendor-icons-CctYQ66i.js";import{R as Fe,T as We,P as Le,C as He,I as A,S as _e,D as bs,a as ws,b as xs,c as Ss,d as Rt,e as gt}from"./vendor-overlays-DWi-xJna.js";import{u as vs,a as ks,D as Is,c as js,S as Cs,h as Ts,P as Es,b as Ns,C as Rs}from"./vendor-dnd-CjSU1Kqk.js";import{_ as ce}from"./vendor-highlight-Cry4x-mr.js";import"./vendor-markdown-ePgMI45n.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const i of r.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&s(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(o){if(o.ep)return;o.ep=!0;const r=n(o);fetch(o.href,r)}})();const qs=new Xn;function dn(e){const t=e.trim().replace(/^#/,""),n=t.length===3?t.split("").map(s=>s+s).join(""):t;if(n.length!==6||/[^0-9a-fA-F]/.test(n))throw new Error(`Invalid hex color: ${e}`);return{r:parseInt(n.slice(0,2),16),g:parseInt(n.slice(2,4),16),b:parseInt(n.slice(4,6),16)}}function Ms(e){return Math.max(0,Math.min(255,Math.round(e)))}function Bs({r:e,g:t,b:n}){const s=o=>Ms(o).toString(16).padStart(2,"0");return`#${s(e)}${s(t)}${s(n)}`}function $s(e){const{r:t,g:n,b:s}=dn(e),o=r=>{const i=r/255;return i<=.03928?i/12.92:((i+.055)/1.055)**2.4};return .2126*o(t)+.7152*o(n)+.0722*o(s)}function jt(e,t="#18181b",n="#ffffff"){return $s(e)>.45?t:n}function As(e,t){const{r:n,g:s,b:o}=dn(e),r=Math.max(0,Math.min(1,t));return Bs({r:n+(255-n)*r,g:s+(255-s)*r,b:o+(255-o)*r})}function Xe(e){const t=e.trim().replace(/^#/,"");return(t.length===3||t.length===6)&&!/[^0-9a-fA-F]/.test(t)}const Q=(e,t,n,s,o,r,i,c,d,h,p)=>({50:e,100:t,200:n,300:s,400:o,500:r,600:i,700:c,800:d,900:h,950:p}),x={zinc:Q("#fafafa","#f4f4f5","#e4e4e7","#d4d4d8","#a1a1aa","#71717a","#52525b","#3f3f46","#27272a","#18181b","#09090b"),gray:Q("#f9fafb","#f3f4f6","#e5e7eb","#d1d5db","#9ca3af","#6b7280","#4b5563","#374151","#1f2937","#111827","#030712"),slate:Q("#f8fafc","#f1f5f9","#e2e8f0","#cbd5e1","#94a3b8","#64748b","#475569","#334155","#1e293b","#0f172a","#020617"),blue:Q("#eff6ff","#dbeafe","#bfdbfe","#93c5fd","#60a5fa","#3b82f6","#2563eb","#1d4ed8","#1e40af","#1e3a8a","#172554"),green:Q("#f0fdf4","#dcfce7","#bbf7d0","#86efac","#4ade80","#22c55e","#16a34a","#15803d","#166534","#14532d","#052e16"),red:Q("#fef2f2","#fee2e2","#fecaca","#fca5a5","#f87171","#ef4444","#dc2626","#b91c1c","#991b1b","#7f1d1d","#450a0a"),teal:Q("#f0fdfa","#ccfbf1","#99f6e4","#5eead4","#2dd4bf","#14b8a6","#0d9488","#0f766e","#115e59","#134e4a","#042f2e"),amber:Q("#fffbeb","#fef3c7","#fde68a","#fcd34d","#fbbf24","#f59e0b","#d97706","#b45309","#92400e","#78350f","#451a03"),yellow:Q("#fefce8","#fef9c3","#fef08a","#fde047","#facc15","#eab308","#ca8a04","#a16207","#854d0e","#713f12","#422006"),purple:Q("#faf5ff","#f3e8ff","#e9d5ff","#d8b4fe","#c084fc","#a855f7","#9333ea","#7e22ce","#6b21a8","#581c87","#3b0764"),orange:Q("#fff7ed","#ffedd5","#fed7aa","#fdba74","#fb923c","#f97316","#ea580c","#c2410c","#9a3412","#7c2d12","#431407"),white:"#ffffff",black:"#000000"},Ds={statusSuccess:"#16a34a",statusDanger:"#dc2626",statusWarning:"#f59e0b",statusMerged:"#9333ea"},Ps={statusSuccess:"#15803d",statusDanger:"#b91c1c",statusWarning:"#d97706",statusMerged:"#7c3aed"};function zs(){return{keyword:x.purple[300],string:x.green[300],number:x.orange[300],boolean:x.orange[300],comment:x.zinc[500],function:x.blue[300],variable:x.zinc[200],type:x.teal[300],class:x.amber[300],constant:x.orange[300],operator:x.zinc[400],punctuation:x.zinc[400],tag:x.red[300],attribute:x.amber[300],property:x.blue[200],regexp:x.teal[300],escape:x.orange[200],heading:x.blue[300],link:x.blue[400],deleted:x.red[400],inserted:x.green[400]}}function Os(){return{keyword:x.purple[700],string:x.green[700],number:x.orange[700],boolean:x.orange[700],comment:x.zinc[500],function:x.blue[700],variable:x.zinc[800],type:x.teal[700],class:x.amber[700],constant:x.orange[700],operator:x.zinc[600],punctuation:x.zinc[600],tag:x.red[700],attribute:x.amber[700],property:x.blue[700],regexp:x.teal[700],escape:x.orange[700],heading:x.blue[700],link:x.blue[600],deleted:x.red[700],inserted:x.green[700]}}function un(e,t,n){return{background:e,foreground:t,cursor:n,cursorAccent:e,selectionBackground:"rgba(255,255,255,0.18)",black:x.zinc[900],red:x.red[500],green:x.green[500],yellow:x.amber[500],blue:x.blue[500],magenta:x.purple[500],cyan:x.teal[500],white:x.zinc[300],brightBlack:x.zinc[600],brightRed:x.red[400],brightGreen:x.green[400],brightYellow:x.amber[400],brightBlue:x.blue[400],brightMagenta:x.purple[400],brightCyan:x.teal[400],brightWhite:x.zinc[50]}}function Me(e){const t=x.zinc[50],n=jt(e.accent);return{surface0:e.surface0,surface1:e.surface1,surface2:e.surface2,surface3:e.surface3,surface4:e.surface4,surfaceDiffEmpty:e.surfaceDiffEmpty,surfaceSidebar:e.surfaceSidebar,surfaceSidebarHover:e.surfaceSidebarHover,surfaceWorkspace:e.surface1,foreground:t,foregroundMuted:e.mutedForeground,accent:e.accent,accentBright:e.accentBright,accentForeground:n,destructive:e.destructive,destructiveForeground:x.white,success:e.accent,successForeground:x.white,border:e.border,borderAccent:e.borderAccent,...Ds,diffAddition:x.green[400],diffDeletion:x.red[500],scrollbarHandle:e.scrollbarHandle,background:e.surface0,popover:e.surface2,popoverForeground:t,primary:e.accent,secondary:e.surface2,muted:e.surface2,mutedForeground:e.mutedForeground,input:e.surface2,ring:e.accent,palette:x,syntax:zs(),terminal:un(e.surface0,t,e.accent)}}function Fs(){const e="#1a1a1e",t="#253e6f";return{surface0:"#ffffff",surface1:"#fafafa",surface2:"#f4f4f5",surface3:"#e4e4e7",surface4:"#d4d4d8",surfaceDiffEmpty:"#f6f6f6",surfaceSidebar:"#f4f4f5",surfaceSidebarHover:"#e9e9ec",surfaceWorkspace:"#ffffff",foreground:e,foregroundMuted:"#71717a",accent:t,accentBright:"#2f4f8e",accentForeground:jt(t),destructive:"#b04138",destructiveForeground:"#ffffff",success:t,successForeground:"#ffffff",border:"#e4e4e7",borderAccent:"#ececf1",...Ps,diffAddition:"#15803d",diffDeletion:"#b91c1c",scrollbarHandle:"#3f3f46",background:"#ffffff",popover:"#ffffff",popoverForeground:e,primary:t,secondary:"#f4f4f5",muted:"#f4f4f5",mutedForeground:"#71717a",input:"#f4f4f5",ring:t,palette:x,syntax:Os(),terminal:{...un("#ffffff",e,t),selectionBackground:"rgba(0,0,0,0.15)",white:"#ffffff",brightWhite:"#fafafa"}}}const Ws={light:"#ffffff",dark:"#3b62b0",zinc:"#808080",midnight:"#4A6BA8",claude:"#D97757",ghostty:"#8caaee"},pn=["light","dark","zinc","midnight","claude","ghostty"];function Ls(e){if(e==="light")return Fs();switch(e){case"dark":return Me({surface0:"#181B1A",surface1:"#1E2120",surface2:"#272A29",surface3:"#434645",surface4:"#595B5B",surfaceDiffEmpty:"#252827",surfaceSidebar:"#141716",surfaceSidebarHover:"#1c1f1e",mutedForeground:"#A1A5A4",scrollbarHandle:"#717574",border:"#252B2A",borderAccent:"#2f3135",accent:"#2e5cb8",accentBright:"#a2b4d7",destructive:"#c64f43"});case"zinc":return Me({surface0:"#18181b",surface1:"#1f1f22",surface2:"#27272a",surface3:"#3f3f46",surface4:"#52525b",surfaceDiffEmpty:"#242427",surfaceSidebar:"#131316",surfaceSidebarHover:"#1b1b1e",mutedForeground:"#a1a1aa",scrollbarHandle:"#71717a",border:"#27272a",borderAccent:"#303036",accent:"#e4e4e7",accentBright:"#fafafa",destructive:"#c44a4a"});case"midnight":return Me({surface0:"#161820",surface1:"#1c1e27",surface2:"#252731",surface3:"#3c3e4c",surface4:"#535564",surfaceDiffEmpty:"#222430",surfaceSidebar:"#121420",surfaceSidebarHover:"#1a1c28",mutedForeground:"#9a9db0",scrollbarHandle:"#6b6e82",border:"#242636",borderAccent:"#2e3040",accent:"#3b6fcf",accentBright:"#7eaaeb",destructive:"#c44a52"});case"claude":return Me({surface0:"#1f1f1e",surface1:"#262523",surface2:"#2f2d2b",surface3:"#4a4745",surface4:"#605d5b",surfaceDiffEmpty:"#2a2826",surfaceSidebar:"#1a1918",surfaceSidebarHover:"#222120",mutedForeground:"#ada9a5",scrollbarHandle:"#78746f",border:"#2c2a27",borderAccent:"#36332f",accent:"#d97757",accentBright:"#e89a7f",destructive:"#cf513e"});case"ghostty":return Me({surface0:"#282c34",surface1:"#2f333d",surface2:"#383c48",surface3:"#4a4f5e",surface4:"#5b6175",surfaceDiffEmpty:"#323643",surfaceSidebar:"#21252d",surfaceSidebarHover:"#292d36",mutedForeground:"#c8ccd8",scrollbarHandle:"#a0a4b2",border:"#353a47",borderAccent:"#3f4454",accent:"#89b4fa",accentBright:"#b4d0fc",destructive:"#c44a55"})}}const fn={};for(const e of pn){const t=e==="light"?"light":"dark";fn[e]={name:e,colorScheme:t,colors:Ls(e),swatch:Ws[e]}}const Hs=fn,Us={0:0,1:4,"1.5":6,2:8,3:12,4:16,6:24,8:32,12:48,16:64,20:80,24:96,32:128},hn={xs:12,code:12,sm:14,base:16,lg:18,xl:20,"2xl":22,"3xl":26,"4xl":34},Ks={normal:"400",medium:"500",semibold:"600",bold:"700"},Vs={none:0,sm:2,base:4,md:6,lg:8,xl:12,"2xl":16,full:9999},Gs={0:0,1:1,2:2},Xs={0:0,50:.5,100:1},Js={xs:12,sm:14,md:16,lg:20},Ys={diff:22},mn='system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif',gn='ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace';function Qs(e){const t=e==="dark"?"rgba(0,0,0,0.55)":"rgba(24,24,27,0.12)";return{sm:{color:t,offsetX:0,offsetY:1,radius:2,elevation:1},md:{color:t,offsetX:0,offsetY:3,radius:8,elevation:4},lg:{color:t,offsetX:0,offsetY:10,radius:24,elevation:12}}}function _n(e){const t=Hs[e];return{name:e,colorScheme:t.colorScheme,colors:t.colors,spacing:Us,fontSize:{...hn},fontFamily:{ui:mn,mono:gn},lineHeight:{...Ys},iconSize:Js,fontWeight:Ks,borderRadius:Vs,borderWidth:Gs,opacity:Xs,shadow:Qs(t.colorScheme),swatch:t.swatch}}const Zs=16,eo=10,to=24;function no(e,t){const n=t.themeName??e.name,s=_n(n),o=t.uiFont&&t.uiFont.trim()!==""?t.uiFont:mn,r=t.monoFont&&t.monoFont.trim()!==""?t.monoFont:gn;let i={...s.fontSize};if(t.fontSize!=null){const d=Math.max(eo,Math.min(to,t.fontSize))/Zs,h=["xs","code","sm","base","lg","xl","2xl","3xl","4xl"];for(const p of h){const w=hn[p];i[p]=Math.round(w*d)}}return{...s,fontSize:i,fontFamily:{ui:o,mono:r}}}function so(e){return _n(e)}const oo="dark";function ro(e){const t={};ao(e.colors,t);for(const[n,s]of Object.entries(e.spacing))t[`--pi-spacing-${n}`]=`${s}px`;for(const[n,s]of Object.entries(e.fontSize))t[`--pi-font-size-${n}`]=`${s}px`;t["--pi-font-ui"]=e.fontFamily.ui,t["--pi-font-mono"]=e.fontFamily.mono,t["--pi-line-height-diff"]=`${e.lineHeight.diff}px`;for(const[n,s]of Object.entries(e.iconSize))t[`--pi-icon-size-${n}`]=`${s}px`;for(const[n,s]of Object.entries(e.fontWeight))t[`--pi-font-weight-${n}`]=String(s);for(const[n,s]of Object.entries(e.borderRadius))t[`--pi-radius-${n}`]=s===9999?"9999px":`${s}px`;for(const[n,s]of Object.entries(e.borderWidth))t[`--pi-border-width-${n}`]=`${s}px`;for(const[n,s]of Object.entries(e.opacity))t[`--pi-opacity-${n}`]=String(s);for(const[n,s]of Object.entries(e.shadow))if(typeof s=="string")t[`--pi-shadow-${n}`]=s;else if(s&&typeof s=="object"){const o=s;t[`--pi-shadow-${n}`]=`${o.offsetX}px ${o.offsetY}px ${o.radius}px ${o.color}`}return t["--pi-color-scheme"]=e.colorScheme,t}function ao(e,t){const{palette:n,syntax:s,terminal:o,...r}=e;for(const[i,c]of Object.entries(r))typeof c=="string"&&(t[`--pi-color-${i}`]=c);s&&io(s,t),o&&(t["--pi-terminal-bg"]=o.background,t["--pi-terminal-fg"]=o.foreground)}function io(e,t){for(const[n,s]of Object.entries(e))typeof s=="string"&&(t[`--syntax-${co(n)}`]=s)}function co(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function lo(e){if(typeof document>"u")return;const t=document.documentElement.style;for(const[s,o]of Object.entries(e))t.setProperty(s,o);const n=e["--pi-color-scheme"];n&&document.documentElement.style.setProperty("color-scheme",n)}function uo(e){const t=ro(e);lo(t)}const Be=l().min(1,"Asset path must not be empty"),po=u({accent:l().refine(Xe,{message:"accent must be a valid #rrggbb hex color"}),accentBright:l().refine(Xe,{message:"accentBright must be a valid #rrggbb hex color"}).optional(),accentForeground:l().refine(Xe,{message:"accentForeground must be a valid #rrggbb hex color"}).optional(),swatch:l().refine(Xe,{message:"swatch must be a valid #rrggbb hex color"}).optional()}),fo=u({logoLight:Be,logoDark:Be,logoMark:Be.optional(),icon:Be,splash:Be.optional()}),ho=u({docs:l().url().optional(),support:l().url().optional(),issues:l().url().optional(),website:l().url().optional()}).optional(),mo=u({copyright:l().optional(),companyName:l().optional()}).optional();u({productName:l().min(1,"productName is required"),shortName:l().optional(),tagline:l().optional(),colors:po,assets:fo,links:ho,legal:mo});function go(e){const t=e.accent,n=e.accentBright??As(t,.35),s=e.accentForeground??jt(t),o=e.swatch??t;return{accent:t,accentBright:n,accentForeground:s,swatch:o}}function _o(e,t){return{...e,colors:{...e.colors,accent:t.accent,accentBright:t.accentBright,accentForeground:t.accentForeground,primary:t.accent,ring:t.accent},swatch:t.swatch}}const qt="pi-studio-appearance";function yo(e,t){let n=c(e),s=null;function o(p){return p==="system"?typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light":p}function r(p,w){const f=o(p),m=so(f);let v=no(m,{...w,themeName:f});if(t!=null&&t.colors){const _=go(t.colors);v=_o(v,_)}return v}function i(){const p=JSON.stringify({mode:n.mode,settings:n.settings});e.set(qt,p)}function c(p){const w=p.get(qt);let f=oo,m={};if(w)try{const _=JSON.parse(w);_.mode&&(pn.includes(_.mode)||_.mode==="system")&&(f=_.mode),_.settings&&typeof _.settings=="object"&&(m=_.settings)}catch{}const v=r(f,m);return{mode:f,settings:m,resolvedTheme:v}}function d(){n={...n,resolvedTheme:r(n.mode,n.settings)},i()}const h={getState(){return n},setMode(p){n={...n,mode:p},d(),h.apply()},updateSettings(p){n={...n,settings:{...n.settings,...p}},d(),h.apply()},apply(){uo(n.resolvedTheme)},listen(){if(typeof window>"u")return()=>{};const p=window.matchMedia("(prefers-color-scheme: dark)"),w=()=>{n.mode==="system"&&(d(),h.apply())};return p.addEventListener("change",w),s=()=>p.removeEventListener("change",w),s}};return h}function bo({store:e,brandConfig:t,children:n}){const s=y.useRef(null);return s.current||(s.current=yo(e,t),s.current.apply()),y.useEffect(()=>s.current.listen(),[]),a.jsx(a.Fragment,{children:n})}const wo={get(e){var t;try{return((t=globalThis.localStorage)==null?void 0:t.getItem(e))??null}catch{return null}},set(e,t){var n;try{(n=globalThis.localStorage)==null||n.setItem(e,t)}catch{}}};function xo({children:e}){return a.jsx(bo,{store:wo,children:a.jsx(Jn,{client:qs,children:e})})}const So="_btn_1chbg_4",vo="_secondary_1chbg_44",ko="_outline_1chbg_53",Io="_ghost_1chbg_62",jo="_destructive_1chbg_72",Co="_iconOnly_1chbg_82",To="_loadingSpinner_1chbg_89",Eo="_piSpin_1chbg_1",Je={btn:So,default:"_default_1chbg_35",secondary:vo,outline:ko,ghost:Io,destructive:jo,iconOnly:Co,loadingSpinner:To,piSpin:Eo},Mt={xs:28,sm:32,md:36,lg:40},No={xs:12,sm:14,md:16,lg:20},Bt={xs:8,sm:10,md:12,lg:16},Ro={xs:12,sm:13,md:14,lg:15};function qo(e){const{disabled:t,loading:n}=e;return t||n?{opacity:.5,isGhostHover:!1}:{opacity:1,isGhostHover:!1}}function K({variant:e="default",size:t="md",loading:n=!1,disabled:s=!1,leftIcon:o,trailing:r,iconOnly:i=!1,children:c,style:d,className:h,...p}){const{opacity:w}=qo({disabled:s??!1,loading:n}),f=s||n,m=No[t];return a.jsxs("button",{className:F(Je.btn,Je[e],i&&Je.iconOnly,h),disabled:f,"aria-busy":n||void 0,style:{minHeight:Mt[t],paddingLeft:i?void 0:Bt[t],paddingRight:i?void 0:Bt[t],fontSize:Ro[t],opacity:w,...i?{width:Mt[t]}:{},...d},...p,children:[n?a.jsx(Zn,{className:Je.loadingSpinner,size:m,"aria-hidden":!0}):o?a.jsx("span",{"aria-hidden":!0,style:{display:"flex",alignItems:"center",flexShrink:0},children:o}):null,c,r&&!n&&a.jsx("span",{"aria-hidden":!0,style:{display:"flex",alignItems:"center",flexShrink:0},children:r})]})}const Mo="_input_a7qyq_3",Bo="_textarea_a7qyq_32",_t={input:Mo,textarea:Bo},ot=y.forwardRef(function({className:t,...n},s){return a.jsx("input",{ref:s,className:F(_t.input,t),...n})}),Ku=y.forwardRef(function({className:t,...n},s){return a.jsx("textarea",{ref:s,className:F(_t.input,_t.textarea,t),...n})}),yn=l().datetime({offset:!0});l().uuid();l().regex(/^[A-Za-z0-9_-]+$/,"expected base64url");const Oe=Zt([B(),yn]),$o=ye(["mobile","browser","cli","mcp"]),Ao=u({type:b("hello"),clientId:l(),clientType:$o,protocolVersion:B(),appVersion:l().optional(),capabilities:ie(l(),$()).optional()}),Do=u({status:b("server_info"),serverId:l(),hostname:l().optional(),version:l().optional(),capabilities:ie(l(),W()),features:ie(l(),W())}),Po=u({type:b("status"),payload:Do}),zo=u({type:b("ping"),requestId:l(),clientSentAt:Oe.optional()}),Oo=u({type:b("pong"),requestId:l(),clientSentAt:Oe.optional(),serverReceivedAt:Oe,serverSentAt:Oe}),bn=ye(["initializing","idle","running","error","closed"]),at=u({mimeType:l().optional(),data:l().optional()}).passthrough(),Fo=u({prs:H(W()).optional(),issues:H(W()).optional()}).passthrough(),Wo=u({provider:l(),cwd:l(),modeId:l().optional(),model:l().optional(),modelProvider:l().optional(),thinkingOptionId:l().optional(),featureValues:ie(l(),W()).optional(),title:l().nullable().optional(),approvalPolicy:l().optional(),sandboxMode:l().optional(),networkAccess:$().optional(),webSearch:$().optional(),extra:u({pi:W().optional()}).passthrough().optional(),systemPrompt:l().optional(),mcpServers:ie(l(),W()).optional()}),Lo=u({type:b("create_agent_request"),requestId:l(),config:Wo,env:ie(l(),l()).optional(),workspaceId:l().optional(),worktreeName:l().optional(),initialPrompt:l().optional(),clientMessageId:l().optional(),outputSchema:ie(l(),W()).optional(),images:H(at).optional(),attachments:Fo.optional(),git:W().optional(),worktree:W().optional(),autoArchive:$().optional(),labels:ie(l(),l()).default({})}),Ho=u({type:b("create_agent_response"),requestId:l(),payload:u({agentId:l()}).passthrough()}),Uo=u({type:b("agent_update"),agentId:l(),status:bn.optional(),title:l().nullable().optional(),labels:ie(l(),l()).optional()}),Ko=u({type:b("agent_status"),agentId:l(),status:bn}),Vo=u({type:b("agent_list"),agents:H(u({id:l()}).passthrough())}),Go=u({type:b("agent_deleted"),agentId:l()}),Xo=u({type:b("agent_archived"),agentId:l(),archivedAt:yn.optional()}),wn=rt("kind",[u({kind:b("shell"),command:l().optional(),output:l().optional()}),u({kind:b("read"),path:l().optional(),output:l().optional()}),u({kind:b("edit"),path:l().optional(),diff:l().optional(),output:l().optional()}),u({kind:b("write"),path:l().optional(),output:l().optional()}),u({kind:b("search"),query:l().optional(),output:l().optional()}),u({kind:b("fetch"),url:l().optional(),output:l().optional()}),u({kind:b("task"),description:l().optional(),output:l().optional()})]),Jo=rt("kind",[u({kind:b("user_message"),messageId:l().optional(),text:l().optional(),images:H(at).optional()}),u({kind:b("assistant_message"),messageId:l().optional(),text:l().optional()}),u({kind:b("reasoning"),text:l().optional()}),u({kind:b("tool_call"),callId:l().optional(),tool:wn,status:l().optional()}),u({kind:b("turn_started"),turnId:l().optional()}),u({kind:b("turn_completed"),turnId:l().optional()}),u({kind:b("turn_failed"),turnId:l().optional(),error:l().optional()}),u({kind:b("turn_canceled"),turnId:l().optional()}),u({kind:b("error"),message:l().optional()}),u({kind:b("queue_update"),steering:H(l()).optional(),followUp:H(l()).optional()})]),Yo=u({type:b("agent_stream"),agentId:l(),seq:B().optional(),timestamp:Oe.optional(),event:Jo}),Qo=ye(["before","after"]),Zo=u({start:B(),end:B()}),er=u({type:b("fetch_agent_timeline_request"),requestId:l(),agentId:l(),cursor:l().nullable().optional(),direction:Qo,limit:B().optional()}),tr=u({type:b("fetch_agent_timeline_response"),requestId:l(),agentId:l().optional(),items:H(W()),seqStart:B(),seqEnd:B(),sourceSeqRanges:H(Zo),collapsed:$(),hasNewer:$(),startCursor:l().nullable().optional(),endCursor:l().nullable().optional()}),nr=u({type:b("agent_permission_request"),requestId:l(),agentId:l(),toolName:l().optional(),tool:wn.optional(),action:W().optional(),responses:H(l()).optional()}),sr=u({type:b("agent_permission_resolved"),requestId:l(),agentId:l(),decision:l().optional()}),or=u({type:b("agent.permission.respond.request"),requestId:l(),permissionRequestId:l(),response:W()}),rr=u({type:b("agent.permission.respond.response"),requestId:l(),payload:u({resolved:$()}).passthrough()}),ar=u({type:b("respond_to_permission"),requestId:l(),permissionRequestId:l(),response:W()}),xn=ye(["conversation","files","both"]),ir=u({type:b("agent.rewind.request"),requestId:l(),agentId:l(),messageId:l(),mode:xn}).passthrough(),cr=u({type:b("agent.rewind.response"),requestId:l(),payload:u({agentId:l(),messageId:l(),mode:xn,truncatedAt:l().optional()}).passthrough()}).passthrough(),lr=u({input:B().optional(),output:B().optional(),cacheRead:B().optional(),cacheWrite:B().optional(),total:B().optional()}).passthrough(),dr=u({tokens:B().nullable().optional(),contextWindow:B().optional(),percent:B().nullable().optional()}).passthrough(),ur=u({type:b("agent_session_stats_request"),requestId:l(),agentId:l()}).passthrough(),pr=u({type:b("agent_session_stats_response"),requestId:l(),payload:u({sessionId:l().optional(),sessionFile:l().optional(),userMessages:B().optional(),assistantMessages:B().optional(),toolCalls:B().optional(),toolResults:B().optional(),totalMessages:B().optional(),tokens:lr.optional(),cost:B().optional(),contextUsage:dr.optional(),model:l().optional()}).passthrough()}).passthrough(),fr=u({type:b("agent_compact_request"),requestId:l(),agentId:l(),customInstructions:l().optional()}).passthrough(),hr=u({type:b("agent_compact_response"),requestId:l(),payload:u({summary:l().optional(),firstKeptEntryId:l().optional(),tokensBefore:B().optional(),details:W().optional()}).passthrough()}).passthrough(),mr=u({type:b("agent_new_session_request"),requestId:l(),agentId:l()}).passthrough(),gr=u({type:b("agent_new_session_response"),requestId:l(),payload:u({cancelled:$()}).passthrough()}).passthrough(),_r=u({type:b("agent_switch_session_request"),requestId:l(),agentId:l(),sessionPath:l()}).passthrough(),yr=u({type:b("agent_switch_session_response"),requestId:l(),payload:u({cancelled:$()}).passthrough()}).passthrough(),br=u({type:b("agent_fork_request"),requestId:l(),agentId:l(),entryId:l()}).passthrough(),wr=u({type:b("agent_fork_response"),requestId:l(),payload:u({text:l(),cancelled:$()}).passthrough()}).passthrough(),xr=u({type:b("agent_fork_messages_request"),requestId:l(),agentId:l()}).passthrough(),Sr=u({type:b("agent_fork_messages_response"),requestId:l(),payload:u({messages:H(u({entryId:l(),text:l()}).passthrough())}).passthrough()}).passthrough(),vr=u({type:b("agent_clone_request"),requestId:l(),agentId:l()}).passthrough(),kr=u({type:b("agent_clone_response"),requestId:l(),payload:u({cancelled:$()}).passthrough()}).passthrough(),Ir=u({type:b("agent_set_session_name_request"),requestId:l(),agentId:l(),name:l()}).passthrough(),jr=u({type:b("agent_set_session_name_response"),requestId:l(),payload:u({}).passthrough().optional()}).passthrough(),Cr=u({type:b("agent_export_html_request"),requestId:l(),agentId:l(),outputPath:l().optional()}).passthrough(),Tr=u({type:b("agent_export_html_response"),requestId:l(),payload:u({path:l()}).passthrough()}).passthrough(),Er=u({type:b("agent_set_model_request"),requestId:l(),agentId:l(),provider:l(),modelId:l()}).passthrough(),Nr=u({type:b("agent_set_model_response"),requestId:l(),payload:u({}).passthrough()}).passthrough(),Rr=u({type:b("agent_cycle_model_request"),requestId:l(),agentId:l()}).passthrough(),qr=u({type:b("agent_cycle_model_response"),requestId:l(),payload:u({model:W().nullable().optional(),thinkingLevel:l().optional(),isScoped:$().optional()}).passthrough()}).passthrough(),Mr=u({type:b("agent_last_assistant_text_request"),requestId:l(),agentId:l()}).passthrough(),Br=u({type:b("agent_last_assistant_text_response"),requestId:l(),payload:u({text:l().nullable()}).passthrough()}).passthrough(),$r=u({type:b("steer_agent_request"),requestId:l(),agentId:l(),message:l(),images:H(at).optional(),clientMessageId:l().optional()}).passthrough(),Ar=u({type:b("steer_agent_response"),requestId:l(),agentId:l(),ok:$()}).passthrough(),Dr=u({type:b("follow_up_agent_request"),requestId:l(),agentId:l(),message:l(),images:H(at).optional(),clientMessageId:l().optional()}).passthrough(),Pr=u({type:b("follow_up_agent_response"),requestId:l(),agentId:l(),ok:$()}).passthrough(),zr=u({name:l(),id:l().optional(),description:l().optional(),source:ye(["extension","prompt","skill"]).optional(),scope:ye(["user","project","temporary"]).optional(),path:l().optional()}).passthrough(),Or=u({type:b("agent_list_commands_request"),requestId:l(),agentId:l()}).passthrough(),Fr=u({type:b("agent_list_commands_response"),requestId:l(),payload:u({commands:H(zr)}).passthrough()}).passthrough(),Wr=u({type:b("rpc_error"),requestId:l(),code:l().optional(),message:l().optional(),error:l().optional()}),Lr=rt("type",[Lo,Ho,Uo,Ko,Vo,Go,Xo,Yo,er,tr,nr,sr,or,rr,ar,ir,cr,ur,pr,fr,hr,mr,gr,_r,yr,br,wr,xr,Sr,vr,kr,Ir,jr,Cr,Tr,Er,Nr,Rr,qr,Mr,Br,$r,Ar,Dr,Pr,Or,Fr,Wr]),Hr=u({type:l()}).passthrough(),Ur=u({type:b("session"),message:Zt([Lr,Hr])});rt("type",[Ao,Po,zo,Oo,Ur]);const Kr={inline_image_markdown:"inline_image_markdown"},we={Output:1,Input:2,Resize:3,Snapshot:4,Restore:5},Vr=Object.fromEntries(Object.entries(we).map(([e,t])=>[t,e])),Sn=u({rows:B().int().nonnegative(),cols:B().int().nonnegative()});class De extends Error{constructor(t){super(t),this.name="TerminalFrameError"}}const Gr=new TextEncoder,Xr=new TextDecoder;function Jr(e){if(!Number.isInteger(e)||e<0||e>255)throw new De(`slot must be an integer 0–255, got ${e}`)}function $e(e,t,n){const s=new Uint8Array(2+n.length);return s[0]=e,s[1]=t,s.set(n,2),s}function Vu(e){switch(Jr(e.slot),e.opcode){case"Output":return $e(we.Output,e.slot,e.data);case"Input":return $e(we.Input,e.slot,e.data);case"Snapshot":return $e(we.Snapshot,e.slot,e.data);case"Restore":return $e(we.Restore,e.slot,e.data);case"Resize":{const t=JSON.stringify(Sn.parse({rows:e.rows,cols:e.cols}));return $e(we.Resize,e.slot,Gr.encode(t))}}}function Yr(e){if(e.length<2)throw new De(`frame too short: ${e.length} bytes (need ≥ 2)`);const t=e[0],n=e[1],s=Vr[t];if(!s)throw new De(`unknown terminal opcode 0x${t.toString(16)}`);const o=e.subarray(2);if(s==="Resize"){let r;try{r=JSON.parse(Xr.decode(o))}catch{throw new De("resize payload is not valid JSON")}const i=Sn.safeParse(r);if(!i.success)throw new De("resize payload is not { rows, cols }");return{opcode:"Resize",slot:n,rows:i.data.rows,cols:i.data.cols}}return{opcode:s,slot:n,data:o.slice()}}const Se={Begin:16,Chunk:17,End:18,Error:19},Qr=Object.fromEntries(Object.entries(Se).map(([e,t])=>[t,e])),vn=u({transferId:l(),fileName:l().optional(),mimeType:l().optional(),totalBytes:B().int().nonnegative().optional()});class Pe extends Error{constructor(t){super(t),this.name="FileTransferFrameError"}}const $t=new TextEncoder,At=new TextDecoder;function Zr(e){if(!Number.isInteger(e)||e<0||e>255)throw new Pe(`stream must be an integer 0–255, got ${e}`)}function Ye(e,t,n){const s=new Uint8Array(2+n.length);return s[0]=e,s[1]=t,s.set(n,2),s}function lt(e){switch(Zr(e.stream),e.opcode){case"Begin":return Ye(Se.Begin,e.stream,$t.encode(JSON.stringify(vn.parse(e.meta))));case"Chunk":return Ye(Se.Chunk,e.stream,e.data);case"End":return Ye(Se.End,e.stream,new Uint8Array([e.ok?1:0]));case"Error":return Ye(Se.Error,e.stream,$t.encode(e.message))}}function ea(e){if(e.length<2)throw new Pe(`frame too short: ${e.length} bytes (need ≥ 2)`);const t=e[0],n=e[1],s=Qr[t];if(!s)throw new Pe(`unknown file-transfer opcode 0x${t.toString(16)}`);const o=e.subarray(2);switch(s){case"Begin":{let r;try{r=JSON.parse(At.decode(o))}catch{throw new Pe("begin payload is not valid JSON")}const i=vn.safeParse(r);if(!i.success)throw new Pe("begin payload is not a valid transfer header");return{opcode:"Begin",stream:n,meta:i.data}}case"Chunk":return{opcode:"Chunk",stream:n,data:o.slice()};case"End":return{opcode:"End",stream:n,ok:(o[0]??1)!==0};case"Error":return{opcode:"Error",stream:n,message:At.decode(o)}}}function ta(e){try{return ea(e)}catch{return null}}const na=l().regex(/^[a-z][a-z0-9-]*$/,"invalid provider id"),sa=ye(["safe","moderate","dangerous","planning"]),oa=u({supportsStreaming:$(),supportsSessionPersistence:$(),supportsDynamicModes:$(),supportsMcpServers:$(),supportsReasoningStream:$(),supportsToolInvocations:$(),supportsRewindConversation:$().optional(),supportsRewindFiles:$().optional(),supportsRewindBoth:$().optional(),supportsSteering:$().optional()}).passthrough(),ra=u({id:l(),label:l().optional(),description:l().optional(),icon:l().optional(),colorTier:sa});u({id:na,label:l(),description:l().optional(),extends:l().optional(),modes:H(ra),capabilities:oa});function yt(e){return typeof e=="string"?e:e instanceof Uint8Array||Buffer.isBuffer(e)?e.toString("utf8"):String(e??"")}function kn(e){let t=null;const n={onMessage:null,onClose:null,onError:null,get isOpen(){return t!==null&&t.readyState===1},connect(s){return new Promise((o,r)=>{const i=e??(()=>new WebSocket(s));try{t=e?i(s):new WebSocket(s),t.binaryType="arraybuffer"}catch(c){r(c);return}t.onopen=()=>o(),t.onerror=c=>{var d;(t==null?void 0:t.readyState)!==1&&r(c),(d=n.onError)==null||d.call(n,c)},t.onclose=c=>{var d;(d=n.onClose)==null||d.call(n,c.code,yt(c.reason))},t.onmessage=c=>{var h,p,w,f;const{data:d}=c;d instanceof ArrayBuffer||d instanceof Uint8Array?(h=n.onMessage)==null||h.call(n,d):typeof d=="string"?(p=n.onMessage)==null||p.call(n,d):typeof Blob<"u"&&d instanceof Blob?(w=n.onMessage)==null||w.call(n,d):Buffer.isBuffer(d)&&((f=n.onMessage)==null||f.call(n,d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength)))}})},sendText(s){t==null||t.send(s)},sendBinary(s){t==null||t.send(s)},close(s=1e3,o=""){t==null||t.close(s,o),t=null}};return n}const ze="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function In(e){let t="";for(let n=0;n<e.length;n+=3){const s=e[n],o=n+1<e.length,r=n+2<e.length,i=o?e[n+1]:0,c=r?e[n+2]:0;t+=ze[s>>2],t+=ze[(s&3)<<4|i>>4],t+=o?ze[(i&15)<<2|c>>6]:"=",t+=r?ze[c&63]:"="}return t}function jn(e){const t=e.replace(/=+$/,""),n=[];let s=0,o=0;for(const r of t){const i=ze.indexOf(r);if(i===-1)throw new Error(`invalid base64 character: ${JSON.stringify(r)}`);s=s<<6|i,o+=6,o>=8&&(o-=8,n.push(s>>o&255))}return new Uint8Array(n)}function aa(e){try{const t=JSON.parse(e);return!t||typeof t.type!="string"?null:t}catch{return null}}const tt=24;function Cn(e,t){const n=ve.randomBytes(tt),s=ve.box.after(e,n,t),o=new Uint8Array(n.length+s.length);return o.set(n,0),o.set(s,n.length),In(o)}function Tn(e,t){let n;try{n=jn(e)}catch{return null}if(n.length<tt)return null;const s=n.slice(0,tt),o=n.slice(tt);return ve.box.open.after(o,s,t)}function ia(e,t){return Cn(new TextEncoder().encode(e),t)}function ca(e,t){const n=Tn(e,t);return n?new TextDecoder().decode(n):null}function la(e,t,n,s,o,r){let i=!1;return n.onClose(c=>{var d;i=!0,(d=s.onClose)==null||d.call(s,c)}),{handleAppFrame(c){var p,w;if(i)return;const d=o();if(!r()||!d)return;const h=ca(c.frame,d);if(h===null){(p=s.onAuthError)==null||p.call(s,new Error(`relay ${e} channel: message failed authentication`));return}(w=s.onMessage)==null||w.call(s,h)},handleBinaryFrame(c){var p,w;if(i)return;const d=o();if(!r()||!d)return;const h=Tn(c.frame,d);if(h===null){(p=s.onAuthError)==null||p.call(s,new Error(`relay ${e} channel: binary message failed authentication`));return}(w=s.onBinaryMessage)==null||w.call(s,h)},send(c){if(i)throw new Error(`relay ${e} channel: cannot send after close()`);const d=o();if(!r()||!d)throw new Error(`relay ${e} channel: cannot send before the E2EE handshake completes`);n.send(JSON.stringify({type:"e2ee_app",frame:ia(c,d)}))},sendBinary(c){if(i)throw new Error(`relay ${e} channel: cannot send after close()`);const d=o();if(!r()||!d)throw new Error(`relay ${e} channel: cannot send before the E2EE handshake completes`);n.send(JSON.stringify({type:"e2ee_bin",frame:Cn(c,d)}))},close(){i||(i=!0,n.close())}}}function da(e){const{transport:t,attachment:n,daemonPublicKey:s}=e,o=e.events??{},r=ve.box.keyPair(),i=ve.box.before(s,r.secretKey);let c=!1;const d=la("client",n,t,o,()=>i,()=>c);return t.onMessage(h=>{var w;const p=aa(h);if(p){if(p.type==="e2ee_ready"){if(c)return;c=!0,(w=o.onReady)==null||w.call(o);return}if(p.type==="e2ee_app"){d.handleAppFrame(p);return}p.type==="e2ee_bin"&&d.handleBinaryFrame(p)}}),t.send(JSON.stringify({type:"e2ee_hello",ephemeralPublicKey:In(r.publicKey)})),{role:"client",attachment:n,get ready(){return c},send:d.send,sendBinary:d.sendBinary,close:d.close}}const ua=16;function pa(e){const t=ve.hash(e);let n="";for(let s=0;s<ua;s++)n+=t[s].toString(16).padStart(2,"0");return n}function fa(e){const t=e.useTls?"wss":"ws",n=e.endpoint.replace(/^(?:https?|wss?):\/\//,"").replace(/\/+$/,"");return`${t}://${n}`}function ha(e){let t=null,n=null;const s=e.sessionId??pa(e.daemonPublicKey),o={onMessage:null,onClose:null,onError:null,get isOpen(){return t!==null&&t.readyState===1&&n!==null&&n.ready},connect(r){return new Promise((i,c)=>{const d=e.factory??(()=>new WebSocket(r));try{t=e.factory?d(r):new WebSocket(r)}catch(f){c(f);return}const h=t,p=[],w=[];h.onopen=()=>{h.send(JSON.stringify({type:"relay_register",sessionId:s})),n=da({transport:{send:f=>h.send(f),onMessage:f=>p.push(f),onClose:f=>w.push(f),close:()=>h.close()},attachment:{sessionId:s},daemonPublicKey:e.daemonPublicKey,events:{onReady:()=>i(),onMessage:f=>{var m;return(m=o.onMessage)==null?void 0:m.call(o,f)},onBinaryMessage:f=>{var m;return(m=o.onMessage)==null?void 0:m.call(o,f.slice().buffer)},onAuthError:f=>{var m;return(m=o.onError)==null?void 0:m.call(o,f)}}})},h.onerror=f=>{var m;h.readyState!==1&&c(f),(m=o.onError)==null||m.call(o,f)},h.onclose=f=>{var m;for(const v of w)v(yt(f.reason));(m=o.onClose)==null||m.call(o,f.code,yt(f.reason))},h.onmessage=f=>{const{data:m}=f;if(typeof m=="string")for(const v of p)v(m)}})},sendText(r){if(!n||!n.ready)throw new Error("relay transport: cannot send before the E2EE handshake completes");n.send(r)},sendBinary(r){if(!n||!n.ready)throw new Error("relay transport: cannot send before the E2EE handshake completes");n.sendBinary(r)},close(r=1e3,i=""){n==null||n.close(),n=null,t==null||t.close(r,i),t=null}};return o}function ma(e){const t=e.indexOf("#"),n=t===-1?e:e.slice(t+1),s=new URLSearchParams(n),o=s.get("offer");if(!o)return null;let r;try{r=jn(o)}catch{return null}const i=s.get("relay");if(i){const d={endpoint:i,useTls:s.get("relayTls")==="1"};return{publicKeyB64:o,publicKey:r,relay:d}}const c=s.get("host")??void 0;return{publicKeyB64:o,publicKey:r,...c?{host:c}:{}}}const ga=1;function bt(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`id-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}class _a extends Error{constructor(t,n,s){super(t),this.requestId=n,this.code=s,this.name="RpcError"}}class Dt extends Error{constructor(t){super(`RPC ${t} timed out`),this.requestId=t,this.name="RpcTimeoutError"}}class ya{constructor(t){C(this,"transport");C(this,"rpcTimeoutMs");C(this,"now");C(this,"_state","idle");C(this,"_serverId",null);C(this,"_features",{});C(this,"_serverCapabilities",{});C(this,"pending",new Map);C(this,"sessionHandlers",new Set);C(this,"terminalHandlers",new Set);C(this,"fileTransferHandlers",new Set);C(this,"stateHandlers",new Set);C(this,"helloResolve",null);C(this,"helloReject",null);this.options=t,this.transport=t.transport??kn(),this.rpcTimeoutMs=t.rpcTimeoutMs??3e4,this.now=t.now??(()=>Date.now()),this.transport.onMessage=n=>this.handleIncoming(n),this.transport.onClose=(n,s)=>this.handleClose(n,s),this.transport.onError=()=>{}}get state(){return this._state}get serverId(){return this._serverId}get features(){return this._features}get serverCapabilities(){return this._serverCapabilities}hasFeature(t){return!!this._features[t]}async connect(){this.setState("connecting"),await this.transport.connect(this.options.url);const t=new Promise((s,o)=>{this.helloResolve=s,this.helloReject=o});this.transport.sendText(JSON.stringify({type:"hello",clientId:this.options.clientId,clientType:this.options.clientType,protocolVersion:this.options.protocolVersion??ga,appVersion:this.options.appVersion,capabilities:this.options.capabilities}));const n=await t;return this._serverId=n.serverId,this._features=n.features,this._serverCapabilities=n.capabilities,this.setState("open"),n}close(t=1e3,n=""){this.setState("closing"),this.transport.close(t,n)}request(t,n={},s){const o=n.requestId??bt();return new Promise((r,i)=>{const c=s??this.rpcTimeoutMs,d=c>0?setTimeout(()=>{this.pending.delete(o),i(new Dt(o))},c):null;this.pending.set(o,{resolve:h=>r(h),reject:i,timer:d}),this.sendSession({type:t,...n,requestId:o})})}sendSession(t){this.transport.sendText(JSON.stringify({type:"session",message:t}))}sendBinary(t){this.transport.sendBinary(t)}ping(t=1e4){const n=bt();return new Promise((s,o)=>{const r=t>0?setTimeout(()=>{this.pending.delete(n),o(new Dt(n))},t):null;this.pending.set(n,{resolve:()=>s(),reject:o,timer:r}),this.transport.sendText(JSON.stringify({type:"ping",requestId:n,clientSentAt:this.now()}))})}onSessionMessage(t){return this.sessionHandlers.add(t),()=>this.sessionHandlers.delete(t)}onTerminalFrame(t){return this.terminalHandlers.add(t),()=>this.terminalHandlers.delete(t)}onFileTransferFrame(t){return this.fileTransferHandlers.add(t),()=>this.fileTransferHandlers.delete(t)}onStateChange(t){return this.stateHandlers.add(t),()=>this.stateHandlers.delete(t)}setState(t){if(this._state!==t){this._state=t;for(const n of this.stateHandlers)n(t)}}handleClose(t,n){this.helloReject&&(this.helloReject(new Error(`socket closed during handshake: ${n}`)),this.helloResolve=null,this.helloReject=null);for(const[,s]of this.pending)s.timer&&clearTimeout(s.timer),s.reject(new Error(`socket closed: ${n}`));this.pending.clear(),this.setState("closed")}handleIncoming(t){if(typeof t=="string"){this.handleTextFrame(t);return}if(t instanceof ArrayBuffer){this.handleBinaryFrame(new Uint8Array(t));return}typeof t.arrayBuffer=="function"&&t.arrayBuffer().then(n=>this.handleBinaryFrame(new Uint8Array(n)))}handleBinaryFrame(t){const n=t[0];if(n!==void 0&&Object.values(Se).includes(n)){const r=ta(t);if(!r)return;for(const i of this.fileTransferHandlers)i(r);return}const o=Yr(t);for(const r of this.terminalHandlers)r(o)}handleTextFrame(t){let n;try{n=JSON.parse(t)}catch{return}const s=n;switch(s.type){case"status":this.handleStatus(s);return;case"pong":this.resolvePending(s.requestId,void 0);return;case"ping":this.transport.sendText(JSON.stringify({type:"pong",requestId:s.requestId,serverReceivedAt:this.now(),serverSentAt:this.now()}));return;case"session":this.handleSession(s.message);return;default:return}}handleStatus(t){const n=t.payload;(n==null?void 0:n.status)==="server_info"&&this.helloResolve&&(this.helloResolve(n),this.helloResolve=null,this.helloReject=null)}handleSession(t){if(!t||typeof t!="object")return;const n=t;if(n.type==="rpc_error"&&typeof n.requestId=="string"){const s=this.pending.get(n.requestId);s&&(s.timer&&clearTimeout(s.timer),this.pending.delete(n.requestId),s.reject(new _a(n.message??n.error??"RPC failed",n.requestId,n.code)));return}if(typeof n.requestId=="string"&&this.pending.has(n.requestId)){const s="payload"in n?n.payload:n;this.resolvePending(n.requestId,s)}for(const s of this.sessionHandlers)s(t)}resolvePending(t,n){const s=this.pending.get(t);s&&(s.timer&&clearTimeout(s.timer),this.pending.delete(t),s.resolve(n))}}class ba{constructor(t){this.daemon=t}get connection(){return this.daemon}async createAgent(t){return await this.daemon.request("create_agent_request",{...t})}agent(t){return new xa(this.daemon,t)}workspace(t){return new Sa(this.daemon,t)}get providers(){return new va(this.daemon)}onAgentUpdate(t){return this.daemon.onSessionMessage(n=>{n.type==="agent_update"&&t(n)})}onWorkspaceUpdate(t){return this.daemon.onSessionMessage(n=>{n.type==="workspace_update"&&t(n)})}}class wa{constructor(t,n){this.daemon=t,this.agentId=n}fetch(t={}){return this.daemon.request("fetch_agent_timeline_request",{agentId:this.agentId,cursor:t.cursor,direction:t.direction,limit:t.limit})}subscribe(t){return this.daemon.onSessionMessage(n=>{const s=n;s.type==="agent_stream"&&s.agentId===this.agentId&&s.event&&t(s.event)})}}class xa{constructor(t,n){C(this,"timeline");this.daemon=t,this.agentId=n,this.timeline=new wa(t,n)}send(t,n={}){return this.daemon.request("send_agent_prompt",{agentId:this.agentId,prompt:t,clientMessageId:n.clientMessageId,images:n.images})}run(t,n){return this.send(t,n)}interrupt(){return this.daemon.request("interrupt_agent",{agentId:this.agentId})}steer(t,n={}){return this.daemon.request("steer_agent_request",{agentId:this.agentId,message:t,clientMessageId:n.clientMessageId,images:n.images})}followUp(t,n={}){return this.daemon.request("follow_up_agent_request",{agentId:this.agentId,message:t,clientMessageId:n.clientMessageId,images:n.images})}update(t){return this.daemon.request("update_agent",{agentId:this.agentId,...t})}resume(){return this.daemon.request("resume_agent",{agentId:this.agentId})}archive(){return this.daemon.request("archive_agent",{agentId:this.agentId})}delete(){return this.daemon.request("delete_agent",{agentId:this.agentId})}onUpdate(t){return this.daemon.onSessionMessage(n=>{const s=n;s.type==="agent_update"&&s.agentId===this.agentId&&t(s)})}sessionStats(){return this.daemon.request("agent_session_stats_request",{agentId:this.agentId})}compact(t){return this.daemon.request("agent_compact_request",{agentId:this.agentId,customInstructions:t})}newSession(){return this.daemon.request("agent_new_session_request",{agentId:this.agentId})}switchSession(t){return this.daemon.request("agent_switch_session_request",{agentId:this.agentId,sessionPath:t})}fork(t){return this.daemon.request("agent_fork_request",{agentId:this.agentId,entryId:t})}forkMessages(){return this.daemon.request("agent_fork_messages_request",{agentId:this.agentId})}clone(){return this.daemon.request("agent_clone_request",{agentId:this.agentId})}setSessionName(t){return this.daemon.request("agent_set_session_name_request",{agentId:this.agentId,name:t})}exportHtml(t){return this.daemon.request("agent_export_html_request",{agentId:this.agentId,outputPath:t})}setModel(t,n){return this.daemon.request("agent_set_model_request",{agentId:this.agentId,provider:t,modelId:n})}cycleModel(){return this.daemon.request("agent_cycle_model_request",{agentId:this.agentId})}lastAssistantText(){return this.daemon.request("agent_last_assistant_text_request",{agentId:this.agentId})}listCommands(){return this.daemon.request("agent_list_commands_request",{agentId:this.agentId})}}class Sa{constructor(t,n){this.daemon=t,this.workspaceId=n}onUpdate(t){return this.daemon.onSessionMessage(n=>{const s=n;s.type==="workspace_update"&&s.workspaceId===this.workspaceId&&t(s)})}}class va{constructor(t){this.daemon=t}listProviders(){return this.daemon.request("list_providers",{})}listModels(t){return this.daemon.request("list_provider_models",{provider:t})}listModes(t){return this.daemon.request("list_provider_modes",{provider:t})}resolveDefaultModel(t,n){return this.daemon.request("resolve_default_model",{provider:t,...n?{cwd:n}:{}})}refreshSnapshot(){return this.daemon.request("providers.snapshot.refresh.request",{})}}const Pt=32*1024;function ka(e){const t=e.reduce((o,r)=>o+r.length,0),n=new Uint8Array(t);let s=0;for(const o of e)n.set(o,s),s+=o.length;return n}class Ia{constructor(t){C(this,"pending",new Map);C(this,"nextStream",1);C(this,"detach",null);this.daemon=t}start(){this.detach||(this.detach=this.daemon.onFileTransferFrame(t=>this.dispatch(t)))}stop(){var t;(t=this.detach)==null||t.call(this),this.detach=null;for(const[n,s]of this.pending)s.reject(new Error("file transfer router stopped")),this.pending.delete(n)}async download(t){const n=await this.daemon.request("file_download_token_request",{path:t});if(!n.ok||!n.token)throw new Error(n.error??"failed to issue download token");const s=this.nextStream++,o=new Promise((i,c)=>{this.pending.set(s,{chunks:[],meta:{},resolve:i,reject:c})}),r=await this.daemon.request("file_download_request",{token:n.token,stream:s});if(!r.ok)throw this.pending.delete(s),new Error(r.error??"download request failed");return o}async upload(t,n){const s=bt(),o=await this.daemon.request("file_upload_request",{path:t,transferId:s});if(!o.ok||o.stream===void 0)throw new Error(o.error??"upload request failed");const r=o.stream;this.daemon.sendBinary(lt({opcode:"Begin",stream:r,meta:{transferId:s}}));for(let i=0;i<n.length;i+=Pt){const c=n.subarray(i,i+Pt);this.daemon.sendBinary(lt({opcode:"Chunk",stream:r,data:c}))}this.daemon.sendBinary(lt({opcode:"End",stream:r,ok:!0}))}dispatch(t){const n=this.pending.get(t.stream);if(n)switch(t.opcode){case"Begin":n.meta.fileName=t.meta.fileName,n.meta.mimeType=t.meta.mimeType;return;case"Chunk":n.chunks.push(t.data);return;case"End":this.pending.delete(t.stream),t.ok?n.resolve({bytes:ka(n.chunks),...n.meta}):n.reject(new Error("download failed"));return;case"Error":this.pending.delete(t.stream),n.reject(new Error(t.message));return}}}class ja{constructor(t,n={}){C(this,"initialDelayMs");C(this,"maxDelayMs");C(this,"factor");C(this,"jitter");C(this,"maxAttempts");C(this,"setTimer");C(this,"clearTimer");C(this,"random");C(this,"attempt",0);C(this,"timer",null);C(this,"active",!1);C(this,"detachState",null);C(this,"reconnectedHandlers",new Set);C(this,"failedHandlers",new Set);this.daemon=t,this.initialDelayMs=n.initialDelayMs??500,this.maxDelayMs=n.maxDelayMs??3e4,this.factor=n.factor??2,this.jitter=n.jitter??.2,this.maxAttempts=n.maxAttempts??Number.POSITIVE_INFINITY,this.setTimer=n.setTimer??((s,o)=>setTimeout(s,o)),this.clearTimer=n.clearTimer??(s=>clearTimeout(s)),this.random=n.random??Math.random}delayForAttempt(t){const n=Math.min(this.maxDelayMs,this.initialDelayMs*this.factor**(t-1)),s=n*this.jitter*(this.random()*2-1);return Math.max(0,Math.round(n+s))}onReconnected(t){return this.reconnectedHandlers.add(t),()=>this.reconnectedHandlers.delete(t)}onReconnectFailed(t){return this.failedHandlers.add(t),()=>this.failedHandlers.delete(t)}start(){this.active||(this.active=!0,this.detachState=this.daemon.onStateChange(t=>{t==="closed"&&this.active&&this.scheduleReconnect(),t==="open"&&(this.attempt=0)}))}stop(){var t;this.active=!1,this.timer&&this.clearTimer(this.timer),this.timer=null,(t=this.detachState)==null||t.call(this),this.detachState=null}get attemptCount(){return this.attempt}scheduleReconnect(){if(!this.active||this.attempt>=this.maxAttempts)return;this.attempt+=1;const t=this.delayForAttempt(this.attempt);this.timer=this.setTimer(()=>{this.timer=null,this.tryReconnect()},t)}async tryReconnect(){if(!this.active)return;const t=this.attempt;try{await this.daemon.connect();for(const n of this.reconnectedHandlers)n({attempt:t,serverId:this.daemon.serverId})}catch(n){for(const s of this.failedHandlers)s(n,t);this.scheduleReconnect()}}}function zt(e){const t=e.trim();if(t==="")return t;const n=t.match(/^([a-z][a-z0-9+.-]*):\/\//i);if(!n)return`ws://${t.replace(/\/+$/,"")}`;const s=n[1].toLowerCase(),o=t.slice(n[0].length).replace(/\/+$/,"");switch(s){case"http":return`ws://${o}`;case"https":return`wss://${o}`;case"ws":case"wss":return`${s}://${o}`;default:return t}}function Ca(e){const t=ma(e);return t!=null&&t.relay?{mode:"relay",url:fa(t.relay),daemonPublicKey:t.publicKey}:t!=null&&t.host?{mode:"direct",url:zt(t.host)}:{mode:"direct",url:zt(e)}}const Ta=32,G=new Map;function Ea(){for(;G.size>Ta;){let e=null;for(const[t,n]of G)if(n.refs===0&&n.entry){URL.revokeObjectURL(n.entry.objectUrl),e=t;break}if(e===null)return;G.delete(e)}}function Gu(e,t){const n=G.get(e);if(n)return n.refs+=1,G.delete(e),G.set(e,n),n.entry?Promise.resolve(n.entry):n.pending;const s={refs:1,entry:null,pending:null};return G.set(e,s),Ea(),s.pending=t(e).then(o=>{const r=new Blob([Uint8Array.from(o.bytes)],{type:o.mimeType||"application/octet-stream"}),i={objectUrl:URL.createObjectURL(r),mimeType:o.mimeType};return G.get(e)===s?(s.entry=i,s.pending=null):URL.revokeObjectURL(i.objectUrl),i}).catch(o=>{throw G.get(e)===s&&G.delete(e),o}),s.pending}function Xu(e){const t=G.get(e);t&&(t.refs=Math.max(0,t.refs-1))}function Na(){for(const e of G.values())e.entry&&URL.revokeObjectURL(e.entry.objectUrl);G.clear()}function Ra(){return"web-"+Math.random().toString(36).slice(2,10)}const E=be()((e,t)=>({status:"idle",serverInfo:null,error:null,daemon:null,client:null,reconnection:null,async connect(n){t().disconnect();const s=Ca(n.url);let o;s.mode==="relay"?o=ha({daemonPublicKey:s.daemonPublicKey}):n.password&&(o=kn(d=>new WebSocket(d,[`pi-studio.bearer.${n.password}`])));const r=new ya({url:s.url,clientId:n.clientId??Ra(),clientType:"browser",capabilities:{[Kr.inline_image_markdown]:!0},transport:o,rpcTimeoutMs:1800*1e3}),i=new ba(r),c=new ja(r);r.onStateChange(d=>e({status:d})),c.onReconnected(()=>e({error:null})),c.onReconnectFailed(d=>{e({error:d instanceof Error?d.message:String(d)})}),e({daemon:r,client:i,reconnection:c,error:null,status:"connecting"});try{const d=await r.connect();e({serverInfo:d}),c.start()}catch(d){throw e({error:d instanceof Error?d.message:String(d)}),d}},disconnect(){const{daemon:n,reconnection:s}=t();s==null||s.stop(),n==null||n.close(),Na(),e({status:"idle",serverInfo:null,daemon:null,client:null,reconnection:null})}})),qa=100,Ma=480,Ba=220,$a=280;function Qe(e){return Math.min(Ma,Math.max(qa,e))}const j=be()(e=>({host:"ws://127.0.0.1:6767",password:"",cwd:"~",cwdPickerOpen:!1,sessionMenu:null,workspaceMenu:null,fileMenu:null,rightSidebarTab:"files",collapsedWorkspaces:new Set,leftSidebarCollapsed:!1,rightSidebarCollapsed:!1,leftSidebarWidth:Ba,rightSidebarWidth:$a,setHost:t=>e({host:t}),setPassword:t=>e({password:t}),setCwd:t=>e({cwd:t}),openCwdPicker:()=>e({cwdPickerOpen:!0}),closeCwdPicker:()=>e({cwdPickerOpen:!1}),openSessionMenu:(t,n,s)=>e({sessionMenu:{sessionId:t,x:n,y:s}}),closeSessionMenu:()=>e({sessionMenu:null}),openWorkspaceMenu:(t,n,s)=>e({workspaceMenu:{cwd:t,x:n,y:s}}),closeWorkspaceMenu:()=>e({workspaceMenu:null}),openFileMenu:(t,n,s,o,r)=>e({fileMenu:{path:t,isDirectory:n,x:s,y:o,background:r}}),closeFileMenu:()=>e({fileMenu:null}),setRightSidebarTab:t=>e({rightSidebarTab:t}),toggleWorkspaceCollapsed:t=>e(n=>{const s=new Set(n.collapsedWorkspaces);return s.has(t)?s.delete(t):s.add(t),{collapsedWorkspaces:s}}),setCollapsedWorkspaces:t=>e({collapsedWorkspaces:t}),toggleLeftSidebar:()=>e(t=>({leftSidebarCollapsed:!t.leftSidebarCollapsed})),toggleRightSidebar:()=>e(t=>({rightSidebarCollapsed:!t.rightSidebarCollapsed})),setLeftSidebarWidth:t=>e({leftSidebarWidth:Qe(t)}),setRightSidebarWidth:t=>e({rightSidebarWidth:Qe(t)}),resizeLeftSidebar:t=>e(n=>({leftSidebarWidth:Qe(n.leftSidebarWidth+t)})),resizeRightSidebar:t=>e(n=>({rightSidebarWidth:Qe(n.rightSidebarWidth+t)}))})),Aa="_wrap_emmus_1",Da="_dot_emmus_8",Pa="_open_emmus_15",za="_connecting_emmus_18",Oa="_closed_emmus_21",Fa="_idle_emmus_22",Wa="_closing_emmus_23",dt={wrap:Aa,dot:Da,open:Pa,connecting:za,closed:Oa,idle:Fa,closing:Wa},La={idle:"disconnected",connecting:"connecting…",open:"connected",closing:"disconnecting…",closed:"disconnected"};function Ha(){const e=E(n=>n.status),t=E(n=>n.error);return a.jsxs("span",{className:dt.wrap,title:t??void 0,children:[a.jsx("span",{className:F(dt.dot,dt[e])}),La[e]??e]})}const Ua="_toolbar_i9hmh_1",Ka="_brand_i9hmh_10",Va="_version_i9hmh_16",Ga="_sep_i9hmh_22",Xa="_host_i9hmh_28",Ja="_password_i9hmh_31",Ya="_sidebarToggles_i9hmh_34",he={toolbar:Ua,brand:Ka,version:Va,sep:Ga,host:Xa,password:Ja,sidebarToggles:Ya};function Qa(){const e=E(f=>f.status),t=E(f=>f.connect),n=E(f=>f.disconnect),s=j(f=>f.host),o=j(f=>f.setHost),r=j(f=>f.password),i=j(f=>f.setPassword),c=j(f=>f.leftSidebarCollapsed),d=j(f=>f.toggleLeftSidebar),h=j(f=>f.rightSidebarCollapsed),p=j(f=>f.toggleRightSidebar),w=e==="open"||e==="connecting";return a.jsxs("div",{className:he.toolbar,children:[a.jsx("span",{className:he.brand,children:"Pi-Studio"}),a.jsxs("span",{className:he.version,children:["v","0.0.51"]}),a.jsx(Ha,{}),a.jsx("div",{className:he.sep}),a.jsx(ot,{className:he.host,value:s,onChange:f=>o(f.target.value),placeholder:"host:port, ws://…/http://…, or a pasted pairing link",disabled:w}),a.jsx(ot,{className:he.password,type:"password",value:r,onChange:f=>i(f.target.value),placeholder:"password",disabled:w}),e==="open"||e==="connecting"||e==="closing"?a.jsx(K,{size:"sm",onClick:()=>n(),children:"Disconnect"}):a.jsx(K,{size:"sm",variant:"default",onClick:()=>void t({url:s,password:r||void 0}),children:"Connect"}),a.jsxs("div",{className:he.sidebarToggles,children:[a.jsx(K,{size:"sm",variant:"ghost",iconOnly:!0,title:c?"Show sessions sidebar":"Hide sessions sidebar",onClick:()=>d(),children:c?a.jsx(es,{size:16}):a.jsx(ts,{size:16})}),a.jsx(K,{size:"sm",variant:"ghost",iconOnly:!0,title:h?"Show files/changes sidebar":"Hide files/changes sidebar",onClick:()=>p(),children:h?a.jsx(ns,{size:16}):a.jsx(ss,{size:16})})]})]})}const wt={rows:[],streamingAssistantIndex:null,streamingReasoningIndex:null,toolIndexByCallId:{}};let Ot=0;function de(){return Ot+=1,`row-${Ot}`}function Za(e){switch(e.kind){case"shell":return e.command??"";case"read":case"write":return e.path??"";case"edit":return e.path??"";case"search":return e.query??"";case"fetch":return e.url??"";case"task":return e.description??"";default:return""}}function ei(e,t){return e??`${t.kind}:${Za(t)}`}function ti(e){return{...e,streamingAssistantIndex:null,streamingReasoningIndex:null}}function ni(e,t){var r;const n=e.rows.slice();let s=e.streamingAssistantIndex;if(s===null||((r=n[s])==null?void 0:r.kind)!=="assistant"){const i={kind:"assistant",id:de(),text:"",streaming:!0};n.push(i),s=n.length-1}const o=n[s];return!o||o.kind!=="assistant"?e:(n[s]={...o,text:o.text+t},{...e,rows:n,streamingAssistantIndex:s,streamingReasoningIndex:null})}function si(e,t){var r;const n=e.rows.slice();let s=e.streamingReasoningIndex;if(s===null||((r=n[s])==null?void 0:r.kind)!=="reasoning"){const i={kind:"reasoning",id:de(),text:"",streaming:!0};n.push(i),s=n.length-1}const o=n[s];return!o||o.kind!=="reasoning"?e:(n[s]={...o,text:o.text+t},{...e,rows:n,streamingReasoningIndex:s,streamingAssistantIndex:null})}function oi(e,t){if(e.kind!==t.kind)return t;const n={...e};for(const[s,o]of Object.entries(t))o!==void 0&&o!==""&&(n[s]=o);return n}function ri(e,t){var c;const n=ei(t.callId,t.tool),s=t.status==="completed"||t.status==="error"?t.status:"running",o=e.toolIndexByCallId[n],r=e.rows.slice();if(o!==void 0&&((c=r[o])==null?void 0:c.kind)==="tool"){const d=r[o];return d.kind!=="tool"?e:(r[o]={...d,tool:oi(d.tool,t.tool),status:s},{...e,rows:r,streamingAssistantIndex:null,streamingReasoningIndex:null})}const i={kind:"tool",id:de(),callId:n,tool:t.tool,status:s};return r.push(i),{...e,rows:r,toolIndexByCallId:{...e.toolIndexByCallId,[n]:r.length-1},streamingAssistantIndex:null,streamingReasoningIndex:null}}function Ct(e){const t=e.rows.slice();if(e.streamingAssistantIndex!==null){const n=t[e.streamingAssistantIndex];(n==null?void 0:n.kind)==="assistant"&&(t[e.streamingAssistantIndex]={...n,streaming:!1})}if(e.streamingReasoningIndex!==null){const n=t[e.streamingReasoningIndex];(n==null?void 0:n.kind)==="reasoning"&&(t[e.streamingReasoningIndex]={...n,streaming:!1})}return{...e,rows:t,streamingAssistantIndex:null,streamingReasoningIndex:null}}function ai(e,t){const n=Ct(e),s={kind:"error",id:de(),text:t||"turn failed"};return{...n,rows:[...n.rows,s]}}function ii(e){const t=Ct(e),n={kind:"system",id:de(),text:"(canceled)"};return{...t,rows:[...t.rows,n]}}function ci(e,t){const n={kind:"error",id:de(),text:t||"error"};return{...e,rows:[...e.rows,n]}}function li(e,t,n,s){if(s!==void 0){const r=e.rows.findIndex(i=>i.kind==="user"&&i.pending&&i.clientMessageId===s);if(r!==-1){const i=e.rows.slice(),c=i[r];if((c==null?void 0:c.kind)==="user")return i[r]={...c,text:t,images:n,pending:!1},{...e,rows:i}}}const o={kind:"user",id:de(),text:t,images:n,clientMessageId:s};return{...e,rows:[...e.rows,o]}}function di(e,t){let n=!1;const s=e.rows.map(o=>o.kind!=="user"||!o.queued||t.includes(o.text)?o:(n=!0,{...o,queued:!1}));return n?{...e,rows:s}:e}function En(e,t){switch(t.kind){case"turn_started":return ti(e);case"user_message":return li(e,t.text??"",t.images,t.messageId);case"assistant_message":return ni(e,t.text??"");case"reasoning":return si(e,t.text??"");case"tool_call":return ri(e,t);case"turn_completed":return Ct(e);case"turn_failed":return ai(e,t.error);case"turn_canceled":return ii(e);case"error":return ci(e,t.message);case"queue_update":return di(e,t.steering??[]);default:return e}}function ui(e,t,n,s,o){const r={kind:"user",id:de(),text:n,images:s,clientMessageId:t,pending:!0,queued:o};return{...e,rows:[...e.rows,r]}}function pi(e,t){const n=e.rows.findIndex(r=>r.kind==="user"&&r.pending&&r.clientMessageId===t);if(n===-1)return e;const s=e.rows.slice(),o=s[n];return(o==null?void 0:o.kind)!=="user"?e:(s[n]={...o,pending:!1,failed:!0},{...e,rows:s})}let Ft=0;function fi(){return Ft+=1,`s-${Date.now().toString(36)}-${Ft}`}const T=be()((e,t)=>({sessions:{},order:[],activeSessionId:null,createSession(n){const s=fi(),o={id:s,agentId:null,title:"New chat",status:"idle",cwd:n,timeline:wt,userMessageCount:0};return e(r=>({sessions:{...r.sessions,[s]:o},order:[s,...r.order],activeSessionId:s})),s},hydrate(n){e(s=>s.sessions[n.id]?s:{sessions:{...s.sessions,[n.id]:n},order:[...s.order,n.id]})},bindAgent(n,s){e(o=>{const r=o.sessions[n];return r?{sessions:{...o.sessions,[n]:{...r,agentId:s}}}:o})},setStatus(n,s){e(o=>{const r=o.sessions[n];return r?{sessions:{...o.sessions,[n]:{...r,status:s}}}:o})},setStatusByAgentId(n,s){const o=t().findByAgentId(n);o&&t().setStatus(o.id,s)},setModel(n,s,o){e(r=>{const i=r.sessions[n];return i?{sessions:{...r.sessions,[n]:{...i,model:s,modelProvider:o}}}:r})},setModelByAgentId(n,s,o){const r=t().findByAgentId(n);r&&t().setModel(r.id,s,o)},setTitle(n,s){e(o=>{const r=o.sessions[n];return r?{sessions:{...o.sessions,[n]:{...r,title:s}}}:o})},setCwd(n,s){e(o=>{const r=o.sessions[n];return r?{sessions:{...o.sessions,[n]:{...r,cwd:s}}}:o})},applyStreamEvent(n,s){e(o=>{const r=o.sessions[n];if(!r)return o;const i=En(r.timeline,s);let c=r.title;if(s.kind==="turn_completed"&&c==="New chat"){const d=i.rows.slice().reverse().find(h=>h.kind==="assistant");d&&d.kind==="assistant"&&d.text&&(c=d.text.slice(0,40)+(d.text.length>40?"…":""))}return{sessions:{...o.sessions,[n]:{...r,timeline:i,title:c}}}})},addOptimisticUserMessage(n,s,o,r,i){e(c=>{const d=c.sessions[n];if(!d)return c;const h=ui(d.timeline,s,o,r,i);return{sessions:{...c.sessions,[n]:{...d,timeline:h,userMessageCount:d.userMessageCount+1}}}})},markUserMessageFailed(n,s){e(o=>{const r=o.sessions[n];if(!r)return o;const i=pi(r.timeline,s);return{sessions:{...o.sessions,[n]:{...r,timeline:i}}}})},activate(n){e({activeSessionId:n})},remove(n){e(s=>{const{[n]:o,...r}=s.sessions,i=s.order.filter(d=>d!==n),c=s.activeSessionId===n?i[0]??null:s.activeSessionId;return{sessions:r,order:i,activeSessionId:c}})},findByAgentId(n){return Object.values(t().sessions).find(s=>s.agentId===n)}})),Wt=new WeakMap;function hi(e,t="pi"){const n=Wt.get(e);if(n)return n;const s=e.providers.resolveDefaultModel(t).then(o=>({model:o.model,modelProvider:o.modelProvider})).catch(()=>({}));return Wt.set(e,s),s}const nt=new Map;function Nn(e,t){const n=T.getState().sessions[t];if(!n)return Promise.reject(new Error(`unknown session: ${t}`));if(n.agentId)return Promise.resolve(n.agentId);const s=nt.get(t);if(s)return s;const o=(async()=>{if(!n.model){const d=await hi(e),h=T.getState().sessions[t];d.model&&h&&!h.model&&T.getState().setModel(t,d.model,d.modelProvider)}const r=T.getState().sessions[t];if(!r)throw new Error(`unknown session: ${t}`);const i={provider:"pi",cwd:r.cwd||"~"};r.model&&(i.model=r.model),r.modelProvider&&(i.modelProvider=r.modelProvider);const c=await e.createAgent({config:i,labels:{}});return T.getState().bindAgent(t,c.agentId),c.agentId})();return nt.set(t,o),o.finally(()=>nt.delete(t)),o}async function mi(e,t){var o;const n=T.getState().sessions[t];if(!n||n.userMessageCount>0||n.timeline.rows.length>0)return!1;await((o=nt.get(t))==null?void 0:o.catch(()=>{}));const s=T.getState().sessions[t];return s?(s.agentId&&e&&await e.agent(s.agentId).delete().catch(()=>{}),T.getState().remove(t),!0):!1}function ut(e,t){return e.filter(n=>n.workspaceCwd===t)}function Ze(e){(e==null?void 0:e.kind)==="chat"&&T.getState().activate(e.data.sessionId)}const N=be()((e,t)=>({tabs:[],activeTabId:null,activeWorkspaceCwd:null,lastActiveTabByWorkspace:{},open(n){const s=t().tabs.find(o=>o.id===n.id);if(s){t().activate(s.id);return}e(o=>({tabs:[...o.tabs,n],activeTabId:n.id,activeWorkspaceCwd:n.workspaceCwd,lastActiveTabByWorkspace:{...o.lastActiveTabByWorkspace,[n.workspaceCwd]:n.id}})),Ze(n)},close(n){let s;e(o=>{const r=o.tabs.find(p=>p.id===n);if(!r)return o;const i=o.tabs.findIndex(p=>p.id===n),c=o.tabs.filter(p=>p.id!==n);let d=o.activeTabId;const h={...o.lastActiveTabByWorkspace};if(d===n){const p=ut(c,r.workspaceCwd),w=Math.min(i,p.length-1),f=p[w];d=(f==null?void 0:f.id)??null,s=f}if(h[r.workspaceCwd]===n){const p=ut(c,r.workspaceCwd)[0];p?h[r.workspaceCwd]=p.id:delete h[r.workspaceCwd]}return{tabs:c,activeTabId:d,lastActiveTabByWorkspace:h}}),Ze(s)},activate(n){let s;e(o=>{const r=o.tabs.find(i=>i.id===n);return r?(s=r,{activeTabId:n,activeWorkspaceCwd:r.workspaceCwd,lastActiveTabByWorkspace:{...o.lastActiveTabByWorkspace,[r.workspaceCwd]:n}}):o}),Ze(s)},switchWorkspace(n){let s;e(o=>{var h;const r=ut(o.tabs,n),i=o.lastActiveTabByWorkspace[n],d=i&&r.some(p=>p.id===i)?i:((h=r[0])==null?void 0:h.id)??null;return s=r.find(p=>p.id===d),{activeWorkspaceCwd:n,activeTabId:d,lastActiveTabByWorkspace:d?{...o.lastActiveTabByWorkspace,[n]:d}:o.lastActiveTabByWorkspace}}),Ze(s)},reorder(n,s){e(o=>{const r=o.tabs.findIndex(h=>h.id===n),i=o.tabs.findIndex(h=>h.id===s);if(r===-1||i===-1||r===i)return o;const c=o.tabs.slice(),[d]=c.splice(r,1);return d?(c.splice(i,0,d),{tabs:c}):o})},updateLabel(n,s){e(o=>({tabs:o.tabs.map(r=>r.id===n?{...r,label:s}:r)}))},updateData(n,s){e(o=>({tabs:o.tabs.map(r=>r.id===n?{...r,data:{...r.data,...s}}:r)}))},closeByPathPrefix(n){const s=t().tabs.filter(o=>{if(o.kind!=="file"&&o.kind!=="diff"&&o.kind!=="molecule")return!1;const r=o.data.path;return r===n||((r==null?void 0:r.startsWith(`${n}/`))??!1)});for(const o of s)t().close(o.id)}})),X={chat:e=>`chat-${e}`,file:e=>`file-${e}`,diff:(e,t)=>`diff-${e}${t?"-staged":""}`,terminal:e=>`term-${e}`,molecule:e=>`mol-${e}`};let pt=0;function Rn(e){pt+=1,N.getState().open({id:X.terminal(`new-${pt}`),kind:"terminal",label:`Terminal ${pt}`,closable:!0,data:{slot:null,cwd:e},workspaceCwd:e})}let ft=0;function gi(e){ft+=1,N.getState().open({id:X.molecule(`new-${ft}`),kind:"molecule",label:`Molecule ${ft}`,closable:!0,data:{path:null},workspaceCwd:e})}function Tt(e){const t=T.getState().createSession(e);N.getState().open({id:X.chat(t),kind:"chat",label:"New chat",closable:!0,data:{sessionId:t},workspaceCwd:e});const n=E.getState().client;n&&Nn(n,t).catch(()=>{})}function xt(e){const t=N.getState().tabs.find(s=>s.id===e);if(N.getState().close(e),(t==null?void 0:t.kind)!=="chat")return;const{sessionId:n}=t.data;mi(E.getState().client,n)}const te=be()(e=>({rootPath:"",expanded:new Set,expandedByRoot:new Map,draft:null,selected:null,setRoot:t=>e(n=>{const s=new Map(n.expandedByRoot);n.rootPath&&s.set(n.rootPath,n.expanded);const o=s.get(t),r=new Set(o);return r.add(t),{rootPath:t,expanded:r,expandedByRoot:s,draft:null,selected:null}}),toggle:t=>e(n=>{if(t===n.rootPath)return n;const s=new Set(n.expanded);s.has(t)?s.delete(t):s.add(t);const o=new Map(n.expandedByRoot);return o.set(n.rootPath,s),{expanded:s,expandedByRoot:o}}),startDraft:(t,n)=>e(s=>{const o=new Set(s.expanded);o.add(t);const r=new Map(s.expandedByRoot);return s.rootPath&&r.set(s.rootPath,o),{draft:{parentPath:t,kind:n},expanded:o,expandedByRoot:r}}),cancelDraft:()=>e({draft:null}),setSelected:t=>e({selected:t})}));let xe=null;const St=new Set;function _i(e){return St.add(e),()=>St.delete(e)}async function it(e){var t;if(xe)return xe;try{const n=await e.connection.request("file_explorer_request",{path:"/home"}),o=(((t=n.result)==null?void 0:t.entries)??n.entries??[]).find(r=>r.kind==="directory"||r.type==="directory");xe="/home/"+((o==null?void 0:o.name)||"user")}catch{return"/tmp"}for(const n of St)n(xe);return xe}function yi(){return xe}async function bi(e,t){return t==="~"||t.startsWith("~/")?await it(e)+t.slice(1):t}function ct(){const e=E(o=>o.client),t=E(o=>o.status),[n,s]=y.useState(yi());return y.useEffect(()=>_i(s),[]),y.useEffect(()=>{!e||t!=="open"||n||it(e)},[e,t,n]),n}const wi="_dot_gfh8u_3",xi="_spinner_gfh8u_16",Lt={dot:wi,spinner:xi};function Si(e){const{status:t,requiresAttention:n,attentionReason:s,showInactive:o}=e;if(!t)return null;if(n)switch(s){case"permission":return"statusWarning";case"error":return"statusDanger";case"finished":default:return"statusSuccess"}switch(t){case"running":case"queued":return"accent";case"waiting":return"statusWarning";case"finished":return"statusSuccess";case"error":return"statusDanger";case"idle":case"archived":return o?"foregroundMuted":null}}const Ht=8,vi={accent:"var(--pi-color-accent)",statusSuccess:"var(--pi-color-statusSuccess)",statusDanger:"var(--pi-color-statusDanger)",statusWarning:"var(--pi-color-statusWarning)",foregroundMuted:"var(--pi-color-foregroundMuted)"};function ki({className:e,...t}){const n=Si(t);if(!n)return null;const s=t.status==="running"&&!t.requiresAttention,o=s?"var(--pi-color-accentBright, #a2b4d7)":vi[n]??"currentColor";return a.jsx("span",{className:`${s?Lt.spinner:Lt.dot}${e?` ${e}`:""}`,style:s?{borderTopColor:o,borderRightColor:o}:{width:Ht,height:Ht,backgroundColor:o},role:"presentation"})}const Ii={initializing:"queued",idle:"idle",running:"running",error:"error",closed:"finished"};function ji(e){return Ii[e]??"idle"}const Ci="_wrap_9bh8u_1",Ti="_header_9bh8u_7",Ei="_openBtn_9bh8u_15",Ni="_list_9bh8u_27",Ri="_item_9bh8u_32",qi="_active_9bh8u_41",Mi="_title_9bh8u_45",Bi="_meta_9bh8u_54",$i="_menuBtn_9bh8u_62",Ai="_workspaceGroup_9bh8u_80",Di="_workspaceHeader_9bh8u_83",Pi="_workspaceChevron_9bh8u_96",zi="_workspaceIcon_9bh8u_107",Oi="_workspaceLabel_9bh8u_111",Fi="_workspaceCount_9bh8u_117",Wi="_workspaceMenuBtn_9bh8u_122",Li="_workspaceSessions_9bh8u_142",Hi="_emptyState_9bh8u_145",O={wrap:Ci,header:Ti,openBtn:Ei,list:Ni,item:Ri,active:qi,title:Mi,meta:Bi,menuBtn:$i,workspaceGroup:Ai,workspaceHeader:Di,workspaceChevron:Pi,workspaceIcon:zi,workspaceLabel:Oi,workspaceCount:Fi,workspaceMenuBtn:Wi,workspaceSessions:Li,emptyState:Hi};function Ui({session:e,active:t,onSelect:n,onOpenMenu:s}){return a.jsxs("div",{className:F(O.item,t&&O.active),onClick:n,onContextMenu:o=>{o.preventDefault(),s(o.clientX,o.clientY)},children:[a.jsxs("div",{className:O.title,children:[a.jsx(ki,{status:ji(e.status),showInactive:!0}),a.jsx("span",{children:e.title})]}),a.jsxs("div",{className:O.meta,children:[e.cwd||"~"," · ",e.agentId?e.agentId.slice(0,8):"new"," ·"," ",e.userMessageCount," msgs"]}),a.jsx("button",{type:"button",className:O.menuBtn,title:"Actions",onClick:o=>{o.stopPropagation();const r=o.currentTarget.getBoundingClientRect();s(r.left,r.bottom)},children:a.jsx(vt,{size:14})})]})}const Ki="_trigger_1t3hw_1",Vi="_content_1t3hw_12",Gi="_item_1t3hw_21",Xi="_danger_1t3hw_39",Ji="_sep_1t3hw_42",L={trigger:Ki,content:Vi,item:Gi,danger:Xi,sep:Ji};function Yi(){const e=j(v=>v.sessionMenu),t=j(v=>v.closeSessionMenu),n=E(v=>v.client),s=y.useRef(null),[o,r]=y.useState(!1);y.useEffect(()=>{r(e!==null)},[e]);const i=T(v=>e?v.sessions[e.sessionId]:void 0);if(!e)return null;const c=!!(i!=null&&i.agentId)&&(i==null?void 0:i.status)==="running";function d(v){r(v),v||t()}function h(){if(!i)return;const v=window.prompt("Rename:",i.title);if(v!=null&&v.trim()){const _=v.trim();T.getState().setTitle(i.id,_),N.getState().updateLabel(X.chat(i.id),_),i.agentId&&(n==null||n.agent(i.agentId).update({title:_}).catch(()=>{}))}t()}function p(){i!=null&&i.agentId&&(n==null||n.agent(i.agentId).interrupt().catch(()=>{})),t()}function w(v){T.getState().remove(v),N.getState().close(X.chat(v))}async function f(){if(i){if(!window.confirm("Archive this agent? It can be resumed later."))return t();if(t(),!i.agentId){w(i.id);return}if(!n){window.alert("Not connected — cannot archive remotely.");return}try{await n.agent(i.agentId).archive(),w(i.id)}catch(v){window.alert(`Failed to archive: ${v instanceof Error?v.message:String(v)}`)}}}async function m(){if(i){if(!window.confirm("Permanently delete this agent? This cannot be undone."))return t();if(t(),!i.agentId){w(i.id);return}if(!n){window.alert("Not connected — cannot delete remotely.");return}try{await n.agent(i.agentId).delete(),w(i.id)}catch(v){window.alert(`Failed to delete: ${v instanceof Error?v.message:String(v)}`)}}}return a.jsxs(Fe,{open:o,onOpenChange:d,modal:!1,children:[a.jsx(We,{asChild:!0,children:a.jsx("button",{ref:s,type:"button",className:L.trigger,style:{left:e.x,top:e.y},"aria-hidden":!0,tabIndex:-1})}),a.jsx(Le,{children:a.jsxs(He,{className:L.content,align:"start",sideOffset:2,children:[a.jsxs(A,{className:L.item,onSelect:h,children:[a.jsx(os,{size:13}),"Rename"]}),a.jsxs(A,{className:L.item,disabled:!c,onSelect:p,children:[a.jsx(rs,{size:13}),"Stop agent"]}),a.jsx(_e,{className:L.sep}),a.jsxs(A,{className:`${L.item} ${L.danger}`,onSelect:f,children:[a.jsx(as,{size:13}),"Archive"]}),a.jsxs(A,{className:`${L.item} ${L.danger}`,onSelect:m,children:[a.jsx(kt,{size:13}),"Delete permanently"]})]})})]})}function Qi({label:e,cwd:t,sessionCount:n,collapsed:s,onToggleCollapsed:o,onOpenMenu:r}){return a.jsxs("div",{className:O.workspaceHeader,onClick:o,title:t,children:[a.jsx("button",{type:"button",className:O.workspaceChevron,"aria-label":s?"Expand workspace":"Collapse workspace",onClick:i=>{i.stopPropagation(),o()},children:s?a.jsx(It,{size:13}):a.jsx(en,{size:13})}),a.jsx(is,{size:13,className:F(O.workspaceIcon)}),a.jsx("span",{className:O.workspaceLabel,children:e}),a.jsx("span",{className:O.workspaceCount,children:n}),a.jsx("button",{type:"button",className:O.workspaceMenuBtn,title:"Workspace actions",onClick:i=>{i.stopPropagation();const c=i.currentTarget.getBoundingClientRect();r(c.left,c.bottom)},children:a.jsx(vt,{size:13})})]})}function je(e,t){return t&&(e==="~"||e.startsWith("~/"))?t+e.slice(1):e}function Et(e,t,n){const s=new Map;for(const o of e){const r=t[o];if(!r)continue;const i=je(r.cwd||"~",n),c=s.get(i);c?c.push(r):s.set(i,[r])}return Array.from(s,([o,r])=>({cwd:o,sessions:r}))}function qn(e){return!e||e==="~"?"~":e.split("/").filter(Boolean).pop()||e}function Zi(e,t){return new Set(e.filter(n=>n.cwd!==t).map(n=>n.cwd))}function ec(){const e=j(m=>m.workspaceMenu),t=j(m=>m.closeWorkspaceMenu),n=E(m=>m.client),s=T(m=>m.order),o=T(m=>m.sessions),r=ct(),i=y.useRef(null),[c,d]=y.useState(!1);if(y.useEffect(()=>{d(e!==null)},[e]),!e)return null;const h=s.map(m=>o[m]).filter(m=>!!m).filter(m=>je(m.cwd||"~",r)===e.cwd);function p(m){d(m),m||t()}function w(){e&&(t(),Tt(e.cwd))}async function f(){if(!e)return;const m=h.length;if(!window.confirm(`Delete all ${m} conversation${m===1?"":"s"} in "${qn(e.cwd)}"? This deletes the conversations only — files on disk are untouched. This cannot be undone.`))return t();t();for(const _ of h){if(_.agentId&&n)try{await n.agent(_.agentId).delete()}catch(g){window.alert(`Failed to delete "${_.title}": ${g instanceof Error?g.message:String(g)}`);continue}T.getState().remove(_.id),N.getState().close(X.chat(_.id))}}return a.jsxs(Fe,{open:c,onOpenChange:p,modal:!1,children:[a.jsx(We,{asChild:!0,children:a.jsx("button",{ref:i,type:"button",className:L.trigger,style:{left:e.x,top:e.y},"aria-hidden":!0,tabIndex:-1})}),a.jsx(Le,{children:a.jsxs(He,{className:L.content,align:"start",sideOffset:2,children:[a.jsxs(A,{className:L.item,onSelect:w,children:[a.jsx(tn,{size:13}),"New conversation"]}),a.jsx(_e,{className:L.sep}),a.jsxs(A,{className:`${L.item} ${L.danger}`,onSelect:f,children:[a.jsx(kt,{size:13}),"Delete workspace (all conversations)"]})]})})]})}function tc(){const e=T(_=>_.order),t=T(_=>_.sessions),n=T(_=>_.activeSessionId),s=T(_=>_.activate),o=N(_=>_.open),r=E(_=>_.status),i=j(_=>_.openSessionMenu),c=j(_=>_.openWorkspaceMenu),d=j(_=>_.setCwd),h=j(_=>_.openCwdPicker),p=j(_=>_.collapsedWorkspaces),w=j(_=>_.toggleWorkspaceCollapsed),f=ct();function m(_){s(_);const g=t[_],R=je((g==null?void 0:g.cwd)||"~",f);g!=null&&g.cwd&&d(g.cwd),o({id:X.chat(_),kind:"chat",label:(g==null?void 0:g.title)??"Chat",closable:!0,data:{sessionId:_},workspaceCwd:R})}const v=Et(e,t,f);return a.jsxs("div",{className:O.wrap,children:[a.jsxs("div",{className:O.header,children:[a.jsx("h3",{children:"Workspaces"}),a.jsx(K,{size:"xs",variant:"ghost",iconOnly:!0,className:O.openBtn,title:r!=="open"?"Connect to open a workspace":"Open a workspace folder",disabled:r!=="open",onClick:()=>h(),children:a.jsx(nn,{size:13})})]}),a.jsxs("div",{className:O.list,children:[v.length===0&&a.jsx("div",{className:O.emptyState,children:r!=="open"?"Not connected":"No workspaces — open a folder to start"}),v.map(_=>{const g=p.has(_.cwd);return a.jsxs("div",{className:O.workspaceGroup,children:[a.jsx(Qi,{label:qn(_.cwd),cwd:_.cwd,sessionCount:_.sessions.length,collapsed:g,onToggleCollapsed:()=>w(_.cwd),onOpenMenu:(R,P)=>c(_.cwd,R,P)}),!g&&a.jsx("div",{className:O.workspaceSessions,children:_.sessions.map(R=>a.jsx(Ui,{session:R,active:R.id===n,onSelect:()=>m(R.id),onOpenMenu:(P,k)=>i(R.id,P,k)},R.id))})]},_.cwd)})]}),a.jsx(Yi,{}),a.jsx(ec,{})]})}const nc="_strip_ha8p4_1",sc="_tab_ha8p4_11",oc="_active_ha8p4_27",rc="_icon_ha8p4_31",ac="_label_ha8p4_36",ic="_close_ha8p4_41",cc="_newTab_ha8p4_51",lc="_content_ha8p4_74",dc="_item_ha8p4_83",uc="_itemIcon_ha8p4_97",U={strip:nc,tab:sc,active:oc,icon:rc,label:ac,close:ic,newTab:cc,content:lc,item:dc,itemIcon:uc},pc={chat:an,file:cs,diff:rn,terminal:on,molecule:sn};function fc({tab:e}){const t=N(p=>p.activeTabId),n=N(p=>p.activate),s=pc[e.kind],{attributes:o,listeners:r,setNodeRef:i,transform:c,transition:d,isDragging:h}=Ns({id:e.id});return a.jsxs("div",{ref:i,className:F(U.tab,e.id===t&&U.active),style:{transform:Rs.Transform.toString(c),transition:d,opacity:h?.5:1},onClick:()=>n(e.id),onAuxClick:p=>{p.button===1&&e.closable&&xt(e.id)},title:e.label,...o,...r,children:[a.jsx("span",{className:U.icon,children:a.jsx(s,{size:13})}),a.jsx("span",{className:U.label,children:e.label}),e.closable&&a.jsx("span",{className:U.close,onClick:p=>{p.stopPropagation(),xt(e.id)},children:a.jsx(ht,{size:12})})]})}function hc({workspaceCwd:e}){const t=e??"~";return a.jsxs(Fe,{children:[a.jsx(We,{asChild:!0,children:a.jsx("button",{type:"button",className:U.newTab,title:"New tab",disabled:!e,children:a.jsx(tn,{size:14})})}),a.jsx(Le,{children:a.jsxs(He,{className:U.content,align:"start",sideOffset:4,children:[a.jsxs(A,{className:U.item,onSelect:()=>Tt(t),children:[a.jsx(an,{size:13,className:U.itemIcon}),"New chat"]}),a.jsxs(A,{className:U.item,onSelect:()=>Rn(t),children:[a.jsx(on,{size:13,className:U.itemIcon}),"New terminal"]}),a.jsxs(A,{className:U.item,onSelect:()=>gi(t),children:[a.jsx(sn,{size:13,className:U.itemIcon}),"New molecule view"]})]})})]})}function mc(){const e=N(i=>i.tabs),t=N(i=>i.activeWorkspaceCwd),n=N(i=>i.reorder),s=e.filter(i=>i.workspaceCwd===t),o=vs(ks(Es,{activationConstraint:{distance:4}}));function r(i){const{active:c,over:d}=i;!d||c.id===d.id||n(String(c.id),String(d.id))}return a.jsxs("div",{className:U.strip,children:[a.jsx(Is,{sensors:o,collisionDetection:js,onDragEnd:r,children:a.jsx(Cs,{items:s.map(i=>i.id),strategy:Ts,children:s.map(i=>a.jsx(fc,{tab:i},i.id))})}),a.jsx(hc,{workspaceCwd:t})]})}const gc="_spinner_1tgzp_3",_c={spinner:gc},yc={xs:12,sm:16,md:20,lg:24},bc={xs:1,sm:2,md:2,lg:3};function Mn({size:e="md",color:t="currentColor",className:n,"aria-label":s="Loading"}){const o=typeof e=="number"?e:yc[e],r=typeof e=="number"?2:bc[e];return a.jsx("span",{className:`${_c.spinner}${n?` ${n}`:""}`,role:"status","aria-label":s,style:{width:o,height:o,borderWidth:r,color:t}})}const wc=y.lazy(()=>ce(()=>import("./ChatPanel-K1uSkIOF.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15])).then(e=>({default:e.ChatPanel}))),Ut=y.lazy(()=>ce(()=>import("./FilePanel-B88cfGeN.js"),__vite__mapDeps([16,1,7,6,5,2,17,11,12,18,19,3,13,14])).then(e=>({default:e.FilePanel}))),xc=y.lazy(()=>ce(()=>import("./TerminalPanel-DgCqvB_u.js"),__vite__mapDeps([20,1,21,22,7,6,5,2,3,13,14,23])).then(e=>({default:e.TerminalPanel}))),Sc=y.lazy(()=>ce(()=>import("./MoleculeViewerPanel-DWiCnr-2.js"),__vite__mapDeps([24,1,25,26,9,10,27,2,17,7,6,5,3,13,14,28])).then(e=>({default:e.MoleculeViewerPanel}))),vc={chat:wc,file:Ut,diff:Ut,terminal:xc,molecule:Sc},kc="_area_z7u01_1",Ic="_panel_z7u01_7",jc="_active_z7u01_14",Cc="_empty_z7u01_17",Tc="_emptyStack_z7u01_25",Ec="_emptyTitle_z7u01_35",Nc="_emptyHint_z7u01_39",ae={area:kc,panel:Ic,active:jc,empty:Cc,emptyStack:Tc,emptyTitle:Ec,emptyHint:Nc};function Rc(){const e=N(i=>i.tabs),t=N(i=>i.activeTabId),n=N(i=>i.activeWorkspaceCwd),s=E(i=>i.status),o=j(i=>i.openCwdPicker),r=e.some(i=>i.workspaceCwd===n);return n===null?a.jsx("div",{className:ae.area,children:a.jsxs("div",{className:ae.emptyStack,children:[a.jsx("div",{className:ae.emptyTitle,children:"No workspace open"}),a.jsx("div",{className:ae.emptyHint,children:"Open a project folder to start a chat."}),a.jsx(K,{size:"sm",variant:"secondary",leftIcon:a.jsx(nn,{size:14}),disabled:s!=="open",title:s!=="open"?"Connect to open a workspace":"Open a workspace folder",onClick:()=>o(),children:"Open Workspace"})]})}):r?a.jsx("div",{className:ae.area,children:e.map(i=>{const c=vc[i.kind];return a.jsx("div",{className:F(ae.panel,i.id===t&&ae.active),children:a.jsx(y.Suspense,{fallback:a.jsx(Mn,{size:"md"}),children:a.jsx(c,{tab:i})})},i.id)})}):a.jsx("div",{className:ae.area,children:a.jsx("div",{className:ae.empty,children:"No open tabs in this workspace"})})}const Ce={fileRead:e=>["file","read",e],fileDownload:e=>["file","download",e],fileText:(e,t)=>["file","text",e,t],fileDiff:(e,t,n)=>["file","diff",e,t,n],fileDiffByPath:e=>["file","diff",e],explorer:e=>["explorer",e],agentList:()=>["agents","list"],providerModels:e=>["providers","models",e],agentTimeline:e=>["agents","timeline",e],agentCommands:e=>["agents","commands",e]};function qc(e){const t=e.kind==="directory"||e.type==="directory"?"directory":"file";return{name:e.name??"",kind:t,size:e.size,mtimeMs:e.mtimeMs}}function Mc(e){return e.slice().sort((t,n)=>t.kind!==n.kind?t.kind==="directory"?-1:1:t.name.localeCompare(n.name))}async function Bn(e,t){const s=(await e.connection.request("file_explorer_request",{path:t})).result;if(!s||s.ok===!1)throw new Error(s&&"error"in s?s.error:"explorer request failed");const o="entries"in s?s.entries??[]:[];return{path:s.resolvedPath??t,entries:Mc(o.map(qc))}}function Bc(e,t=!0){const n=E(s=>s.client);return Qt({queryKey:Ce.explorer(e),queryFn:()=>{if(!n)throw new Error("not connected");return Bn(n,e)},enabled:!!n&&!!e&&t})}function $c(e){const t=E(o=>o.client),n=y.useMemo(()=>Array.from(e),[e]),s=Yn({queries:n.map(o=>({queryKey:Ce.explorer(o),queryFn:()=>{if(!t)throw new Error("not connected");return Bn(t,o)},enabled:!!t&&!!o}))});return y.useMemo(()=>{const o=new Map;return n.forEach((r,i)=>{const c=s[i];o.set(r,{listing:c==null?void 0:c.data,isLoading:!!(c!=null&&c.isLoading),isError:!!(c!=null&&c.isError),error:c==null?void 0:c.error})}),o},[n,s])}function Ac(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="file_changed"&&"path"in e&&typeof e.path=="string"}function Dc(e,t){const n=new Set,s=e.connection.onSessionMessage(o=>{const r=o;Ac(r)&&n.has(r.path)&&t(r.path)});return{sync(o){for(const r of n)o.has(r)||(n.delete(r),e.connection.request("file_watch_unsubscribe",{path:r}).catch(()=>{}));for(const r of o)n.has(r)||(n.add(r),e.connection.request("file_watch_subscribe",{path:r}).then(i=>{const c=i;(c==null?void 0:c.ok)===!1&&console.warn(`useExplorerWatch: ${c.error??"subscribe failed"} for "${r}"`)}).catch(()=>{}))},dispose(){s();for(const o of n)e.connection.request("file_watch_unsubscribe",{path:o}).catch(()=>{});n.clear()}}}function Pc(e){const t=E(i=>i.client),n=Ie(),s=y.useRef(null),o=y.useRef(null),r=Array.from(e).toSorted().join("\0");y.useEffect(()=>{var i,c;t&&(o.current!==t&&((i=s.current)==null||i.dispose(),s.current=Dc(t,d=>{n.invalidateQueries({queryKey:Ce.explorer(d)})}),o.current=t),(c=s.current)==null||c.sync(new Set(r?r.split("\0"):[])))},[t,r,n]),y.useEffect(()=>()=>{var i;(i=s.current)==null||i.dispose(),s.current=null,o.current=null},[])}const Kt=new WeakMap;function Vt(e){let t=Kt.get(e);return t||(t=new Ia(e),t.start(),Kt.set(e,t)),t}function zc(e,t,n){const s=new Blob([Uint8Array.from(e)],{type:n||"application/octet-stream"}),o=URL.createObjectURL(s),r=document.createElement("a");r.href=o,r.download=t,r.rel="noopener",document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(o),0)}function $n(){const e=E(o=>o.daemon),t=Ie(),n=y.useCallback(async(o,r)=>{if(!e)throw new Error("not connected");const i=o?`${o}/${r.name}`:r.name,c=new Uint8Array(await r.arrayBuffer());await Vt(e).upload(i,c),await t.invalidateQueries({queryKey:["explorer"]})},[e,t]),s=y.useCallback(async o=>{if(!e)throw new Error("not connected");const r=await Vt(e).download(o);zc(r.bytes,r.fileName||o.split("/").pop()||"download",r.mimeType)},[e]);return{upload:n,saveToDisk:s}}function Ju(e,t){return e?e.startsWith("/")||e.startsWith("~")?e:t?`${t.replace(/\/+$/,"")}/${e}`:null:null}function An(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):"/"}function Oc(e,t){return!t||!e.startsWith(t)?e:e.slice(t.length).replace(/^\/+/,"")}function Fc(e,t){return e.endsWith("/")?`${e}${t}`:`${e}/${t}`}function Dn(e,t,n,s,o,r){var c;(r==null?void 0:r.parentPath)===t&&e.push({kind:"draft",path:`${t}::draft`,depth:n,draftKind:r.kind,parentPath:t});const i=o.get(t);if(!i||i.isLoading){e.push({kind:"loading",path:t,depth:n});return}if(i.isError){const d=i.error instanceof Error?i.error.message:"failed to load";e.push({kind:"error",path:t,depth:n,message:d});return}for(const d of((c=i.listing)==null?void 0:c.entries)??[])Wc(e,t,d,n,s,o,r)}function Wc(e,t,n,s,o,r,i){const c=Fc(t,n.name);if(n.kind!=="directory"){e.push({kind:"file",path:c,name:n.name,depth:s});return}const d=o.has(c);e.push({kind:"directory",path:c,name:n.name,depth:s,expanded:d}),d&&Dn(e,c,s+1,o,r,i)}function Lc(e,t,n,s){if(!e)return[];const o=[];return Dn(o,e,0,t,n,s),o}const Hc="_container_q6lzp_1",Uc="_header_q6lzp_7",Kc="_uploadButton_q6lzp_14",Vc="_hiddenInput_q6lzp_33",Gc="_status_q6lzp_36",Xc="_statusError_q6lzp_37",Jc="_rowAction_q6lzp_50",Yc="_item_q6lzp_65",Qc="_dropOverlay_q6lzp_68",Zc="_list_q6lzp_83",el="_active_q6lzp_102",tl="_selected_q6lzp_107",nl="_chevronSlot_q6lzp_111",sl="_chevron_q6lzp_111",ol="_chevronOpen_q6lzp_122",rl="_icon_q6lzp_125",al="_name_q6lzp_132",il="_dirName_q6lzp_137",cl="_statusRow_q6lzp_143",ll="_statusRowError_q6lzp_154",dl="_emptyState_q6lzp_157",ul="_draftInput_q6lzp_163",M={container:Hc,header:Uc,uploadButton:Kc,hiddenInput:Vc,status:Gc,statusError:Xc,rowAction:Jc,item:Yc,dropOverlay:Qc,list:Zc,active:el,selected:tl,chevronSlot:nl,chevron:sl,chevronOpen:ol,icon:rl,name:al,dirName:il,statusRow:cl,statusRowError:ll,emptyState:dl,draftInput:ul};function pl({draftKind:e,indentStyle:t,onSubmit:n,onCancel:s}){const[o,r]=y.useState("");return a.jsxs("div",{className:M.item,style:t,onClick:i=>i.stopPropagation(),children:[a.jsx("span",{className:M.chevronSlot}),a.jsx("span",{className:M.icon,children:e==="directory"?a.jsx(ke,{size:14}):a.jsx(cn,{size:14})}),a.jsx("input",{className:M.draftInput,autoFocus:!0,spellCheck:!1,placeholder:e==="directory"?"New folder":"New file",value:o,onChange:i=>r(i.target.value),onKeyDown:i=>{if(i.key==="Enter"){i.preventDefault();const c=o.trim();c?n(c):s()}else i.key==="Escape"&&(i.preventDefault(),s())},onBlur:s})]})}const fl=14;function hl({row:e,active:t,selected:n,onToggle:s,onOpenFile:o,onContextMenu:r,onSubmitDraft:i,onCancelDraft:c}){const d={paddingLeft:8+e.depth*fl};if(e.kind==="loading")return a.jsx("div",{className:M.statusRow,style:d,children:"Loading…"});if(e.kind==="error")return a.jsx("div",{className:F(M.statusRow,M.statusRowError),style:d,children:e.message??"failed to load"});if(e.kind==="draft")return a.jsx(pl,{draftKind:e.draftKind,indentStyle:d,onSubmit:p=>i(e.parentPath,p),onCancel:c});const h=e.kind==="directory";return a.jsxs("div",{className:F(M.item,t&&M.active,n&&M.selected),style:d,title:e.path,onClick:()=>h?s(e.path):o(e.path),onContextMenu:p=>{p.preventDefault(),p.stopPropagation(),r(e.path,h,p.clientX,p.clientY)},children:[a.jsx("span",{className:M.chevronSlot,children:h&&a.jsx(It,{size:12,className:F(M.chevron,e.expanded&&M.chevronOpen)})}),a.jsx("span",{className:M.icon,children:h?a.jsx(ke,{size:14}):a.jsx(cn,{size:14})}),a.jsx("span",{className:h?M.dirName:M.name,children:e.name}),a.jsx("button",{type:"button",className:M.rowAction,title:"Actions",onClick:p=>{p.stopPropagation();const w=p.currentTarget.getBoundingClientRect();r(e.path,h,w.left,w.bottom)},children:a.jsx(vt,{size:12})})]})}async function Gt(e){var n;if((n=navigator.clipboard)!=null&&n.writeText)try{await navigator.clipboard.writeText(e);return}catch{}const t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.focus(),t.select();try{if(!document.execCommand("copy"))throw new Error('execCommand("copy") failed')}finally{t.remove()}}const ml=y.lazy(()=>ce(()=>import("./TextViewer-CCNwnC6m.js"),__vite__mapDeps([29,1,30,2,7,6,5,31,27,18,19,3,13,14,32])).then(e=>({default:e.TextViewer}))),gl=y.lazy(()=>ce(()=>import("./MarkdownFileViewer-D9pKcm5W.js"),__vite__mapDeps([33,1,30,2,7,6,5,31,4,8,18,19,3,13,14,34])).then(e=>({default:e.MarkdownFileViewer}))),_l=y.lazy(()=>ce(()=>import("./ImageViewer-DMuVw1TC.js"),__vite__mapDeps([35,1,27,2,18,19,7,6,5,3,13,14,36])).then(e=>({default:e.ImageViewer}))),yl=y.lazy(()=>ce(()=>import("./VideoViewer-F211X3SB.js"),__vite__mapDeps([37,1,27,2,18,19,7,6,5,3,13,14,38])).then(e=>({default:e.VideoViewer}))),bl=y.lazy(()=>ce(()=>import("./BinaryFallbackViewer-BCheCWlj.js"),__vite__mapDeps([39,1,27,2,3,7,6,5,13,14,40])).then(e=>({default:e.BinaryFallbackViewer}))),Yu={text:ml,markdown:gl,image:_l,video:yl,binary:bl},wl={md:"markdown",markdown:"markdown",mdx:"markdown",png:"image",jpg:"image",jpeg:"image",gif:"image",webp:"image",svg:"image",bmp:"image",ico:"image",avif:"image",mp4:"video",webm:"video",mov:"video",m4v:"video",ogv:"video",pdf:"binary",zip:"binary",gz:"binary",tar:"binary",exe:"binary",wasm:"binary",woff:"binary",woff2:"binary",ttf:"binary",otf:"binary"},xl=[["image/","image"],["video/","video"]];function Pn(e){const t=e.split("/").pop()??e,n=t.lastIndexOf(".");return n>0?t.slice(n+1).toLowerCase():""}const Sl={pdb:!0,cif:!0,mmcif:!0,mol:!0,mol2:!0,xyz:!0,extxyz:!0,gro:!0,lammpstrj:!0,xsf:!0},vl={poscar:!0,contcar:!0};function kl(e){if(Sl[Pn(e)])return!0;const t=e.split("/").pop()??e;return!!vl[t.toLowerCase()]}function Qu(e,t={}){const n=wl[Pn(e)];if(n)return n;const s=t.mimeHint??"";for(const[o,r]of xl)if(s.startsWith(o))return r;return t.isBinary?"binary":"text"}function zn(e,t){const n=e.split("/").pop()||e;if(kl(e)){N.getState().open({id:X.molecule(e),kind:"molecule",label:n,closable:!0,data:{path:e},workspaceCwd:t});return}N.getState().open({id:X.file(e),kind:"file",label:n,closable:!0,data:{path:e},workspaceCwd:t})}const Il="_trigger_1fejp_1",jl="_content_1fejp_12",Cl="_item_1fejp_21",Tl="_danger_1fejp_35",El="_sep_1fejp_38",D={trigger:Il,content:jl,item:Cl,danger:Tl,sep:El};function Nl(){const e=j(k=>k.fileMenu),t=j(k=>k.closeFileMenu),n=E(k=>k.client),s=te(k=>k.startDraft),o=te(k=>k.rootPath),r=N(k=>k.activeWorkspaceCwd),{saveToDisk:i}=$n(),c=Ie(),d=y.useRef(null),[h,p]=y.useState(!1);if(y.useEffect(()=>{p(e!==null)},[e]),!e)return null;const w=e.path.split("/").pop()||e.path;function f(k){p(k),k||t()}function m(){e&&(t(),zn(e.path,r||"~"))}async function v(){if(e){t();try{await Gt(e.path)}catch{window.alert("Failed to copy to clipboard.")}}}async function _(){if(e){t();try{await Gt(Oc(e.path,o)||"/")}catch{window.alert("Failed to copy to clipboard.")}}}async function g(){if(e){t();try{await i(e.path)}catch(k){window.alert(`Failed to download: ${k instanceof Error?k.message:String(k)}`)}}}async function R(){if(!e)return;const k=e.isDirectory?"folder (and everything inside it)":"file";if(!window.confirm(`Permanently delete this ${k}? "${w}" — this cannot be undone.`))return t();if(t(),!n){window.alert("Not connected — cannot delete remotely.");return}try{const V=await n.connection.request("file_delete_request",{path:e.path});if(!V.ok)throw new Error(V.error??"delete failed");await c.invalidateQueries({queryKey:["explorer"]}),N.getState().closeByPathPrefix(e.path)}catch(V){window.alert(`Failed to delete: ${V instanceof Error?V.message:String(V)}`)}}function P(k){if(!e)return;const V=e.isDirectory?e.path:An(e.path);t(),s(V,k)}return a.jsxs(Fe,{open:h,onOpenChange:f,modal:!1,children:[a.jsx(We,{asChild:!0,children:a.jsx("button",{ref:d,type:"button",className:D.trigger,style:{left:e.x,top:e.y},"aria-hidden":!0,tabIndex:-1})}),a.jsx(Le,{children:a.jsx(He,{className:D.content,align:"start",sideOffset:2,children:e.background?a.jsxs(a.Fragment,{children:[a.jsxs(A,{className:D.item,onSelect:()=>P("file"),children:[a.jsx(mt,{size:13}),"New File"]}),a.jsxs(A,{className:D.item,onSelect:()=>P("directory"),children:[a.jsx(st,{size:13}),"New Folder"]}),a.jsx(_e,{className:D.sep}),a.jsxs(A,{className:D.item,onSelect:v,children:[a.jsx(Ge,{size:13}),"Copy Current Directory Path"]}),a.jsxs(A,{className:D.item,onSelect:_,children:[a.jsx(Ge,{size:13}),"Copy Current Directory Relative Path"]})]}):a.jsxs(a.Fragment,{children:[!e.isDirectory&&a.jsxs(a.Fragment,{children:[a.jsxs(A,{className:D.item,onSelect:m,children:[a.jsx(ls,{size:13}),"Open"]}),a.jsx(_e,{className:D.sep})]}),e.isDirectory&&a.jsxs(a.Fragment,{children:[a.jsxs(A,{className:D.item,onSelect:()=>P("file"),children:[a.jsx(mt,{size:13}),"New File"]}),a.jsxs(A,{className:D.item,onSelect:()=>P("directory"),children:[a.jsx(st,{size:13}),"New Folder"]}),a.jsx(_e,{className:D.sep})]}),a.jsxs(A,{className:D.item,onSelect:v,children:[a.jsx(Ge,{size:13}),"Copy Absolute Path"]}),a.jsxs(A,{className:D.item,onSelect:_,children:[a.jsx(Ge,{size:13}),"Copy Relative Path"]}),a.jsx(_e,{className:D.sep}),!e.isDirectory&&a.jsxs(a.Fragment,{children:[a.jsxs(A,{className:D.item,onSelect:g,children:[a.jsx(ds,{size:13}),"Download"]}),a.jsx(_e,{className:D.sep})]}),a.jsxs(A,{className:`${D.item} ${D.danger}`,onSelect:R,children:[a.jsx(kt,{size:13}),"Delete"]})]})})})]})}const Rl={empty_path:"Choose a folder first.",invalid_name:'Invalid name — cannot be empty or contain "/".',exists:"An item with that name already exists here.",not_found:"That folder no longer exists.",not_a_directory:"That path is not a folder.",unreadable:"That folder is not readable."};async function On(e,t,n,s){const o=await e.connection.request("file_create_request",{path:t,name:n,kind:s});if(!o.ok){const r=o.error??"";throw new Error(Rl[r]??r??"Failed to create")}return o.path??(t.endsWith("/")?`${t}${n}`:`${t}/${n}`)}const ql=24;function Ml(){const e=E(S=>S.client),t=te(S=>S.rootPath),n=te(S=>S.expanded),s=te(S=>S.setRoot),o=te(S=>S.toggle),r=te(S=>S.draft),i=te(S=>S.startDraft),c=te(S=>S.cancelDraft),d=te(S=>S.selected),h=te(S=>S.setSelected),p=N(S=>S.activeWorkspaceCwd),w=N(S=>S.tabs.find(q=>q.id===S.activeTabId)),{upload:f}=$n(),m=j(S=>S.openFileMenu),v=Ie(),[_,g]=y.useState(null),[R,P]=y.useState(!1),[k,V]=y.useState(null),Te=y.useRef(null),Ee=y.useRef(null),Ue=(w==null?void 0:w.kind)==="file"||(w==null?void 0:w.kind)==="molecule"?w.data.path:null,re=d?d.isDirectory?d.path:An(d.path):t,ue=y.useRef(null);y.useEffect(()=>{if(!e)return;const S=p||"~";ue.current!==S&&(ue.current=S,bi(e,S).then(q=>s(q)))},[e,p,s]);const Ne=$c(n);Pc(n);const pe=y.useMemo(()=>Lc(t,n,Ne,r),[t,n,Ne,r]),Re=Qn({count:pe.length,getScrollElement:()=>Ee.current,estimateSize:()=>ql,overscan:12,getItemKey:S=>{var q;return((q=pe[S])==null?void 0:q.path)??S}});function Ke(S){zn(S,p||"~")}async function I(S,q){const z=(r==null?void 0:r.kind)??"file";if(c(),!!e)try{const Y=await On(e,S,q,z);await v.invalidateQueries({queryKey:Ce.explorer(S)}),g({text:`Created ${Y}`,error:!1}),z==="file"&&Ke(Y)}catch(Y){g({text:Y instanceof Error?Y.message:"Failed to create",error:!0})}}async function fe(S,q){var Ve;if(!q.length||!S)return;const z=(Ve=Ne.get(S))==null?void 0:Ve.listing,Y=new Set((z==null?void 0:z.entries.map(ne=>ne.name))??[]),qe=q.filter(ne=>Y.has(ne.name));if(qe.length>0){const ne=qe.map(Un=>Un.name).join(", ");if(!window.confirm(`Overwrite ${qe.length>1?"these files":"this file"}? ${ne}`))return}g({text:`Uploading ${q.length} file${q.length>1?"s":""}…`,error:!1});try{for(const ne of q)await f(S,ne);g({text:`Uploaded ${q.length} file${q.length>1?"s":""}`,error:!1})}catch(ne){g({text:`Upload failed: ${ne instanceof Error?ne.message:"unknown"}`,error:!0})}}function Ln(S){S.preventDefault(),P(!1);const q=k??t;V(null);const z=Array.from(S.dataTransfer.files);fe(q,z)}function Hn(S){S.dataTransfer.types.includes("Files")&&(S.preventDefault(),P(!0))}return e?a.jsxs("div",{className:M.container,onDragOver:Hn,onDragLeave:()=>P(!1),onDrop:Ln,children:[a.jsxs("div",{className:M.header,children:[a.jsx("button",{type:"button",className:M.uploadButton,onClick:()=>i(re,"file"),disabled:!t,title:d?`New file in ${re.split("/").pop()||"/"}`:"New file in workspace root",children:a.jsx(mt,{size:12})}),a.jsx("button",{type:"button",className:M.uploadButton,onClick:()=>i(re,"directory"),disabled:!t,title:d?`New folder in ${re.split("/").pop()||"/"}`:"New folder in workspace root",children:a.jsx(st,{size:12})}),a.jsxs("button",{type:"button",className:M.uploadButton,onClick:()=>{var S;return(S=Te.current)==null?void 0:S.click()},disabled:!t,title:"Upload files to the workspace root",children:[a.jsx(us,{size:12}),a.jsx("span",{children:"Upload"})]}),a.jsx("input",{ref:Te,type:"file",multiple:!0,className:M.hiddenInput,onChange:S=>{fe(t,Array.from(S.target.files??[])),S.target.value=""}})]}),_&&a.jsx("div",{className:_.error?M.statusError:M.status,children:_.text}),a.jsxs("div",{className:M.list,ref:Ee,onContextMenu:S=>{S.preventDefault(),m(t,!0,S.clientX,S.clientY,!0)},children:[pe.length===0&&a.jsx("div",{className:M.emptyState,children:"No files loaded"}),a.jsx("div",{style:{position:"relative",height:Re.getTotalSize()},children:Re.getVirtualItems().map(S=>{const q=pe[S.index];return q?a.jsx("div",{"data-index":S.index,style:{position:"absolute",top:0,left:0,width:"100%",height:S.size,transform:`translateY(${S.start}px)`},onDragEnter:()=>{q.kind==="directory"&&V(q.path)},children:a.jsx(hl,{row:q,active:(q.kind==="file"||q.kind==="directory")&&q.path===Ue,selected:(q.kind==="file"||q.kind==="directory")&&q.path===(d==null?void 0:d.path),onToggle:z=>{h({path:z,isDirectory:!0}),o(z)},onOpenFile:z=>{h({path:z,isDirectory:!1}),Ke(z)},onContextMenu:(z,Y,qe,Ve)=>m(z,Y,qe,Ve),onSubmitDraft:(z,Y)=>void I(z,Y),onCancelDraft:c})},S.key):null})})]}),R&&a.jsx("div",{className:M.dropOverlay,children:"Drop to upload"}),a.jsx(Nl,{})]}):a.jsx("div",{className:M.emptyState,children:"Connect to browse files"})}const Xt={available:!1,branch:null,upstream:null,ahead:0,behind:0,detached:!1,conflictCount:0},oe=be()(e=>({subscribedCwd:null,changes:[],...Xt,setSubscribedCwd:t=>e({subscribedCwd:t}),applyProjection:t=>{if(!t||!t.available){e({changes:[],...Xt});return}const n=[];for(const s of t.staged)n.push({path:s.path,status:s.indexStatus==="A"?"added":s.indexStatus==="D"?"deleted":"modified",staged:!0});for(const s of t.unstaged)n.push({path:s.path,status:s.worktreeStatus==="D"?"deleted":"modified",staged:!1});for(const s of t.untracked)n.push({path:s,status:"added",staged:!1});e({changes:n,available:!0,branch:t.branch,upstream:t.upstream,ahead:t.ahead,behind:t.behind,detached:t.detached,conflictCount:t.conflicted.length})}})),Bl="_list_1pgby_1",$l="_summary_1pgby_4",Al="_item_1pgby_11",Dl="_badge_1pgby_23",Pl="_added_1pgby_30",zl="_modified_1pgby_34",Ol="_deleted_1pgby_38",Fl="_name_1pgby_42",Wl="_emptyState_1pgby_47",me={list:Bl,summary:$l,item:Al,badge:Dl,added:Pl,modified:zl,deleted:Ol,name:Fl,emptyState:Wl},Ll={added:"A",modified:"M",deleted:"D"};function Hl(){const t=N(r=>r.activeWorkspaceCwd)||"~",n=oe(r=>r.changes),s=N(r=>r.open);function o(r,i){s({id:X.diff(r,i),kind:"diff",label:r.split("/").pop()||r,closable:!0,data:{path:r,staged:i},workspaceCwd:t})}return n.length===0?a.jsx("div",{className:me.emptyState,children:"No changes detected"}):a.jsxs("div",{className:me.list,children:[a.jsxs("div",{className:me.summary,children:[n.length," changed file",n.length===1?"":"s"]}),n.map((r,i)=>a.jsxs("div",{className:me.item,onClick:()=>o(r.path,r.staged),children:[a.jsx("span",{className:F(me.badge,me[r.status]),children:Ll[r.status]}),a.jsx("span",{className:me.name,children:r.path})]},`${r.path}-${r.staged}-${i}`))]})}const Ul="_wrap_oh56x_1",Kl="_tabBar_oh56x_7",Vl="_tabBtn_oh56x_13",Gl="_active_oh56x_29",Xl="_refreshBtn_oh56x_33",Jl="_content_oh56x_37",le={wrap:Ul,tabBar:Kl,tabBtn:Vl,active:Gl,refreshBtn:Xl,content:Jl};function Yl(){const e=j(c=>c.rightSidebarTab),t=j(c=>c.setRightSidebarTab),s=N(c=>c.activeWorkspaceCwd)||"~",o=E(c=>c.client),r=Ie();function i(){r.invalidateQueries({queryKey:["explorer"]}),o&&s&&o.connection.request("checkout_refresh_request",{cwd:s}).catch(()=>{})}return a.jsxs("div",{className:le.wrap,children:[a.jsxs("div",{className:le.tabBar,children:[a.jsxs("button",{type:"button",className:F(le.tabBtn,e==="files"&&le.active),onClick:()=>t("files"),children:[a.jsx(ke,{size:13}),"Files"]}),a.jsxs("button",{type:"button",className:F(le.tabBtn,e==="changes"&&le.active),onClick:()=>t("changes"),children:[a.jsx(rn,{size:13}),"Changes"]}),a.jsx(K,{size:"xs",variant:"ghost",iconOnly:!0,title:"Refresh",className:le.refreshBtn,onClick:i,children:a.jsx(ps,{size:13})})]}),a.jsx("div",{className:le.content,children:e==="files"?a.jsx(Ml,{}):a.jsx(Hl,{})})]})}const Fn=be()(e=>({bySession:{},setStats(t,n){e(s=>({bySession:{...s.bySession,[t]:{...s.bySession[t],...n}}}))},clear(t){e(n=>{const{[t]:s,...o}=n.bySession;return{bySession:o}})}})),Ql=12e3;function Zl(e,t){return e==="running"&&t!=="running"}function Jt(e,t){var s,o,r,i,c,d;const n={};((s=t.contextUsage)==null?void 0:s.tokens)!=null&&(n.contextTokens=t.contextUsage.tokens),((o=t.contextUsage)==null?void 0:o.contextWindow)!==void 0&&(n.contextWindow=t.contextUsage.contextWindow),((r=t.contextUsage)==null?void 0:r.percent)!=null&&(n.contextPercent=t.contextUsage.percent),((i=t.tokens)==null?void 0:i.total)!==void 0&&(n.totalTokens=t.tokens.total),((c=t.tokens)==null?void 0:c.input)!==void 0&&(n.inputTokens=t.tokens.input),((d=t.tokens)==null?void 0:d.output)!==void 0&&(n.outputTokens=t.tokens.output),t.cost!==void 0&&(n.cost=t.cost),t.model!==void 0&&(n.model=t.model,T.getState().setModel(e,t.model)),Fn.getState().setStats(e,n)}function ed(e){const t=E(c=>c.client),n=E(c=>c.status),s=T(c=>{var d;return e?((d=c.sessions[e])==null?void 0:d.agentId)??null:null}),o=T(c=>{var d;return e?(d=c.sessions[e])==null?void 0:d.status:void 0}),r=y.useRef(!1),i=y.useRef(void 0);y.useEffect(()=>{if(n!=="open"||!t||!e||!s)return;let c=!1;const d=async()=>{if(!r.current){r.current=!0;try{const p=await t.agent(s).sessionStats();c||Jt(e,p)}catch{}finally{r.current=!1}}};d();const h=setInterval(()=>void d(),Ql);return()=>{c=!0,clearInterval(h)}},[n,t,e,s]),y.useEffect(()=>{const c=i.current;i.current=o,Zl(c,o)&&(n!=="open"||!t||!e||!s||(r.current=!1,t.agent(s).sessionStats().then(d=>Jt(e,d)).catch(()=>{})))},[o,n,t,e,s])}function td(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="checkout_status_update"&&"cwd"in e&&typeof e.cwd=="string"&&"projection"in e&&typeof e.projection=="object"&&e.projection!==null}function nd(e){const t=E(r=>r.client),n=oe(r=>r.applyProjection),s=oe(r=>r.setSubscribedCwd),o=y.useRef(t);return o.current=t,y.useEffect(()=>{if(!t||!e)return;let r=!1;t.connection.request("checkout_status_subscribe",{cwd:e}).catch(()=>{}),s(e);const i=t.connection.onSessionMessage(c=>{if(r)return;const d=c;td(d)&&d.cwd===e&&n(d.projection)});return t.connection.request("checkout_refresh_request",{cwd:e}).catch(()=>{}),()=>{r=!0,i(),t.connection.request("checkout_status_unsubscribe",{cwd:e}).catch(()=>{}),s(null)}},[t,e,n,s]),{refresh(){const r=o.current;!r||!e||r.connection.request("checkout_refresh_request",{cwd:e}).catch(()=>{})}}}const Nt="--";function Ae(e){return e===void 0?Nt:e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(1)}k`:`${(e/1e6).toFixed(1)}M`}function sd(e){if(e==null)return Nt;const t=e<=1?e*100:e;return`${Math.round(t)}%`}function od(e){if(e===void 0)return Nt;const t=e<1?4:2;return`$${e.toFixed(t)}`}function rd(e,t){return t?e===t?"~":e.startsWith(`${t}/`)?`~${e.slice(t.length)}`:e:e}function ad(e,t){const n=[];return e>0&&n.push(`↑${e}`),t>0&&n.push(`↓${t}`),n.join(" ")}function id(e,t=!0){const n=E(s=>s.client);return Qt({queryKey:Ce.providerModels(e),queryFn:async()=>{if(!n)throw new Error("not connected");return(await n.providers.listModels(e)).models},enabled:!!n&&!!e&&t})}function cd(e,t){if(t.trim()==="")return e;const n=t.toLowerCase();return e.filter(s=>s.label.toLowerCase().includes(n)||s.description!==void 0&&s.description.toLowerCase().includes(n))}function ld(e,t){if(!t)return e;const n=e.find(s=>s.id===t);return n?[n,...e.filter(s=>s.id!==t)]:e}function dd(e){const t=new Set;return e.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const ud="_content_1imfv_4",pd="_search_1imfv_17",fd="_list_1imfv_35",hd="_item_1imfv_40",md="_itemActive_1imfv_54",gd="_checkSlot_1imfv_58",_d="_label_1imfv_67",yd="_modelId_1imfv_73",bd="_state_1imfv_80",wd="_stateError_1imfv_89",xd="_commandContent_1imfv_99",Sd="_commandList_1imfv_102",vd="_commandItem_1imfv_107",kd="_commandItemHeader_1imfv_140",Id="_commandKindBadge_1imfv_154",jd="_commandKindExtension_1imfv_173",Cd="_commandKindPrompt_1imfv_178",Td="_commandKindSkill_1imfv_183",Ed="_commandDescription_1imfv_188",se={content:ud,search:pd,list:fd,item:hd,itemActive:md,checkSlot:gd,label:_d,modelId:yd,state:bd,stateError:wd,commandContent:xd,commandList:Sd,commandItem:vd,commandItemHeader:kd,commandKindBadge:Id,commandKindExtension:jd,commandKindPrompt:Cd,commandKindSkill:Td,commandDescription:Ed};function Nd({currentModel:e,provider:t,onSelect:n,renderTrigger:s}){const[o,r]=y.useState(!1),[i,c]=y.useState(""),d=y.useRef(null),{data:h=[],isLoading:p,isError:w,error:f}=id(t,o),m=dd(ld(h,e));y.useEffect(()=>{var k;o&&(c(""),(k=d.current)==null||k.focus())},[o]);const v=new Map(m.map(k=>[k.id,k.provider])),_=m.map(k=>({value:k.id,label:k.label??k.id,description:k.id})),g=cd(_,i),R=f instanceof Error?f.message:"Failed to load models";function P(k){k.stopPropagation(),k.key==="Escape"&&r(!1)}return a.jsxs(Fe,{open:o,onOpenChange:r,modal:!1,children:[a.jsx(We,{asChild:!0,children:s(e)}),a.jsx(Le,{children:a.jsxs(He,{className:se.content,align:"start",sideOffset:4,children:[a.jsx("input",{ref:d,className:se.search,placeholder:"Search models…",value:i,onChange:k=>c(k.target.value),onKeyDown:P}),p&&a.jsx("div",{className:se.state,children:a.jsx(Mn,{size:"sm"})}),!p&&w&&a.jsx("div",{className:se.stateError,children:R}),!p&&!w&&g.length===0&&a.jsx("div",{className:se.state,children:"No models found"}),!p&&!w&&g.length>0&&a.jsx("div",{className:se.list,children:g.map(k=>a.jsxs(A,{className:se.item,onSelect:()=>n(k.value,v.get(k.value)),children:[a.jsx("span",{className:se.checkSlot,"aria-hidden":!0,children:k.value===e&&a.jsx(ln,{size:14})}),a.jsx("span",{className:se.label,children:k.label}),a.jsxs("span",{className:se.modelId,children:["(",k.value,")"]})]},k.value))})]})})]})}const Rd="_statusBar_tm1j6_1",qd="_segmentGroup_tm1j6_16",Md="_chevron_tm1j6_20",Bd="_segment_tm1j6_16",$d="_icon_tm1j6_33",Ad="_modelSegment_tm1j6_39",Dd="_modelChevron_tm1j6_63",Pd="_text_tm1j6_74",Z={statusBar:Rd,segmentGroup:qd,chevron:Md,segment:Bd,icon:$d,modelSegment:Ad,modelChevron:Dd,text:Pd};function zd(){const e=T(g=>g.activeSessionId),t=T(g=>e?g.sessions[e]:void 0),n=E(g=>g.client),s=T(g=>g.setModel),o=ct(),r=N(g=>g.activeWorkspaceCwd);nd(r||"");const i=oe(g=>g.available),c=oe(g=>g.branch),d=oe(g=>g.ahead),h=oe(g=>g.behind),p=oe(g=>g.detached),w=oe(g=>g.conflictCount),f=oe(g=>g.changes.length),m=Fn(g=>e?g.bySession[e]:void 0);ed(e);const v=[];if(t){const g=rd(t.cwd,o);v.push({key:"cwd",icon:a.jsx(ke,{size:13}),text:g,title:t.cwd})}if(i){const g=ad(d,h),R=[p?"(detached)":c??"?"];g&&R.push(g),f>0&&R.push(`●${f}`),w>0&&R.push(`⚠${w}`),v.push({key:"branch",icon:a.jsx(fs,{size:13}),text:R.join(" ")})}if(t){const g=`${sd(m==null?void 0:m.contextPercent)} (${Ae(m==null?void 0:m.contextTokens)}/${Ae(m==null?void 0:m.contextWindow)})`;v.push({key:"context",icon:a.jsx(hs,{size:13}),text:g}),v.push({key:"tokens",icon:a.jsx(ms,{size:13}),text:Ae(m==null?void 0:m.totalTokens),title:`in ${Ae(m==null?void 0:m.inputTokens)} / out ${Ae(m==null?void 0:m.outputTokens)}`}),v.push({key:"cost",icon:a.jsx(gs,{size:13}),text:od(m==null?void 0:m.cost)})}function _(g,R){e&&(s(e,g,R),!(!n||!R)&&(async()=>{const P=await Nn(n,e);await n.agent(P).setModel(R,g)})().catch(()=>{}))}return a.jsxs("div",{className:Z.statusBar,children:[t&&a.jsx("span",{className:Z.segmentGroup,children:a.jsx(Nd,{currentModel:t.model,provider:"pi",onSelect:_,renderTrigger:g=>a.jsxs("button",{type:"button",className:Z.modelSegment,disabled:!n,title:g?`Model: ${g}`:"Select model",children:[a.jsx("span",{className:Z.icon,children:a.jsx(_s,{size:13})}),a.jsx("span",{className:Z.text,children:g??"Model"}),a.jsx(en,{size:12,className:Z.modelChevron,"aria-hidden":"true"})]})})}),v.map((g,R)=>a.jsxs("span",{className:Z.segmentGroup,children:[(!!t||R>0)&&a.jsx(It,{size:12,className:Z.chevron,"aria-hidden":"true"}),a.jsxs("span",{className:Z.segment,title:g.title,children:[a.jsx("span",{className:Z.icon,children:g.icon}),a.jsx("span",{className:Z.text,children:g.text})]})]},g.key))]})}const Od="_wrapper_131x2_3",Fd="_box_131x2_18",Wd="_checkmark_131x2_36",Ld="_nativeInput_131x2_41",et={wrapper:Od,box:Fd,checkmark:Wd,nativeInput:Ld};y.forwardRef(function({label:t,checked:n=!1,disabled:s,className:o,onChange:r,...i},c){return a.jsxs("label",{className:et.wrapper,"data-disabled":s||void 0,children:[a.jsx("input",{ref:c,type:"checkbox",className:et.nativeInput,checked:n,disabled:s,onChange:r,...i}),a.jsx("span",{className:et.box,"data-checked":n,"aria-hidden":!0,children:n&&a.jsx(ln,{size:12,className:et.checkmark})}),t&&a.jsx("span",{children:t})]})});const Hd="_select_vj45v_3",Ud={select:Hd};y.forwardRef(function({options:t,placeholder:n,className:s,...o},r){return a.jsxs("select",{ref:r,className:F(Ud.select,s),...o,children:[n&&a.jsx("option",{value:"",disabled:!0,children:n}),t.map(i=>a.jsx("option",{value:i.value,children:i.label},i.value))]})});const Kd="_overlay_1yaef_1",Vd="_contentWrapper_1yaef_7",Gd="_dialog_1yaef_16",Xd="_header_1yaef_28",Jd="_title_1yaef_36",Yd="_closeBtn_1yaef_43",Qd="_body_1yaef_57",Zd="_footer_1yaef_63",eu="_bare_1yaef_72",tu="_bareBody_1yaef_78",nu="_bareCloseBtn_1yaef_82",su="_visuallyHidden_1yaef_101",J={overlay:Kd,contentWrapper:Vd,dialog:Gd,header:Xd,title:Jd,closeBtn:Yd,body:Qd,footer:Zd,bare:eu,bareBody:tu,bareCloseBtn:nu,visuallyHidden:su},ou=gt;function ru({open:e,onOpenChange:t,title:n,children:s,footer:o,width:r,className:i,bare:c=!1}){return a.jsx(bs,{open:e,onOpenChange:t,children:a.jsxs(ws,{children:[a.jsx(xs,{className:J.overlay}),a.jsx("div",{className:J.contentWrapper,children:a.jsxs(Ss,{className:F(J.dialog,c&&J.bare,i),style:r!==void 0?{width:r}:void 0,children:[c?a.jsx(Rt,{className:J.visuallyHidden,children:n}):a.jsxs("div",{className:J.header,children:[a.jsx(Rt,{className:J.title,children:n}),a.jsx(gt,{asChild:!0,children:a.jsx("button",{type:"button",className:J.closeBtn,"aria-label":"Close",children:a.jsx(ht,{size:16})})})]}),a.jsx("div",{className:F(J.body,c&&J.bareBody),children:s}),c&&a.jsx(gt,{asChild:!0,children:a.jsx("button",{type:"button",className:J.bareCloseBtn,"aria-label":"Close",children:a.jsx(ht,{size:16})})}),o&&a.jsx("div",{className:J.footer,children:o})]})})]})})}const au="_handle_1ocv1_1",iu={handle:au};function Yt({side:e,onResize:t,className:n}){const s=y.useRef(0),o=y.useCallback(c=>{const d=c.clientX-s.current;s.current=c.clientX,t(e==="left"?d:-d)},[t,e]),r=y.useCallback(c=>{var d,h;window.removeEventListener("pointermove",o),window.removeEventListener("pointerup",r),document.body.style.cursor="",document.body.style.userSelect="",(h=(d=c.target)==null?void 0:d.releasePointerCapture)==null||h.call(d,c.pointerId)},[o]);function i(c){c.preventDefault(),s.current=c.clientX,document.body.style.cursor="col-resize",document.body.style.userSelect="none",window.addEventListener("pointermove",o),window.addEventListener("pointerup",r)}return a.jsx("div",{className:F(iu.handle,n),onPointerDown:i,role:"separator","aria-orientation":"vertical"})}function cu(e,t){const{order:n,sessions:s}=T.getState(),r=Et(n,s,t).find(i=>i.cwd===e);if(r!=null&&r.sessions[0]){const i=r.sessions[0].id;T.getState().activate(i);const c=T.getState().sessions[i];N.getState().open({id:X.chat(i),kind:"chat",label:(c==null?void 0:c.title)??"New chat",closable:!0,data:{sessionId:i},workspaceCwd:e})}else Tt(e);j.getState().setCwd(e)}const lu="_pathRow_trimn_1",du="_pathInput_trimn_9",uu="_createRow_trimn_13",pu="_createInput_trimn_21",fu="_createError_trimn_25",hu="_list_trimn_30",mu="_item_trimn_37",gu="_name_trimn_49",_u="_emptyState_trimn_54",ee={pathRow:lu,pathInput:du,createRow:uu,createInput:pu,createError:fu,list:hu,item:mu,name:gu,emptyState:_u};function yu(){const e=j(I=>I.cwdPickerOpen),t=j(I=>I.closeCwdPicker),n=N(I=>I.activeWorkspaceCwd),s=j(I=>I.cwd),o=E(I=>I.client),r=ct(),[i,c]=y.useState("/"),[d,h]=y.useState("/"),[p,w]=y.useState(!1),[f,m]=y.useState(""),[v,_]=y.useState(null),[g,R]=y.useState(!1),P=Ie();y.useEffect(()=>{if(!e)return;const I=je(n||s||"~",r);c(I),h(I),re()},[e,o,n,s]);const{data:k,isLoading:V,isError:Te,error:Ee}=Bc(i,e&&!!o),Ue=((k==null?void 0:k.entries)??[]).filter(I=>I.kind==="directory");function re(){w(!1),m(""),_(null)}function ue(I){c(I),h(I),re()}function Ne(){ue(i.split("/").slice(0,-1).join("/")||"/")}function pe(){ue(d.trim())}async function Re(){const I=f.trim();if(!(!I||!o||g)){R(!0),_(null);try{const fe=await On(o,i,I,"directory");await P.invalidateQueries({queryKey:Ce.explorer(i)}),ue(fe)}catch(fe){_(fe instanceof Error?fe.message:"Failed to create folder")}finally{R(!1)}}}function Ke(){cu(i,r),t()}return a.jsxs(ru,{open:e,onOpenChange:I=>!I&&t(),title:"Open Workspace",footer:a.jsxs(a.Fragment,{children:[a.jsx(ou,{asChild:!0,children:a.jsx(K,{size:"sm",variant:"secondary",children:"Cancel"})}),a.jsx(K,{size:"sm",onClick:Ke,children:"Open this folder"})]}),children:[a.jsxs("div",{className:ee.pathRow,children:[a.jsx(K,{size:"xs",variant:"ghost",iconOnly:!0,title:"Up",onClick:Ne,children:a.jsx(ys,{size:13})}),a.jsx(ot,{className:ee.pathInput,value:d,onChange:I=>h(I.target.value),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),pe())}}),a.jsx(K,{size:"xs",onClick:pe,children:"Go"}),a.jsx(K,{size:"xs",variant:"ghost",iconOnly:!0,title:"New folder",disabled:!o||Te||p,onClick:()=>{w(!0),m(""),_(null)},children:a.jsx(st,{size:13})})]}),p&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:ee.createRow,children:[a.jsx(ke,{size:14}),a.jsx(ot,{className:ee.createInput,autoFocus:!0,placeholder:"New folder name",value:f,onChange:I=>m(I.target.value),onKeyDown:I=>{I.key==="Enter"?(I.preventDefault(),Re()):I.key==="Escape"&&(I.preventDefault(),I.stopPropagation(),re())}}),a.jsx(K,{size:"xs",loading:g,disabled:!f.trim()||g,onClick:()=>void Re(),children:"Create"}),a.jsx(K,{size:"xs",variant:"secondary",onClick:re,children:"Cancel"})]}),v&&a.jsx("div",{className:ee.createError,children:v})]}),a.jsx("div",{className:ee.list,children:V?a.jsx("div",{className:ee.emptyState,children:"Loading..."}):Te?a.jsxs("div",{className:ee.emptyState,children:["Error: ",Ee instanceof Error?Ee.message:"unknown error"]}):Ue.length===0?a.jsx("div",{className:ee.emptyState,children:"No subdirectories"}):Ue.map(I=>a.jsxs("div",{className:ee.item,onClick:()=>ue(i==="/"?`/${I.name}`:`${i}/${I.name}`),children:[a.jsx(ke,{size:14}),a.jsx("span",{className:ee.name,children:I.name})]},I.name))})]})}const bu="_shell_1m1nv_1",wu="_main_1m1nv_7",xu="_sidebarLeft_1m1nv_13",Su="_leftHandle_1m1nv_21",vu="_center_1m1nv_24",ku="_sidebarRight_1m1nv_31",Iu="_rightHandle_1m1nv_39",ge={shell:bu,main:wu,sidebarLeft:xu,leftHandle:Su,center:vu,sidebarRight:ku,rightHandle:Iu};function ju(){const e=j(i=>i.leftSidebarCollapsed),t=j(i=>i.rightSidebarCollapsed),n=j(i=>i.leftSidebarWidth),s=j(i=>i.rightSidebarWidth),o=j(i=>i.resizeLeftSidebar),r=j(i=>i.resizeRightSidebar);return a.jsxs("div",{className:ge.shell,children:[a.jsx(Qa,{}),a.jsxs("div",{className:ge.main,children:[!e&&a.jsxs("aside",{className:ge.sidebarLeft,style:{width:n},children:[a.jsx(tc,{}),a.jsx(Yt,{side:"left",className:ge.leftHandle,onResize:o})]}),a.jsxs("div",{className:ge.center,children:[a.jsx(mc,{}),a.jsx(Rc,{})]}),!t&&a.jsxs("aside",{className:ge.sidebarRight,style:{width:s},children:[a.jsx(Yt,{side:"right",className:ge.rightHandle,onResize:r}),a.jsx(Yl,{})]})]}),a.jsx(zd,{}),a.jsx(yu,{})]})}function Cu(){const e=y.useRef(!1);y.useEffect(()=>{if(e.current)return;if(e.current=!0,window.location.hash.includes("offer=")){const d=window.location.href;j.getState().setHost(d),E.getState().connect({url:d});return}const t=new URLSearchParams(window.location.search),n=t.get("host"),s=t.get("pair"),o=t.get("password"),r=t.get("cwd"),i=t.get("connect")==="1",c=j.getState();if(s?c.setHost(s):n&&c.setHost(n),o&&c.setPassword(o),r&&c.setCwd(r),s)E.getState().connect({url:s});else if(i){const{host:d,password:h}=j.getState();E.getState().connect({url:d,password:h||void 0})}},[])}function Tu(e){return typeof e=="object"&&e!==null&&"kind"in e}function Eu(e){const t=[];for(const n of e)if(Tu(n))if(n.kind==="other")n.event&&t.push(n.event);else for(const s of n.events??[])t.push(s);return t}async function Nu(e){const t=[];let n=null;for(;;){const s=await e(n);if(s.items.length===0||(t.push(...Eu(s.items)),!s.hasNewer))return t;const o=s.endCursor;if(typeof o!="string"||o===n)return t;n=o}}function Ru(e){return typeof e.model=="string"}function qu(){const e=E(s=>s.client),t=E(s=>s.status),n=y.useRef(!1);y.useEffect(()=>{t!=="open"||!e||n.current||(n.current=!0,(async()=>{var w;let s=[];try{s=(await e.connection.request("list_agents_request",{all:!1})).agents??[]}catch{s=[]}s.sort((f,m)=>(m.lastActivity??0)-(f.lastActivity??0));const o=T.getState();for(const f of s){if(o.findByAgentId(f.agentId))continue;let m=wt;try{m=(await Nu(g=>e.agent(f.agentId).timeline.fetch({direction:"after",cursor:g??void 0,limit:200}))).reduce(En,wt)}catch{}const v=m.rows.length===0;o.hydrate({id:`s-${f.agentId.slice(0,12)}`,agentId:f.agentId,title:f.title||(v?"New chat":(w=f.cwd)==null?void 0:w.split("/").pop())||"Restored",status:f.status??"idle",cwd:f.cwd||"~",timeline:m,userMessageCount:m.rows.filter(_=>_.kind==="user").length,model:f.model,modelProvider:f.modelProvider})}const{order:r,sessions:i}=T.getState(),c=r.length>0?i[r[0]??""]:void 0;if(!c)return;const d=await it(e).catch(()=>null),h=je(c.cwd||"~",d),p=Et(r,i,d);j.getState().setCollapsedWorkspaces(Zi(p,h)),T.getState().activate(c.id),j.getState().setCwd(c.cwd),N.getState().open({id:X.chat(c.id),kind:"chat",label:c.title,closable:!0,data:{sessionId:c.id},workspaceCwd:h})})())},[t,e]),y.useEffect(()=>{if(!(t!=="open"||!e))return e.onAgentUpdate(s=>{if(Ru(s)){const o=typeof s.modelProvider=="string"?s.modelProvider:void 0;T.getState().setModelByAgentId(s.agentId,s.model,o)}})},[t,e])}function Mu(){const e=E(s=>s.client),t=E(s=>s.status),n=y.useRef(!1);y.useEffect(()=>{t!=="open"||!e||n.current||(n.current=!0,(async()=>{let s=[];try{s=(await e.connection.request("list_terminals_request",{})).terminals??[]}catch{s=[]}if(s.length===0)return;const o=await it(e).catch(()=>null),r=N.getState().open;for(const i of s){if(i.closed)continue;const c=je(i.cwd||"~",o);r({id:X.terminal(i.slot),kind:"terminal",label:i.name,closable:!0,data:{slot:i.slot,cwd:c},workspaceCwd:c})}})())},[t,e])}function Bu(){y.useEffect(()=>{function e(t){const n=j.getState();if(t.key==="Escape"){n.closeCwdPicker(),n.closeSessionMenu();return}const s=t.ctrlKey||t.metaKey;if(s&&t.key.toLowerCase()==="t"){t.preventDefault(),Rn(N.getState().activeWorkspaceCwd||"~");return}if(s&&t.key.toLowerCase()==="w"){const{activeTabId:o,tabs:r}=N.getState();if(!o)return;const i=r.find(c=>c.id===o);(i==null?void 0:i.closable)!==!1&&(t.preventDefault(),xt(o))}}return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[])}function $u(){return Cu(),qu(),Mu(),Bu(),null}function Au(){return a.jsxs(xo,{children:[a.jsx($u,{}),a.jsx(ju,{})]})}const Wn=document.getElementById("root");if(!Wn)throw new Error("Missing #root element");Gn.createRoot(Wn).render(a.jsx(y.StrictMode,{children:a.jsx(Au,{})}));export{K as B,ru as D,Mn as S,Ku as T,Yu as V,E as a,ct as b,Ju as c,Qu as d,Nn as e,cd as f,Vu as g,N as h,Gu as i,Xu as j,Vt as k,X as l,je as n,Ce as r,se as s,Za as t,T as u};
3
+ //# sourceMappingURL=index-CqmgQdsG.js.map